@mailwoman/core 7.2.0 → 7.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/api/APIClient.ts +175 -0
  2. package/api/headless.ts +23 -0
  3. package/api/index.ts +11 -0
  4. package/api/responses.ts +135 -0
  5. package/coarse-placer/coarse-placer.ts +300 -0
  6. package/coarse-placer/featurize.ts +171 -0
  7. package/coarse-placer/tools/build-dataset.ts +223 -0
  8. package/coarse-placer/tools/build-outlier-exposure.ts +172 -0
  9. package/coarse-placer/tools/build-outlier-latin.ts +200 -0
  10. package/coarse-placer/tools/build-outlier-oa.ts +231 -0
  11. package/coarse-placer/tools/eval-latin-offmap.ts +140 -0
  12. package/coarse-placer/tools/eval-openset.ts +519 -0
  13. package/coarse-placer/tools/eval-quant-compare.ts +151 -0
  14. package/coarse-placer/tools/eval.ts +187 -0
  15. package/coarse-placer/tools/fnv-hash.ts +24 -0
  16. package/coarse-placer/tools/index.ts +23 -0
  17. package/coarse-placer/tools/probe-frontier.ts +216 -0
  18. package/coarse-placer/tools/quantize.ts +116 -0
  19. package/coarse-placer/tools/train.ts +244 -0
  20. package/collections.ts +134 -0
  21. package/db/schema.ts +21 -0
  22. package/decoder/build-tree.ts +228 -0
  23. package/decoder/calibration.ts +101 -0
  24. package/decoder/containment.ts +87 -0
  25. package/decoder/index.ts +17 -0
  26. package/decoder/proposals-to-tree.ts +83 -0
  27. package/decoder/resolve-proposal-overlaps.ts +79 -0
  28. package/decoder/serialize-json.ts +70 -0
  29. package/decoder/serialize-tuples.ts +61 -0
  30. package/decoder/serialize-xml.ts +209 -0
  31. package/decoder/types.ts +159 -0
  32. package/decoder/unknown-spans.ts +103 -0
  33. package/decoder/validate-tree.ts +100 -0
  34. package/env/index.ts +42 -0
  35. package/env/load.ts +14 -0
  36. package/env/paths.ts +40 -0
  37. package/env/schema.ts +125 -0
  38. package/errors/index.ts +9 -0
  39. package/errors/schema.ts +155 -0
  40. package/fs/node.ts +38 -0
  41. package/identifiers.ts +58 -0
  42. package/index.ts +13 -0
  43. package/kysley/adapter.ts +29 -0
  44. package/kysley/client.ts +30 -0
  45. package/kysley/dialect-config.ts +30 -0
  46. package/kysley/dialect.ts +67 -0
  47. package/kysley/driver.ts +175 -0
  48. package/layers/index.ts +12 -0
  49. package/layers/manifest.ts +154 -0
  50. package/layers/schema.ts +105 -0
  51. package/lifecycle/ServiceSymbol.ts +95 -0
  52. package/lifecycle/index.ts +11 -0
  53. package/lifecycle/lru-cache.ts +44 -0
  54. package/lifecycle/services.ts +322 -0
  55. package/locale/index.ts +9 -0
  56. package/locale/locale.ts +49 -0
  57. package/locale/profiles/en-us.ts +69 -0
  58. package/locale/profiles/fr-fr.ts +75 -0
  59. package/locale/profiles/index.ts +9 -0
  60. package/locale/profiles/ja-jp.ts +33 -0
  61. package/locale/registry.ts +68 -0
  62. package/logging/index.ts +8 -0
  63. package/logging/shared.ts +145 -0
  64. package/logging/utils.ts +46 -0
  65. package/objects.ts +211 -0
  66. package/package.json +195 -104
  67. package/pipeline/index.ts +46 -0
  68. package/pipeline/reconcile-lookups.ts +108 -0
  69. package/pipeline/reconcile.ts +542 -0
  70. package/pipeline/runtime-pipeline.ts +732 -0
  71. package/pipeline/span-logit-aggregation.ts +151 -0
  72. package/pipeline/span-proposer.ts +587 -0
  73. package/pipeline/types.ts +348 -0
  74. package/policy/defaults.ts +35 -0
  75. package/policy/index.ts +10 -0
  76. package/policy/policy.ts +60 -0
  77. package/policy/proposal-collection.ts +64 -0
  78. package/policy/registry.ts +149 -0
  79. package/resolver/index.ts +29 -0
  80. package/resolver/types.ts +584 -0
  81. package/resources/LocaleIndex.ts +124 -0
  82. package/resources/ResourceMapCache.ts +126 -0
  83. package/resources/collections.ts +93 -0
  84. package/resources/debugging.ts +19 -0
  85. package/resources/git.ts +54 -0
  86. package/resources/index.ts +17 -0
  87. package/resources/languages/index.ts +49 -0
  88. package/resources/languages/types.gen.ts +1368 -0
  89. package/resources/libaddressinput.ts +105 -0
  90. package/resources/libpostal.ts +182 -0
  91. package/resources/locale.ts +23 -0
  92. package/resources/set.ts +179 -0
  93. package/resources/whosonfirst/DataSourceCache.ts +72 -0
  94. package/resources/whosonfirst/PlacetypeDataSource.ts +199 -0
  95. package/resources/whosonfirst/index.ts +10 -0
  96. package/resources/whosonfirst/loader.ts +157 -0
  97. package/resources/whosonfirst/placetypes/Placetype.ts +438 -0
  98. package/resources/whosonfirst/placetypes/admin.ts +173 -0
  99. package/resources/whosonfirst/placetypes/definition.ts +135 -0
  100. package/resources/whosonfirst/placetypes/graph.ts +0 -0
  101. package/resources/whosonfirst/placetypes/index.ts +12 -0
  102. package/resources/whosonfirst/placetypes/mermaid.ts +168 -0
  103. package/resources/whosonfirst/placetypes/tree.ts +46 -0
  104. package/routing/index.ts +208 -0
  105. package/scripting/index.ts +40 -0
  106. package/scripting/utils/index.ts +106 -0
  107. package/tokenization/Graph.ts +50 -0
  108. package/tokenization/Span.ts +297 -0
  109. package/tokenization/index.ts +9 -0
  110. package/tokenization/normalizer.ts +123 -0
  111. package/tools/download-libpostal-resources.ts +98 -0
  112. package/tools/download-ssl-address.ts +99 -0
  113. package/tools/generate-language-types.ts +194 -0
  114. package/tools/index.ts +13 -0
  115. package/types/Classification.ts +211 -0
  116. package/types/classifier.ts +133 -0
  117. package/types/component.ts +75 -0
  118. package/types/index.ts +10 -0
  119. package/types/mapping.ts +81 -0
  120. package/utils/data-root.ts +56 -0
  121. package/utils/hash.ts +27 -0
  122. package/utils/index.ts +14 -0
  123. package/utils/jsonl.ts +43 -0
  124. package/utils/python-json.ts +105 -0
  125. package/utils/python-random.ts +90 -0
  126. package/utils/repo.ts +118 -0
  127. package/utils/sealed-db.ts +85 -0
  128. package/utils/stats.ts +32 -0
  129. package/vitest.config.ts +53 -0
@@ -0,0 +1,199 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ import { DatabaseSync, type DatabaseSyncOptions, type SQLInputValue } from "node:sqlite"
8
+
9
+ import {
10
+ Alpha2LanguageCode,
11
+ type Alpha3bLanguageCode,
12
+ Alpha3bToAlpha2,
13
+ isAlpha3bLanguageCode,
14
+ } from "@mailwoman/core/resources/languages"
15
+ import { PathBuilder, type PathBuilderLike } from "path-ts"
16
+
17
+ import { tryWithBackoff } from "./DataSourceCache.ts"
18
+ import type { WhosOnFirstPlacetype } from "./placetypes/definition.ts"
19
+
20
+ export interface PlacetypeDataSourceOptions<
21
+ P extends WhosOnFirstPlacetype = WhosOnFirstPlacetype,
22
+ L extends Alpha3bLanguageCode | Alpha2LanguageCode = Alpha3bLanguageCode,
23
+ > {
24
+ placetype: P
25
+ languageCode: L
26
+ dataDirectory: PathBuilderLike
27
+ }
28
+
29
+ export interface PlacetypeRecord {
30
+ /**
31
+ * The WhosOnFirst ID of the record.
32
+ */
33
+ id: number
34
+ /**
35
+ * The source of the record, e.g. "whosonfirst", "quattroshapes", etc.
36
+ */
37
+ src: string
38
+ /**
39
+ * The parent ID of the record
40
+ */
41
+ parent_id: number
42
+ /**
43
+ * The name of the record. This is the name of the record typically in English.
44
+ */
45
+ name: string
46
+ /**
47
+ * The preferred name of the record.
48
+ */
49
+ preferred: string | null
50
+ /**
51
+ * A common variant of the name.
52
+ */
53
+ variant: string | null
54
+ /**
55
+ * A colloquial usage of the name.
56
+ */
57
+ colloquial: string | null
58
+ /**
59
+ * An abbreviation of the name.
60
+ */
61
+ abbr: string | null
62
+ /**
63
+ * A short form of the name.
64
+ */
65
+ short: string | null
66
+ }
67
+
68
+ /**
69
+ * A data source for WhosOnFirst placetype records.
70
+ */
71
+ export class PlacetypeDataSource implements Disposable {
72
+ #db: DatabaseSync
73
+
74
+ public static createPath<P extends WhosOnFirstPlacetype, L extends Alpha3bLanguageCode | Alpha2LanguageCode>({
75
+ placetype,
76
+ languageCode,
77
+ dataDirectory,
78
+ }: Pick<PlacetypeDataSourceOptions<P, L>, "placetype" | "languageCode" | "dataDirectory">) {
79
+ const normalizedLanguageCode = isAlpha3bLanguageCode(languageCode)
80
+ ? Alpha3bToAlpha2.get(languageCode)
81
+ : languageCode
82
+
83
+ return PathBuilder.from(
84
+ dataDirectory,
85
+ placetype,
86
+ `${normalizedLanguageCode}.db`
87
+ ) as unknown as PathBuilder<`/${P}/${L}.db`>
88
+ }
89
+
90
+ public prepareTables(): void {
91
+ // Raw DDL by design: this runs in a synchronous construction path; Kysely's schema-builder is
92
+ // async, so migrating would force an async-factory refactor across every consumer. See AGENTS.md.
93
+ this.#db.exec(/* sql */ `
94
+
95
+ CREATE TABLE IF NOT EXISTS records (
96
+ 'id' INTEGER NOT NULL,
97
+ 'src' TEXT NOT NULL,
98
+ 'name' TEXT NOT NULL,
99
+ 'preferred' TEXT,
100
+ 'variant' TEXT,
101
+ 'colloquial' TEXT,
102
+ 'abbr' TEXT,
103
+ 'short' TEXT,
104
+ 'parent_id' INTEGER,
105
+ PRIMARY KEY ('id', 'src', 'name')
106
+ );
107
+ `)
108
+ }
109
+
110
+ public prepareIndexes(): void {
111
+ this.#db.exec(/* sql */ `
112
+
113
+ CREATE INDEX IF NOT EXISTS idx_id ON records ('id');
114
+ CREATE INDEX IF NOT EXISTS idx_src ON records ('src');
115
+ CREATE INDEX IF NOT EXISTS idx_name ON records ('name');
116
+ CREATE INDEX IF NOT EXISTS idx_preferred ON records ('preferred');
117
+ CREATE INDEX IF NOT EXISTS idx_variant ON records ('variant');
118
+ CREATE INDEX IF NOT EXISTS idx_colloquial ON records ('colloquial');
119
+ CREATE INDEX IF NOT EXISTS idx_abbr ON records ('abbr');
120
+ CREATE INDEX IF NOT EXISTS idx_short ON records ('short');
121
+ CREATE INDEX IF NOT EXISTS idx_parent_id ON records ('parent_id');
122
+ `)
123
+ }
124
+
125
+ constructor(databasePath: PathBuilderLike, dbOptions?: DatabaseSyncOptions) {
126
+ this.#db = dbOptions
127
+ ? new DatabaseSync(databasePath.toString(), dbOptions)
128
+ : new DatabaseSync(databasePath.toString())
129
+
130
+ // node:sqlite has no .pragma() helper; pragmas are executed as plain SQL.
131
+ this.#db.exec("PRAGMA busy_timeout = 10000")
132
+ this.#db.exec("PRAGMA journal_mode = WAL")
133
+ this.#db.exec("PRAGMA synchronous = OFF")
134
+
135
+ this.prepareTables()
136
+ //this.prepareIndexes()
137
+ }
138
+
139
+ public [Symbol.dispose]() {
140
+ this.#db.close()
141
+ }
142
+
143
+ /**
144
+ * Find a placetype record by at least one criteria.
145
+ */
146
+
147
+ public find(criteria: Partial<PlacetypeRecord>): IteratorObject<PlacetypeRecord> {
148
+ const statement = this.#db.prepare(/* sql */ `
149
+ SELECT *
150
+ FROM records
151
+ WHERE ${Object.keys(criteria)
152
+ .map((key) => `${key} = @${key}`)
153
+ .join(" OR ")}
154
+ `)
155
+
156
+ // node:sqlite's StatementSync.iterate() accepts named params via an object whose keys match
157
+ // the `@name` / `:name` / `$name` placeholders in the SQL.
158
+ return Iterator.from(
159
+ statement.iterate(criteria as unknown as Record<string, SQLInputValue>)
160
+ ) as unknown as IteratorObject<PlacetypeRecord>
161
+ }
162
+
163
+ /**
164
+ * Given a placetype record, insert or update into the database.
165
+ *
166
+ * @param record The placetype record to upsert.
167
+ */
168
+ public async upsert(record: PlacetypeRecord): Promise<void> {
169
+ const perform = () => {
170
+ const statement = this.#db.prepare(/* sql */ `
171
+ INSERT INTO records
172
+ (id, src, name, preferred, variant, colloquial, abbr, short, parent_id)
173
+ VALUES (
174
+ @id,
175
+ @src,
176
+ @name,
177
+ @preferred,
178
+ @variant,
179
+ @colloquial,
180
+ @abbr,
181
+ @short,
182
+ @parent_id
183
+ )
184
+ ON CONFLICT (id, src, name)
185
+ DO UPDATE SET
186
+ preferred = excluded.preferred,
187
+ variant = excluded.variant,
188
+ colloquial = excluded.colloquial,
189
+ abbr = excluded.abbr,
190
+ short = excluded.short,
191
+ parent_id = excluded.parent_id
192
+ `)
193
+
194
+ statement.run(record as unknown as Record<string, SQLInputValue>)
195
+ }
196
+
197
+ await tryWithBackoff(5, perform)
198
+ }
199
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ export * from "./DataSourceCache.ts"
8
+ export * from "./loader.ts"
9
+ export * from "./PlacetypeDataSource.ts"
10
+ export * from "./placetypes/index.ts"
@@ -0,0 +1,157 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ import type { Alpha3bLanguageCode } from "@mailwoman/core/resources/languages"
8
+ import { TextNormalizer } from "@mailwoman/core/tokenization"
9
+ import FastGlob, { type Entry } from "fast-glob"
10
+ import { PathBuilder, type PathBuilderLike } from "path-ts"
11
+ import { TextSpliterator } from "spliterator"
12
+
13
+ import type { Displayable } from "../debugging.ts"
14
+ import { ResourceMapCache } from "../ResourceMapCache.ts"
15
+ import { DisposableSet } from "../set.ts"
16
+ import { parsePlacetypeSource } from "./placetypes/admin.ts"
17
+
18
+ /**
19
+ * Index mapping a specific value to originating languages.
20
+ *
21
+ * If a value is present in this index, it means that the value is a valid value in at least one language.
22
+ */
23
+ export type WhosOnFirstLocaleIndex = Map<string, Set<string>>
24
+ export type ReadonlyWhosOnFirstIndex = ReadonlyMap<string, ReadonlySet<string>>
25
+
26
+ export interface WOFCacheOptions {
27
+ dataDirectory: PathBuilderLike
28
+ internalDataDirectory: PathBuilderLike
29
+ patterns: string[]
30
+ normalizer: TextNormalizer
31
+ blacklist?: Set<string>
32
+ }
33
+
34
+ /**
35
+ * Index mapping a specific **placename** to its originating languages.
36
+ *
37
+ * If a value is present in this index, it means that the value is a valid in at least one language.
38
+ */
39
+ export class WOFPlacenameCache extends ResourceMapCache<string, DisposableSet<Alpha3bLanguageCode>> {
40
+ normalizer: TextNormalizer
41
+ blacklist?: Set<string>
42
+ dataDirectory: PathBuilder
43
+ internalDataDirectory: PathBuilder
44
+ patterns: string[]
45
+
46
+ public override displayName = "wof"
47
+
48
+ constructor(options: WOFCacheOptions) {
49
+ super((_placename: string) => {
50
+ const nextLanguageSet: Displayable<DisposableSet<Alpha3bLanguageCode>> = new DisposableSet<Alpha3bLanguageCode>()
51
+
52
+ nextLanguageSet.displayName = this.displayName
53
+
54
+ return nextLanguageSet
55
+ })
56
+
57
+ this.normalizer = options?.normalizer
58
+ this.blacklist = options?.blacklist
59
+ this.dataDirectory = PathBuilder.from(options.dataDirectory)
60
+ this.internalDataDirectory = PathBuilder.from(options.internalDataDirectory)
61
+ this.patterns = options.patterns
62
+ }
63
+
64
+ /**
65
+ * Add a collection of language codes to a placename.
66
+ *
67
+ * @param placename The placename to add.
68
+ * @param languageCodes The language codes to add.
69
+ */
70
+ public add(placename: string, ...languageCodes: Alpha3bLanguageCode[]) {
71
+ if (this.normalizer) {
72
+ placename = this.normalizer.normalize(placename)
73
+
74
+ if (!this.normalizer.validate(placename)) return
75
+ }
76
+
77
+ if (!placename) return
78
+
79
+ if (this.blacklist?.has(placename)) return
80
+
81
+ const placenameIndex = this.open(placename)
82
+
83
+ for (const language of languageCodes) {
84
+ placenameIndex.add(language)
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Remove a placename from the index.
90
+ *
91
+ * @param placename The placename to remove.
92
+ */
93
+ public remove(placename: string): void {
94
+ if (this.normalizer) {
95
+ placename = this.normalizer.normalize(placename)
96
+ }
97
+
98
+ if (!placename) return
99
+
100
+ this.close(placename)
101
+ }
102
+
103
+ public async ready(): Promise<this> {
104
+ await this.marshall(this.patterns, this.dataDirectory)
105
+ await this.marshall(this.patterns, this.internalDataDirectory)
106
+
107
+ return this
108
+ }
109
+
110
+ public async marshall(filePatterns: string[], dataDirectory: PathBuilder): Promise<void> {
111
+ const globStream = FastGlob.stream(filePatterns, {
112
+ cwd: dataDirectory.toString(),
113
+ absolute: true,
114
+ objectMode: true,
115
+ }) as AsyncIterable<Entry>
116
+
117
+ for await (const fileEntry of globStream) {
118
+ const { languageCode = "eng" } = parsePlacetypeSource(fileEntry.name)
119
+
120
+ const lines = TextSpliterator.fromAsync(fileEntry.path)
121
+
122
+ for await (const line of lines) {
123
+ const row = line.trim()
124
+
125
+ if (!row.length) continue
126
+ const firstCharacter = row[0]
127
+
128
+ // Skip comments.
129
+ if (firstCharacter === "#") continue
130
+
131
+ // Are we removing a placename?
132
+ if (firstCharacter === "!") {
133
+ for (const placename of row.slice(1).split("|")) {
134
+ this.remove(placename)
135
+ }
136
+
137
+ continue
138
+ }
139
+
140
+ for (const placename of row.split("|")) {
141
+ this.remove(placename)
142
+ this.add(placename, languageCode)
143
+ }
144
+ }
145
+ }
146
+ }
147
+
148
+ public toJSON() {
149
+ const entries: Array<[string, Alpha3bLanguageCode[]]> = []
150
+
151
+ for (const [placename, languages] of this) {
152
+ entries.push([placename, Array.from(languages)])
153
+ }
154
+
155
+ return entries
156
+ }
157
+ }