@mailwoman/core 7.2.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/package.json +195 -104
- 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,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Canonical address component schema for the neural classifier pipeline.
|
|
7
|
+
*
|
|
8
|
+
* This file is the single source of truth for `ComponentTag`. Any change here requires (per #5 of
|
|
9
|
+
* the Mailwoman Neural plan):
|
|
10
|
+
*
|
|
11
|
+
* 1. A written rationale in the commit message.
|
|
12
|
+
* 2. A migration plan for corpus rows tagged with the prior schema.
|
|
13
|
+
* 3. A same-commit check that alignment, training, and inference code is updated to match.
|
|
14
|
+
*
|
|
15
|
+
* The legacy `Classifications` set in `../classification/scheme.ts` is kept independent on purpose:
|
|
16
|
+
* rule classifiers continue to emit those, the neural classifier emits these. The bridge between
|
|
17
|
+
* the two lives in the adapter layer (see #6).
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The canonical address component tag union, ordered by phase and locale.
|
|
22
|
+
*
|
|
23
|
+
* - Universal (Phase 1): country, region, locality, dependent_locality, postcode, subregion
|
|
24
|
+
* - Street-level (Phase 2): house_number, street, street_prefix*, street_suffix, intersection_a/b, unit
|
|
25
|
+
* - Venue-level (Phase 3): venue, attention, po_box
|
|
26
|
+
* - FR-specific: cedex
|
|
27
|
+
* - JP-specific (Phase 6, declared but unused before then): prefecture, municipality, district, block, sub_block,
|
|
28
|
+
* building_number, building_name
|
|
29
|
+
*/
|
|
30
|
+
export const COMPONENT_TAGS = [
|
|
31
|
+
// Universal
|
|
32
|
+
"country",
|
|
33
|
+
"region",
|
|
34
|
+
"locality",
|
|
35
|
+
"dependent_locality",
|
|
36
|
+
"postcode",
|
|
37
|
+
"subregion",
|
|
38
|
+
// Street-level
|
|
39
|
+
"house_number",
|
|
40
|
+
"street",
|
|
41
|
+
"street_prefix",
|
|
42
|
+
"street_prefix_particle",
|
|
43
|
+
"street_suffix",
|
|
44
|
+
"intersection_a",
|
|
45
|
+
"intersection_b",
|
|
46
|
+
"unit",
|
|
47
|
+
// Venue-level
|
|
48
|
+
"venue",
|
|
49
|
+
"attention",
|
|
50
|
+
"po_box",
|
|
51
|
+
// FR-specific
|
|
52
|
+
"cedex",
|
|
53
|
+
// JP-specific (Phase 6 — declared but unused until then)
|
|
54
|
+
"prefecture",
|
|
55
|
+
"municipality",
|
|
56
|
+
"district",
|
|
57
|
+
"block",
|
|
58
|
+
"sub_block",
|
|
59
|
+
"building_number",
|
|
60
|
+
"building_name",
|
|
61
|
+
] as const
|
|
62
|
+
|
|
63
|
+
/** Union of every recognized address component tag. */
|
|
64
|
+
export type ComponentTag = (typeof COMPONENT_TAGS)[number]
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* BIO-encoded label set: one `O` plus a `B-` / `I-` pair per tag.
|
|
68
|
+
*
|
|
69
|
+
* Used as the per-token output alphabet for the sequence-labeling neural model. Inference decodes a stream of these
|
|
70
|
+
* back into character-aligned `ClassificationProposal`s.
|
|
71
|
+
*/
|
|
72
|
+
export const BIO_LABELS = ["O", ...COMPONENT_TAGS.flatMap((tag) => [`B-${tag}`, `I-${tag}`] as const)] as const
|
|
73
|
+
|
|
74
|
+
/** Union of every BIO label. */
|
|
75
|
+
export type BIOLabel = (typeof BIO_LABELS)[number]
|
package/types/index.ts
ADDED
package/types/mapping.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Bridge between Mailwoman's legacy `Classification` set (40+ internal labels including
|
|
7
|
+
* non-component states like `alpha`, `numeric`, `stop_word`) and the canonical `ComponentTag`
|
|
8
|
+
* schema used by the neural classifier (per #5).
|
|
9
|
+
*
|
|
10
|
+
* Not every legacy classification maps to a `ComponentTag`. Internal states (`alpha`, `area`,
|
|
11
|
+
* `start_token`, etc.) return `null` and are dropped by the adapter.
|
|
12
|
+
*
|
|
13
|
+
* Intersection handling is intentionally coarse: the legacy `intersection` tag becomes
|
|
14
|
+
* `intersection_a` by default. Producing `intersection_a` vs `intersection_b` requires positional
|
|
15
|
+
* reasoning that the legacy classifiers don't expose; deferred to the neural model where the
|
|
16
|
+
* schema natively distinguishes them.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import type { Classification } from "./Classification.ts"
|
|
20
|
+
import type { ComponentTag } from "./component.ts"
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Static mapping table. Tags not in this table map to `null` (treated as "not a component" — internal classifier
|
|
24
|
+
* state).
|
|
25
|
+
*/
|
|
26
|
+
const LEGACY_TO_COMPONENT: Partial<Record<Classification, ComponentTag>> = {
|
|
27
|
+
country: "country",
|
|
28
|
+
region: "region",
|
|
29
|
+
locality: "locality",
|
|
30
|
+
dependency: "dependent_locality",
|
|
31
|
+
postcode: "postcode",
|
|
32
|
+
house_number: "house_number",
|
|
33
|
+
street: "street",
|
|
34
|
+
street_prefix: "street_prefix",
|
|
35
|
+
street_suffix: "street_suffix",
|
|
36
|
+
unit: "unit",
|
|
37
|
+
venue: "venue",
|
|
38
|
+
intersection: "intersection_a",
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Translate a legacy classification tag into a canonical {@link ComponentTag}, or `null` if the legacy tag has no
|
|
43
|
+
* externally visible component equivalent.
|
|
44
|
+
*/
|
|
45
|
+
export function legacyClassificationToComponentTag(legacy: Classification): ComponentTag | null {
|
|
46
|
+
return LEGACY_TO_COMPONENT[legacy] ?? null
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The full set of legacy tags that have a `ComponentTag` mapping. Useful for adapter wrappers that filter the span
|
|
51
|
+
* graph by "which legacy tags do I expect this classifier to produce."
|
|
52
|
+
*/
|
|
53
|
+
export const MAPPED_LEGACY_CLASSIFICATIONS = Object.keys(LEGACY_TO_COMPONENT) as Classification[]
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Inverse of {@link LEGACY_TO_COMPONENT}. Picks the FIRST legacy entry that maps to each component — for tags with
|
|
57
|
+
* multiple legacy aliases (e.g. `intersection_a` and `intersection_b` both come from legacy `intersection`), the
|
|
58
|
+
* deterministic "first wins" rule is documented and tested.
|
|
59
|
+
*/
|
|
60
|
+
const COMPONENT_TO_LEGACY: Partial<Record<ComponentTag, Classification>> = (() => {
|
|
61
|
+
const out: Partial<Record<ComponentTag, Classification>> = {}
|
|
62
|
+
|
|
63
|
+
for (const [legacy, component] of Object.entries(LEGACY_TO_COMPONENT) as Array<[Classification, ComponentTag]>) {
|
|
64
|
+
if (!(component in out)) {
|
|
65
|
+
out[component] = legacy
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
return out
|
|
70
|
+
})()
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Translate a canonical {@link ComponentTag} into a legacy {@link Classification}, or `null` when the component has no
|
|
74
|
+
* legacy equivalent (e.g. JP-specific tags that don't exist in the rule path).
|
|
75
|
+
*
|
|
76
|
+
* Used by the parser-level proposal pipeline to write surviving neural proposals back into the `TokenContext`'s span
|
|
77
|
+
* graph as classifications the solver can read.
|
|
78
|
+
*/
|
|
79
|
+
export function componentTagToLegacyClassification(component: ComponentTag): Classification | null {
|
|
80
|
+
return COMPONENT_TO_LEGACY[component] ?? null
|
|
81
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* The Mailwoman data root — the single, env-configurable home for every shard, model, anchor, and
|
|
7
|
+
* manifest the runtime + build tooling read. Centralized here (mirroring isp-nexus's
|
|
8
|
+
* `dataSourcePathBuilder`) so the lab `/mnt/playpen/...` default lives in EXACTLY ONE place instead
|
|
9
|
+
* of as a literal scattered across the codebase, and so consumers compose paths through
|
|
10
|
+
* {@link dataRootPath} rather than re-deriving the string. Going public, this is the only file that
|
|
11
|
+
* names the operator's filesystem layout; everything else reads `$MAILWOMAN_DATA_ROOT`.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { resolvePath } from "path-ts"
|
|
15
|
+
|
|
16
|
+
import { $public } from "../env/index.ts"
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The lab default data root — the ONE place this literal appears. Everything else builds on {@link dataRootPath} /
|
|
20
|
+
* {@link mailwomanDataRoot}; override per-deployment with `$MAILWOMAN_DATA_ROOT`.
|
|
21
|
+
*/
|
|
22
|
+
const DEFAULT_MAILWOMAN_DATA_ROOT = "/mnt/playpen/mailwoman-data"
|
|
23
|
+
|
|
24
|
+
/** The Mailwoman data root: `$MAILWOMAN_DATA_ROOT` when set, else the lab default. */
|
|
25
|
+
export function mailwomanDataRoot(): string {
|
|
26
|
+
return $public.MAILWOMAN_DATA_ROOT ?? DEFAULT_MAILWOMAN_DATA_ROOT
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Build an absolute path under the data root, e.g. `dataRootPath("wof", "admin-global-priority.db")`. Reads the env on
|
|
31
|
+
* each call, so a late environment change (or a test stub) is honored.
|
|
32
|
+
*/
|
|
33
|
+
export function dataRootPath(...segments: string[]): string {
|
|
34
|
+
return resolvePath(mailwomanDataRoot(), ...segments)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The default WOF shard list the FTS backend probes when no single `--wof-db` is given: the global admin-priority shard
|
|
39
|
+
* + the US postcode shard + the GeoNames-postal tail shard (#920 — postcode coverage for the namesake-tail locales
|
|
40
|
+
* FI/CZ/SK/SI/DK/NO/HR/PL; country-aware routing in `pickShardForPlacetype` sends each postcode query to the shard that
|
|
41
|
+
* claims its country). All under `dataRoot` (defaults to the configured {@link mailwomanDataRoot}; callers thread a
|
|
42
|
+
* `--data-root` option through). A fresh array each call; callers filter with `existsSync`, so a deployment without the
|
|
43
|
+
* tail shard degrades to the pre-#920 pair.
|
|
44
|
+
*/
|
|
45
|
+
export function wofShardPaths(dataRoot: string = mailwomanDataRoot()): [string, string, string, string, string] {
|
|
46
|
+
// TODO: Redo this as an object.
|
|
47
|
+
return [
|
|
48
|
+
resolvePath(dataRoot, "wof", "admin-global-priority.db"),
|
|
49
|
+
resolvePath(dataRoot, "wof", "postalcode-us.db"),
|
|
50
|
+
resolvePath(dataRoot, "wof", "postalcode-geonames-tail.db"),
|
|
51
|
+
resolvePath(dataRoot, "wof", "postalcode-intl.db"),
|
|
52
|
+
// #977: the NL PC6 full-postcode shard (CBS via PDOK; scripts/build-postalcode-nl-pc6.ts) — the
|
|
53
|
+
// data the lookup's NL PC6 ladder ("1012 LG" → joined "1012LG" → 4-digit stem) resolves against.
|
|
54
|
+
resolvePath(dataRoot, "wof", "postalcode-nl-pc6.db"),
|
|
55
|
+
]
|
|
56
|
+
}
|
package/utils/hash.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* File/content hashing — the canonical home for the ~12 `sha256OfFile` clones the 2026-07-09
|
|
7
|
+
* dedupe survey found across the corpus fetch scripts.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { createHash } from "node:crypto"
|
|
11
|
+
import { createReadStream } from "node:fs"
|
|
12
|
+
|
|
13
|
+
/** Streaming SHA-256 of a file, hex-encoded. */
|
|
14
|
+
export async function sha256File(path: string): Promise<string> {
|
|
15
|
+
const hash = createHash("sha256")
|
|
16
|
+
|
|
17
|
+
for await (const chunk of createReadStream(path)) {
|
|
18
|
+
hash.update(chunk as Buffer)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
return hash.digest("hex")
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** SHA-256 of in-memory content, hex-encoded. */
|
|
25
|
+
export function sha256Hex(data: string | NodeJS.ArrayBufferView): string {
|
|
26
|
+
return createHash("sha256").update(data).digest("hex")
|
|
27
|
+
}
|
package/utils/index.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export * from "./data-root.ts"
|
|
8
|
+
export * from "./hash.ts"
|
|
9
|
+
export * from "./jsonl.ts"
|
|
10
|
+
export * from "./python-json.ts"
|
|
11
|
+
export * from "./python-random.ts"
|
|
12
|
+
export * from "./repo.ts"
|
|
13
|
+
export * from "./sealed-db.ts"
|
|
14
|
+
export * from "./stats.ts"
|
package/utils/jsonl.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* JSON Lines helpers — the canonical home for the `split("\n") + JSON.parse` idiom that was
|
|
7
|
+
* re-rolled across ~88 scripts (2026-07-09 dedupe survey). `iterateJSONL` streams via spliterator
|
|
8
|
+
* for files too large to slurp.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { readFileSync, writeFileSync } from "node:fs"
|
|
12
|
+
|
|
13
|
+
import { TextSpliterator } from "spliterator"
|
|
14
|
+
|
|
15
|
+
/** Read an entire JSONL file into memory. Blank and whitespace-only lines are skipped. */
|
|
16
|
+
export function readJSONL<T>(path: string): T[] {
|
|
17
|
+
return readFileSync(path, "utf8")
|
|
18
|
+
.split("\n")
|
|
19
|
+
.filter((line) => line.trim().length > 0)
|
|
20
|
+
.map((line) => JSON.parse(line) as T)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Write rows as JSONL (one `JSON.stringify` per line, trailing newline). Returns the row count. */
|
|
24
|
+
export function writeJSONL(path: string, rows: Iterable<unknown>): number {
|
|
25
|
+
let count = 0
|
|
26
|
+
let out = ""
|
|
27
|
+
|
|
28
|
+
for (const row of rows) {
|
|
29
|
+
out += JSON.stringify(row) + "\n"
|
|
30
|
+
count++
|
|
31
|
+
}
|
|
32
|
+
writeFileSync(path, out, "utf8")
|
|
33
|
+
|
|
34
|
+
return count
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Stream a JSONL file row-by-row without loading it whole. Blank lines are skipped. */
|
|
38
|
+
export async function* iterateJSONL<T>(path: string): AsyncIterable<T> {
|
|
39
|
+
for await (const line of TextSpliterator.fromAsync(path)) {
|
|
40
|
+
if (!line.trim()) continue
|
|
41
|
+
yield JSON.parse(line) as T
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* A faithful reimplementation of Python's `json.dumps` single-line serialization, used by the
|
|
7
|
+
* ported `scripts/eval/*.ts` golden/eval builders so their JSONL output is byte-identical to the
|
|
8
|
+
* Python originals (the committed `data/eval/**` files were written by `json.dumps`).
|
|
9
|
+
*
|
|
10
|
+
* Two things `JSON.stringify` gets "wrong" relative to Python and that this fixes:
|
|
11
|
+
*
|
|
12
|
+
* 1. **Separators.** Python's default is `(", ", ": ")` — a space after every comma and colon.
|
|
13
|
+
* `JSON.stringify` is compact (`","` / `":"`). The committed files are spaced, so we match.
|
|
14
|
+
* 2. **`ensure_ascii`.** Python defaults to escaping every non-ASCII codepoint as `\uXXXX` (surrogate
|
|
15
|
+
* pairs for astral chars). `JSON.stringify` emits raw UTF-8. We replicate Python's default
|
|
16
|
+
* (`ensureAscii: true`) and allow `ensure_ascii=False` (`ensureAscii: false`).
|
|
17
|
+
*
|
|
18
|
+
* String escaping of ASCII (quote, backslash, `\n`/`\t`/`\r`/`\b`/`\f`, other control -> `\u00xx`)
|
|
19
|
+
* is identical between `JSON.stringify` and Python's json, so we delegate per-string base
|
|
20
|
+
* escaping to `JSON.stringify` and only post-escape the non-ASCII range when `ensureAscii` is
|
|
21
|
+
* on.
|
|
22
|
+
*
|
|
23
|
+
* Caveat: JS has a single number type, so a whole-valued float (e.g. an exact `5.0` coordinate)
|
|
24
|
+
* serializes as `5`, whereas Python's `float(5.0)` -> `"5.0"`. Real-world lat/lon land on exact
|
|
25
|
+
* integers vanishingly rarely; the builders that emit coordinates accept this edge.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
export interface PyJSONOptions {
|
|
29
|
+
/** Escape non-ASCII as `\uXXXX` (Python `ensure_ascii`). Defaults to `true`, matching Python. */
|
|
30
|
+
ensureAscii?: boolean
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Serialize one string the way Python's json does (then optionally `ensure_ascii`-escape it). */
|
|
34
|
+
function serializeString(value: string, ensureAscii: boolean): string {
|
|
35
|
+
// JSON.stringify handles the quote/backslash/control escaping identically to Python's json.
|
|
36
|
+
const out = JSON.stringify(value)
|
|
37
|
+
|
|
38
|
+
if (!ensureAscii) return out
|
|
39
|
+
// ensure_ascii: escape every code unit >= 0x80 as \uXXXX (surrogate halves handled per-unit,
|
|
40
|
+
// exactly as CPython emits astral codepoints as a \u-pair).
|
|
41
|
+
let escaped = ""
|
|
42
|
+
|
|
43
|
+
for (let i = 0; i < out.length; i++) {
|
|
44
|
+
const code = out.charCodeAt(i)
|
|
45
|
+
escaped += code > 0x7f ? "\\u" + code.toString(16).padStart(4, "0") : out[i]
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return escaped
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Serialize one finite/non-finite number the way Python's json does. */
|
|
52
|
+
function serializeNumber(value: number): string {
|
|
53
|
+
if (Number.isFinite(value)) return JSON.stringify(value)
|
|
54
|
+
|
|
55
|
+
// Python json renders these literally (not RFC-valid, but it's what json.dumps does by default).
|
|
56
|
+
if (Number.isNaN(value)) return "NaN"
|
|
57
|
+
|
|
58
|
+
return value > 0 ? "Infinity" : "-Infinity"
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function serialize(value: unknown, ensureAscii: boolean): string {
|
|
62
|
+
if (value === null || value === undefined) return "null"
|
|
63
|
+
const t = typeof value
|
|
64
|
+
|
|
65
|
+
if (t === "boolean") return value ? "true" : "false"
|
|
66
|
+
|
|
67
|
+
if (t === "number") return serializeNumber(value as number)
|
|
68
|
+
|
|
69
|
+
if (t === "string") return serializeString(value as string, ensureAscii)
|
|
70
|
+
|
|
71
|
+
if (Array.isArray(value)) {
|
|
72
|
+
return "[" + value.map((v) => serialize(v, ensureAscii)).join(", ") + "]"
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (t === "object") {
|
|
76
|
+
const parts: string[] = []
|
|
77
|
+
|
|
78
|
+
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
|
|
79
|
+
if (v === undefined) continue // a key Python would never have produced
|
|
80
|
+
parts.push(serializeString(k, ensureAscii) + ": " + serialize(v, ensureAscii))
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return "{" + parts.join(", ") + "}"
|
|
84
|
+
}
|
|
85
|
+
throw new TypeError(`pyJSONDumps: unsupported value of type ${t}`)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** `json.dumps(value)` — single line, `(", ", ": ")` separators, `ensure_ascii` per options. */
|
|
89
|
+
export function pyJSONDumps(value: unknown, options: PyJSONOptions = {}): string {
|
|
90
|
+
return serialize(value, options.ensureAscii ?? true)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Render a string->number map the way Python prints `dict(...)` / `dict(Counter(...))` — single-quoted keys, `, ` / `:
|
|
95
|
+
* ` separators (e.g. `{'US': 1840, 'FR': 950}`). Insertion order is preserved.
|
|
96
|
+
*/
|
|
97
|
+
export function pyReprDict(entries: Iterable<readonly [string, number]>): string {
|
|
98
|
+
const parts: string[] = []
|
|
99
|
+
|
|
100
|
+
for (const [k, v] of entries) {
|
|
101
|
+
parts.push(`'${k}': ${v}`)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return "{" + parts.join(", ") + "}"
|
|
105
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* A tiny seeded PRNG shaped like Python's `random.Random` (the `random()` / `randint()` /
|
|
7
|
+
* `choice()` / `choices()` surface the `scripts/extract-tuples*.py` originals used). Lives here
|
|
8
|
+
* so the two ported extractors share one implementation.
|
|
9
|
+
*
|
|
10
|
+
* NOTE — this is deliberately NOT a bit-exact port of CPython's MT19937. The source scripts draw
|
|
11
|
+
* their rows with SQL `ORDER BY RANDOM()` (already non-deterministic across runs) and the
|
|
12
|
+
* postcodes are synthetic shape-data ("the model learns the SHAPE, not the exact mapping"), so a
|
|
13
|
+
* byte-identical random stream buys nothing observable. What is preserved is what matters: a
|
|
14
|
+
* seeded, deterministic-per-input stream and Python's helper semantics — inclusive `randint`,
|
|
15
|
+
* uniform `choice`, with-replacement `choices`.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** Seeded `random.Random`-equivalent. Backed by mulberry32 (a 32-bit stateful generator). */
|
|
19
|
+
export class SeededRandom {
|
|
20
|
+
#state: number
|
|
21
|
+
|
|
22
|
+
constructor(seed: number) {
|
|
23
|
+
// mulberry32 wants a non-zero 32-bit state.
|
|
24
|
+
this.#state = seed >>> 0 || 1
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Float in `[0, 1)`. Mirrors Python `random.random()`. */
|
|
28
|
+
random(): number {
|
|
29
|
+
let t = (this.#state += 0x6d2b79f5)
|
|
30
|
+
t = Math.imul(t ^ (t >>> 15), t | 1)
|
|
31
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
|
|
32
|
+
|
|
33
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Integer in `[lo, hi]` inclusive. Mirrors Python `random.randint(lo, hi)`. */
|
|
37
|
+
randint(lo: number, hi: number): number {
|
|
38
|
+
return lo + Math.floor(this.random() * (hi - lo + 1))
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** One uniformly-chosen element. Mirrors Python `random.choice(seq)`. */
|
|
42
|
+
choice<T>(seq: readonly T[]): T {
|
|
43
|
+
return seq[Math.floor(this.random() * seq.length)]!
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** `k` elements chosen with replacement. Mirrors Python `random.choices(seq, k=k)`. */
|
|
47
|
+
choices<T>(seq: readonly T[], k: number): T[] {
|
|
48
|
+
const out: T[] = []
|
|
49
|
+
|
|
50
|
+
for (let i = 0; i < k; i++) {
|
|
51
|
+
out.push(this.choice(seq))
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return out
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* In-place Fisher-Yates shuffle. Mirrors Python `random.shuffle(x)` — distribution-correct, but NOT bit-identical to
|
|
59
|
+
* CPython's `_randbelow` stream (see the module header on the seeded-but-not- MT19937 tradeoff).
|
|
60
|
+
*/
|
|
61
|
+
shuffle<T>(arr: T[]): void {
|
|
62
|
+
for (let i = arr.length - 1; i > 0; i--) {
|
|
63
|
+
const j = this.randint(0, i)
|
|
64
|
+
const tmp = arr[i]!
|
|
65
|
+
arr[i] = arr[j]!
|
|
66
|
+
arr[j] = tmp
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* `k` distinct elements without replacement, as a NEW array. Mirrors Python `random.sample(seq, k)` semantics
|
|
72
|
+
* (uniform, no mutation of the input); the selection ORDER is partial-Fisher-Yates, which — like {@link shuffle} — is
|
|
73
|
+
* uniform but not CPython-bit-identical. `k` must be `<= seq.length`.
|
|
74
|
+
*/
|
|
75
|
+
sample<T>(seq: readonly T[], k: number): T[] {
|
|
76
|
+
const pool = seq.slice()
|
|
77
|
+
const n = pool.length
|
|
78
|
+
const out: T[] = []
|
|
79
|
+
|
|
80
|
+
for (let i = 0; i < k; i++) {
|
|
81
|
+
const j = this.randint(i, n - 1)
|
|
82
|
+
const tmp = pool[i]!
|
|
83
|
+
pool[i] = pool[j]!
|
|
84
|
+
pool[j] = tmp
|
|
85
|
+
out.push(pool[i]!)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return out
|
|
89
|
+
}
|
|
90
|
+
}
|
package/utils/repo.ts
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { basename, dirname, resolve } from "node:path"
|
|
8
|
+
import { fileURLToPath } from "node:url"
|
|
9
|
+
|
|
10
|
+
import { createPathBuilderResolver, createPathResolver, type Join, type PathBuilder } from "path-ts"
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Aliased path to the root of the repository.
|
|
14
|
+
*
|
|
15
|
+
* @typedef {"mailwoman"} RepoRootAlias
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Compiled directory name for TS output files.
|
|
20
|
+
*/
|
|
21
|
+
export const OutDirectoryName = "out"
|
|
22
|
+
export type OutDirectoryName = typeof OutDirectoryName
|
|
23
|
+
|
|
24
|
+
const RepoRootAlias = "mailwoman" as const
|
|
25
|
+
type RepoRootAlias = typeof RepoRootAlias
|
|
26
|
+
|
|
27
|
+
const PathReflection = ["core", "out", "utils"] as const
|
|
28
|
+
type PathReflection = typeof PathReflection
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The directory path of the current file, post-compilation.
|
|
32
|
+
*/
|
|
33
|
+
const __dirname = dirname(fileURLToPath(import.meta.url)) as Join<[RepoRootAlias, ...PathReflection], "/">
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The absolute path to the root of the repository.
|
|
37
|
+
*
|
|
38
|
+
* In compiled mode this file lives at `core/out/utils/repo.js` (so the PARENT of `utils` is `out/`) and in source mode
|
|
39
|
+
* at `core/utils/repo.ts` (the parent is `core/`). Detect the mode by checking whether the parent directory
|
|
40
|
+
* (`resolve("..")`) is `out/` — uses `basename` on the resolved path rather than a substring match on `__dirname`, so
|
|
41
|
+
* it survives symlinks and output-directory renames.
|
|
42
|
+
*
|
|
43
|
+
* (Earlier this checked `resolve("..", "..")`, which overshoots `out/` to `core/` and so was always false — the
|
|
44
|
+
* compiled tree then resolved `CorePackageAbsolutePath` to `core/out` instead of `core/`, landing dictionary reads at
|
|
45
|
+
* the nonexistent `core/out/data` and requiring an external symlink bridge to find `core/data`. #481.)
|
|
46
|
+
*/
|
|
47
|
+
const __isCompiledTree = basename(resolve(__dirname, "..")) === OutDirectoryName
|
|
48
|
+
const __upCount = __isCompiledTree ? PathReflection.length : PathReflection.length - 1
|
|
49
|
+
const RepoRootAbsolutePath = resolve(__dirname, ...Array.from({ length: __upCount }, () => ".."))
|
|
50
|
+
type RepoRootAbsolutePath = RepoRootAlias
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Path builder relative to the repo root.
|
|
54
|
+
*/
|
|
55
|
+
export const repoRootPathBuilder = createPathBuilderResolver<RepoRootAlias>(RepoRootAbsolutePath)
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Absolute-path-string resolver relative to the repo root — the string-returning sibling of {@link repoRootPathBuilder},
|
|
59
|
+
* for handing paths straight to `node:fs` and other string APIs without a `.toString()`.
|
|
60
|
+
*/
|
|
61
|
+
export const repoRootPath = createPathResolver<RepoRootAlias>(RepoRootAbsolutePath)
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Path builder relative to the `@mailwoman/core` workspace root (the directory containing `package.json` for this
|
|
65
|
+
* package).
|
|
66
|
+
*
|
|
67
|
+
* In compiled mode this resolves to `core/` (one level above `core/out/utils/repo.js`'s `out/`). In source mode it's
|
|
68
|
+
* the same `core/` directly above `core/utils/repo.ts`. Used to locate package-bundled assets (dictionary data) that
|
|
69
|
+
* live under the workspace root, NOT the repo root — so that `npm install @mailwoman/core` ships those assets alongside
|
|
70
|
+
* the JS without any post-install copy step.
|
|
71
|
+
*/
|
|
72
|
+
const CorePackageAbsolutePath = resolve(__dirname, "..", __isCompiledTree ? ".." : "")
|
|
73
|
+
export const corePackagePathBuilder = createPathBuilderResolver<RepoRootAlias>(CorePackageAbsolutePath)
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Absolute-path-string resolver relative to the `@mailwoman/core` workspace root — the string-returning sibling of
|
|
77
|
+
* {@link corePackagePathBuilder}.
|
|
78
|
+
*/
|
|
79
|
+
export const corePackagePath = createPathResolver<RepoRootAlias>(CorePackageAbsolutePath)
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Path builder relative to a specific package's output directory.
|
|
83
|
+
*/
|
|
84
|
+
export function tsOutPathBuilder<S extends string[]>(
|
|
85
|
+
...pathSegments: S
|
|
86
|
+
): PathBuilder<Join<[RepoRootAlias, OutDirectoryName, ...S], "/">> {
|
|
87
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
88
|
+
return repoRootPathBuilder(OutDirectoryName, ...pathSegments) as any
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export type AddressResource = "chromium-i18n/ssl-address" | "libpostal" | "internal" | "whosonfirst"
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Path builder relative to a address resource dictionary directory.
|
|
95
|
+
*
|
|
96
|
+
* Data lives at `core/data/<resource>/dictionaries/...` so the @mailwoman/core npm package ships dictionaries via its
|
|
97
|
+
* `files` glob. Use {@link corePackagePathBuilder} directly for non- dictionary assets (e.g. chromium-i18n/ssl-address)
|
|
98
|
+
* that don't have the `dictionaries/` subdir.
|
|
99
|
+
*/
|
|
100
|
+
export function resourceDictionaryPathBuilder<A extends AddressResource, S extends string[]>(
|
|
101
|
+
resource: A,
|
|
102
|
+
...pathSegments: S
|
|
103
|
+
) {
|
|
104
|
+
return corePackagePathBuilder("data", resource, "dictionaries", ...pathSegments)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Absolute-path-string resolver for an address resource dictionary directory — the string-returning sibling of
|
|
109
|
+
* {@link resourceDictionaryPathBuilder}.
|
|
110
|
+
*/
|
|
111
|
+
export function resourceDictionaryPath<A extends AddressResource, S extends string[]>(resource: A, ...pathSegments: S) {
|
|
112
|
+
return corePackagePath("data", resource, "dictionaries", ...pathSegments)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Absolute path to the test directory.
|
|
117
|
+
*/
|
|
118
|
+
export const functionTestsDirectory = repoRootPathBuilder("test")
|