Node library API
This page describes the principal Node library calls. A parser from createParser parsesaddress parsingThe process of decomposing a free-text postal address string into structured components — house number, street name, locality, region, postcode, and country — so a geocoder can resolve them to coordinates. an address into a labeled tree. A geocode also requires a resolverresolverThe component that converts parsed address components (locality, region, postcode) into coordinates by looking them up in the gazetteer. The resolver ranks candidates by name match, population, and proximity, and returns the best-matching place with its centroid or polygon. and geographic databases. Parse and geocode result schema defines the result fields, tags, coordinate tiers, and provenance values.
Imports
| Import | Public entry points covered here |
|---|---|
mailwoman | createParser, the tree readers below, and the AddressNode and PipelineResult types |
mailwoman/engine/runtime-pipeline | createRuntimePipeline |
mailwoman/geocode | parseForGeocode, geocodeAddress, geocodeStream, createRegionDatabaseProvider |
@mailwoman/neural | NeuralAddressClassifier |
@mailwoman/core/decoder | createCalibrator |
The mailwoman package installs the classifier and the en-US modelneural classifierThe machine learning model at the core of Mailwoman's parser — a transformer encoder (~30M parameters) trained from scratch to do BIO token classification over addresses. It learns the 'grammar' of address formats; the gazetteer supplies the 'atlas.', so a parseaddress parsingThe process of decomposing a free-text postal address string into structured components — house number, street name, locality, region, postcode, and country — so a geocoder can resolve them to coordinates. needs no other package.
Parse calls
function createParser(options?: ParserOptions): Promise<Parser>
interface Parser extends AsyncDisposable {
parse(raw: string, runOpts?: PipelineOpts): Promise<PipelineResult>
readonly scope: ServiceRegistry
}
createParser loads a parser with the options below, en-US when you state none. The parser keeps its modelneural classifierThe machine learning model at the core of Mailwoman's parser — a transformer encoder (~30M parameters) trained from scratch to do BIO token classification over addresses. It learns the 'grammar' of address formats; the gazetteer supplies the 'atlas.' loaded for every parse call, and the caller owns it: the package holds zero parser of its own between calls. await using releases the modelneural classifierThe machine learning model at the core of Mailwoman's parser — a transformer encoder (~30M parameters) trained from scratch to do BIO token classification over addresses. It learns the 'grammar' of address formats; the gazetteer supplies the 'atlas.' when the scope ends, and a long-lived service keeps one parser and calls await parser[Symbol.asyncDispose]() at shutdown:
await using parser = await createParser({ locale: "en-US", machinePreferences: "none" })
const result = await parser.parse("10118")
An input in another script, such as Chinese or Japanese text, routes to that script's modelneural classifierThe machine learning model at the core of Mailwoman's parser — a transformer encoder (~30M parameters) trained from scratch to do BIO token classification over addresses. It learns the 'grammar' of address formats; the gazetteer supplies the 'atlas.' when its weightsparameterA single learned number inside a model — one weight or bias. Mailwoman's encoder has roughly 30 million of them; training is the search for good values. package is installed. Otherwise the parser logs one warning and parsesaddress parsingThe process of decomposing a free-text postal address string into structured components — house number, street name, locality, region, postcode, and country — so a geocoder can resolve them to coordinates. it with the localelocaleThe combination of language and country an address comes from. en-US and fr-FR are the locales Mailwoman ships weights for.'s modelneural classifierThe machine learning model at the core of Mailwoman's parser — a transformer encoder (~30M parameters) trained from scratch to do BIO token classification over addresses. It learns the 'grammar' of address formats; the gazetteer supplies the 'atlas.'.
| Parser option | Type and default | Effect |
|---|---|---|
locale | BCP-47 localelocaleThe combination of language and country an address comes from. en-US and fr-FR are the locales Mailwoman ships weights for.; en-US | Selects the weightsparameterA single learned number inside a model — one weight or bias. Mailwoman's encoder has roughly 30 million of them; training is the search for good values. package of the primary modelneural classifierThe machine learning model at the core of Mailwoman's parser — a transformer encoder (~30M parameters) trained from scratch to do BIO token classification over addresses. It learns the 'grammar' of address formats; the gazetteer supplies the 'atlas.'. |
dataRoot | path, absent | Overlays the installed weightsparameterA single learned number inside a model — one weight or bias. Mailwoman's encoder has roughly 30 million of them; training is the search for good values. with the data root's weights/ directory. |
weightsCacheRoot | path, absent | Loads the weightsparameterA single learned number inside a model — one weight or bias. Mailwoman's encoder has roughly 30 million of them; training is the search for good values. only from this cache. |
machinePreferences | auto, none, or preferences; auto | Supplies host localelocaleThe combination of language and country an address comes from. en-US and fr-FR are the locales Mailwoman ships weights for. preferences when the caller and input provide none. |
caseNormalization | title-case or preserve; title-case | Sets the default case treatment for calls. |
placerCountryUse | filter or prior; filter | Sets how a confident coarse countrycountryThe top-level address component (an ISO country). Closed-vocabulary, so it is best handled by a deterministic matcher feeding a proposal rather than a retrained model head. guess constrains resolution. |
poiQueryKind | extract or none; extract | Detects point-of-interest queries. |
scope | ServiceRegistry, absent | Reuses the classifier a geocode process scope already holds. |
These functions read the tree a parseaddress parsingThe process of decomposing a free-text postal address string into structured components — house number, street name, locality, region, postcode, and country — so a geocoder can resolve them to coordinates. returns:
| Function | Returns |
|---|---|
decodeAsJSON(tree) | One value per tag. The neural classifier section describes its options. |
decodeAsTuples(tree) | [tag, value] pairs in source order, repeated tags included. |
groupTuplesByTag(tree) | A Map from each tag to all of its values, in source order. |
flattenTreeNodes(tree) | Every node in source order with its tag, value, spanspanA contiguous range of characters or tokens in the input string, tagged with an address component type (street, locality, postcode, etc.). Parsed addresses are represented as collections of spans, possibly nested in a tree., score and resolved place fields. |
decodeAsOutline(tree) | Text with one node per line, tag [start, end): "value", each child indented under its parent. |
walkNodes(roots) | A generator over every node in depth-first order, each parent before its children. |
console.table(flattenTreeNodes(result.tree), ["tag", "value", "start", "end"]) prints the components with their spansspanA contiguous range of characters or tokens in the input string, tagged with an address component type (street, locality, postcode, etc.). Parsed addresses are represented as collections of spans, possibly nested in a tree..
Runtime pipeline
interface RuntimePipeline extends AsyncDisposable {
(raw: string, runOpts?: PipelineOpts): Promise<PipelineResult>
}
function createRuntimePipeline(opts?: CreateRuntimePipelineOpts, scope?: { parent?: ServiceRegistry }): RuntimePipeline
mailwoman/engine/runtime-pipeline exports the factory that createParser builds on. Use it to supply your own classifier, a resolverresolverThe component that converts parsed address components (locality, region, postcode) into coordinates by looking them up in the gazetteer. The resolver ranks candidates by name match, population, and proximity, and returns the best-matching place with its centroid or polygon., or a POIpoint of interest (POI). A named place that is not strictly an address — landmark, transit stop, venue, amenity, or franchise. Mailwoman tags these as venue and resolves them through the gazetteer. database. The factory returns a parseaddress parsingThe process of decomposing a free-text postal address string into structured components — house number, street name, locality, region, postcode, and country — so a geocoder can resolve them to coordinates. function synchronously. The returned function runs the async pipelinestaged pipelineMailwoman's runtime architecture: a sequence of pure-function stages (normalize → query-shape → locale-hint → kind-classifier → phrase-grouper → classifier → decoder) connected by typed handoffs. Each stage is published as its own npm package..
The pipelinestaged pipelineMailwoman's runtime architecture: a sequence of pure-function stages (normalize → query-shape → locale-hint → kind-classifier → phrase-grouper → classifier → decoder) connected by typed handoffs. Each stage is published as its own npm package. owns what it loads for an auto stagestageOne of the dataflow stages in the runtime pipeline (normalize, locale check, kind classify, phrase group, token classify, sequence correct, reconcile, resolve). Distinct from tier (model vocabulary) and phase (plan milestone).: the bundled coarse placer, the streetstreetThe named linear feature along which house numbers are ordered. Decomposes into a name plus street affixes; one of the Tier 2 fine labels. index and the POIpoint of interest (POI). A named place that is not strictly an address — landmark, transit stop, venue, amenity, or franchise. Mailwoman tags these as venue and resolves them through the gazetteer. database. It loads each on the first call and closes it when the pipelinestaged pipelineMailwoman's runtime architecture: a sequence of pure-function stages (normalize → query-shape → locale-hint → kind-classifier → phrase-grouper → classifier → decoder) connected by typed handoffs. Each stage is published as its own npm package. is disposed, so hold a pipelinestaged pipelineMailwoman's runtime architecture: a sequence of pure-function stages (normalize → query-shape → locale-hint → kind-classifier → phrase-grouper → classifier → decoder) connected by typed handoffs. Each stage is published as its own npm package. with await using or call its Symbol.asyncDispose after the last parseaddress parsingThe process of decomposing a free-text postal address string into structured components — house number, street name, locality, region, postcode, and country — so a geocoder can resolve them to coordinates.. A process holds no shared copy of these. A caller that builds several pipelinesstaged pipelineMailwoman's runtime architecture: a sequence of pure-function stages (normalize → query-shape → locale-hint → kind-classifier → phrase-grouper → classifier → decoder) connected by typed handoffs. Each stage is published as its own npm package. calls registerRuntimePipelineServices(registry) on one ServiceRegistry from async-init and passes { parent: registry } to each, so the registry loads each default once and closes it at its own disposal. An omitted classifier leaves the structural stagesstageOne of the dataflow stages in the runtime pipeline (normalize, locale check, kind classify, phrase group, token classify, sequence correct, reconcile, resolve). Distinct from tier (model vocabulary) and phase (plan milestone). available, but a neural classifierneural classifierThe machine learning model at the core of Mailwoman's parser — a transformer encoder (~30M parameters) trained from scratch to do BIO token classification over addresses. It learns the 'grammar' of address formats; the gazetteer supplies the 'atlas.' is required for a labeled parseaddress parsingThe process of decomposing a free-text postal address string into structured components — house number, street name, locality, region, postcode, and country — so a geocoder can resolve them to coordinates.. The pipelinestaged pipelineMailwoman's runtime architecture: a sequence of pure-function stages (normalize → query-shape → locale-hint → kind-classifier → phrase-grouper → classifier → decoder) connected by typed handoffs. Each stage is published as its own npm package. can add resolved places to the tree when resolver is supplied.
The following factory options are the settings a caller uses to choose the stagesstageOne of the dataflow stages in the runtime pipeline (normalize, locale check, kind classify, phrase group, token classify, sequence correct, reconcile, resolve). Distinct from tier (model vocabulary) and phase (plan milestone). and their defaults. CreateRuntimePipelineOpts also exposes stagestageOne of the dataflow stages in the runtime pipeline (normalize, locale check, kind classify, phrase group, token classify, sequence correct, reconcile, resolve). Distinct from tier (model vocabulary) and phase (plan milestone).-replacement callbacks and prior controls for custom pipelinesstaged pipelineMailwoman's runtime architecture: a sequence of pure-function stages (normalize → query-shape → locale-hint → kind-classifier → phrase-grouper → classifier → decoder) connected by typed handoffs. Each stage is published as its own npm package.. Read the exported TypeScript declaration for those advanced fields.
| Factory option | Type and default | Effect |
|---|---|---|
classifier | classification stagestageOne of the dataflow stages in the runtime pipeline (normalize, locale check, kind classify, phrase group, token classify, sequence correct, reconcile, resolve). Distinct from tier (model vocabulary) and phase (plan milestone)., absent | Supplies labeled address spansspanA contiguous range of characters or tokens in the input string, tagged with an address component type (street, locality, postcode, etc.). Parsed addresses are represented as collections of spans, possibly nested in a tree.. The published neural classifierneural classifierThe machine learning model at the core of Mailwoman's parser — a transformer encoder (~30M parameters) trained from scratch to do BIO token classification over addresses. It learns the 'grammar' of address formats; the gazetteer supplies the 'atlas.' implements this stagestageOne of the dataflow stages in the runtime pipeline (normalize, locale check, kind classify, phrase group, token classify, sequence correct, reconcile, resolve). Distinct from tier (model vocabulary) and phase (plan milestone).. |
resolver | Resolver, absent | Resolves parsed places when a geographic database backs it. |
fst | auto, none, or matcher; auto | Loads the classifier's gazetteergazetteerA geographical index that maps place names and postcodes to real-world coordinates. Mailwoman uses a custom-built Who's On First (WOF) SQLite database as its gazetteer — the 'atlas' half of the grammar/atlas architecture. matcher when available. |
streetMorphology | auto, none, or matcher; auto | Supplies streetstreetThe named linear feature along which house numbers are ordered. Decomposes into a name plus street affixes; one of the Tier 2 fine labels.-form evidence when a matcher is available. |
anchorRegions | auto, none, or lookup; auto | Supplies the admin ancestry of an anchored postcodepostcodeThe country-specific postcode (US ZIP, French code postal, etc.). Mailwoman handles postcode parsing entirely by rule classifier — a regex problem, not an ML one. beside an auto gazetteergazetteerA geographical index that maps place names and postcodes to real-world coordinates. Mailwoman uses a custom-built Who's On First (WOF) SQLite database as its gazetteer — the 'atlas' half of the grammar/atlas architecture.. |
streetEvidence | auto, none, or evidence index; auto | Supplies a streetstreetThe named linear feature along which house numbers are ordered. Decomposes into a name plus street affixes; one of the Tier 2 fine labels. reranking index when available. |
placeCountry | auto, none, or function; auto | Supplies the coarse countrycountryThe top-level address component (an ISO country). Closed-vocabulary, so it is best handled by a deterministic matcher feeding a proposal rather than a retrained model head. guess. |
machinePreferences | auto, none, or preferences; auto | Supplies host localelocaleThe combination of language and country an address comes from. en-US and fr-FR are the locales Mailwoman ships weights for. preferences when the caller and input provide none. |
poiQueryKind | extract, none, or { poiDatabasePath }; extract | Detects point-of-interest queries. The object form also opens a lookup for execution. |
caseNormalization | title-case or preserve; title-case | Sets the default case treatment for calls. |
placerCountryUse | filter or prior; filter | Sets how a confident coarse countrycountryThe top-level address component (an ISO country). Closed-vocabulary, so it is best handled by a deterministic matcher feeding a proposal rather than a retrained model head. guess constrains resolution. |
hardCountrySafelist | ReadonlySet<string>, artifact or built-in default | Replaces the countries eligible for a hard countrycountryThe top-level address component (an ISO country). Closed-vocabulary, so it is best handled by a deterministic matcher feeding a proposal rather than a retrained model head. filter. |
Parser.parse and the function createRuntimePipeline returns accept these PipelineOpts fields on each call. A per-call value for caseNormalization, placerCountryUse, or hardCountrySafelist replaces the factory value for that call.
| Per-call option | Type and default | Effect |
|---|---|---|
locale | BCP-47 localelocaleThe combination of language and country an address comes from. en-US and fr-FR are the locales Mailwoman ships weights for., detected when omitted | Supplies a localelocaleThe combination of language and country an address comes from. en-US and fr-FR are the locales Mailwoman ships weights for. hint. |
userLocation | coordinate, countrycountryThe top-level address component (an ISO country). Closed-vocabulary, so it is best handled by a deterministic matcher feeding a proposal rather than a retrained model head., or regionregionThe first-level administrative subdivision of a country — a US state, a French region, a province. The component between country and locality. and countrycountryThe top-level address component (an ISO country). Closed-vocabulary, so it is best handled by a deterministic matcher feeding a proposal rather than a retrained model head.. Absent by default. | Supplies the resolverresolverThe component that converts parsed address components (locality, region, postcode) into coordinates by looking them up in the gazetteer. The resolver ranks candidates by name match, population, and proximity, and returns the best-matching place with its centroid or polygon. with the caller's location. |
inputMode | auto, fragmented, or formatted; auto | Selects the input register from the query kindquery kindThe coarse category the kind classifier assigns to the whole input — postcode_only, locality_only, structured_address, intersection, po_box, landmark, or vague — used to route processing. when auto. |
forceFullPipeline | boolean, false | Disables postcodepostcodeThe country-specific postcode (US ZIP, French code postal, etc.). Mailwoman handles postcode parsing entirely by rule classifier — a regex problem, not an ML one. and localitylocalityThe city / town / settlement component of an address: a populated place sitting between region and neighborhood in the hierarchy. fast paths. Point-of-interest routing still applies. |
resolveOpts | ResolveOpts, absent | Passes resolverresolverThe component that converts parsed address components (locality, region, postcode) into coordinates by looking them up in the gazetteer. The resolver ranks candidates by name match, population, and proximity, and returns the best-matching place with its centroid or polygon.-specific options through. |
caseNormalization | title-case or preserve; factory default | Sets letter-case treatment. |
placetypePair | inherit, off, or prior object; inherit | Selects the placetypeplacetypeThe Who's On First hierarchical classification of places: planet → continent → country → region → county → locality → neighborhood. The resolver uses placetype to rank candidates — an exact locality match outranks a county-level match.-pair prior. |
placerCountryUse | filter or prior; factory default | Sets coarse countrycountryThe top-level address component (an ISO country). Closed-vocabulary, so it is best handled by a deterministic matcher feeding a proposal rather than a retrained model head.-guess use. |
hardCountrySafelist | ReadonlySet<string>, factory default | Replaces the hard-countrycountryThe top-level address component (an ISO country). Closed-vocabulary, so it is best handled by a deterministic matcher feeding a proposal rather than a retrained model head. filter set. |
signal | AbortSignal, absent | Allows cancellation of the call. |
PipelineResult includes input, normalized, queryShape, locale, kind, phraseProposals, tree, poiIntent, timing, faults, intentMarkers, and path. faults records stagestageOne of the dataflow stages in the runtime pipeline (normalize, locale check, kind classify, phrase group, token classify, sequence correct, reconcile, resolve). Distinct from tier (model vocabulary) and phase (plan milestone). failures that the coordinator caught and continued past. An empty faults array means no stagestageOne of the dataflow stages in the runtime pipeline (normalize, locale check, kind classify, phrase group, token classify, sequence correct, reconcile, resolve). Distinct from tier (model vocabulary) and phase (plan milestone). faulted in that call. The result schema gives each field's type and meaning.
Neural classifier
NeuralAddressClassifier.loadFromWeights(
...args: Parameters<typeof loadClassifierFromWeights>
): Promise<NeuralAddressClassifier>
loadFromWeights loads a modelneural classifierThe machine learning model at the core of Mailwoman's parser — a transformer encoder (~30M parameters) trained from scratch to do BIO token classification over addresses. It learns the 'grammar' of address formats; the gazetteer supplies the 'atlas.' for one localelocaleThe combination of language and country an address comes from. en-US and fr-FR are the locales Mailwoman ships weights for.. The published en-US exercise installs @mailwoman/neural-weights-en-us@11.0.0 and passes { locale: "en-US" }. The loader also accepts explicit modelPath, tokenizerPath or charVocabPath, modelCardPath, tier, and cacheRoot options. tier is server by default; pocket omits lexicons and keeps the postcode anchoranchor inferenceA technique where structured knowledge (postcode locations, gazetteer place names) is injected into the model as soft input features — not as deterministic overrides. The model still decides the final labels, but the anchor signal biases it toward correct admin tags.. The full loader type is ResolveWeightsOpts plus inferenceinferenceRunning the trained model on new input to get predictions, as opposed to training, which produces the model. In Mailwoman that means a small transformer encoder reads an address string and classifies every token — house number, street, locality, region, postcode, and the rest. A Who's On First gazetteer can feed soft location hints into the pass, but the model makes the final call on every label. Where a generative model writes text token by token, Mailwoman's output is a retrieval-augmented token classification: one label per input piece. and diagnostic options in packages/neural/lib/classifier/loader.ts.
| Method | Return type | Projection |
|---|---|---|
parse(text, opts?) | Promise<AddressTree> | Nested labeled tree. |
parseJSON(text, opts?) | Promise<Partial<Record<ComponentTag, string>>> | One string per retained tag. With serialization options, the result can also contain unknown and dropped arrays. |
parseTuples(text, opts?) | Promise<Array<[ComponentTag, string]>> | Source-ordered tag and value pairs, including repeated tags. With includeUnknown, a tuple's tag can also be "unknown". |
parseXML(text, opts?) | Promise<string> | XML serialization. |
parseWithLogits(text, opts?) | Promise<ParseWithLogitsResult> | Parsed tree, raw modelneural classifierThe machine learning model at the core of Mailwoman's parser — a transformer encoder (~30M parameters) trained from scratch to do BIO token classification over addresses. It learns the 'grammar' of address formats; the gazetteer supplies the 'atlas.' logitslogitA raw, unnormalized per-label score the model outputs before softmax. Priors and biases are added in logit space, then softmax turns logits into probabilities. from before priors and repairs, and piece offsets. |
traceParse(text, opts?) | Promise<NeuralParseTrace> | Serializable decode trace. The trace omits opts.calibrate. |
Each method takes ParseOpts where shown. Common settings include inputMode, caseNormalization, queryShape, fst, calibrate, and placetypePair. Direct classifier calls have their own defaults and omit the runtime pipelinestaged pipelineMailwoman's runtime architecture: a sequence of pure-function stages (normalize → query-shape → locale-hint → kind-classifier → phrase-grouper → classifier → decoder) connected by typed handoffs. Each stage is published as its own npm package.'s surrounding stagesstageOne of the dataflow stages in the runtime pipeline (normalize, locale check, kind classify, phrase group, token classify, sequence correct, reconcile, resolve). Distinct from tier (model vocabulary) and phase (plan milestone).. Use createParser for the complete parseaddress parsingThe process of decomposing a free-text postal address string into structured components — house number, street name, locality, region, postcode, and country — so a geocoder can resolve them to coordinates. path and the classifier methods when the direct modelneural classifierThe machine learning model at the core of Mailwoman's parser — a transformer encoder (~30M parameters) trained from scratch to do BIO token classification over addresses. It learns the 'grammar' of address formats; the gazetteer supplies the 'atlas.' result or logitslogitA raw, unnormalized per-label score the model outputs before softmax. Priors and biases are added in logit space, then softmax turns logits into probabilities. are needed.
decodeAsJSON(tree, opts?) flattens an AddressTree to one value per tag. Its includeUnknown and includeDropped options add diagnostic arrays, including empty arrays when requested and no spansspanA contiguous range of characters or tokens in the input string, tagged with an address component type (street, locality, postcode, etc.). Parsed addresses are represented as collections of spans, possibly nested in a tree. qualify. When two spansspanA contiguous range of characters or tokens in the input string, tagged with an address component type (street, locality, postcode, etc.). Parsed addresses are represented as collections of spans, possibly nested in a tree. have the same tag, the projection keeps the grounded spanspanA contiguous range of characters or tokens in the input string, tagged with an address component type (street, locality, postcode, etc.). Parsed addresses are represented as collections of spans, possibly nested in a tree. first, then uses document order for administrative and postal tags or labelcomponent tagOne of the 25 labels in Mailwoman's address schema — street, locality, region, postcode, house_number, unit, po_box, country, venue, intersection, and others. Each parsed span carries exactly one component tag. confidence for other tags. The dropped array identifies a discarded value and the value that took its slot. Read tree when repeated spansspanA contiguous range of characters or tokens in the input string, tagged with an address component type (street, locality, postcode, etc.). Parsed addresses are represented as collections of spans, possibly nested in a tree. or tree nesting matter.
Geocode and batch calls
function parseForGeocode(
input: string,
deps: Pick<
GeocodeDeps,
| "classifier"
| "normalizeInput"
| "caseNormalization"
| "inputMode"
| "fst"
| "streetMorphology"
| "streetMorphologyPrior"
| "anchorRegions"
| "venueHead"
| "venueHeadOpts"
>
): Promise<AddressTree>
function geocodeAddress(input: string, deps: GeocodeDeps): Promise<GeocodeResult>
function geocodeStream(
records: AsyncIterable<SourceRecord> | Iterable<SourceRecord>,
opts: GeocodeStreamOptions
): AsyncIterableIterator<SourceRecord>
Import these functions from mailwoman/geocode. GeocodeDeps requires a classifier, a resolver and a placeCountry. placeCountry is the coarse countrycountryThe top-level address component (an ISO country). Closed-vocabulary, so it is best handled by a deterministic matcher feeding a proposal rather than a retrained model head. router behind the soft countrycountryThe top-level address component (an ISO country). Closed-vocabulary, so it is best handled by a deterministic matcher feeding a proposal rather than a retrained model head. prior, or "none" for no prior. geocodeAddress loads no router by itself: loadBundledPlaceCountry() from mailwoman/default/placer loads the bundled one, and a caller loads it once and passes the same function to every call. A call that states neither throws a TypeError. A geocode also requires geographic data behind the resolverresolverThe component that converts parsed address components (locality, region, postcode) into coordinates by looking them up in the gazetteer. The resolver ranks candidates by name match, population, and proximity, and returns the best-matching place with its centroid or polygon.. The optional databases, nationalDatabases, and osmDatabases fields select additional regionregionThe first-level administrative subdivision of a country — a US state, a French region, a province. The component between country and locality. and address-point layerslayerOne transformer block — attention plus a feed-forward network, with normalization and residual connections — applied to every position. Stacking layers lets the model build up richer representations; Mailwoman's encoder has 6.. parseForGeocode accepts the parseaddress parsingThe process of decomposing a free-text postal address string into structured components — house number, street name, locality, region, postcode, and country — so a geocoder can resolve them to coordinates.-related subset of GeocodeDeps and returns a tree without running the full coordinate cascade. createRegionDatabaseProvider(factory, dataRoot, catalog?) returns a disposable provider of each regionregionThe first-level administrative subdivision of a country — a US state, a French region, a province. The component between country and locality.'s address-point and interpolationinterpolationA geocoding technique that estimates a coordinate along a street segment based on the house number range. Used as the middle tier of Mailwoman's geocode cascade when exact address-point data is unavailable. databases, keyed by the regionregionThe first-level administrative subdivision of a country — a US state, a French region, a province. The component between country and locality.'s ISO 3166-2 code, such as US-TX. It reads the address-layerlayerOne transformer block — attention plus a feed-forward network, with normalization and residual connections — applied to every position. Stacking layers lets the model build up richer representations; Mailwoman's encoder has 6. manifest of every countrycountryThe top-level address component (an ISO country). Closed-vocabulary, so it is best handled by a deterministic matcher feeding a proposal rather than a retrained model head. that has one under the data root, then the release manifest and the per-state database paths of US, before it returns. A regionregionThe first-level administrative subdivision of a country — a US state, a French region, a province. The component between country and locality. with no file answers an empty bundleevidence bundleThe pair of retrieval-augmented input channels (street-type + locality-surface) that feed lexicon membership as soft per-token evidence alongside the text. Shipped in 6.7.0; trained natively from step 0 in the from-scratch base line., and a listed file that can't be opened throws. It uses the supplied catalog snapshot when present and reads the active selection otherwise. Its factory supplies the SQLite lookup classes.
geocodeStream starts workers with these GeocodeStreamOptions fields. Each worker builds one geocode session from the serializable geocode configuration, the session mailwoman geocode builds. When geocode.country is absent, the worker uses "US" as the resolverresolverThe component that converts parsed address components (locality, region, postcode) into coordinates by looking them up in the gazetteer. The resolver ranks candidates by name match, population, and proximity, and returns the best-matching place with its centroid or polygon.'s default countrycountryThe top-level address component (an ISO country). Closed-vocabulary, so it is best handled by a deterministic matcher feeding a proposal rather than a retrained model head.. A record with raw input and a mapped address receives the geocode result in its address field, or null when the geocoder returns no address. A record without raw input or a mapped address passes through unchanged. The stream yields records in worker completion order. A caller that needs input order must retain each record's input position and reorder the results by its SourceRecord.id.
| Stream option | Type and default | Effect |
|---|---|---|
mapping | ColumnMapping, required | Recomputes each record's address in the worker. Use the mapping used to normalizenormalizeStage 1 of the runtime pipeline: deterministic input preprocessing (Unicode NFC, punctuation normalization, whitespace collapse). Returns a NormalizedInput with an offsetMap that maps normalized positions back to the raw input. the input. |
geocode | GeocodeStreamConfig, required | Supplies wofDBPath, dataRoot, and locale; country is optional. |
concurrency | number; Math.min(4, availableParallelism()) | Sets the worker pool size. Each worker loads the modelneural classifierThe machine learning model at the core of Mailwoman's parser — a transformer encoder (~30M parameters) trained from scratch to do BIO token classification over addresses. It learns the 'grammar' of address formats; the gazetteer supplies the 'atlas.' and opens the database. |
batchSize | number; 32 | Sets the number of records per dispatched batchbatch sizeHow many examples the model processes before each parameter update. Larger batches give smoother gradients but cost more memory; gradient accumulation simulates a big batch on a small GPU.. |
worker | string or URL; compiled geocode worker | Replaces the worker module. The source uses this option for tests. |
GeocodeResult separates parsed components from lat, lon, resolution_tier, epistemic_status, and coordinate_source. The result schema defines those fields. The geocodinggeocodingThe process of converting an address into geographic coordinates (latitude and longitude). Mailwoman geocodes in a multi-tier cascade: exact address-point match → street interpolation → locality centroid. Each tier is progressively coarser but more widely available. calls and stream were checked against the published 11.0.0 declarations and repository source, without a geographic database, so this page records no geocodinggeocodingThe process of converting an address into geographic coordinates (latitude and longitude). Mailwoman geocodes in a multi-tier cascade: exact address-point match → street interpolation → locality centroid. Each tier is progressively coarser but more widely available. response or batchbatch sizeHow many examples the model processes before each parameter update. Larger batches give smoother gradients but cost more memory; gradient accumulation simulates a big batch on a small GPU. output. Geocode a file of addresses shows executed geocodes.
Confidence calibration
function createCalibrator(table: CalibrationTable | CalibrationBin[]): Calibrator
type Calibrator = (rawConfidence: number) => number
createCalibrator from @mailwoman/core/decoder makes a function from a supplied calibration table. It sorts the bins by center, interpolates between adjacent centers, and clamps inputs outside the table to its endpoint values. Pass that function as ParseOpts.calibrate on a direct classifier call. The default parseaddress parsingThe process of decomposing a free-text postal address string into structured components — house number, street name, locality, region, postcode, and country — so a geocoder can resolve them to coordinates. path doesn't apply a calibration table. The caller supplies a table fitted for the modelneural classifierThe machine learning model at the core of Mailwoman's parser — a transformer encoder (~30M parameters) trained from scratch to do BIO token classification over addresses. It learns the 'grammar' of address formats; the gazetteer supplies the 'atlas.' being used. This function doesn't select one.
Errors and absence
| Call or field | Observed or declared behavior | Caller action |
|---|---|---|
loadFromWeights({ modelPath: "/tmp/mailwoman-r01-missing.onnx", tokenizerPath: "/tmp/mailwoman-r01-missing.model" }) | Published 11.0.0 threw Explicit modelPath does not exist: /tmp/mailwoman-r01-missing.onnx. | Supply an existing modelneural classifierThe machine learning model at the core of Mailwoman's parser — a transformer encoder (~30M parameters) trained from scratch to do BIO token classification over addresses. It learns the 'grammar' of address formats; the gazetteer supplies the 'atlas.' path or install the localelocaleThe combination of language and country an address comes from. en-US and fr-FR are the locales Mailwoman ships weights for.'s weightsparameterA single learned number inside a model — one weight or bias. Mailwoman's encoder has roughly 30 million of them; training is the search for good values. package. |
createCalibrator([]) | Published 11.0.0 threw createCalibrator: empty calibration table. | Supply at least one calibration bin. |
geocodeAddress | Its declaration and source allow a fatal parseaddress parsingThe process of decomposing a free-text postal address string into structured components — house number, street name, locality, region, postcode, and country — so a geocoder can resolve them to coordinates. or resolve error to reject the promise. The exact error text depends on the failing dependency and is unknown from this page's runs. | Inspect the classifier, resolverresolverThe component that converts parsed address components (locality, region, postcode) into coordinates by looking them up in the gazetteer. The resolver ranks candidates by name match, population, and proximity, and returns the best-matching place with its centroid or polygon., and data paths for the failing call. |
PipelineResult.faults | The coordinator returns caught stagestageOne of the dataflow stages in the runtime pipeline (normalize, locale check, kind classify, phrase group, token classify, sequence correct, reconcile, resolve). Distinct from tier (model vocabulary) and phase (plan milestone). failures in this array. The executed example returned an empty array. | Inspect each reported stagestageOne of the dataflow stages in the runtime pipeline (normalize, locale check, kind classify, phrase group, token classify, sequence correct, reconcile, resolve). Distinct from tier (model vocabulary) and phase (plan milestone)., name, and message before using a partial tree. |
Example: parse one address
The example needs Node.js ^24.22.3 || >=26.13.1 and an ECMAScript module project with "type": "module" in its package.json. Install the package:
- npm
- Yarn
- pnpm
- Bun
npm install mailwoman
yarn add mailwoman
pnpm add mailwoman
bun add mailwoman
Save this complete file as library.ts:
import { createParser, decodeAsJSON } from "mailwoman"
await using parser = await createParser()
const result = await parser.parse("apt 4b 350 5th ave new york ny 10118")
console.log("kind:", result.kind.kind)
console.log("path:", result.path)
console.log("faults:", result.faults.length)
console.table(decodeAsJSON(result.tree))
Run node library.ts. The script prints this output on Linux x64:
kind: structured_address
path: full
faults: 0
┌───────────────┬────────────┐
│ (index) │ Values │
├───────────────┼────────────┤
│ region │ 'NY' │
│ locality │ 'New York' │
│ postcode │ '10118' │
│ street │ '5TH' │
│ unit │ 'Apt 4B' │
│ house_number │ '350' │
│ street_suffix │ 'Ave' │
└───────────────┴────────────┘
See also
- Install Mailwoman and inspect a first parse explains how to read the tree.
- Inspect the decisions behind a parse captures a parser trace.
- Parse and geocode result schema defines result fields and values.