@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/resolver/types.ts CHANGED
@@ -65,6 +65,41 @@ export interface ResolvedPlace {
65
65
  * to score-based ordering.
66
66
  */
67
67
  prominence?: number
68
+ /**
69
+ * REFERENTIAL likelihood in [0, 1] — population-anchored, the named form of the key namesake ranking has always used
70
+ * (ROAD_TO_V9 §2, ratified 2026-08-06: "the importance of a knowledge-base article is not the probability that this
71
+ * is the place the user means"). Absent when the backend has no population for the place.
72
+ */
73
+ referential?: number
74
+ /**
75
+ * STRICT encyclopedia-evidence importance in [0, 1] — CARRIED FOR CONSUMERS, NEVER RANKED ON.
76
+ *
77
+ * RESERVED SLOT: it awaits a strict-channel source. Only a backend reading a post-split `place_importance` table can
78
+ * populate it, and today the FTS backend's clauses emit NULL for everything (no shipped admin DB carries the split
79
+ * columns), so nothing produces it and nothing consumes it. The BLENDED prior the ranking reads is
80
+ * {@link ResolvedPlace.importance} — keep the two apart.
81
+ *
82
+ * Ranking on this channel is forbidden even once populated. The canonical reason is Saint-Denis: the
83
+ * Seine-Saint-Denis suburb (pop 96,128) scores 0.1173 while the Aude hamlet (pop 418) scores 0.5683, so ranking on it
84
+ * inverts the answer every user means.
85
+ *
86
+ * Absent means "no encyclopedia entry" OR "this gazetteer predates the two-score split" — both absence, neither 0.
87
+ */
88
+ encyclopedic?: number
89
+ /**
90
+ * BLENDED global toponym prior in [0, 1] (#28) — the fame key the bare-toponym class is decided on.
91
+ *
92
+ * The value is the score source's legacy blended importance: the concordance's encyclopedia-derived channel where a
93
+ * concordance matched, a population-derived proxy everywhere else. The blend is deliberate — it is the only scale on
94
+ * which EVERY bearer of a name is scored comparably (the strict channel reaches eleven countries and is blind on
95
+ * CA/AU/RU, exactly the homonym contests the prior exists to settle; see `candidate-schema.ts` →
96
+ * `CandidateTable.importance`). Consumed by `rankByImportance` (`resolver/toponym-prior.ts`), a soft tier-safe
97
+ * re-rank, never a gate.
98
+ *
99
+ * Absent means UNMEASURED — the score source had no row, the join refused it, or the artifact predates the column —
100
+ * and an unmeasured candidate holds the rank population gave it (meaning-of-zero: never fill a 0 in).
101
+ */
102
+ importance?: number
68
103
  /**
69
104
  * Set by the backend when this candidate is an EXACT name/alias match for the query (vs a partial token match). The
70
105
  * postcode-anchor re-rank (#369) uses it as the PRIMARY key so a country posterior can pin the country WITHOUT
@@ -202,6 +237,13 @@ export interface ResolverBackend {
202
237
  * recovering localities the name-match alone misses. Backends without postcode support ignore it.
203
238
  */
204
239
  postcode?: string
240
+ /**
241
+ * Postcode-containment coherence (#31, Mechanism 2) — when set, a coordinate-first backend may re-rank locality
242
+ * candidates by distance to the sibling postcode's own centroid (bounded by a 25 km containment gate) instead of
243
+ * answering blind population-first. Opt-in, strictly beneath the #741 exact `(name_key, postcode)` probe; backends
244
+ * without postcode support ignore it.
245
+ */
246
+ postcodeContainmentCoherence?: boolean
205
247
  /**
206
248
  * Proximity-bias points — a SOFT prominence re-rank; backends without support ignore it.
207
249
  */
@@ -374,6 +416,42 @@ export interface StreetCentroidLookup {
374
416
  find(query: { street: string; postcode?: string; locality?: string }): StreetCentroidHit | null
375
417
  }
376
418
 
419
+ /**
420
+ * One admin-ancestry entry a PFX1 node asserts (coarsest-first: country → constituent country → district).
421
+ */
422
+ export interface PostcodePrefixAncestor {
423
+ placetype: string
424
+ wofID: number
425
+ name: string
426
+ }
427
+
428
+ /**
429
+ * A PFX1 postcode-prefix node — the partial-code prior's payload ({@link ResolveOpts.postcodePrefixPrior}, #31
430
+ * Mechanism 3). The coordinate is OPTIONAL and its absence is meaningful: an ancestry-only tier (NI's 80 BT districts)
431
+ * carries `ancestors` and no `lat`/`lon` — representable as absence, never as `0,0` (the meaning-of-zero rule).
432
+ * `radiusP95Km` is mandatory whenever a coordinate is present (M-3's receipt: a 1-digit US band and a GB outward code
433
+ * are both "a prefix with a centroid" and differ by 200×).
434
+ */
435
+ export interface PostcodePrefixNode {
436
+ prefix: string
437
+ ancestors: readonly PostcodePrefixAncestor[]
438
+ lat?: number
439
+ lon?: number
440
+ radiusP95Km?: number
441
+ unitCount: number
442
+ }
443
+
444
+ /**
445
+ * The PFX1 index the resolver probes — minimal, structural (`probe` + optional `country`), so `@mailwoman/resolver`
446
+ * consumes an index built in `@mailwoman/neural` without depending on it (B3-5: the partial-code prior touches zero
447
+ * model inputs). `country` is the ISO-3166 alpha-2 the index was built for (upper-case); the resolver only probes an
448
+ * index whose country matches the query's country scope.
449
+ */
450
+ export interface PostcodePrefixIndexLike {
451
+ probe(prefix: string): PostcodePrefixNode | null
452
+ readonly country?: string
453
+ }
454
+
377
455
  export interface ResolveOpts {
378
456
  /**
379
457
  * Hard cap on how many backend lookups one tree may issue. Default 10. Prevents a tree with dozens of candidate nodes
@@ -440,6 +518,39 @@ export interface ResolveOpts {
440
518
  * Only consulted when `anchorPosterior` is set.
441
519
  */
442
520
  anchorWeight?: number
521
+ /**
522
+ * #27 — the LOCALE's country as a SOFT ranking prior on the admin walk, for the one query shape that has no other
523
+ * country signal: a bare toponym.
524
+ *
525
+ * `--locale en-GB "Whitby"` and `--default-country GB "Whitby"` should not disagree, and they do: the second is gold
526
+ * and the first answers Whitby, Ontario, 5,508 km away. The #912 guard in the CLI is why — it drops the
527
+ * locale-inferred country entirely for a bare-locality tree, because as a HARD filter that country is a disaster
528
+ * (`--locale en-US "Zürich"` hard-scoped to US returns Zurich, Kansas, population 81). Dropping it is the right call
529
+ * for a filter and the wrong call for a prior, and this field is the third option: `rankByCountryPrior`
530
+ * (`resolver/toponym-prior.ts`) adds {@link localeCountryPriorWeight} to an in-country candidate's prominence, within
531
+ * the exact tier, never as a filter.
532
+ *
533
+ * **Undefined by default, and the CLI leaves it undefined** — this is an OPT-IN lever (`--locale-country-prior`), not
534
+ * a shipped default, and the reason is measured rather than cautious. In log10-population units the weight needed to
535
+ * flip the four bare GB panel rows is ≥ 0.99 (Whitby CA 5.11 over GB 4.12), and the weight that leaves the en-US
536
+ * board intact is < 0.07 (Cambridge CA 5.14 over US 5.07). The two intervals are disjoint, and they interleave:
537
+ * `Athens` (GR over US, gap 0.38) and `Cambridge` (0.07) sit BELOW `Warwick` (0.41) and `Epping` (0.41), so no
538
+ * threshold, margin or rank rule separates the class either. Population plus a locale cannot answer this question.
539
+ * The key that can is `importance` — the blended global toponym prior, which ranks all four the right way round and
540
+ * whose consumer (`rankByImportance`) is already wired here; the #28 candidate build produces it. See
541
+ * `scratchpad/resolver-plumbing-receipt-2026-08-10.md`.
542
+ *
543
+ * Ignored whenever a {@link defaultCountry} or an {@link anchorPosterior} is in force: a hard scope makes the prior a
544
+ * no-op by construction, and a posterior derived from the address's own postcode is EVIDENCE, which outranks a guess
545
+ * about where the user is sitting.
546
+ */
547
+ localeCountryPrior?: string
548
+ /**
549
+ * Weight of {@link localeCountryPrior}, in log10(population + 1) — the candidate backend's own `prominence` scale.
550
+ * Default `DEFAULT_COUNTRY_PRIOR_WEIGHT` (2): "the in-country place may be up to 100x smaller and still win". Only
551
+ * consulted when `localeCountryPrior` is set.
552
+ */
553
+ localeCountryPriorWeight?: number
443
554
  /**
444
555
  * #743/#194 — a CONFIDENT coarse-placer country applied as a HARD candidate filter (`query.country`), not the soft
445
556
  * {@link anchorPosterior} boost. This collapses the off-continent tail for LOW-population places the soft prior can't
@@ -585,6 +696,102 @@ export interface ResolveOpts {
585
696
  * re-picked or demoted. Default 50.
586
697
  */
587
698
  postcodeConsistencyGateKm?: number
699
+ /**
700
+ * Postcode-country coherence (#42) — the ONLY mechanism permitted to override {@link defaultCountry}, and the only
701
+ * one that runs BEFORE the walk rather than re-picking after it.
702
+ *
703
+ * `12 Rue de Rivoli, 75001 Paris` under the en-US locale resolves to Paris, **Texas**: the locale's region subtag
704
+ * becomes `defaultCountry: "US"`, the backend turns that into a hard `spr.country = 'US'` filter, and the candidate
705
+ * pool is all-US before ranking begins — so a coarse placer that called the address FR at confidence 0.9999908844 has
706
+ * nothing to promote (a soft re-rank downstream of a hard filter is inert by construction). With the postal shards
707
+ * attached it degrades further: the postcode resolves to ZIP 75001 (Addison TX) and {@link postcodeConsistency} then
708
+ * drags the locality onto that point.
709
+ *
710
+ * The postcode's SHAPE cannot settle this — `75001` is a valid US ZIP, French CP and German PLZ, and the gazetteer
711
+ * holds the literal string in four countries. Its GEOMETRY can: this pass asks, per candidate country from codex's
712
+ * shape test, whether the postcode resolves there AND a same-named locality sits within
713
+ * {@link postcodeCountryCoherenceGateKm} of it — then scopes the whole walk to the country where the pair is
714
+ * consistent. Measured over 800 real pairs (400 US ZIP+city, 400 FR CP+commune): **zero** border crossings at both
715
+ * the 15 km and 25 km gates.
716
+ *
717
+ * Soft by construction, per the positive-evidence-only rule: the caller's `defaultCountry` is tested FIRST and a
718
+ * coherent default always wins (returning immediately, ≤2 lookups, byte-identical walk), and both zero coherent
719
+ * countries and two-or-more abstain. It fires only when a `defaultCountry` is in force AND the tree carries both a
720
+ * postcode and a locality AND the default cannot make them consistent.
721
+ *
722
+ * **Default ON** (operator-promoted 2026-08-05 after the D-rule evidence in
723
+ * `docs/records/evals/2026-08-05-postcode-coherence-default-on-evidence.md`: the standard gauntlet run pinned both
724
+ * ways produced ZERO newly-failing gated cases — 65/68 either way, the same three unrelated failures — and 56,000
725
+ * pair evaluations across BOTH backends (28,000 FTS + 28,000 candidate; OpenAddresses US/FR + OSM GB, domestic and
726
+ * mis-scoped legs) returned zero false positives. The rescue leg fixes ~9 in 10 mis-scoped defaults. Set `false` to
727
+ * opt out (byte-stable then). Costs 2 lookups on the byte-stable path, at most 8 when it fires.
728
+ *
729
+ * Reach is bounded by codex's `candidateSystemsForPostcode` and the attached gazetteer: measured 2026-08-05 it can
730
+ * speak for US/DE/FR/GB on the production FTS shard set and additionally CA/AU on the candidate table; JP and NZ have
731
+ * a codex slice with no postcode rows behind it, so the pass abstains there at the cost of its two lookups.
732
+ */
733
+ postcodeCountryCoherence?: boolean
734
+ /**
735
+ * Gate radius (km) for {@link postcodeCountryCoherence} — how near a same-named locality must sit to the resolved
736
+ * postcode to count that country as consistent. Default 25 (what the 800-pair scale run measured; the confound board
737
+ * returned identical verdicts at 15, 25 and 50, so the pass is not gate-tuned).
738
+ */
739
+ postcodeCountryCoherenceGateKm?: number
740
+ /**
741
+ * Postcode-shape coherence (#31, Mechanism 1, `resolver/postcode-shape-coherence.ts`) — shape as CONFIDENCE and
742
+ * EXCLUSION, downstream of the siblings. The decoder sometimes tags a HOUSE NUMBER as `postcode` when its digits form
743
+ * a foreign postcode shape ("1200" in a Longmont CO address is accepted only by the AU/NZ 4-digit shape while every
744
+ * sibling placetype says US). This pre-walk pass intersects each postcode span's codex candidate systems with the
745
+ * systems the tree's country / region / `country_hint` siblings assert: a non-empty intersection CONFIRMS the span
746
+ * (additive `postcode_shape_systems` stamp, byte-identical resolution); an empty intersection with confident siblings
747
+ * EXCLUDES it (a digit-only span is demoted to `house_number`, a letter-bearing one keeps its tag with a
748
+ * `postcode_shape_excluded` stamp — either way the span's contribution to the resolve is stripped); no confident
749
+ * siblings ABSTAIN. `defaultCountry` is never evidence (B1-3's confound: "Sydney NSW 2000, Australia" reached with a
750
+ * US default must not have its 2000 excluded — that row is exactly what {@link postcodeCountryCoherence} rescues).
751
+ * Confirmed spans narrow the country-scope pass's candidate list to the intersection (a pure subset, safe).
752
+ *
753
+ * **Default OFF** (D-rule: demotion is the failure mode with teeth — a default-on promotion needs the full B1 gate
754
+ * set from `docs/superpowers/plans/2026-08-05-postcode-structure-arc.md`: B1-1 byte-stability, B1-2 exclusion board
755
+ * ≥90% with the correct sibling tag surviving, B1-3 confound ≤2% false exclusions, kill on any δ).
756
+ */
757
+ postcodeShapeCoherence?: boolean
758
+ /**
759
+ * Postcode-containment coherence (#31, Mechanism 2) — the reverse arrow, generalized. When a locality-wanting query
760
+ * carries a postcode and the #741 exact `(name_key, postcode)` probe misses, a coordinate-first backend resolves the
761
+ * postcode's centroid once and re-ranks the name candidates by distance to it, bounded by a 25 km containment gate —
762
+ * "Paris TX 75460" and "Paris 75001" differ by which candidate the postcode is near, and the population ranking
763
+ * cannot see that. Strictly beneath the #741 short-circuit (B2-1: byte-identical wherever the fast path fires); no
764
+ * in-gate candidate → unchanged (B2-2's postcode-removed arm). Rides `FindPlaceQuery.postcodeContainmentCoherence` to
765
+ * the backend.
766
+ *
767
+ * **Default OFF.** The promotion decision must measure it JOINTLY with {@link postcodeConsistency} (B2-3: the arms
768
+ * agree on ≥98%), because this rung partially subsumes #370 — the compliant outcome may be that mechanism 2 replaces
769
+ * it rather than joining it. B2-4: one postcode lookup per locality miss, ≤15% p95 latency.
770
+ */
771
+ postcodeContainmentCoherence?: boolean
772
+ /**
773
+ * Postcode-prefix prior (#31, Mechanism 3) — the partial-code prior for postcodes the full-code gazetteer does not
774
+ * carry (#1480's abstention, e.g. a BT unit with no permissive source behind it). When a `postalcode` lookup misses
775
+ * AND a {@link postcodePrefixIndex} for the query's country is supplied, derive the code's prefix (GB: outward — the
776
+ * compact form minus its trailing 3 unit chars; US: the first 3 digits) and probe the index. A hit resolves the node
777
+ * from the prefix's centroid and/or ancestry: `metadata.postcode_prefix`, `postcode_prefix_ancestors` (+
778
+ * `postcode_prefix_radius_p95_km` when the artifact measured one), and `coordinate_source: "postcode_prefix"` only
779
+ * when the node actually carries a coordinate — an ancestry-only tier (NI's 80 BT districts) contributes its DISTRICT
780
+ * and stays coordinate-free (the meaning-of-zero rule; inventing a BT centroid would reproduce the `BT3 9QQ` →
781
+ * Sheffield defect #1480 just fixed).
782
+ *
783
+ * **Default OFF** (D-rule + the PCN1 posture: data + loader + offline probe, no decode wiring; the header ships
784
+ * without `delta` until a calibration measures one). B3-5: the probe touches zero model inputs — the index is a
785
+ * structural type (`PostcodePrefixIndexLike`), injected, never imported from `@mailwoman/neural`.
786
+ */
787
+ postcodePrefixPrior?: boolean
788
+ /**
789
+ * The PFX1 postcode-prefix index to probe when {@link postcodePrefixPrior} is on — injected by the pipeline (loaded
790
+ * from `$MAILWOMAN_DATA_ROOT/postcode-prefix/postcode-prefix-<cc>.bin`), never constructed here. Structural
791
+ * (`PostcodePrefixIndexLike`), so the resolver consumes an index built in `@mailwoman/neural` without depending on it
792
+ * (B3-5).
793
+ */
794
+ postcodePrefixIndex?: PostcodePrefixIndexLike
588
795
  /**
589
796
  * Admin descendant-consistency (#263). When a region resolved but its child locality did NOT — the greedy region pick
590
797
  * (name + population) chose a foreign namesake whose descendants hold no such locality ("Portland, ME" → Messina IT;
@@ -4,7 +4,6 @@
4
4
  * @author Teffen Ellis, et al.
5
5
  */
6
6
 
7
- export * from "./collections.ts"
8
7
  export * from "./debugging.ts"
9
8
  export * from "./git.ts"
10
9
  export * from "./languages/index.ts"
@@ -12,10 +12,9 @@ import type { Alpha2LanguageCode } from "@mailwoman/core/resources/languages"
12
12
  import { TextNormalizer, type TextNormalizerInit } from "@mailwoman/core/tokenization"
13
13
  import type { PathBuilder } from "path-ts"
14
14
  import pluralize from "pluralize"
15
- import { TextSpliterator } from "spliterator"
15
+ import { AsyncSequence, TextSpliterator } from "spliterator"
16
16
 
17
17
  import { resourceDictionaryPathBuilder } from "../utils/repo.ts"
18
- import { takeAsync } from "./collections.ts"
19
18
  import { LocaleIndex } from "./LocaleIndex.ts"
20
19
 
21
20
  const batchSize = availableParallelism()
@@ -104,7 +103,10 @@ export async function prepareLocaleIndex(
104
103
 
105
104
  // Default resolves lazily (#481 — the former TLA value).
106
105
  const codes = languageCodes ?? (await getAvailableLanguages())
107
- const fileEntries = takeAsync(findFilesMatchingLocale(filename, libPostalDataDirectory, codes), batchSize)
106
+
107
+ const fileEntries = AsyncSequence.from(findFilesMatchingLocale(filename, libPostalDataDirectory, codes)).chunks(
108
+ batchSize
109
+ )
108
110
 
109
111
  for await (const batch of fileEntries) {
110
112
  await Promise.all(
@@ -122,10 +124,9 @@ export async function prepareLocaleIndex(
122
124
  )
123
125
  }
124
126
 
125
- const internalFileEntries = takeAsync(
126
- findFilesMatchingLocale(filename, libPostalInternalDataDirectory, codes),
127
- batchSize
128
- )
127
+ const internalFileEntries = AsyncSequence.from(
128
+ findFilesMatchingLocale(filename, libPostalInternalDataDirectory, codes)
129
+ ).chunks(batchSize)
129
130
 
130
131
  for await (const batch of internalFileEntries) {
131
132
  await Promise.all(
@@ -7,4 +7,5 @@
7
7
  export * from "./DataSourceCache.ts"
8
8
  export * from "./loader.ts"
9
9
  export * from "./PlacetypeDataSource.ts"
10
+ export * from "./sharded-repo.ts"
10
11
  export * from "./placetypes/index.ts"
@@ -6,11 +6,12 @@
6
6
 
7
7
  import * as fs from "node:fs/promises"
8
8
 
9
+ import { parseJSONStrict } from "@mailwoman/core/objects"
10
+ import { prepareRepositoryDirectories, type RepositorySource } from "@mailwoman/core/resources"
9
11
  import FastGlob from "fast-glob"
10
12
  import type { PathBuilder } from "path-ts"
13
+ import { parallelMap } from "spliterator"
11
14
 
12
- import { takeInParallel } from "../../collections.ts"
13
- import { prepareRepositoryDirectories, type RepositorySource } from "../../git.ts"
14
15
  import {
15
16
  normalizePlacetypeDefinition,
16
17
  type PlacetypeDefinition,
@@ -79,14 +80,18 @@ export class Placetype implements Disposable {
79
80
  absolute: true,
80
81
  })
81
82
 
82
- const batchIterator = takeInParallel(definitionPaths, batchSize, async (definitionPath) => {
83
- const definitionContent = await fs.readFile(definitionPath, "utf8")
84
- const definition: PlacetypeDefinition = JSON.parse(definitionContent)
83
+ const batchIterator = parallelMap(
84
+ definitionPaths,
85
+ async (definitionPath) => {
86
+ const definitionContent = await fs.readFile(definitionPath, "utf8")
87
+ const definition = parseJSONStrict<PlacetypeDefinition>(definitionContent)
85
88
 
86
- Placetype.register(definition)
89
+ Placetype.register(definition)
87
90
 
88
- return definition
89
- })
91
+ return definition
92
+ },
93
+ { concurrency: batchSize }
94
+ )
90
95
 
91
96
  await Array.fromAsync(batchIterator)
92
97
  }
@@ -11,7 +11,7 @@ import {
11
11
  isAlpha2LanguageCode,
12
12
  isAlpha3bLanguageCode,
13
13
  } from "@mailwoman/core/resources/languages"
14
- import type { Feature, Geometry } from "geojson"
14
+ import type { GeoFeature, GeometryLiteral } from "@mailwoman/spatial"
15
15
 
16
16
  import type { WhosOnFirstPlacetype } from "./definition.ts"
17
17
 
@@ -26,6 +26,12 @@ export interface WOFBaseProperties {
26
26
  "wof:supersedes"?: number[]
27
27
  "wof:country"?: string
28
28
  "wof:concordances"?: Record<string, string | number>
29
+ /**
30
+ * Every ancestor chain the place belongs to, coarsest key first — `[{ country_id, region_id, locality_id }, …]`. More
31
+ * than one entry means the place has multiple parents, which is what `wof:parent_id` records as the `-4` sentinel;
32
+ * the keys present vary by branch, so a missing rung is absent rather than null.
33
+ */
34
+ "wof:hierarchy"?: Array<Record<string, number>>
29
35
  "wof:population"?: number
30
36
  "wof:lastmodified"?: number
31
37
  "geom:latitude"?: number
@@ -55,7 +61,10 @@ export type WOFLanguageProperties = Partial<Record<LanguageSpecificKey, string |
55
61
 
56
62
  export type WOFProperties = WOFBaseProperties & WOFLanguageProperties
57
63
 
58
- export type WOFFeature = Feature<Geometry, WOFProperties>
64
+ /**
65
+ * A single record from the Who's On First GeoJSON distribution.
66
+ */
67
+ export type WOFFeature = GeoFeature<GeometryLiteral, WOFProperties>
59
68
 
60
69
  type LocalizedPlacetypePropMap = Map<WOFNameKind, string>
61
70
 
@@ -100,6 +109,7 @@ export function pluckPlacetypeSpec({
100
109
  "wof:supersedes": supersedes,
101
110
  "wof:country": country,
102
111
  "wof:concordances": concordances,
112
+ "wof:hierarchy": _hierarchy,
103
113
  "wof:population": wofPopulation,
104
114
  "wof:lastmodified": lastmodified,
105
115
  "geom:latitude": latitude,
@@ -0,0 +1,69 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Reading a place out of a cloned Who's On First data repo.
7
+ *
8
+ * WOF stores each record at a path derived from its own id: the decimal id split into three-character directories,
9
+ * then `<id>.geojson`. `85977539` lives at `859/775/39/85977539.geojson`. The rule is not written down in the data —
10
+ * it is layout knowledge every reader has to carry — so it lives here once, next to the {@link WOFFeature} type the
11
+ * parsed record has.
12
+ */
13
+
14
+ import { existsSync, readFileSync } from "node:fs"
15
+
16
+ import { tryParsingJSON } from "@mailwoman/core/objects"
17
+ import { resolvePath } from "path-ts"
18
+
19
+ import type { WOFFeature } from "./placetypes/admin.ts"
20
+
21
+ /**
22
+ * Characters per directory level. A trailing group shorter than this is its own directory — `85977539` ends in `39`,
23
+ * not `390`.
24
+ */
25
+ const ID_CHUNK = 3
26
+
27
+ /**
28
+ * A WOF id → its repo-relative path segments, ending in `<id>.geojson`.
29
+ *
30
+ * Segments rather than a joined string so a caller can append them to whatever root it already holds — the repos layout
31
+ * puts a `data` directory under each `whosonfirst-data-*` clone, and callers reach it differently.
32
+ */
33
+ export function wofIDPathSegments(id: number): string[] {
34
+ const digits = String(id)
35
+ const segments: string[] = []
36
+
37
+ for (let i = 0; i < digits.length; i += ID_CHUNK) {
38
+ segments.push(digits.slice(i, i + ID_CHUNK))
39
+ }
40
+
41
+ segments.push(`${digits}.geojson`)
42
+
43
+ return segments
44
+ }
45
+
46
+ /**
47
+ * Read a place's GeoJSON from the first `root` that holds it, or `null` when no root does or the file will not parse.
48
+ *
49
+ * `null` conflates "absent" with "unparseable" on purpose: every caller so far treats both as "no evidence for this
50
+ * place" and continues. A caller that needs to tell them apart should read the file itself.
51
+ */
52
+ export function readWOFFeature(id: number, roots: readonly string[]): WOFFeature | null {
53
+ const segments = wofIDPathSegments(id)
54
+
55
+ for (const root of roots) {
56
+ const path = resolvePath(root, ...segments)
57
+
58
+ if (!existsSync(path)) continue
59
+
60
+ try {
61
+ return tryParsingJSON<WOFFeature>(readFileSync(path, "utf8"))
62
+ } catch {
63
+ // The file vanished or turned unreadable between existsSync and the read — same "no evidence" verdict.
64
+ return null
65
+ }
66
+ }
67
+
68
+ return null
69
+ }
@@ -1,8 +1,7 @@
1
+ import { ResourceError } from "@mailwoman/core/errors"
2
+ import { ConsoleLogger } from "@mailwoman/core/logging"
1
3
  import { defaultRegistry } from "async-init"
2
4
 
3
- import { ResourceError } from "../../errors/index.ts"
4
- import { ConsoleLogger } from "../../logging/index.ts"
5
-
6
5
  /**
7
6
  * Logs an error that occurred while running a script.
8
7
  */
@@ -41,6 +41,7 @@ const DICTIONARIES_DIR = resourceDictionaryPath("libpostal")
41
41
  async function sortFileInPlace(path: string): Promise<void> {
42
42
  const text = await readFile(path, "utf8")
43
43
  const hadTrailingNewline = text.endsWith("\n")
44
+ // oxlint-disable-next-line mailwoman/prefer-spliterator -- Sorting needs every line resident; the largest libpostal dictionary is 409 KB.
44
45
  const lines = text.split("\n")
45
46
 
46
47
  // Drop the empty element produced by a trailing newline so it isn't re-sorted as a blank line.
@@ -9,10 +9,10 @@
9
9
  * Usage: mailwoman dev generate language-types
10
10
  */
11
11
 
12
- import { createReadStream } from "node:fs"
13
12
  import * as fs from "node:fs/promises"
14
13
 
15
14
  import { pascalCase } from "change-case"
15
+ import { CSVSpliterator } from "spliterator"
16
16
 
17
17
  import { repoRootPath, resourceDictionaryPath } from "../utils/index.ts"
18
18
 
@@ -50,19 +50,10 @@ export async function generateLanguageTypes(
50
50
 
51
51
  report?.(`Reading ${dataSourcePath}`)
52
52
 
53
- // csv-parse is an optional peer — lazy import (the pipeline convention).
54
- const csv = await import("csv-parse")
55
-
56
- const parser = csv.parse({
57
- delimiter: ",",
58
- columns: false,
59
- skip_empty_lines: true,
60
- from_line: 2,
61
- })
62
-
63
- const stream = createReadStream(dataSourcePath).pipe(parser)
64
-
65
- for await (const columns of stream) {
53
+ // Quote handling is on and load-bearing: six labels wrap an embedded comma
54
+ // (`gre,el,"Greek, Modern (1453-)"`), and the spliterator leaves quoting off by default.
55
+ // `header` defaults true, which is what skips the `alpha3-b,alpha2,English` line.
56
+ for await (const columns of CSVSpliterator.fromAsync(dataSourcePath, { enableQuoteHandling: true })) {
66
57
  const alpha3b = columns[0] as string
67
58
  const alpha2 = columns[1] as string
68
59
  const labelsConcatenated = columns[2] as string
@@ -38,13 +38,29 @@ export function dataRootPath(...segments: string[]): string {
38
38
 
39
39
  /**
40
40
  * The default WOF shard list the FTS backend probes when no single `--wof-db` is given: the global admin-priority shard
41
- * + the US postcode shard + the GeoNames-postal tail shard (#920 — postcode coverage for the namesake-tail locales
42
- * FI/CZ/SK/SI/DK/NO/HR/PL; country-aware routing in `pickShardForPlacetype` sends each postcode query to the shard that
43
- * claims its country). All under `dataRoot` (defaults to the configured {@link mailwomanDataRoot}; callers thread a
44
- * `--data-root` option through). A fresh array each call; callers filter with `existsSync`, so a deployment without the
45
- * tail shard degrades to the pre-#920 pair.
41
+ * plus the postcode shards, with country-aware routing in `pickShardForPlacetype` sending each postcode query to the
42
+ * shard that claims its country (#920). All under `dataRoot` (defaults to the configured {@link mailwomanDataRoot};
43
+ * callers thread a `--data-root` option through). A fresh array each call; callers filter with `existsSync`, so a
44
+ * deployment missing any of them degrades to whatever is present.
45
+ *
46
+ * This list is DELIBERATELY SMALLER than `DEFAULT_POSTCODE_SHARDS` (`mailwoman/gazetteer-pipeline/index.ts`), which is
47
+ * the set the candidate gazetteer is BUILT from — twenty-odd shards including the 876 MB Code-Point Open GB one. These
48
+ * are attached live per query, so the cost of a member is paid at every boot rather than once at build time; membership
49
+ * here is earned by a shard the runtime cannot resolve its locales without.
50
+ *
51
+ * Two notes on specific members, because both look like mistakes and are not:
52
+ *
53
+ * - The tail shard's own contents moved on 2026-08-05. It carried GB (1,839,678 of 1,895,753 rows, ~946 MB) until
54
+ * Code-Point Open replaced those rows under a clean licence; it is now the nine-country namesake set
55
+ * FI/CZ/SK/SI/DK/NO/HR/PL/SE at 26 MB. Rebuild: `mailwoman gazetteer build postcode-geonames`.
56
+ * - `postalcode-ni-osm.db` is **build-local**: OSM `addr:postcode` under ODbL, never published, so on any machine that
57
+ * did not build it the `existsSync` filter simply drops it and GB postcode queries behave as they did before. It is
58
+ * listed rather than special-cased because that filter IS the tier's enforcement. It is also the only GB-claiming
59
+ * shard in this list — the Code-Point Open shard is not here — so nothing competes with it for `BT` routing.
46
60
  */
47
- export function wofShardPaths(dataRoot: string = mailwomanDataRoot()): [string, string, string, string, string] {
61
+ export function wofShardPaths(
62
+ dataRoot: string = mailwomanDataRoot()
63
+ ): [string, string, string, string, string, string] {
48
64
  // TODO: Redo this as an object.
49
65
  return [
50
66
  resolvePath(dataRoot, "wof", "admin-global-priority.db"),
@@ -54,5 +70,10 @@ export function wofShardPaths(dataRoot: string = mailwomanDataRoot()): [string,
54
70
  // #977: the NL PC6 full-postcode shard (CBS via PDOK; scripts/build-postalcode-nl-pc6.ts) — the
55
71
  // data the lookup's NL PC6 ladder ("1012 LG" → joined "1012LG" → 4-digit stem) resolves against.
56
72
  resolvePath(dataRoot, "wof", "postalcode-nl-pc6.db"),
73
+ // Northern Ireland (BT) from OpenStreetMap — 4,757 of 50,032 live NI postcodes (9.5 %), the only
74
+ // coverage that exists for the hole Code-Point Open leaves. ODbL, build-local, 2.5 MB. A miss on a
75
+ // BT code means NOT ATTESTED IN OSM; since #1480 an unknown postcode abstains, so the shard is
76
+ // strictly additive. Rebuild: `mailwoman gazetteer build postcode-ni-osm`.
77
+ resolvePath(dataRoot, "wof", "postalcode-ni-osm.db"),
57
78
  ]
58
79
  }
package/utils/hash.ts CHANGED
@@ -46,3 +46,12 @@ export async function md5File(path: string): Promise<string> {
46
46
 
47
47
  return hash.digest("hex")
48
48
  }
49
+
50
+ /**
51
+ * MD5 of in-memory content, hex-encoded — the {@link md5File} counterpart for a string that never becomes a file. Same
52
+ * provenance-only rationale, and the same non-security caveat: it exists so a query text, a manifest line or a config
53
+ * blob can be fingerprinted with the SAME algorithm as the files recorded beside it in one `meta` table.
54
+ */
55
+ export function md5Hex(data: string | NodeJS.ArrayBufferView): string {
56
+ return createHash("md5").update(data).digest("hex")
57
+ }
package/utils/index.ts CHANGED
@@ -8,6 +8,7 @@ export * from "./data-root.ts"
8
8
  export * from "./hash.ts"
9
9
  export * from "./jsonl.ts"
10
10
  export * from "./python-json.ts"
11
+ export * from "./python-numeric.ts"
11
12
  export * from "./python-random.ts"
12
13
  export * from "./repo.ts"
13
14
  export * from "./sealed-db.ts"
package/utils/jsonl.ts CHANGED
@@ -3,9 +3,14 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  *
6
- * JSON Lines helpers — the canonical home for the `split("\n") + JSON.parse` idiom that was
7
- * re-rolled across ~88 scripts (2026-07-09 dedupe survey). `iterateJSONL` streams via spliterator
8
- * for files too large to slurp.
6
+ * JSON Lines helpers, all three DEPRECATED — `spliterator` covers the whole surface, and a thin
7
+ * wrapper in front of it only hides which half you are getting.
8
+ *
9
+ * - `readJSONL` → `Array.fromAsync(JSONSpliterator.fromAsync<T>(path))`
10
+ * - `iterateJSONL` → `JSONSpliterator.fromAsync<T>(path)`
11
+ * - `writeJSONL` → `createNewlineWriter(path)`
12
+ *
13
+ * Kept exported because `@mailwoman/core` is published; they go in the next major.
9
14
  */
10
15
 
11
16
  import { readFileSync, writeFileSync } from "node:fs"
@@ -14,16 +19,26 @@ import { TextSpliterator } from "spliterator"
14
19
 
15
20
  /**
16
21
  * Read an entire JSONL file into memory. Blank and whitespace-only lines are skipped.
22
+ *
23
+ * @deprecated Use `Array.fromAsync(JSONSpliterator.fromAsync<T>(path))` from `spliterator`. This buffers the whole file
24
+ * as one string, which throws `ERR_STRING_TOO_LONG` past V8's 512 MiB cap.
17
25
  */
18
26
  export function readJSONL<T>(path: string): T[] {
19
- return readFileSync(path, "utf8")
20
- .split("\n")
21
- .filter((line) => line.trim().length > 0)
22
- .map((line) => JSON.parse(line) as T)
27
+ // The whole-buffer read and the throw-on-corrupt parse are both part of the shipped contract this
28
+ // function is deprecated FOR; rewriting either would change what remaining callers get.
29
+ return (
30
+ [...TextSpliterator.from(readFileSync(path, "utf8"))]
31
+ .filter((line) => line.trim().length > 0)
32
+ // oxlint-disable-next-line no-restricted-properties
33
+ .map((line) => JSON.parse(line) as T)
34
+ )
23
35
  }
24
36
 
25
37
  /**
26
38
  * Write rows as JSONL (one `JSON.stringify` per line, trailing newline). Returns the row count.
39
+ *
40
+ * @deprecated Use `createNewlineWriter(path)` from `spliterator`. This concatenates every row into one string before it
41
+ * writes anything, so the output is capped the same way the input is.
27
42
  */
28
43
  export function writeJSONL(path: string, rows: Iterable<unknown>): number {
29
44
  let count = 0
@@ -42,10 +57,14 @@ export function writeJSONL(path: string, rows: Iterable<unknown>): number {
42
57
 
43
58
  /**
44
59
  * Stream a JSONL file row-by-row without loading it whole. Blank lines are skipped.
60
+ *
61
+ * @deprecated Use `JSONSpliterator.fromAsync<T>(path)` from `spliterator` — this is a decode-then-parse wrapper around
62
+ * exactly that.
45
63
  */
46
64
  export async function* iterateJSONL<T>(path: string): AsyncIterable<T> {
47
65
  for await (const line of TextSpliterator.fromAsync(path)) {
48
66
  if (!line.trim()) continue
67
+ // oxlint-disable-next-line no-restricted-properties -- Throw-on-corrupt is this function's shipped contract.
49
68
  yield JSON.parse(line) as T
50
69
  }
51
70
  }