@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
package/README.md CHANGED
@@ -81,8 +81,8 @@ The dictionaries are ~9 MB total and are loaded lazily.
81
81
  - [`mailwoman`](../mailwoman) — the user-facing CLI + `AddressParser`
82
82
  - [`@mailwoman/normalize`](../normalize) — Stage 1 of the pipeline
83
83
  - [`@mailwoman/neural`](../neural) — neural classifier (ONNX runtime)
84
- - [What Mailwoman Is](https://mailwoman.sister.software/articles/concepts/what-mailwoman-is/)
85
- - [Staged Pipeline Contract](https://mailwoman.sister.software/articles/plan/reference/STAGES/)
84
+ - [What Mailwoman Is](https://mailwoman.sister.software/docs/developers/get-started/what-mailwoman-is)
85
+ - [Staged Pipeline Contract](https://github.com/sister-software/mailwoman/blob/main/docs/engineering/reference/STAGES.mdx)
86
86
 
87
87
  ## License
88
88
 
package/api/clock.ts 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`),
@@ -30,6 +30,7 @@ import { join } from "node:path"
30
30
  import { type AxiosStorage, buildStorage, type NotEmptyStorageValue, type StorageValue } from "axios-cache-interceptor"
31
31
 
32
32
  import { ConsoleLogger, type IRuntimeLogger } from "../logging/index.ts"
33
+ import { tryParsingJSON } from "../objects.ts"
33
34
  import { sha256Hex } from "../utils/hash.ts"
34
35
 
35
36
  /**
@@ -157,9 +158,9 @@ export function buildDiskStorage(options: DiskStorageOptions): AxiosStorage {
157
158
  return undefined
158
159
  }
159
160
 
160
- try {
161
- return JSON.parse(raw) as StorageValue
162
- } catch {
161
+ const parsed = tryParsingJSON<StorageValue>(raw)
162
+
163
+ if (parsed === null) {
163
164
  // A truncated or hand-edited entry is a miss, not a crash — re-fetching is always safe.
164
165
  logger.warn(`Discarding an unreadable cache entry for ${key}.`)
165
166
 
@@ -167,6 +168,8 @@ export function buildDiskStorage(options: DiskStorageOptions): AxiosStorage {
167
168
 
168
169
  return undefined
169
170
  }
171
+
172
+ return parsed
170
173
  },
171
174
 
172
175
  set: async (key, value) => {
@@ -13,11 +13,36 @@
13
13
  import type { ClockLike } from "./clock.ts"
14
14
 
15
15
  /**
16
- * How many consecutive event-loop turns {@linkcode VirtualClock.runUntilSettled} tolerates with nothing pending before
17
- * declaring the work stuck. Generous — a real `readFile` resolves in a handful of turns — but finite, so a genuinely
18
- * blocked test reports what happened instead of timing out.
16
+ * How much REAL time {@linkcode VirtualClock.runUntilSettled} tolerates with nothing pending before declaring the work
17
+ * stuck. Finite, so a genuinely blocked test reports what happened instead of timing out.
18
+ *
19
+ * This used to be a budget of 1000 idle event-loop TURNS, on the stated assumption that "a real `readFile` resolves in
20
+ * a handful of turns". Turns are not time: an idle turn is a `setImmediate` round-trip costing microseconds, so the
21
+ * whole budget expired in single-digit milliseconds while the I/O it was waiting for took tens. On an unloaded machine
22
+ * the race happened to go the right way. Under load it did not, and the guard fired on WORKING code — observed
23
+ * 2026-08-02 on the lab at load 15.25 and then on a hosted GitHub runner, in `filer/sdk/sec-client.test.ts` and
24
+ * `bdc/sdk/client.test.ts`.
25
+ *
26
+ * Measured with `performance.now()`, NOT `Date.now()`: consumers run under `vi.useFakeTimers({ toFake: ["Date"] })`,
27
+ * which freezes `Date` while leaving `performance` and `setTimeout` real. A Date-based budget would never expire inside
28
+ * those blocks, so genuinely stuck work would hang exactly where this is supposed to report it.
29
+ */
30
+ const IDLE_BUDGET_MS = 5000
31
+
32
+ /**
33
+ * Idle turns to spin on {@linkcode drainMicrotasks} before backing off to real sleeps.
34
+ *
35
+ * The spin is the fast path — work that is one promise-chain away settles within a few turns and should not pay a
36
+ * timer. Past that the wait is on something real, and continuing to spin actively HARMS it: back-to-back `setImmediate`
37
+ * turns monopolize the event loop and starve the very I/O the loop is waiting for. That feedback loop is why the old
38
+ * guard got worse exactly when the machine was busiest.
19
39
  */
20
- const MAX_IDLE_TURNS = 1000
40
+ const IDLE_SPIN_TURNS = 50
41
+
42
+ /**
43
+ * Real backoff between idle polls once {@linkcode IDLE_SPIN_TURNS} is exhausted.
44
+ */
45
+ const IDLE_BACKOFF_MS = 1
21
46
 
22
47
  /**
23
48
  * Run every queued microtask to quiescence. A `setImmediate` is scheduled behind the entire microtask queue, so
@@ -29,6 +54,16 @@ export function drainMicrotasks(): Promise<void> {
29
54
  })
30
55
  }
31
56
 
57
+ /**
58
+ * Yield the event loop for `ms` of REAL time. Used only by {@linkcode VirtualClock.runUntilSettled}'s idle backoff, to
59
+ * let pending real I/O actually be serviced instead of competing with a `setImmediate` spin.
60
+ */
61
+ function realDelay(ms: number): Promise<void> {
62
+ return new Promise<void>((resolve) => {
63
+ setTimeout(resolve, ms)
64
+ })
65
+ }
66
+
32
67
  /**
33
68
  * A {@linkcode ClockLike} whose `sleep()` bumps `now()` and resolves immediately.
34
69
  */
@@ -135,8 +170,8 @@ export class VirtualClock implements ClockLike {
135
170
  * the clock past the deadlines that are registered a moment later, and the test hangs. This polls instead: drain, and
136
171
  * if any sleep is pending, advance to the earliest deadline; if none is, yield and look again.
137
172
  *
138
- * Throws rather than hanging when the work neither settles nor schedules anything for {@linkcode MAX_IDLE_TURNS}
139
- * consecutive turns — a diagnosable failure beats a test-timeout stack trace pointing at the `it()`.
173
+ * Throws rather than hanging when the work neither settles nor schedules anything for {@linkcode IDLE_BUDGET_MS} of
174
+ * REAL time — a diagnosable failure beats a test-timeout stack trace pointing at the `it()`.
140
175
  */
141
176
  public async runUntilSettled<T>(work: Promise<T>): Promise<T> {
142
177
  let settled = false
@@ -159,6 +194,7 @@ export class VirtualClock implements ClockLike {
159
194
  observed.catch(() => undefined)
160
195
 
161
196
  let idleTurns = 0
197
+ let idleSince: number | null = null
162
198
 
163
199
  for (;;) {
164
200
  await drainMicrotasks()
@@ -170,19 +206,31 @@ export class VirtualClock implements ClockLike {
170
206
  const earliest = this.#earliestPendingDeadline()
171
207
 
172
208
  if (earliest === null) {
209
+ idleSince ??= performance.now()
210
+
173
211
  idleTurns++
174
212
 
175
- if (idleTurns > MAX_IDLE_TURNS) {
213
+ const idleFor = performance.now() - idleSince
214
+
215
+ if (idleFor > IDLE_BUDGET_MS) {
176
216
  throw new Error(
177
- `VirtualClock.runUntilSettled: no pending sleep and no progress for ${MAX_IDLE_TURNS} turns at ` +
178
- `t=${this.#now}. The work is blocked on something this clock does not drive.`
217
+ `VirtualClock.runUntilSettled: no pending sleep and no progress for ${Math.round(idleFor)}ms of ` +
218
+ `real time at t=${this.#now}. The work is blocked on something this clock does not drive.`
179
219
  )
180
220
  }
181
221
 
222
+ // Past the spin window the wait is on something real. Back off so it can be serviced —
223
+ // spinning here starves the I/O we are waiting for, which is why the old turn-budgeted
224
+ // guard failed hardest on the busiest machines.
225
+ if (idleTurns > IDLE_SPIN_TURNS) {
226
+ await realDelay(IDLE_BACKOFF_MS)
227
+ }
228
+
182
229
  continue
183
230
  }
184
231
 
185
232
  idleTurns = 0
233
+ idleSince = null
186
234
 
187
235
  await this.advance(Math.max(earliest - this.#now, 0))
188
236
  }
@@ -0,0 +1,182 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ * @file A scripted stub Axios ADAPTER for testing {@linkcode APIClient} subclasses, and the
6
+ * Axios-shaped error builder it rejects with. The sibling of `./test-clocks.ts`: that module makes
7
+ * time deterministic, this one makes the network deterministic, and a pacing test needs both.
8
+ *
9
+ * Extracted from `filer/sdk/sec-client.test.ts` and `bdc/sdk/client.test.ts`, which had grown
10
+ * near-identical copies of it. That is the expected shape of the duplication rather than a
11
+ * surprise: `AGENTS.md` names those two as the worked examples for the `APIClient` migration, so
12
+ * the second client's tests were written from the first's, and every client migrated after them
13
+ * would have copied it again.
14
+ *
15
+ * Everything here is built STRUCTURALLY — `isAxiosError: true` plus `config`/`code`/`response`,
16
+ * and the adapter typed through `APIClientConfig["axios"]` — because the packages under test
17
+ * depend on neither `axios` nor `axios-cache-interceptor`, reaching both only through
18
+ * `@mailwoman/core`. A test file is not a reason to breach that, so this module does not import
19
+ * axios either.
20
+ */
21
+
22
+ import type { APIClientConfig } from "./APIClient.ts"
23
+
24
+ const HTTP_OK = 200
25
+ const HTTP_MULTIPLE_CHOICES = 300
26
+ const HTTP_SERVER_ERROR_MIN = 500
27
+
28
+ /**
29
+ * The interesting subset of an Axios request config, as a stub adapter sees it.
30
+ */
31
+ export interface StubRequestConfig {
32
+ url?: string
33
+ headers?: Record<string, unknown>
34
+ timeout?: number
35
+ /**
36
+ * Set by a binary request path (`"arraybuffer"`). Absent on a JSON client's calls.
37
+ */
38
+ responseType?: string
39
+ /**
40
+ * The per-request `axios-cache-interceptor` override — `false` is how a caller turns caching off for one call without
41
+ * touching `core/api`.
42
+ */
43
+ cache?: unknown
44
+ }
45
+
46
+ /**
47
+ * One scripted adapter outcome.
48
+ */
49
+ export interface StubOutcome {
50
+ status?: number
51
+ statusText?: string
52
+ /**
53
+ * The RAW body, as the transport would hand it to Axios's `transformResponse`. A string here is what an upstream
54
+ * serving HTML under a 200 actually looks like; a `Buffer` is what Axios's Node adapter produces for `responseType:
55
+ * "arraybuffer"`. Anything else is JSON-serialized the way a JSON endpoint would.
56
+ */
57
+ body?: unknown
58
+ headers?: Record<string, string>
59
+ /**
60
+ * A transport-level failure — no HTTP response ever arrives. `code` picks the class: `ERR_NETWORK` for a dropped
61
+ * socket, `ECONNABORTED` for this attempt's own timeout firing.
62
+ */
63
+ throws?: { message: string; code: string }
64
+ }
65
+
66
+ /**
67
+ * The Axios overrides an {@linkcode APIClient} accepts, reached through `APIClientConfig` rather than by importing
68
+ * `axios`.
69
+ */
70
+ export type AxiosOverrides = NonNullable<APIClientConfig["axios"]>
71
+
72
+ export interface StubTransport {
73
+ /**
74
+ * Spread into the client factory as its `axios` override.
75
+ */
76
+ axios: AxiosOverrides
77
+ /**
78
+ * Every dispatched URL, in order.
79
+ */
80
+ calls: string[]
81
+ /**
82
+ * Every dispatched request config, in order — headers, timeout, responseType, per-request cache override.
83
+ */
84
+ configs: StubRequestConfig[]
85
+ /**
86
+ * `clock.now()` at each dispatch, when a clock was supplied. The pacing assertions read this.
87
+ */
88
+ dispatchTimes: number[]
89
+ }
90
+
91
+ export interface StubTransportOptions {
92
+ /**
93
+ * Records a timestamp into {@linkcode StubTransport.dispatchTimes} on every dispatch. Omit when timing is not under
94
+ * test.
95
+ */
96
+ clock?: { now(): number }
97
+ /**
98
+ * The body served when an outcome names none. Defaults to `{ ok: true }`; pass the envelope the client under test
99
+ * expects when it validates one (BDC's `{ data: [] }`, say).
100
+ */
101
+ defaultBody?: unknown
102
+ }
103
+
104
+ /**
105
+ * Build an Axios-shaped rejection without importing `axios`. `isAxiosError(payload)` is `isObject(payload) &&
106
+ * payload.isAxiosError === true`, and everything downstream reads `config`, `code`, and `response` — so this is the
107
+ * full contract that matters.
108
+ */
109
+ export function axiosLikeError(message: string, code: string, config: StubRequestConfig, response?: unknown): Error {
110
+ const error = new Error(message) as Error & Record<string, unknown>
111
+
112
+ error.isAxiosError = true
113
+ error.code = code
114
+ error.config = config
115
+
116
+ if (response) {
117
+ error.response = response
118
+ }
119
+
120
+ return error
121
+ }
122
+
123
+ /**
124
+ * A stub Axios adapter that replays `outcomes` (holding on the last entry once exhausted) and records every dispatch.
125
+ *
126
+ * It reproduces what Axios's real adapters do on a failing status — reject with an Axios-shaped error CARRYING the
127
+ * response — because `validateStatus` is applied by the adapter, not by the interceptor chain. A test that resolves
128
+ * with a 4xx instead would exercise a path the real transport never takes.
129
+ */
130
+ export function stubTransport(outcomes: StubOutcome[], options: StubTransportOptions = {}): StubTransport {
131
+ const { clock, defaultBody = { ok: true } } = options
132
+ const calls: string[] = []
133
+ const configs: StubRequestConfig[] = []
134
+ const dispatchTimes: number[] = []
135
+ let index = 0
136
+
137
+ const adapter = async (config: StubRequestConfig): Promise<unknown> => {
138
+ calls.push(String(config.url))
139
+ configs.push(config)
140
+
141
+ if (clock) {
142
+ dispatchTimes.push(clock.now())
143
+ }
144
+
145
+ const outcome = outcomes[Math.min(index, outcomes.length - 1)]!
146
+
147
+ index++
148
+
149
+ if (outcome.throws) {
150
+ throw axiosLikeError(outcome.throws.message, outcome.throws.code, config)
151
+ }
152
+
153
+ const status = outcome.status ?? HTTP_OK
154
+
155
+ const response = {
156
+ // Axios's `transformResponse` runs on the RAW body, so hand it exactly what the wire would: a
157
+ // string passes through untouched (that is how an HTML error page under a 200 actually arrives),
158
+ // bytes pass through untouched, and anything else is serialized the way a JSON endpoint would.
159
+ data:
160
+ typeof outcome.body === "string" || Buffer.isBuffer(outcome.body)
161
+ ? outcome.body
162
+ : JSON.stringify(outcome.body ?? defaultBody),
163
+ status,
164
+ statusText: outcome.statusText ?? "OK",
165
+ headers: outcome.headers ?? {},
166
+ config,
167
+ }
168
+
169
+ if (status >= HTTP_OK && status < HTTP_MULTIPLE_CHOICES) return response
170
+
171
+ throw axiosLikeError(
172
+ `Request failed with status code ${status}`,
173
+ status >= HTTP_SERVER_ERROR_MIN ? "ERR_BAD_RESPONSE" : "ERR_BAD_REQUEST",
174
+ config,
175
+ response
176
+ )
177
+ }
178
+
179
+ // Structurally an Axios adapter. The precise `AxiosAdapter` signature isn't nameable here without
180
+ // importing `axios`, which the packages under test deliberately do not depend on.
181
+ return { axios: { adapter } as AxiosOverrides, calls, configs, dispatchTimes }
182
+ }
@@ -11,6 +11,7 @@
11
11
  */
12
12
 
13
13
  import { $public } from "../env/index.ts"
14
+ import { parseJSONStrict } from "../objects.ts"
14
15
  import { featurize } from "./featurize.ts"
15
16
 
16
17
  export { COARSE_CLASSES, FEATURE_DIM, featurize } from "./featurize.ts"
@@ -152,7 +153,7 @@ export class CoarsePlacer {
152
153
  static async fromArtifactDir(dir: string, opts?: CoarsePlacerOpts): Promise<CoarsePlacer> {
153
154
  const { readFile } = await import("node:fs/promises")
154
155
  const { join } = await import("node:path")
155
- const meta = JSON.parse(await readFile(join(dir, "meta.json"), "utf8")) as CoarsePlacerMeta
156
+ const meta = parseJSONStrict<CoarsePlacerMeta>(await readFile(join(dir, "meta.json"), "utf8"))
156
157
  const buf = await readFile(join(dir, "weights.bin"))
157
158
  // Copy out of the (possibly pooled, possibly mis-aligned) Buffer into a fresh ArrayBuffer so the
158
159
  // typed-array view is always validly aligned.
@@ -21,8 +21,8 @@
21
21
  import { mkdirSync, writeFileSync } from "node:fs"
22
22
  import * as path from "node:path"
23
23
 
24
- import { dataRootPath } from "../../utils/data-root.ts"
25
- import { repoRootPath } from "../../utils/repo.ts"
24
+ import { dataRootPath, repoRootPath } from "@mailwoman/core/utils"
25
+
26
26
  import { hashFNV1a } from "./fnv-hash.ts"
27
27
 
28
28
  interface DatasetRow {
@@ -20,8 +20,8 @@ import { appendFileSync } from "node:fs"
20
20
  import * as path from "node:path"
21
21
  import { DatabaseSync } from "node:sqlite"
22
22
 
23
- import { dataRootPath } from "../../utils/data-root.ts"
24
- import { repoRootPath } from "../../utils/repo.ts"
23
+ import { dataRootPath, repoRootPath } from "@mailwoman/core/utils"
24
+
25
25
  import { hashFNV1a } from "./fnv-hash.ts"
26
26
 
27
27
  /**
@@ -26,8 +26,8 @@
26
26
  import { appendFileSync, writeFileSync } from "node:fs"
27
27
  import * as path from "node:path"
28
28
 
29
- import { dataRootPath } from "../../utils/data-root.ts"
30
- import { repoRootPath } from "../../utils/repo.ts"
29
+ import { dataRootPath, repoRootPath } from "@mailwoman/core/utils"
30
+
31
31
  import { hashFNV1a } from "./fnv-hash.ts"
32
32
 
33
33
  /**
@@ -151,6 +151,7 @@ export async function buildOutlierLatin(
151
151
  `SELECT number, street, postcode, postal_city, address_levels FROM read_parquet('${f}') LIMIT ${PER}`
152
152
  )
153
153
  } catch (error) {
154
+ // oxlint-disable-next-line mailwoman/prefer-spliterator -- An in-memory error message, not a file.
154
155
  report?.(` ${cc}: SKIP (${(error as Error).message.split("\n")[0]})`)
155
156
 
156
157
  return []
@@ -32,8 +32,8 @@
32
32
  import { appendFileSync, writeFileSync } from "node:fs"
33
33
  import * as path from "node:path"
34
34
 
35
- import { dataRootPath } from "../../utils/data-root.ts"
36
- import { repoRootPath } from "../../utils/repo.ts"
35
+ import { dataRootPath, repoRootPath } from "@mailwoman/core/utils"
36
+
37
37
  import { hashFNV1a } from "./fnv-hash.ts"
38
38
 
39
39
  /**
@@ -168,6 +168,7 @@ export async function buildOutlierOA(
168
168
  `SELECT COLUMNS('(?i)^(number|street|city|postcode)$') FROM read_csv_auto('${glob}', union_by_name=true, ignore_errors=true, sample_size=-1) LIMIT ${PER * 8}`
169
169
  )
170
170
  } catch (error) {
171
+ // oxlint-disable-next-line mailwoman/prefer-spliterator -- An in-memory error message, not a file.
171
172
  report?.(` ${cc}: SKIP (${(error as Error).message.split("\n")[0]})`)
172
173
 
173
174
  return []
@@ -16,9 +16,10 @@
16
16
  import { readFileSync } from "node:fs"
17
17
  import * as path from "node:path"
18
18
 
19
- import { dataRootPath } from "../../utils/data-root.ts"
20
- import { repoRootPath } from "../../utils/repo.ts"
21
- import { formatPercent } from "../../utils/stats.ts"
19
+ import { parseJSONStrict } from "@mailwoman/core/objects"
20
+ import { dataRootPath, repoRootPath, formatPercent } from "@mailwoman/core/utils"
21
+ import { JSONSpliterator } from "spliterator"
22
+
22
23
  import { CoarsePlacer, type CoarsePlacerMeta, type CoarsePrediction } from "../coarse-placer.ts"
23
24
 
24
25
  /**
@@ -67,7 +68,7 @@ export async function evalLatinOffmap(options: EvalLatinOffmapOptions = {}): Pro
67
68
  const abstain = options.abstain ?? 0.5
68
69
  const dataDir = options.data || repoRootPath("data", "coarse-placer")
69
70
 
70
- const meta = JSON.parse(readFileSync(path.join(modelDir, "meta.json"), "utf8")) as CoarsePlacerMeta
71
+ const meta = parseJSONStrict<CoarsePlacerMeta>(readFileSync(path.join(modelDir, "meta.json"), "utf8"))
71
72
  const buf = readFileSync(path.join(modelDir, "weights.bin"))
72
73
  const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
73
74
  let weights: Float32Array
@@ -93,10 +94,9 @@ export async function evalLatinOffmap(options: EvalLatinOffmapOptions = {}): Pro
93
94
 
94
95
  const placer = new CoarsePlacer({ ...meta, weights }, { abstainBelow: abstain })
95
96
 
96
- const rows: OffMapRow[] = readFileSync(path.join(dataDir, "test-latin-offmap.jsonl"), "utf8")
97
- .trim()
98
- .split("\n")
99
- .map((l) => JSON.parse(l) as OffMapRow)
97
+ const rows = await Array.fromAsync(
98
+ JSONSpliterator.fromAsync<OffMapRow>(path.join(dataDir, "test-latin-offmap.jsonl"))
99
+ )
100
100
 
101
101
  const handled = (p: CoarsePrediction): boolean => p.abstained || p.country === "OTHER"
102
102
  const by: Record<string, { n: number; ok: number }> = {} // key → {n, ok}
@@ -36,8 +36,10 @@
36
36
  import { readFileSync, writeFileSync } from "node:fs"
37
37
  import * as path from "node:path"
38
38
 
39
- import { dataRootPath } from "../../utils/data-root.ts"
40
- import { repoRootPath } from "../../utils/repo.ts"
39
+ import { parseJSONStrict } from "@mailwoman/core/objects"
40
+ import { dataRootPath, repoRootPath } from "@mailwoman/core/utils"
41
+ import { JSONSpliterator } from "spliterator"
42
+
41
43
  import type { CoarsePlacerMeta } from "../coarse-placer.ts"
42
44
  import { COARSE_CLASSES, featurize } from "../featurize.ts"
43
45
 
@@ -192,8 +194,17 @@ export async function evalOpenSet(
192
194
  const dataDir = options.data || repoRootPath("data", "coarse-placer")
193
195
  const fitPerClass = options.fitPerClass ?? 2000
194
196
 
195
- const meta = JSON.parse(readFileSync(path.join(modelDir, "meta.json"), "utf8")) as CoarsePlacerMeta
196
- const W = new Float32Array(readFileSync(path.join(modelDir, "weights.bin")).buffer)
197
+ const meta = parseJSONStrict<CoarsePlacerMeta>(readFileSync(path.join(modelDir, "meta.json"), "utf8"))
198
+ const weightBytes = readFileSync(path.join(modelDir, "weights.bin"))
199
+
200
+ // Read through the Buffer's own window: `readFileSync` serves files under 4 KiB out of a shared 8 KiB pool, so
201
+ // `.buffer` alone would start at the pool's origin and run its full length — the wrong floats, and 2048 of them.
202
+ const W = new Float32Array(
203
+ weightBytes.buffer,
204
+ weightBytes.byteOffset,
205
+ weightBytes.byteLength / Float32Array.BYTES_PER_ELEMENT
206
+ )
207
+
197
208
  const bias = Float32Array.from(meta.bias)
198
209
  const C = meta.classes.length
199
210
  const D = meta.featureDim
@@ -229,17 +240,14 @@ export async function evalOpenSet(
229
240
  */
230
241
  const inVec = (z: Float64Array): number[] => IN.map((c) => z[c]!)
231
242
 
232
- function load(file: string): DataRow[] {
233
- return readFileSync(path.join(dataDir, file), "utf8")
234
- .trim()
235
- .split("\n")
236
- .map((l) => JSON.parse(l) as DataRow)
243
+ function load(file: string): Promise<DataRow[]> {
244
+ return Array.fromAsync(JSONSpliterator.fromAsync<DataRow>(path.join(dataDir, file)))
237
245
  }
238
246
 
239
247
  // Fit the Mahalanobis params on IN-MAP TRAIN logits (no test leak): per-class
240
248
  // mean in the nIn-dim in-map-logit space + a tied (shared) covariance.
241
249
  report?.("fitting Mahalanobis on in-map train logits…")
242
- const trainRows = load("train.jsonl")
250
+ const trainRows = await load("train.jsonl")
243
251
  const byClass = new Map<string, string[]>(COARSE_CLASSES.map((c): [string, string[]] => [c, []]))
244
252
 
245
253
  for (const r of trainRows) {
@@ -387,8 +395,8 @@ export async function evalOpenSet(
387
395
  }
388
396
  }
389
397
 
390
- const inmapTest = load("test.jsonl").filter((r) => r.country !== "OTHER") // the 11 countries only
391
- const heldout = load("test-latin-offmap.jsonl").filter((r) => r.group === "heldout")
398
+ const inmapTest = (await load("test.jsonl")).filter((r) => r.country !== "OTHER") // the 11 countries only
399
+ const heldout = (await load("test-latin-offmap.jsonl")).filter((r) => r.group === "heldout")
392
400
 
393
401
  const inmapScored = inmapTest.map((r) => scoreRow(r.raw, r.country))
394
402
  const heldoutScored = heldout.map((r) => scoreRow(r.raw, undefined))
@@ -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 } from "../coarse-placer.ts"
20
22
 
21
23
  interface TestRow {
@@ -74,7 +76,7 @@ export async function evalQuantCompare(options: EvalQuantCompareOptions = {}): P
74
76
  const dataDir = options.data || repoRootPath("data", "coarse-placer")
75
77
 
76
78
  function loadFp32(dir: string): CoarsePlacer {
77
- const meta = JSON.parse(readFileSync(path.join(dir, "meta.json"), "utf8")) as CoarsePlacerMeta
79
+ const meta = parseJSONStrict<CoarsePlacerMeta>(readFileSync(path.join(dir, "meta.json"), "utf8"))
78
80
  const buf = readFileSync(path.join(dir, "weights.bin"))
79
81
  const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
80
82
  const weights = new Float32Array(ab)
@@ -83,7 +85,7 @@ export async function evalQuantCompare(options: EvalQuantCompareOptions = {}): P
83
85
  }
84
86
 
85
87
  function loadInt8(dir: string): CoarsePlacer {
86
- const meta = JSON.parse(readFileSync(path.join(dir, "meta.json"), "utf8")) as CoarsePlacerMeta
88
+ const meta = parseJSONStrict<CoarsePlacerMeta>(readFileSync(path.join(dir, "meta.json"), "utf8"))
87
89
  const buf = readFileSync(path.join(dir, "weights.bin"))
88
90
  const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
89
91
  const int8 = new Int8Array(ab)
@@ -107,12 +109,9 @@ export async function evalQuantCompare(options: EvalQuantCompareOptions = {}): P
107
109
  const fp32 = loadFp32(fp32Dir)
108
110
  const int8 = loadInt8(int8Dir)
109
111
 
110
- const test: TestRow[] = readFileSync(path.join(dataDir, "test.jsonl"), "utf8")
111
- .trim()
112
- .split("\n")
113
- .map((l) => JSON.parse(l) as TestRow)
112
+ const test = await Array.fromAsync(JSONSpliterator.fromAsync<TestRow>(path.join(dataDir, "test.jsonl")))
114
113
 
115
- const classes = (JSON.parse(readFileSync(path.join(fp32Dir, "meta.json"), "utf8")) as CoarsePlacerMeta).classes
114
+ const classes = parseJSONStrict<CoarsePlacerMeta>(readFileSync(path.join(fp32Dir, "meta.json"), "utf8")).classes
116
115
  let okF = 0
117
116
  let okI = 0
118
117
  let agree = 0