@mailwoman/core 8.6.0 → 9.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (238) hide show
  1. package/README.md +2 -2
  2. package/api/clock.ts +1 -1
  3. package/api/disk-storage.ts +7 -4
  4. package/api/test-clocks.ts +57 -9
  5. package/api/test-transport.ts +182 -0
  6. package/coarse-placer/coarse-placer.ts +2 -1
  7. package/coarse-placer/tools/build-dataset.ts +2 -2
  8. package/coarse-placer/tools/build-outlier-exposure.ts +2 -2
  9. package/coarse-placer/tools/build-outlier-latin.ts +3 -2
  10. package/coarse-placer/tools/build-outlier-oa.ts +3 -2
  11. package/coarse-placer/tools/eval-latin-offmap.ts +8 -8
  12. package/coarse-placer/tools/eval-openset.ts +20 -12
  13. package/coarse-placer/tools/eval-quant-compare.ts +8 -9
  14. package/coarse-placer/tools/eval.ts +30 -23
  15. package/coarse-placer/tools/probe-frontier.ts +9 -7
  16. package/coarse-placer/tools/quantize.ts +4 -2
  17. package/coarse-placer/tools/train.ts +10 -10
  18. package/collections.ts +2 -128
  19. package/crypto/node.ts +68 -0
  20. package/decoder/build-tree.ts +19 -0
  21. package/env/schema.ts +58 -2
  22. package/fs/zip.ts +297 -0
  23. package/identifiers.ts +48 -0
  24. package/layers/manifest.ts +2 -1
  25. package/locale/profiles/en-us.ts +2 -3
  26. package/locale/profiles/fr-fr.ts +1 -1
  27. package/locale/profiles/ja-jp.ts +7 -7
  28. package/objects.ts +40 -8
  29. package/out/api/clock.d.ts +1 -1
  30. package/out/api/clock.js +1 -1
  31. package/out/api/disk-storage.d.ts +1 -1
  32. package/out/api/disk-storage.d.ts.map +1 -1
  33. package/out/api/disk-storage.js +5 -5
  34. package/out/api/disk-storage.js.map +1 -1
  35. package/out/api/test-clocks.d.ts +2 -2
  36. package/out/api/test-clocks.d.ts.map +1 -1
  37. package/out/api/test-clocks.js +51 -9
  38. package/out/api/test-clocks.js.map +1 -1
  39. package/out/api/test-transport.d.ts +112 -0
  40. package/out/api/test-transport.d.ts.map +1 -0
  41. package/out/api/test-transport.js +84 -0
  42. package/out/api/test-transport.js.map +1 -0
  43. package/out/coarse-placer/coarse-placer.d.ts.map +1 -1
  44. package/out/coarse-placer/coarse-placer.js +2 -1
  45. package/out/coarse-placer/coarse-placer.js.map +1 -1
  46. package/out/coarse-placer/tools/build-dataset.js +1 -2
  47. package/out/coarse-placer/tools/build-dataset.js.map +1 -1
  48. package/out/coarse-placer/tools/build-outlier-exposure.js +1 -2
  49. package/out/coarse-placer/tools/build-outlier-exposure.js.map +1 -1
  50. package/out/coarse-placer/tools/build-outlier-latin.d.ts.map +1 -1
  51. package/out/coarse-placer/tools/build-outlier-latin.js +2 -2
  52. package/out/coarse-placer/tools/build-outlier-latin.js.map +1 -1
  53. package/out/coarse-placer/tools/build-outlier-oa.d.ts.map +1 -1
  54. package/out/coarse-placer/tools/build-outlier-oa.js +2 -2
  55. package/out/coarse-placer/tools/build-outlier-oa.js.map +1 -1
  56. package/out/coarse-placer/tools/eval-latin-offmap.d.ts.map +1 -1
  57. package/out/coarse-placer/tools/eval-latin-offmap.js +5 -8
  58. package/out/coarse-placer/tools/eval-latin-offmap.js.map +1 -1
  59. package/out/coarse-placer/tools/eval-openset.d.ts.map +1 -1
  60. package/out/coarse-placer/tools/eval-openset.js +12 -11
  61. package/out/coarse-placer/tools/eval-openset.js.map +1 -1
  62. package/out/coarse-placer/tools/eval-quant-compare.d.ts.map +1 -1
  63. package/out/coarse-placer/tools/eval-quant-compare.js +7 -9
  64. package/out/coarse-placer/tools/eval-quant-compare.js.map +1 -1
  65. package/out/coarse-placer/tools/eval.d.ts.map +1 -1
  66. package/out/coarse-placer/tools/eval.js +20 -21
  67. package/out/coarse-placer/tools/eval.js.map +1 -1
  68. package/out/coarse-placer/tools/probe-frontier.d.ts.map +1 -1
  69. package/out/coarse-placer/tools/probe-frontier.js +8 -8
  70. package/out/coarse-placer/tools/probe-frontier.js.map +1 -1
  71. package/out/coarse-placer/tools/quantize.d.ts.map +1 -1
  72. package/out/coarse-placer/tools/quantize.js +3 -2
  73. package/out/coarse-placer/tools/quantize.js.map +1 -1
  74. package/out/coarse-placer/tools/train.d.ts.map +1 -1
  75. package/out/coarse-placer/tools/train.js +7 -10
  76. package/out/coarse-placer/tools/train.js.map +1 -1
  77. package/out/collections.d.ts +1 -59
  78. package/out/collections.d.ts.map +1 -1
  79. package/out/collections.js +2 -90
  80. package/out/collections.js.map +1 -1
  81. package/out/crypto/node.d.ts +43 -0
  82. package/out/crypto/node.d.ts.map +1 -0
  83. package/out/crypto/node.js +43 -0
  84. package/out/crypto/node.js.map +1 -0
  85. package/out/decoder/build-tree.d.ts.map +1 -1
  86. package/out/decoder/build-tree.js +17 -0
  87. package/out/decoder/build-tree.js.map +1 -1
  88. package/out/env/index.d.ts +8 -0
  89. package/out/env/index.d.ts.map +1 -1
  90. package/out/env/schema.d.ts +9 -1
  91. package/out/env/schema.d.ts.map +1 -1
  92. package/out/env/schema.js +54 -2
  93. package/out/env/schema.js.map +1 -1
  94. package/out/fs/zip.d.ts +116 -0
  95. package/out/fs/zip.d.ts.map +1 -0
  96. package/out/fs/zip.js +216 -0
  97. package/out/fs/zip.js.map +1 -0
  98. package/out/identifiers.d.ts +23 -0
  99. package/out/identifiers.d.ts.map +1 -1
  100. package/out/identifiers.js +39 -0
  101. package/out/identifiers.js.map +1 -1
  102. package/out/layers/manifest.d.ts.map +1 -1
  103. package/out/layers/manifest.js +2 -1
  104. package/out/layers/manifest.js.map +1 -1
  105. package/out/locale/profiles/en-us.d.ts +2 -3
  106. package/out/locale/profiles/en-us.d.ts.map +1 -1
  107. package/out/locale/profiles/en-us.js +2 -3
  108. package/out/locale/profiles/en-us.js.map +1 -1
  109. package/out/locale/profiles/fr-fr.d.ts +1 -1
  110. package/out/locale/profiles/fr-fr.js +1 -1
  111. package/out/locale/profiles/ja-jp.d.ts +7 -7
  112. package/out/locale/profiles/ja-jp.js +7 -7
  113. package/out/objects.d.ts +18 -2
  114. package/out/objects.d.ts.map +1 -1
  115. package/out/objects.js +29 -3
  116. package/out/objects.js.map +1 -1
  117. package/out/pipeline/index.d.ts +2 -2
  118. package/out/pipeline/index.d.ts.map +1 -1
  119. package/out/pipeline/index.js +1 -1
  120. package/out/pipeline/index.js.map +1 -1
  121. package/out/pipeline/runtime-pipeline.d.ts +1 -1
  122. package/out/pipeline/runtime-pipeline.d.ts.map +1 -1
  123. package/out/pipeline/runtime-pipeline.js +74 -18
  124. package/out/pipeline/runtime-pipeline.js.map +1 -1
  125. package/out/pipeline/span-proposer.d.ts +24 -0
  126. package/out/pipeline/span-proposer.d.ts.map +1 -1
  127. package/out/pipeline/span-proposer.js +36 -1
  128. package/out/pipeline/span-proposer.js.map +1 -1
  129. package/out/pipeline/types.d.ts +155 -3
  130. package/out/pipeline/types.d.ts.map +1 -1
  131. package/out/pipeline/types.js +41 -1
  132. package/out/pipeline/types.js.map +1 -1
  133. package/out/resolver/index.d.ts +3 -1
  134. package/out/resolver/index.d.ts.map +1 -1
  135. package/out/resolver/index.js +1 -0
  136. package/out/resolver/index.js.map +1 -1
  137. package/out/resolver/referential.d.ts +73 -0
  138. package/out/resolver/referential.d.ts.map +1 -0
  139. package/out/resolver/referential.js +71 -0
  140. package/out/resolver/referential.js.map +1 -0
  141. package/out/resolver/types.d.ts +204 -0
  142. package/out/resolver/types.d.ts.map +1 -1
  143. package/out/resolver/types.js.map +1 -1
  144. package/out/resources/index.d.ts +0 -1
  145. package/out/resources/index.d.ts.map +1 -1
  146. package/out/resources/index.js +0 -1
  147. package/out/resources/index.js.map +1 -1
  148. package/out/resources/libpostal.d.ts.map +1 -1
  149. package/out/resources/libpostal.js +3 -4
  150. package/out/resources/libpostal.js.map +1 -1
  151. package/out/resources/whosonfirst/index.d.ts +1 -0
  152. package/out/resources/whosonfirst/index.d.ts.map +1 -1
  153. package/out/resources/whosonfirst/index.js +1 -0
  154. package/out/resources/whosonfirst/index.js.map +1 -1
  155. package/out/resources/whosonfirst/placetypes/Placetype.d.ts.map +1 -1
  156. package/out/resources/whosonfirst/placetypes/Placetype.js +6 -5
  157. package/out/resources/whosonfirst/placetypes/Placetype.js.map +1 -1
  158. package/out/resources/whosonfirst/placetypes/admin.d.ts +12 -3
  159. package/out/resources/whosonfirst/placetypes/admin.d.ts.map +1 -1
  160. package/out/resources/whosonfirst/placetypes/admin.js +1 -1
  161. package/out/resources/whosonfirst/placetypes/admin.js.map +1 -1
  162. package/out/resources/whosonfirst/sharded-repo.d.ts +28 -0
  163. package/out/resources/whosonfirst/sharded-repo.d.ts.map +1 -0
  164. package/out/resources/whosonfirst/sharded-repo.js +58 -0
  165. package/out/resources/whosonfirst/sharded-repo.js.map +1 -0
  166. package/out/scripting/utils/index.d.ts.map +1 -1
  167. package/out/scripting/utils/index.js +2 -2
  168. package/out/scripting/utils/index.js.map +1 -1
  169. package/out/tools/download-libpostal-resources.d.ts.map +1 -1
  170. package/out/tools/download-libpostal-resources.js +1 -0
  171. package/out/tools/download-libpostal-resources.js.map +1 -1
  172. package/out/tools/generate-language-types.d.ts.map +1 -1
  173. package/out/tools/generate-language-types.js +5 -11
  174. package/out/tools/generate-language-types.js.map +1 -1
  175. package/out/utils/data-root.d.ts +20 -6
  176. package/out/utils/data-root.d.ts.map +1 -1
  177. package/out/utils/data-root.js +24 -5
  178. package/out/utils/data-root.js.map +1 -1
  179. package/out/utils/hash.d.ts +6 -0
  180. package/out/utils/hash.d.ts.map +1 -1
  181. package/out/utils/hash.js +8 -0
  182. package/out/utils/hash.js.map +1 -1
  183. package/out/utils/index.d.ts +1 -0
  184. package/out/utils/index.d.ts.map +1 -1
  185. package/out/utils/index.js +1 -0
  186. package/out/utils/index.js.map +1 -1
  187. package/out/utils/jsonl.d.ts +17 -3
  188. package/out/utils/jsonl.d.ts.map +1 -1
  189. package/out/utils/jsonl.js +23 -6
  190. package/out/utils/jsonl.js.map +1 -1
  191. package/out/utils/python-json.d.ts +3 -3
  192. package/out/utils/python-json.js +9 -9
  193. package/out/utils/python-numeric.d.ts +33 -0
  194. package/out/utils/python-numeric.d.ts.map +1 -0
  195. package/out/utils/python-numeric.js +149 -0
  196. package/out/utils/python-numeric.js.map +1 -0
  197. package/out/utils/python-random.d.ts +26 -1
  198. package/out/utils/python-random.d.ts.map +1 -1
  199. package/out/utils/python-random.js +43 -7
  200. package/out/utils/python-random.js.map +1 -1
  201. package/out/utils/repo.d.ts.map +1 -1
  202. package/out/utils/repo.js +18 -0
  203. package/out/utils/repo.js.map +1 -1
  204. package/out/utils/sealed-db.d.ts +12 -0
  205. package/out/utils/sealed-db.d.ts.map +1 -1
  206. package/out/utils/sealed-db.js +32 -1
  207. package/out/utils/sealed-db.js.map +1 -1
  208. package/package.json +34 -7
  209. package/pipeline/index.ts +3 -1
  210. package/pipeline/runtime-pipeline.ts +88 -27
  211. package/pipeline/span-proposer.ts +64 -1
  212. package/pipeline/types.ts +160 -2
  213. package/resolver/index.ts +13 -0
  214. package/resolver/referential.ts +84 -0
  215. package/resolver/types.ts +207 -0
  216. package/resources/index.ts +0 -1
  217. package/resources/libpostal.ts +8 -7
  218. package/resources/whosonfirst/index.ts +1 -0
  219. package/resources/whosonfirst/placetypes/Placetype.ts +13 -8
  220. package/resources/whosonfirst/placetypes/admin.ts +12 -2
  221. package/resources/whosonfirst/sharded-repo.ts +69 -0
  222. package/scripting/utils/index.ts +2 -3
  223. package/tools/download-libpostal-resources.ts +1 -0
  224. package/tools/generate-language-types.ts +5 -14
  225. package/utils/data-root.ts +27 -6
  226. package/utils/hash.ts +9 -0
  227. package/utils/index.ts +1 -0
  228. package/utils/jsonl.ts +26 -7
  229. package/utils/python-json.ts +10 -10
  230. package/utils/python-numeric.ts +168 -0
  231. package/utils/python-random.ts +49 -8
  232. package/utils/repo.ts +18 -0
  233. package/utils/sealed-db.ts +38 -1
  234. package/out/resources/collections.d.ts +0 -22
  235. package/out/resources/collections.d.ts.map +0 -1
  236. package/out/resources/collections.js +0 -69
  237. package/out/resources/collections.js.map +0 -1
  238. package/resources/collections.ts +0 -96
@@ -14,8 +14,10 @@
14
14
  import { readFileSync } from "node:fs"
15
15
  import * as path from "node:path"
16
16
 
17
- import { dataRootPath } from "../../utils/data-root.ts"
18
- import { repoRootPath } from "../../utils/repo.ts"
17
+ import { parseJSONStrict } from "@mailwoman/core/objects"
18
+ import { dataRootPath, repoRootPath } from "@mailwoman/core/utils"
19
+ import { JSONSpliterator } from "spliterator"
20
+
19
21
  import { CoarsePlacer, type CoarsePlacerMeta, type CoarsePrediction } from "../coarse-placer.ts"
20
22
 
21
23
  /**
@@ -80,23 +82,30 @@ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): P
80
82
  const abstain = options.abstain ?? 0.5
81
83
  const dataDir = options.data || repoRootPath("data", "coarse-placer")
82
84
 
83
- const meta = JSON.parse(readFileSync(path.join(modelDir, "meta.json"), "utf8")) as CoarsePlacerMeta
84
- const weights = new Float32Array(readFileSync(path.join(modelDir, "weights.bin")).buffer)
85
+ const meta = parseJSONStrict<CoarsePlacerMeta>(readFileSync(path.join(modelDir, "meta.json"), "utf8"))
86
+ const weightBytes = readFileSync(path.join(modelDir, "weights.bin"))
87
+
88
+ // Read through the Buffer's own window: `readFileSync` serves files under 4 KiB out of a shared 8 KiB pool, so
89
+ // `.buffer` alone would start at the pool's origin and run its full length — the wrong floats, and 2048 of them.
90
+ const weights = new Float32Array(
91
+ weightBytes.buffer,
92
+ weightBytes.byteOffset,
93
+ weightBytes.byteLength / Float32Array.BYTES_PER_ELEMENT
94
+ )
95
+
85
96
  const placer = new CoarsePlacer({ ...meta, weights }, { abstainBelow: abstain })
86
97
 
87
98
  // --- In-distribution test: accuracy + per-class + ECE ---
88
- const test: TestRow[] = readFileSync(path.join(dataDir, "test.jsonl"), "utf8")
89
- .trim()
90
- .split("\n")
91
- .map((l) => JSON.parse(l) as TestRow)
92
-
99
+ let testN = 0
93
100
  let correct = 0
94
101
  const perClass: Record<string, { n: number; ok: number }> = {} // country → {n, ok}
95
102
  const confusion: Record<string, Record<string, number>> = {} // true → {pred → n}
96
103
  const buckets = Array.from({ length: 10 }, () => ({ n: 0, ok: 0 }))
97
104
 
98
- // ECE deciles
99
- for (const r of test) {
105
+ // ECE deciles. The split streams: every figure below is an accumulator, so the rows never all need to be resident.
106
+ for await (const r of JSONSpliterator.fromAsync<TestRow>(path.join(dataDir, "test.jsonl"))) {
107
+ testN++
108
+
100
109
  const p = placer.predict(r.raw)
101
110
 
102
111
  const pred = p.country ?? "(abstain)"
@@ -119,8 +128,8 @@ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): P
119
128
  }
120
129
  }
121
130
 
122
- console.log(`coarse-placer eval — test n=${test.length}`)
123
- console.log(` overall accuracy: ${((100 * correct) / test.length).toFixed(2)}% (abstain threshold ${abstain})`)
131
+ console.log(`coarse-placer eval — test n=${testN}`)
132
+ console.log(` overall accuracy: ${((100 * correct) / testN).toFixed(2)}% (abstain threshold ${abstain})`)
124
133
  console.log(` per-class recall:`)
125
134
 
126
135
  for (const c of meta.classes) {
@@ -132,7 +141,7 @@ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): P
132
141
  }
133
142
 
134
143
  let ece = 0
135
- const N = test.length
144
+ const N = testN
136
145
 
137
146
  for (let i = 0; i < 10; i++) {
138
147
  const bk = buckets[i]!
@@ -165,24 +174,22 @@ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): P
165
174
  const msPath = repoRootPath("data", "eval", "multi-script", "v0.5.0-a0.jsonl")
166
175
 
167
176
  try {
168
- const ms: MultiScriptRow[] = readFileSync(msPath, "utf8")
169
- .trim()
170
- .split("\n")
171
- .map((l) => JSON.parse(l) as MultiScriptRow)
172
-
173
177
  const TRAINED_SCRIPTS = new Set(["latin", "cjk"]) // the only scripts among the 11 trained countries
174
178
  // With the OTHER class, an off-map input is HANDLED if it routes to OTHER or abstains — either way
175
179
  // it's not a confident mis-placement onto a wrong country.
176
180
  const handled = (p: CoarsePrediction): boolean => p.abstained || p.country === "OTHER"
177
181
 
178
- let offN = 0,
182
+ let msN = 0,
183
+ offN = 0,
179
184
  offOk = 0,
180
185
  missN = 0,
181
186
  missOk = 0
182
187
 
183
188
  const offMiss: string[] = []
184
189
 
185
- for (const r of ms) {
190
+ for await (const r of JSONSpliterator.fromAsync<MultiScriptRow>(msPath)) {
191
+ msN++
192
+
186
193
  const p = placer.predict(r.raw)
187
194
  const offMap = !TRAINED_SCRIPTS.has(r.script)
188
195
 
@@ -205,7 +212,7 @@ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): P
205
212
  }
206
213
  }
207
214
 
208
- console.log(`\nmulti-script off-map handling (n=${ms.length}):`)
215
+ console.log(`\nmulti-script off-map handling (n=${msN}):`)
209
216
  console.log(
210
217
  ` OFF-map scripts (Cyrillic/Arabic/Thai/…) routed to OTHER-or-abstain: ${offOk}/${offN} (${((100 * offOk) / Math.max(1, offN)).toFixed(0)}%) ← want HIGH`
211
218
  )
@@ -221,5 +228,5 @@ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): P
221
228
  console.log(`\n(multi-script set not found at ${msPath}: ${(error as Error).message})`)
222
229
  }
223
230
 
224
- return { n: test.length, accuracy: (100 * correct) / test.length, ece }
231
+ return { n: testN, accuracy: (100 * correct) / testN, ece }
225
232
  }
@@ -21,9 +21,11 @@
21
21
 
22
22
  import { readFileSync, writeFileSync } from "node:fs"
23
23
 
24
- import { dataRootPath } from "../../utils/data-root.ts"
25
- import { corePackagePath } from "../../utils/repo.ts"
26
- import { median } from "../../utils/stats.ts"
24
+ import { parseJSONStrict } from "@mailwoman/core/objects"
25
+ import { dataRootPath, corePackagePath, median } from "@mailwoman/core/utils"
26
+ import { join } from "path-ts"
27
+ import { TSVSpliterator } from "spliterator"
28
+
27
29
  import { CoarsePlacer, type CoarsePlacerMeta } from "../coarse-placer.ts"
28
30
 
29
31
  /**
@@ -127,7 +129,7 @@ export async function probeFrontier(
127
129
  // `@mailwoman/codex` is a devDependency of core (operator tooling) — lazy-imported inside the fn.
128
130
  const { ISO2_TO_NAME } = await import("@mailwoman/codex/country")
129
131
 
130
- const meta = JSON.parse(readFileSync(`${modelDir}/meta.json`, "utf8")) as CoarsePlacerMeta
132
+ const meta = parseJSONStrict<CoarsePlacerMeta>(readFileSync(join(String(modelDir), "meta.json"), "utf8"))
131
133
  // The deployed bundle is int8-per-row quantized — fromArtifactDir dequantizes via meta.scales.
132
134
  const placer = await CoarsePlacer.fromArtifactDir(modelDir, { abstainBelow: 0 })
133
135
  const classSet = new Set(meta.classes)
@@ -143,9 +145,8 @@ export async function probeFrontier(
143
145
 
144
146
  const all: Q[] = []
145
147
 
146
- for (const line of readFileSync(CITIES, "utf8").split("\n")) {
147
- if (!line) continue
148
- const f = line.split("\t")
148
+ // `header: false` — cities15000 is headerless, so row 1 is a city.
149
+ for await (const f of TSVSpliterator.fromAsync(CITIES, { header: false })) {
149
150
  const name = f[1]
150
151
  const cc = f[8]
151
152
 
@@ -235,6 +236,7 @@ export async function probeFrontier(
235
236
 
236
237
  const md = L.join("\n")
237
238
 
239
+ // oxlint-disable-next-line mailwoman/prefer-spliterator -- Re-splitting a string joined two lines above.
238
240
  console.log(md.split("\n").slice(0, 12).join("\n"))
239
241
  console.log("…")
240
242
 
@@ -19,7 +19,9 @@
19
19
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs"
20
20
  import * as path from "node:path"
21
21
 
22
- import { dataRootPath } from "../../utils/data-root.ts"
22
+ import { parseJSONStrict } from "@mailwoman/core/objects"
23
+ import { dataRootPath } from "@mailwoman/core/utils"
24
+
23
25
  import type { CoarsePlacerMeta } from "../coarse-placer.ts"
24
26
 
25
27
  /**
@@ -62,7 +64,7 @@ export async function quantizeCoarsePlacer(
62
64
  const inDir = options.in || dataRootPath("coarse-placer", "model")
63
65
  const outDir = options.out || dataRootPath("coarse-placer", "model-int8")
64
66
 
65
- const meta = JSON.parse(readFileSync(path.join(inDir, "meta.json"), "utf8")) as CoarsePlacerMeta
67
+ const meta = parseJSONStrict<CoarsePlacerMeta>(readFileSync(path.join(inDir, "meta.json"), "utf8"))
66
68
  const buf = readFileSync(path.join(inDir, "weights.bin"))
67
69
  const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
68
70
  const w = new Float32Array(ab)
@@ -12,11 +12,12 @@
12
12
  * $MAILWOMAN_DATA_ROOT/coarse-placer/model]`
13
13
  */
14
14
 
15
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs"
15
+ import { mkdirSync, writeFileSync } from "node:fs"
16
16
  import * as path from "node:path"
17
17
 
18
- import { dataRootPath } from "../../utils/data-root.ts"
19
- import { repoRootPath } from "../../utils/repo.ts"
18
+ import { dataRootPath, repoRootPath } from "@mailwoman/core/utils"
19
+ import { JSONSpliterator } from "spliterator"
20
+
20
21
  import { COARSE_CLASSES, FEATURE_DIM, featurize } from "../featurize.ts"
21
22
 
22
23
  /**
@@ -93,11 +94,10 @@ export async function trainCoarsePlacer(
93
94
  const D = FEATURE_DIM
94
95
  const classIdx = new Map<string, number>(COARSE_CLASSES.map((c, i): [string, number] => [c, i]))
95
96
 
96
- function load(split: string): Sample[] {
97
- const rows = readFileSync(path.join(dataDir, `${split}.jsonl`), "utf8")
98
- .trim()
99
- .split("\n")
100
- .map((l) => JSON.parse(l) as { raw: string; country: string })
97
+ async function load(split: string): Promise<Sample[]> {
98
+ const rows = await Array.fromAsync(
99
+ JSONSpliterator.fromAsync<{ raw: string; country: string }>(path.join(dataDir, `${split}.jsonl`))
100
+ )
101
101
 
102
102
  // Precompute features once: Int32Array of active indices + label id per row.
103
103
  const out: Sample[] = []
@@ -113,8 +113,8 @@ export async function trainCoarsePlacer(
113
113
  }
114
114
 
115
115
  report?.("featurizing…")
116
- const train = load("train")
117
- const val = load("val")
116
+ const train = await load("train")
117
+ const val = await load("val")
118
118
  report?.(`train ${train.length} val ${val.length} classes ${C} dim ${D}`)
119
119
 
120
120
  const W = new Float32Array(C * D)
package/collections.ts CHANGED
@@ -4,131 +4,5 @@
4
4
  * @author Teffen Ellis, et al.
5
5
  */
6
6
 
7
- /**
8
- * Extracts the property keys of an object that are of type `number`.
9
- */
10
- export type NumericProperties<T> = {
11
- [K in keyof T]: T[K] extends number ? K : never
12
- }[keyof T]
13
-
14
- /**
15
- * Given an iterable of objects, returns the sum of the specified property.
16
- */
17
- export function sumOf<T extends object>(iterable: Iterable<T>, prop: NumericProperties<T>): number {
18
- let total = 0
19
-
20
- for (const item of iterable) {
21
- total += item[prop] as number
22
- }
23
-
24
- return total
25
- }
26
-
27
- /**
28
- * Given an iterable, returns an array of arrays of the specified size.
29
- *
30
- * This is useful for batching asynchronous operations.
31
- *
32
- * @param collection The collection to batch.
33
- * @param batchSize The size of each batch.
34
- *
35
- * @returns An iterable of arrays of the specified size.
36
- */
37
- export function* take<T>(collection: Iterable<T>, batchSize: number): Iterable<T[]> {
38
- const batch: T[] = []
39
-
40
- for (const item of collection) {
41
- batch.push(item)
42
-
43
- if (batch.length === batchSize) {
44
- yield batch
45
-
46
- batch.length = 0
47
- }
48
- }
49
-
50
- if (batch.length) {
51
- yield batch
52
- }
53
- }
54
-
55
- /**
56
- * Convenience function to await an async iterable.
57
- */
58
- export async function iterateInParallel<T>(asyncIterable: AsyncIterable<T>): Promise<void> {
59
- for await (const _ of asyncIterable) {
60
- /* empty */
61
- }
62
- }
63
-
64
- /**
65
- * Given an iterable of values, maps each value to a record of the value and the result of the callback.
66
- *
67
- * This is a convenience function when an iterable needs mapping to an object-like structure.
68
- *
69
- * @category Collections
70
- * @category Object
71
- */
72
- export function pivot<T extends PropertyKey, C extends (value: T) => Promise<unknown> | unknown>(
73
- /**
74
- * The iterable to pivot.
75
- */
76
- iterable: Iterable<T>,
77
- /**
78
- * The callback to transform each value.
79
- */
80
- callback: C
81
- ): ReturnType<C> extends PromiseLike<infer U> ? Promise<Record<T, U>> : Record<T, ReturnType<C>> {
82
- const entries: Array<[T, ReturnType<C>]> = []
83
- let foundThenable = false
84
-
85
- for (const value of iterable) {
86
- const result = callback(value)
87
-
88
- if (result && typeof result === "object" && "then" in result) {
89
- foundThenable = true
90
- }
91
-
92
- entries.push([value, result as ReturnType<C>])
93
- }
94
-
95
- if (foundThenable) {
96
- return Promise.all(
97
- entries.map(([key, value]) => {
98
- return Promise.resolve(value).then((resolvedValue) => [key, resolvedValue] as const)
99
- })
100
- ).then(Object.fromEntries) as unknown as ReturnType<C> extends PromiseLike<infer U>
101
- ? Promise<Record<T, U>>
102
- : Record<T, ReturnType<C>>
103
- }
104
-
105
- const pivotedRecord = Object.fromEntries(entries)
106
-
107
- return pivotedRecord as unknown as ReturnType<C> extends PromiseLike<infer U>
108
- ? Promise<Record<T, U>>
109
- : Record<T, ReturnType<C>>
110
- }
111
-
112
- /**
113
- * Type-predicate for checking if a value is iterable.
114
- *
115
- * @category Type Guard
116
- * @category Object
117
- */
118
- export function isIterable<T>(input: unknown): input is Iterable<T> {
119
- return Symbol.iterator in new Object(input)
120
- }
121
-
122
- /**
123
- * Iterable that can be checked for the existence of a member.
124
- */
125
- export interface IndexedIterable<T = unknown> extends Iterable<T> {
126
- has(value: T): boolean
127
- }
128
-
129
- /**
130
- * Type-predicate for checking if an member within an iterable can be checked for existence.
131
- */
132
- export function isIndexedIterable<T>(value: Iterable<T>): value is IndexedIterable<T> {
133
- return value && typeof (value as IndexedIterable).has === "function"
134
- }
7
+ // Empty module: Fill out as needed.
8
+ export {}
package/crypto/node.ts ADDED
@@ -0,0 +1,68 @@
1
+ /**
2
+ * @copyright Sister Software.
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ import { createHash } from "node:crypto"
8
+
9
+ /**
10
+ * A value that can be used as input to {@link simpleSHA3}.
11
+ *
12
+ * Values are converted to strings via {@link String}, trimmed, and empty values are discarded before hashing.
13
+ *
14
+ * @internal
15
+ */
16
+ export type SHA3Seed = string | number | boolean | null | Date | undefined
17
+
18
+ /**
19
+ * Input accepted by {@link simpleSHA3}.
20
+ *
21
+ * Arrays preserve insertion order. Object inputs are hashed using the order returned by {@link Object.values}.
22
+ *
23
+ * @internal
24
+ */
25
+ export type SHA3Input = Record<string | number, SHA3Seed> | SHA3Seed[]
26
+
27
+ /**
28
+ * Converts hash input into a normalized array of non-empty strings.
29
+ *
30
+ * @param input - Seeds to normalize.
31
+ *
32
+ * @returns Normalized string values.
33
+ * @throws {Error} If no non-empty values remain after normalization.
34
+ * @internal
35
+ */
36
+ export function normalizeSHASeeds(input: SHA3Input): string[] {
37
+ const seeds = Array.isArray(input) ? input : Object.values(input)
38
+
39
+ const normalizedSeeds = seeds.map((seed) => seed?.toString().trim()).filter(Boolean) as string[]
40
+
41
+ if (!normalizedSeeds.length) {
42
+ throw new Error("Cannot generate a SHA3 hash without input.")
43
+ }
44
+
45
+ return normalizedSeeds
46
+ }
47
+
48
+ /**
49
+ * Generates an uppercase SHAKE128 digest from one or more input values.
50
+ *
51
+ * Each normalized seed is fed into the hash sequentially.
52
+ *
53
+ * @param seeds - Values to hash.
54
+ * @param outputLength - Length of the digest in **bytes**. Defaults to `32` (256-bit output).
55
+ *
56
+ * @returns Uppercase hexadecimal digest.
57
+ */
58
+ export function simpleSHA3(seeds: SHA3Input, outputLength = 32): string {
59
+ const hash = createHash("shake128", {
60
+ outputLength,
61
+ })
62
+
63
+ for (const seed of normalizeSHASeeds(seeds)) {
64
+ hash.update(seed, "utf8")
65
+ }
66
+
67
+ return hash.digest("hex").toUpperCase()
68
+ }
@@ -72,16 +72,35 @@ function bioParts(label: BIOLabel): { prefix: "B" | "I" | "O"; tag: ComponentTag
72
72
  // v0.4.0 entry). The model's tag attribution is correct, only the boundary is fuzzy. Trimming
73
73
  // produces a clean canonical value AND clean start/end offsets so downstream consumers slicing
74
74
  // raw[start:end] get the same string as node.value.
75
+ //
76
+ // EXCEPTION: a trailing period directly adjacent to a word character is an abbreviation marker
77
+ // ("Str." / "St." / "Ave."). The model includes these in the span correctly; stripping them loses
78
+ // the abbreviation suffix. We preserve the period when it is immediately preceded by \p{L}\p{N}
79
+ // and NOT separated by whitespace — the slip pattern we guard against is ", 22220" / "Paris 75004,"
80
+ // / wrapping quotes, where the punctuation is isolated from the word body. (#1519 trailing-dot half)
75
81
  function trimBoundary(raw: string, start: number, end: number): { start: number; end: number } {
76
82
  let s = start
77
83
  let e = end
78
84
  const isWordChar = (i: number): boolean => /[\p{L}\p{N}]/u.test(raw[i] ?? "")
79
85
 
86
+ // Leading trim: skip punctuation not part of an abbreviation prefix (e.g. leading "." before a
87
+ // word char is rare but symmetric — preserve it).
80
88
  while (s < e && !isWordChar(s)) {
89
+ if (raw[s] === "." && s + 1 < e && isWordChar(s + 1)) {
90
+ // Abbreviation-dot prefix: ".com" style — preserve.
91
+ break
92
+ }
93
+
81
94
  s++
82
95
  }
83
96
 
97
+ // Trailing trim: skip punctuation, but preserve a trailing abbreviation period.
84
98
  while (e > s && !isWordChar(e - 1)) {
99
+ if (raw[e - 1] === "." && e - 2 >= s && isWordChar(e - 2)) {
100
+ // Abbreviation-dot suffix: "Str." / "Ave." — adjacent to the last word char, preserve.
101
+ break
102
+ }
103
+
85
104
  e--
86
105
  }
87
106
 
package/env/schema.ts CHANGED
@@ -1,5 +1,20 @@
1
1
  import { z } from "zod"
2
2
 
3
+ /**
4
+ * Wrap a coerced schema so a BLANK value means the same as an absent one.
5
+ *
6
+ * A shell `export FOO=`, an unset Docker/CI `${VAR}` interpolation and a compose file with a missing key all arrive as
7
+ * an empty string rather than as nothing. `z.coerce.number()` turns that into `0`, which any `.positive()` or `.min()`
8
+ * then rejects — so the process dies at import instead of falling back to its default, and the message points at a
9
+ * variable the operator believes they never set.
10
+ *
11
+ * The `.optional()`/`.default()` must be applied to `inner` BEFORE it reaches here: the outer value is present, so an
12
+ * outer `.optional()` never fires — `inner` is what receives the `undefined` this produces.
13
+ */
14
+ function blankAsAbsent<T extends z.ZodType>(inner: T) {
15
+ return z.preprocess((v) => (v === "" ? undefined : v), inner)
16
+ }
17
+
3
18
  /**
4
19
  * Non-secret operational config, exposed via `$public`. Add a key here to make it visible to the runtime; anything not
5
20
  * listed is stripped from `process.env` on parse.
@@ -18,6 +33,11 @@ export const PublicEnvSchema = z.object({
18
33
  MAILWOMAN_FST_BIN: z.string().optional(),
19
34
  MAILWOMAN_MODEL_CARD: z.string().optional(),
20
35
  MAILWOMAN_COARSE_PLACER_DIR: z.string().optional(),
36
+
37
+ // ONNX intra-op thread cap. Deployment-shaped rather than code-shaped: the right value depends on how many
38
+ // mailwoman processes share the host, which the library cannot know. See DEFAULT_INTRA_OP_THREADS.
39
+ //
40
+ MAILWOMAN_INTRA_OP_THREADS: blankAsAbsent(z.coerce.number().int().positive().optional()),
21
41
  WOF_DATA_DIR: z.string().optional(),
22
42
 
23
43
  // Geocode server batch row cap (`POST /v1/batch`).
@@ -27,8 +47,8 @@ export const PublicEnvSchema = z.object({
27
47
  // releasing to the libuv pool, and `node:sqlite` reads are synchronous. Measured 1.00x flat from
28
48
  // 1→16 workers on both parse and full geocode. Don't reintroduce it without re-measuring; worker
29
49
  // threads (see `mailwoman/geocode-stream.ts`) are the only lever that moves this in Node.
30
- // Receipts: `docs/articles/plan/reference/performance.mdx`.
31
- MAILWOMAN_BATCH_MAX: z.coerce.number().int().positive().default(1000),
50
+ // Receipts: `docs/engineering/reference/performance.mdx`.
51
+ MAILWOMAN_BATCH_MAX: blankAsAbsent(z.coerce.number().int().positive().default(1000)),
32
52
 
33
53
  // The gazetteer/model data root (`core/utils/data-root.ts`, `scripts/copy-weights.ts`).
34
54
  MAILWOMAN_DATA_ROOT: z.string().optional(),
@@ -97,6 +117,27 @@ export const PublicEnvSchema = z.object({
97
117
  MAILWOMAN_DIAG_INTERP: z.string().optional(),
98
118
  MAILWOMAN_DUMP_MISS_TAG: z.string().optional(),
99
119
  MAILWOMAN_WORD_CONSISTENCY: z.string().optional(),
120
+ /**
121
+ * PIX1 whole-edge parent bias (#46) — the δ applied to the PARENT window of a placetype-pair hit, over the child
122
+ * tag's allowed parents in `containmentFor(system)`. UNSET (the default) = child-only, byte-identical to every
123
+ * pre-#46 build.
124
+ *
125
+ * A bar-gated toggle, not a shipped knob: the mechanism stays off until the four bars in
126
+ * `docs/superpowers/plans/2026-08-04-pix1-whole-edge-preregistration.md` clear, and this is how the ON leg of B-1's
127
+ * ON-vs-OFF comparison is driven through `mailwoman eval gauntlet` without a code edit between the two runs.
128
+ */
129
+ MAILWOMAN_PAIR_PARENT_DELTA: blankAsAbsent(z.coerce.number().optional()),
130
+ /**
131
+ * Gates the with-data half of `mailwoman/test/dropin-cold-start.test.ts` — a real `mailwoman data pull candidate`
132
+ * (~1.65 GB) plus booting all three drop-in servers against it. Unset in CI; the always-on half (missing-data +
133
+ * libpostal's zero-data boot) downloads nothing and needs no guard.
134
+ */
135
+ MAILWOMAN_COLD_START_FULL: z.string().optional(),
136
+ /**
137
+ * Reuse an already-populated data root for the gated cold-start suite above instead of pulling candidate.db fresh
138
+ * into a throwaway temp dir — avoids a redundant ~1.65 GB re-download across repeated local runs.
139
+ */
140
+ MAILWOMAN_COLD_START_DATA_ROOT: z.string().optional(),
100
141
  MW_DUMP_REGRESSIONS: z.string().optional(),
101
142
  PROBE_N: z.string().optional(),
102
143
  DEBUG: z.string().optional(),
@@ -140,4 +181,19 @@ export const PrivateEnvSchema = z.object({
140
181
 
141
182
  // SEC EDGAR fair-access User-Agent (`filer/sdk/sec-client.ts`) — "Company Name AdminContact@domain.com".
142
183
  SEC_EDGAR_USER_AGENT: z.string().optional(),
184
+ /**
185
+ * Descriptive User-Agent for the FCC CORES lookup (`filer/sdk/cores-client.ts`). Optional in a way
186
+ * `SEC_EDGAR_USER_AGENT` is not: SEC 403s a request that fails to identify itself, FCC does not. Falls back to
187
+ * `SEC_EDGAR_USER_AGENT` — the same contact address — when unset.
188
+ */
189
+ FCC_CORES_USER_AGENT: z.string().optional(),
190
+
191
+ USAC_API_KEY_ID: z.string().optional(),
192
+ USAC_API_SECRET_KEY: z.string().optional(),
193
+
194
+ // Google Maps Platform key for the reference-geocoder ORACLE (`geocode-oracle/sdk/google-client.ts`).
195
+ // Verification tooling only — nothing on the parse path reads this, and `@mailwoman/geocode-oracle` is
196
+ // a private workspace precisely so it cannot become a runtime dependency of a published package.
197
+ // BILLED PER REQUEST: the client caches for 30 days and paces at 60/minute by default for that reason.
198
+ GOOGLE_MAPS_API_KEY: z.string().optional(),
143
199
  })