@mailwoman/core 8.6.0 → 9.0.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 (209) 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-outlier-latin.ts +1 -0
  8. package/coarse-placer/tools/build-outlier-oa.ts +1 -0
  9. package/coarse-placer/tools/eval-latin-offmap.ts +7 -5
  10. package/coarse-placer/tools/eval-openset.ts +19 -10
  11. package/coarse-placer/tools/eval-quant-compare.ts +7 -7
  12. package/coarse-placer/tools/eval.ts +29 -21
  13. package/coarse-placer/tools/probe-frontier.ts +8 -4
  14. package/coarse-placer/tools/quantize.ts +2 -1
  15. package/coarse-placer/tools/train.ts +9 -8
  16. package/collections.ts +2 -128
  17. package/crypto/node.ts +68 -0
  18. package/env/schema.ts +49 -2
  19. package/identifiers.ts +48 -0
  20. package/layers/manifest.ts +2 -1
  21. package/locale/profiles/en-us.ts +2 -3
  22. package/locale/profiles/fr-fr.ts +1 -1
  23. package/locale/profiles/ja-jp.ts +7 -7
  24. package/objects.ts +40 -8
  25. package/out/api/clock.d.ts +1 -1
  26. package/out/api/clock.js +1 -1
  27. package/out/api/disk-storage.d.ts +1 -1
  28. package/out/api/disk-storage.d.ts.map +1 -1
  29. package/out/api/disk-storage.js +5 -5
  30. package/out/api/disk-storage.js.map +1 -1
  31. package/out/api/test-clocks.d.ts +2 -2
  32. package/out/api/test-clocks.d.ts.map +1 -1
  33. package/out/api/test-clocks.js +51 -9
  34. package/out/api/test-clocks.js.map +1 -1
  35. package/out/api/test-transport.d.ts +112 -0
  36. package/out/api/test-transport.d.ts.map +1 -0
  37. package/out/api/test-transport.js +84 -0
  38. package/out/api/test-transport.js.map +1 -0
  39. package/out/coarse-placer/coarse-placer.d.ts.map +1 -1
  40. package/out/coarse-placer/coarse-placer.js +2 -1
  41. package/out/coarse-placer/coarse-placer.js.map +1 -1
  42. package/out/coarse-placer/tools/build-outlier-latin.d.ts.map +1 -1
  43. package/out/coarse-placer/tools/build-outlier-latin.js +1 -0
  44. package/out/coarse-placer/tools/build-outlier-latin.js.map +1 -1
  45. package/out/coarse-placer/tools/build-outlier-oa.d.ts.map +1 -1
  46. package/out/coarse-placer/tools/build-outlier-oa.js +1 -0
  47. package/out/coarse-placer/tools/build-outlier-oa.js.map +1 -1
  48. package/out/coarse-placer/tools/eval-latin-offmap.d.ts.map +1 -1
  49. package/out/coarse-placer/tools/eval-latin-offmap.js +4 -5
  50. package/out/coarse-placer/tools/eval-latin-offmap.js.map +1 -1
  51. package/out/coarse-placer/tools/eval-openset.d.ts.map +1 -1
  52. package/out/coarse-placer/tools/eval-openset.js +11 -9
  53. package/out/coarse-placer/tools/eval-openset.js.map +1 -1
  54. package/out/coarse-placer/tools/eval-quant-compare.d.ts.map +1 -1
  55. package/out/coarse-placer/tools/eval-quant-compare.js +6 -7
  56. package/out/coarse-placer/tools/eval-quant-compare.js.map +1 -1
  57. package/out/coarse-placer/tools/eval.d.ts.map +1 -1
  58. package/out/coarse-placer/tools/eval.js +19 -19
  59. package/out/coarse-placer/tools/eval.js.map +1 -1
  60. package/out/coarse-placer/tools/probe-frontier.d.ts.map +1 -1
  61. package/out/coarse-placer/tools/probe-frontier.js +7 -5
  62. package/out/coarse-placer/tools/probe-frontier.js.map +1 -1
  63. package/out/coarse-placer/tools/quantize.d.ts.map +1 -1
  64. package/out/coarse-placer/tools/quantize.js +2 -1
  65. package/out/coarse-placer/tools/quantize.js.map +1 -1
  66. package/out/coarse-placer/tools/train.d.ts.map +1 -1
  67. package/out/coarse-placer/tools/train.js +6 -8
  68. package/out/coarse-placer/tools/train.js.map +1 -1
  69. package/out/collections.d.ts +1 -59
  70. package/out/collections.d.ts.map +1 -1
  71. package/out/collections.js +2 -90
  72. package/out/collections.js.map +1 -1
  73. package/out/crypto/node.d.ts +43 -0
  74. package/out/crypto/node.d.ts.map +1 -0
  75. package/out/crypto/node.js +43 -0
  76. package/out/crypto/node.js.map +1 -0
  77. package/out/env/index.d.ts +5 -0
  78. package/out/env/index.d.ts.map +1 -1
  79. package/out/env/schema.d.ts +6 -1
  80. package/out/env/schema.d.ts.map +1 -1
  81. package/out/env/schema.js +46 -2
  82. package/out/env/schema.js.map +1 -1
  83. package/out/identifiers.d.ts +23 -0
  84. package/out/identifiers.d.ts.map +1 -1
  85. package/out/identifiers.js +39 -0
  86. package/out/identifiers.js.map +1 -1
  87. package/out/layers/manifest.d.ts.map +1 -1
  88. package/out/layers/manifest.js +2 -1
  89. package/out/layers/manifest.js.map +1 -1
  90. package/out/locale/profiles/en-us.d.ts +2 -3
  91. package/out/locale/profiles/en-us.d.ts.map +1 -1
  92. package/out/locale/profiles/en-us.js +2 -3
  93. package/out/locale/profiles/en-us.js.map +1 -1
  94. package/out/locale/profiles/fr-fr.d.ts +1 -1
  95. package/out/locale/profiles/fr-fr.js +1 -1
  96. package/out/locale/profiles/ja-jp.d.ts +7 -7
  97. package/out/locale/profiles/ja-jp.js +7 -7
  98. package/out/objects.d.ts +18 -2
  99. package/out/objects.d.ts.map +1 -1
  100. package/out/objects.js +29 -3
  101. package/out/objects.js.map +1 -1
  102. package/out/pipeline/index.d.ts +2 -2
  103. package/out/pipeline/index.d.ts.map +1 -1
  104. package/out/pipeline/index.js +1 -1
  105. package/out/pipeline/index.js.map +1 -1
  106. package/out/pipeline/runtime-pipeline.d.ts +1 -1
  107. package/out/pipeline/runtime-pipeline.d.ts.map +1 -1
  108. package/out/pipeline/runtime-pipeline.js +57 -17
  109. package/out/pipeline/runtime-pipeline.js.map +1 -1
  110. package/out/pipeline/span-proposer.d.ts +24 -0
  111. package/out/pipeline/span-proposer.d.ts.map +1 -1
  112. package/out/pipeline/span-proposer.js +36 -1
  113. package/out/pipeline/span-proposer.js.map +1 -1
  114. package/out/pipeline/types.d.ts +40 -1
  115. package/out/pipeline/types.d.ts.map +1 -1
  116. package/out/pipeline/types.js +11 -1
  117. package/out/pipeline/types.js.map +1 -1
  118. package/out/resolver/types.d.ts +41 -0
  119. package/out/resolver/types.d.ts.map +1 -1
  120. package/out/resolver/types.js.map +1 -1
  121. package/out/resources/index.d.ts +0 -1
  122. package/out/resources/index.d.ts.map +1 -1
  123. package/out/resources/index.js +0 -1
  124. package/out/resources/index.js.map +1 -1
  125. package/out/resources/libpostal.d.ts.map +1 -1
  126. package/out/resources/libpostal.js +3 -4
  127. package/out/resources/libpostal.js.map +1 -1
  128. package/out/resources/whosonfirst/index.d.ts +1 -0
  129. package/out/resources/whosonfirst/index.d.ts.map +1 -1
  130. package/out/resources/whosonfirst/index.js +1 -0
  131. package/out/resources/whosonfirst/index.js.map +1 -1
  132. package/out/resources/whosonfirst/placetypes/Placetype.d.ts.map +1 -1
  133. package/out/resources/whosonfirst/placetypes/Placetype.js +5 -4
  134. package/out/resources/whosonfirst/placetypes/Placetype.js.map +1 -1
  135. package/out/resources/whosonfirst/placetypes/admin.d.ts +12 -3
  136. package/out/resources/whosonfirst/placetypes/admin.d.ts.map +1 -1
  137. package/out/resources/whosonfirst/placetypes/admin.js +1 -1
  138. package/out/resources/whosonfirst/placetypes/admin.js.map +1 -1
  139. package/out/resources/whosonfirst/sharded-repo.d.ts +28 -0
  140. package/out/resources/whosonfirst/sharded-repo.d.ts.map +1 -0
  141. package/out/resources/whosonfirst/sharded-repo.js +58 -0
  142. package/out/resources/whosonfirst/sharded-repo.js.map +1 -0
  143. package/out/tools/download-libpostal-resources.d.ts.map +1 -1
  144. package/out/tools/download-libpostal-resources.js +1 -0
  145. package/out/tools/download-libpostal-resources.js.map +1 -1
  146. package/out/tools/generate-language-types.d.ts.map +1 -1
  147. package/out/tools/generate-language-types.js +5 -11
  148. package/out/tools/generate-language-types.js.map +1 -1
  149. package/out/utils/data-root.d.ts +20 -6
  150. package/out/utils/data-root.d.ts.map +1 -1
  151. package/out/utils/data-root.js +24 -5
  152. package/out/utils/data-root.js.map +1 -1
  153. package/out/utils/hash.d.ts +6 -0
  154. package/out/utils/hash.d.ts.map +1 -1
  155. package/out/utils/hash.js +8 -0
  156. package/out/utils/hash.js.map +1 -1
  157. package/out/utils/index.d.ts +1 -0
  158. package/out/utils/index.d.ts.map +1 -1
  159. package/out/utils/index.js +1 -0
  160. package/out/utils/index.js.map +1 -1
  161. package/out/utils/jsonl.d.ts +17 -3
  162. package/out/utils/jsonl.d.ts.map +1 -1
  163. package/out/utils/jsonl.js +23 -6
  164. package/out/utils/jsonl.js.map +1 -1
  165. package/out/utils/python-json.d.ts +3 -3
  166. package/out/utils/python-json.js +9 -9
  167. package/out/utils/python-numeric.d.ts +33 -0
  168. package/out/utils/python-numeric.d.ts.map +1 -0
  169. package/out/utils/python-numeric.js +149 -0
  170. package/out/utils/python-numeric.js.map +1 -0
  171. package/out/utils/python-random.d.ts +26 -1
  172. package/out/utils/python-random.d.ts.map +1 -1
  173. package/out/utils/python-random.js +43 -7
  174. package/out/utils/python-random.js.map +1 -1
  175. package/out/utils/repo.d.ts.map +1 -1
  176. package/out/utils/repo.js +18 -0
  177. package/out/utils/repo.js.map +1 -1
  178. package/out/utils/sealed-db.d.ts +12 -0
  179. package/out/utils/sealed-db.d.ts.map +1 -1
  180. package/out/utils/sealed-db.js +32 -1
  181. package/out/utils/sealed-db.js.map +1 -1
  182. package/package.json +22 -6
  183. package/pipeline/index.ts +2 -1
  184. package/pipeline/runtime-pipeline.ts +69 -26
  185. package/pipeline/span-proposer.ts +64 -1
  186. package/pipeline/types.ts +43 -1
  187. package/resolver/types.ts +41 -0
  188. package/resources/index.ts +0 -1
  189. package/resources/libpostal.ts +8 -7
  190. package/resources/whosonfirst/index.ts +1 -0
  191. package/resources/whosonfirst/placetypes/Placetype.ts +12 -7
  192. package/resources/whosonfirst/placetypes/admin.ts +12 -2
  193. package/resources/whosonfirst/sharded-repo.ts +69 -0
  194. package/tools/download-libpostal-resources.ts +1 -0
  195. package/tools/generate-language-types.ts +5 -14
  196. package/utils/data-root.ts +27 -6
  197. package/utils/hash.ts +9 -0
  198. package/utils/index.ts +1 -0
  199. package/utils/jsonl.ts +26 -7
  200. package/utils/python-json.ts +10 -10
  201. package/utils/python-numeric.ts +168 -0
  202. package/utils/python-random.ts +49 -8
  203. package/utils/repo.ts +18 -0
  204. package/utils/sealed-db.ts +38 -1
  205. package/out/resources/collections.d.ts +0 -22
  206. package/out/resources/collections.d.ts.map +0 -1
  207. package/out/resources/collections.js +0 -69
  208. package/out/resources/collections.js.map +0 -1
  209. package/resources/collections.ts +0 -96
@@ -21,6 +21,10 @@
21
21
 
22
22
  import { readFileSync, writeFileSync } from "node:fs"
23
23
 
24
+ import { join } from "path-ts"
25
+ import { TSVSpliterator } from "spliterator"
26
+
27
+ import { parseJSONStrict } from "../../objects.ts"
24
28
  import { dataRootPath } from "../../utils/data-root.ts"
25
29
  import { corePackagePath } from "../../utils/repo.ts"
26
30
  import { median } from "../../utils/stats.ts"
@@ -127,7 +131,7 @@ export async function probeFrontier(
127
131
  // `@mailwoman/codex` is a devDependency of core (operator tooling) — lazy-imported inside the fn.
128
132
  const { ISO2_TO_NAME } = await import("@mailwoman/codex/country")
129
133
 
130
- const meta = JSON.parse(readFileSync(`${modelDir}/meta.json`, "utf8")) as CoarsePlacerMeta
134
+ const meta = parseJSONStrict<CoarsePlacerMeta>(readFileSync(join(String(modelDir), "meta.json"), "utf8"))
131
135
  // The deployed bundle is int8-per-row quantized — fromArtifactDir dequantizes via meta.scales.
132
136
  const placer = await CoarsePlacer.fromArtifactDir(modelDir, { abstainBelow: 0 })
133
137
  const classSet = new Set(meta.classes)
@@ -143,9 +147,8 @@ export async function probeFrontier(
143
147
 
144
148
  const all: Q[] = []
145
149
 
146
- for (const line of readFileSync(CITIES, "utf8").split("\n")) {
147
- if (!line) continue
148
- const f = line.split("\t")
150
+ // `header: false` — cities15000 is headerless, so row 1 is a city.
151
+ for await (const f of TSVSpliterator.fromAsync(CITIES, { header: false })) {
149
152
  const name = f[1]
150
153
  const cc = f[8]
151
154
 
@@ -235,6 +238,7 @@ export async function probeFrontier(
235
238
 
236
239
  const md = L.join("\n")
237
240
 
241
+ // oxlint-disable-next-line mailwoman/prefer-spliterator -- Re-splitting a string joined two lines above.
238
242
  console.log(md.split("\n").slice(0, 12).join("\n"))
239
243
  console.log("…")
240
244
 
@@ -19,6 +19,7 @@
19
19
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs"
20
20
  import * as path from "node:path"
21
21
 
22
+ import { parseJSONStrict } from "../../objects.ts"
22
23
  import { dataRootPath } from "../../utils/data-root.ts"
23
24
  import type { CoarsePlacerMeta } from "../coarse-placer.ts"
24
25
 
@@ -62,7 +63,7 @@ export async function quantizeCoarsePlacer(
62
63
  const inDir = options.in || dataRootPath("coarse-placer", "model")
63
64
  const outDir = options.out || dataRootPath("coarse-placer", "model-int8")
64
65
 
65
- const meta = JSON.parse(readFileSync(path.join(inDir, "meta.json"), "utf8")) as CoarsePlacerMeta
66
+ const meta = parseJSONStrict<CoarsePlacerMeta>(readFileSync(path.join(inDir, "meta.json"), "utf8"))
66
67
  const buf = readFileSync(path.join(inDir, "weights.bin"))
67
68
  const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
68
69
  const w = new Float32Array(ab)
@@ -12,9 +12,11 @@
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 { JSONSpliterator } from "spliterator"
19
+
18
20
  import { dataRootPath } from "../../utils/data-root.ts"
19
21
  import { repoRootPath } from "../../utils/repo.ts"
20
22
  import { COARSE_CLASSES, FEATURE_DIM, featurize } from "../featurize.ts"
@@ -93,11 +95,10 @@ export async function trainCoarsePlacer(
93
95
  const D = FEATURE_DIM
94
96
  const classIdx = new Map<string, number>(COARSE_CLASSES.map((c, i): [string, number] => [c, i]))
95
97
 
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 })
98
+ async function load(split: string): Promise<Sample[]> {
99
+ const rows = await Array.fromAsync(
100
+ JSONSpliterator.fromAsync<{ raw: string; country: string }>(path.join(dataDir, `${split}.jsonl`))
101
+ )
101
102
 
102
103
  // Precompute features once: Int32Array of active indices + label id per row.
103
104
  const out: Sample[] = []
@@ -113,8 +114,8 @@ export async function trainCoarsePlacer(
113
114
  }
114
115
 
115
116
  report?.("featurizing…")
116
- const train = load("train")
117
- const val = load("val")
117
+ const train = await load("train")
118
+ const val = await load("val")
118
119
  report?.(`train ${train.length} val ${val.length} classes ${C} dim ${D}`)
119
120
 
120
121
  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
+ }
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,10 @@ 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
+ // Google Maps Platform key for the reference-geocoder ORACLE (`geocode-oracle/sdk/google-client.ts`).
186
+ // Verification tooling only — nothing on the parse path reads this, and `@mailwoman/geocode-oracle` is
187
+ // a private workspace precisely so it cannot become a runtime dependency of a published package.
188
+ // BILLED PER REQUEST: the client caches for 30 days and paces at 60/minute by default for that reason.
189
+ GOOGLE_MAPS_API_KEY: z.string().optional(),
143
190
  })
package/identifiers.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  */
6
+
6
7
  import { camelCase, capitalCase, snakeCase } from "change-case"
7
8
  import type { CamelCase, SnakeCase } from "type-fest"
8
9
 
@@ -56,3 +57,50 @@ export function smartCapitalCase(input: string): string {
56
57
 
57
58
  return capitalCase(input)
58
59
  }
60
+
61
+ /**
62
+ * Python `str.isupper()`: at least one cased character, and every cased character uppercase.
63
+ *
64
+ * Distinct from {@link isUniformlyCased}, which reports `true` for a string with no cased characters at all — `"123"` is
65
+ * uniformly cased and is NOT `isupper()`. Ports that gate a titlecase on the Python predicate need this one.
66
+ */
67
+ export function pyIsUpper(input: string): boolean {
68
+ let hasCased = false
69
+
70
+ for (const ch of input) {
71
+ if (ch.toLowerCase() === ch.toUpperCase()) continue
72
+
73
+ hasCased = true
74
+
75
+ if (ch !== ch.toUpperCase()) return false
76
+ }
77
+
78
+ return hasCased
79
+ }
80
+
81
+ /**
82
+ * Python `str.title()`: titlecase the first cased character of each run, lowercase the rest.
83
+ *
84
+ * Not `capitalCase` from change-case, which splits on word boundaries and drops punctuation — Python titlecases
85
+ * `"o'brien"` to `"O'Brien"` because the apostrophe ends a cased run.
86
+ */
87
+ export function pyTitle(input: string): string {
88
+ let out = ""
89
+ let prevCased = false
90
+
91
+ for (const ch of input) {
92
+ const cased = ch.toLowerCase() !== ch.toUpperCase()
93
+
94
+ out += prevCased ? ch.toLowerCase() : ch.toUpperCase()
95
+ prevCased = cased
96
+ }
97
+
98
+ return out
99
+ }
100
+
101
+ /**
102
+ * Titlecase a SHOUTED string, leave anything else alone — the shape source dumps use when a field arrives ALL CAPS.
103
+ */
104
+ export function titlecaseIfUpper(input: string): string {
105
+ return pyIsUpper(input) ? pyTitle(input) : input
106
+ }
@@ -10,6 +10,7 @@
10
10
 
11
11
  import type { Kysely } from "kysely"
12
12
 
13
+ import { parseJSONStrict } from "../objects.ts"
13
14
  import { LayerFreshnessPolicy, LayerTier, type LayerContractDatabase } from "./schema.ts"
14
15
 
15
16
  /**
@@ -119,7 +120,7 @@ export async function readLayerManifest(db: Kysely<LayerContractDatabase>): Prom
119
120
  buildCmd: row.build_cmd,
120
121
  buildSHA: row.build_sha,
121
122
  freshnessPolicy: row.freshness_policy as LayerFreshnessPolicy,
122
- spineKeys: JSON.parse(row.spine_keys) as SpineKeys,
123
+ spineKeys: parseJSONStrict<SpineKeys>(row.spine_keys),
123
124
  createdAt: row.created_at,
124
125
  }
125
126
 
@@ -3,9 +3,8 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  *
6
- * En-US locale profile (per Phase 0 task 5). Lists the rule classifier IDs the legacy registry will
7
- * assign and the `ComponentTag`s the US locale actually uses. No `weightsPackage` is set in Phase
8
- * 0 — neural weights ship in Phase 3.
6
+ * En-US locale profile. Lists the rule classifier IDs active in this locale and the
7
+ * `ComponentTag`s the US locale actually uses.
9
8
  */
10
9
 
11
10
  import type { LocaleProfile } from "../locale.ts"
@@ -3,7 +3,7 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  *
6
- * Fr-FR locale profile (per Phase 0 task 5). Uses the same rule classifier set as en-US for
6
+ * Fr-FR locale profile. Uses the same rule classifier set as en-US for
7
7
  * locale-agnostic primitives, with the French-specific component set: cedex (postal routing),
8
8
  * street_prefix_particle (de la / du / des), and dependent_locality (arrondissement). The
9
9
  * `central_european_street_name` classifier lives in the registry for FR / DE / etc. and is
@@ -3,14 +3,14 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  *
6
- * Ja-JP locale profile, used in Phase 0 §8 for the forward-compat sanity check (#8 task 8): does
7
- * the core abstraction accept a locale that omits `street` and `house_number` entirely without
8
- * throwing or tripping a type assertion? If this profile registers cleanly today, Phase 6 (Japan)
9
- * does not need a core refactor.
6
+ * Ja-JP locale profile, and the core abstraction's forward-compat sanity check (#8): does the
7
+ * registry accept a locale that omits `street` entirely, and whose hierarchy runs
8
+ * largest-to-smallest, without throwing or tripping a type assertion? While this profile registers
9
+ * cleanly, Japan support needs no core refactor.
10
10
  *
11
- * Note: no rule classifiers are listed because the JP profile is neural-only in Phase 6. The rule
12
- * pipeline does not produce Japanese-specific tags; declaring an empty list here verifies the
13
- * system does not assume there are rule classifiers for every locale.
11
+ * No rule classifiers are listed because the JP profile is neural-only — the rule pipeline produces
12
+ * no Japanese-specific tags. The empty list is itself the assertion that nothing in the system
13
+ * assumes every locale has rule classifiers.
14
14
  */
15
15
 
16
16
  import type { LocaleProfile } from "../locale.ts"
package/objects.ts CHANGED
@@ -6,10 +6,10 @@
6
6
  * Utility functions for working with objects.
7
7
  */
8
8
 
9
+ import type { PathBuilderLike } from "path-ts"
10
+ import { isIterable } from "spliterator"
9
11
  import type { JsonObject } from "type-fest"
10
12
 
11
- import { isIterable } from "./collections.ts"
12
-
13
13
  type SetLike<T> = { has(value: T): boolean } | Iterable<T>
14
14
 
15
15
  /**
@@ -172,17 +172,49 @@ export function omitNullable<T extends object>(input: T): NonNullableObject<T> {
172
172
 
173
173
  /**
174
174
  * Given serialized JSON, attempt to parse it.
175
+ *
176
+ * Non-throwing: invalid JSON — and any non-string input, `Buffer` included — returns the fallback (`null` unless one is
177
+ * given). Callers that need a throw on corrupt input, or `JSON.parse`'s reviver parameter, use `JSON.parse` directly
178
+ * behind a scoped lint disable.
175
179
  */
176
- export function tryParsingJSON<T = unknown>(input: unknown, fallback?: undefined): T | undefined
177
- export function tryParsingJSON<T = unknown>(input: unknown, fallback: null): T | null
180
+ export function tryParsingJSON<T = unknown>(input: unknown): T | null
181
+ export function tryParsingJSON<T = unknown, F = T>(input: unknown, fallback: F): T | F
178
182
 
179
- export function tryParsingJSON<T = unknown, F = null>(input: unknown, fallback?: F): T | F {
180
- if (typeof input !== "string") return (fallback ?? null) as F
183
+ export function tryParsingJSON<T = unknown, F = T>(input: unknown, fallback?: F): T | F | null {
184
+ if (typeof input !== "string") return fallback ?? null
181
185
 
182
186
  try {
183
- return JSON.parse(input)
187
+ // oxlint-disable-next-line no-restricted-properties -- The wrapper the rule recommends.
188
+ return JSON.parse(input) as T
184
189
  } catch {
185
- return (fallback ?? null) as F
190
+ return fallback ?? null
191
+ }
192
+ }
193
+
194
+ export class JSONParseError extends Error {
195
+ constructor(message: string, options?: ErrorOptions) {
196
+ super(message, options)
197
+ this.name = "JSONParseError"
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Parses JSON input or throws a `JSONParseError` if parsing fails.
203
+ *
204
+ * @param input - The JSON input to parse.
205
+ *
206
+ * @returns The parsed object.
207
+ */
208
+ export function parseJSONStrict<T = unknown>(input: PathBuilderLike): T {
209
+ if (!input) {
210
+ throw new JSONParseError(`Expected JSON input, got ${input}`)
211
+ }
212
+
213
+ try {
214
+ // oxlint-disable-next-line no-restricted-properties -- The wrapper the rule recommends.
215
+ return JSON.parse(String(input)) as T
216
+ } catch (error: unknown) {
217
+ throw new JSONParseError(`Failed to parse JSON`, { cause: error })
186
218
  }
187
219
  }
188
220
 
@@ -4,7 +4,7 @@
4
4
  * @author Teffen Ellis, et al.
5
5
  * @file The injectable time source every timing-sensitive part of {@linkcode APIClient} reads through.
6
6
  *
7
- * Lifted from `filer/sdk/sec-client.ts` (3b task 5) when the SEC client's bespoke pacing/retry
7
+ * Lifted from `filer/sdk/sec-client.ts` when the SEC client's bespoke pacing/retry
8
8
  * machinery moved down into `@mailwoman/core/api`. Keeping the seam is the whole reason the pacing
9
9
  * and backoff suites are deterministic and finish in milliseconds instead of sleeping on the wall
10
10
  * clock — a rate-limit test that actually waits 100ms per grant costs 4s for a 40-call fan-out and
package/out/api/clock.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * @author Teffen Ellis, et al.
5
5
  * @file The injectable time source every timing-sensitive part of {@linkcode APIClient} reads through.
6
6
  *
7
- * Lifted from `filer/sdk/sec-client.ts` (3b task 5) when the SEC client's bespoke pacing/retry
7
+ * Lifted from `filer/sdk/sec-client.ts` when the SEC client's bespoke pacing/retry
8
8
  * machinery moved down into `@mailwoman/core/api`. Keeping the seam is the whole reason the pacing
9
9
  * and backoff suites are deterministic and finish in milliseconds instead of sleeping on the wall
10
10
  * clock — a rate-limit test that actually waits 100ms per grant costs 4s for a 40-call fan-out and
@@ -3,7 +3,7 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  * @file An on-disk `axios-cache-interceptor` storage adapter, so a client gets a durable HTTP cache by
6
- * CONFIGURATION rather than by hand-rolling one (3b task 5).
6
+ * CONFIGURATION rather than by hand-rolling one.
7
7
  *
8
8
  * NODE ONLY, and deliberately NOT re-exported from `./index.ts`: `core/api` reaches a browser bundle
9
9
  * (`docs`'s `DashboardMap` → `@mailwoman/cartographer` → `tiles/api.ts` → `@mailwoman/core/api`),
@@ -1 +1 @@
1
- {"version":3,"file":"disk-storage.d.ts","sourceRoot":"","sources":["../../api/disk-storage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAMH,OAAO,EAAE,KAAK,YAAY,EAAgB,KAAK,oBAAoB,EAAqB,MAAM,yBAAyB,CAAA;AAEvH,OAAO,EAAiB,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAA;AAGxE;;GAEG;AACH,MAAM,WAAW,kBAAkB;IAClC;;OAEG;IACH,SAAS,EAAE,MAAM,CAAA;IACjB;;;;;;;OAOG;IACH,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,oBAAoB,KAAK,OAAO,CAAA;IACnD;;OAEG;IACH,MAAM,CAAC,EAAE,cAAc,CAAA;CACvB;AA0BD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,kBAAkB,GAAG,YAAY,CA+I1E"}
1
+ {"version":3,"file":"disk-storage.d.ts","sourceRoot":"","sources":["../../api/disk-storage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAMH,OAAO,EAAE,KAAK,YAAY,EAAgB,KAAK,oBAAoB,EAAqB,MAAM,yBAAyB,CAAA;AAEvH,OAAO,EAAiB,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAA;AAIxE;;GAEG;AACH,MAAM,WAAW,kBAAkB;IAClC;;OAEG;IACH,SAAS,EAAE,MAAM,CAAA;IACjB;;;;;;;OAOG;IACH,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,oBAAoB,KAAK,OAAO,CAAA;IACnD;;OAEG;IACH,MAAM,CAAC,EAAE,cAAc,CAAA;CACvB;AA0BD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,kBAAkB,GAAG,YAAY,CAiJ1E"}
@@ -3,7 +3,7 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  * @file An on-disk `axios-cache-interceptor` storage adapter, so a client gets a durable HTTP cache by
6
- * CONFIGURATION rather than by hand-rolling one (3b task 5).
6
+ * CONFIGURATION rather than by hand-rolling one.
7
7
  *
8
8
  * NODE ONLY, and deliberately NOT re-exported from `./index.ts`: `core/api` reaches a browser bundle
9
9
  * (`docs`'s `DashboardMap` → `@mailwoman/cartographer` → `tiles/api.ts` → `@mailwoman/core/api`),
@@ -27,6 +27,7 @@ import { mkdir, readFile, rename, rm, unlink, writeFile } from "node:fs/promises
27
27
  import { join } from "node:path";
28
28
  import { buildStorage } from "axios-cache-interceptor";
29
29
  import { ConsoleLogger } from "../logging/index.js";
30
+ import { tryParsingJSON } from "../objects.js";
30
31
  import { sha256Hex } from "../utils/hash.js";
31
32
  /**
32
33
  * Whether a storage value is one worth persisting. `loading` is an in-flight marker with no reusable body — it belongs
@@ -117,15 +118,14 @@ export function buildDiskStorage(options) {
117
118
  catch {
118
119
  return undefined;
119
120
  }
120
- try {
121
- return JSON.parse(raw);
122
- }
123
- catch {
121
+ const parsed = tryParsingJSON(raw);
122
+ if (parsed === null) {
124
123
  // A truncated or hand-edited entry is a miss, not a crash — re-fetching is always safe.
125
124
  logger.warn(`Discarding an unreadable cache entry for ${key}.`);
126
125
  await removeEntry(key);
127
126
  return undefined;
128
127
  }
128
+ return parsed;
129
129
  },
130
130
  set: async (key, value) => {
131
131
  if (!isPersistableState(value)) {