@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,124 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ import { TextNormalizer } from "../tokenization/normalizer.ts"
8
+ import type { Displayable } from "./debugging.ts"
9
+
10
+ /**
11
+ * Options for the locale index.
12
+ */
13
+ export interface LocaleIndexOptions {
14
+ displayName: string
15
+ normalizer?: TextNormalizer
16
+ }
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 class LocaleIndex<LanguageCodes extends string> extends Map<string, Set<LanguageCodes>> {
24
+ /**
25
+ * The normalizer to use for placenames.
26
+ */
27
+ public readonly normalizer?: TextNormalizer
28
+
29
+ /**
30
+ * The source of the index.
31
+ */
32
+ public displayName: string
33
+
34
+ constructor(entries: Iterable<readonly [string, Iterable<LanguageCodes>]> = [], options: LocaleIndexOptions) {
35
+ super()
36
+
37
+ this.displayName = options?.displayName ?? "unknown"
38
+ this.normalizer = options?.normalizer
39
+
40
+ for (const [placename, languageCodes] of entries) {
41
+ this.add(placename, ...languageCodes)
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Add a placename to the index, associating it with the given language codes.
47
+ *
48
+ * @param placename The placename to add.
49
+ * @param languageCodes The language codes to associate with the placename.
50
+ */
51
+ public add(placename: string, ...languageCodes: LanguageCodes[]): void {
52
+ if (languageCodes.length === 0) {
53
+ throw new Error(`At least one language code must be provided for "${placename}".`)
54
+ }
55
+
56
+ if (this.normalizer) {
57
+ placename = this.normalizer.normalize(placename)
58
+
59
+ if (!this.normalizer.validate(placename)) return
60
+ }
61
+
62
+ if (!placename) return
63
+
64
+ const placenameIndex = this.open(placename)
65
+
66
+ placenameIndex.displayName = this.displayName
67
+
68
+ for (const language of languageCodes) {
69
+ placenameIndex.add(language)
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Remove a placename from the index.
75
+ *
76
+ * @param placename The placename to remove.
77
+ */
78
+ public remove(placename: string) {
79
+ if (this.normalizer) {
80
+ placename = this.normalizer.normalize(placename)
81
+ }
82
+
83
+ if (!placename) return
84
+
85
+ super.delete(placename)
86
+ }
87
+
88
+ public open(placename: string): Displayable<Set<LanguageCodes>> {
89
+ if (this.normalizer) {
90
+ placename = this.normalizer.normalize(placename)
91
+ }
92
+
93
+ if (!placename) {
94
+ throw new Error(`Placename "${placename}" is empty or invalid.`)
95
+ }
96
+
97
+ let placenameIndex: Displayable<Set<LanguageCodes>> | undefined = this.get(placename)
98
+
99
+ if (!placenameIndex) {
100
+ placenameIndex = new Set<LanguageCodes>()
101
+ this.set(placename, placenameIndex)
102
+ }
103
+
104
+ return placenameIndex
105
+ }
106
+
107
+ /**
108
+ * Get the language codes associated with a placename.
109
+ */
110
+ declare get: (placename: string) => Displayable<Set<LanguageCodes>> | undefined
111
+
112
+ /**
113
+ * Serialize the index to JSON.
114
+ */
115
+ public toJSON() {
116
+ const entries: Array<[string, LanguageCodes[]]> = []
117
+
118
+ for (const [placename, languages] of this) {
119
+ entries.push([placename, Array.from(languages)])
120
+ }
121
+
122
+ return entries
123
+ }
124
+ }
@@ -0,0 +1,126 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ /**
8
+ * A resource that can be disposed of either synchronously or asynchronously.
9
+ */
10
+ export type DisposableLike = Disposable | AsyncDisposable
11
+
12
+ export type ResourceConstructor<K extends PropertyKey, R extends DisposableLike> = new (key: K) => R
13
+ export type ResourceFactory<K extends PropertyKey, R extends DisposableLike> = (key: K) => R | Promise<R>
14
+
15
+ export type ResourceFactoryLike<K extends PropertyKey = PropertyKey, R extends DisposableLike = DisposableLike> =
16
+ | ResourceConstructor<K, R>
17
+ | ResourceFactory<K, R>
18
+
19
+ export type InferResource<F> =
20
+ F extends ResourceConstructor<infer _K, infer R> ? R : F extends ResourceFactory<infer _K, infer R> ? R : never
21
+
22
+ export type OpenResourceResult<F> =
23
+ F extends ResourceConstructor<infer _K, infer R>
24
+ ? R
25
+ : F extends ResourceFactory<infer _K, infer _R>
26
+ ? ReturnType<F>
27
+ : never
28
+
29
+ /**
30
+ * Type-guard to determine if a function is a constructor.
31
+ */
32
+ function isConstructor<T>(value: unknown): value is T {
33
+ if (typeof value !== "function") return false
34
+
35
+ return Boolean(value.prototype && value.prototype.constructor === value)
36
+ }
37
+
38
+ /**
39
+ * Type-guard to determine if a value is a promise-like object.
40
+ */
41
+ export function isPromiseLike<T>(value: unknown): value is PromiseLike<T> {
42
+ if (typeof value !== "object" || value === null) return false
43
+
44
+ return typeof (value as PromiseLike<T>).then === "function"
45
+ }
46
+
47
+ /**
48
+ * A map-like object that caches disposable resources, creating them on demand.
49
+ */
50
+ export class ResourceMapCache<
51
+ K extends PropertyKey = PropertyKey,
52
+ R extends DisposableLike = DisposableLike,
53
+ F extends ResourceFactoryLike<K, R> = ResourceConstructor<K, R>,
54
+ >
55
+ extends Map<K, R>
56
+ implements AsyncDisposable
57
+ {
58
+ /**
59
+ * The human-readable name of the resource.
60
+ */
61
+ public displayName: string = "ResourceMapCache"
62
+
63
+ protected readonly factoryLike: F
64
+
65
+ constructor(ResourceConstructor: ResourceConstructor<K, R>)
66
+ constructor(factory: ResourceFactory<K, R>)
67
+ constructor(factoryLike: F) {
68
+ super()
69
+
70
+ this.factoryLike = factoryLike
71
+ }
72
+
73
+ /**
74
+ * Gets a resource from the cache, creating if it doesn't exist.
75
+ */
76
+ public open(key: K): OpenResourceResult<F> {
77
+ const existingResource = super.get(key)
78
+
79
+ if (existingResource) return existingResource as OpenResourceResult<F>
80
+
81
+ if (isConstructor<ResourceConstructor<K, R>>(this.factoryLike)) {
82
+ const resource = new this.factoryLike(key)
83
+
84
+ super.set(key, resource)
85
+
86
+ return resource as OpenResourceResult<F>
87
+ }
88
+
89
+ const factoryResult = this.factoryLike(key)
90
+
91
+ if (isPromiseLike(factoryResult)) {
92
+ return factoryResult.then((resolvedResource) => {
93
+ super.set(key, resolvedResource)
94
+
95
+ return resolvedResource
96
+ }) as OpenResourceResult<F>
97
+ }
98
+
99
+ super.set(key, factoryResult)
100
+
101
+ return factoryResult as OpenResourceResult<F>
102
+ }
103
+
104
+ /**
105
+ * Closes a resource and removes it from the cache.
106
+ */
107
+ public close(key: K): void {
108
+ const resource = super.get(key)
109
+
110
+ if (resource && Symbol.dispose in resource) {
111
+ resource[Symbol.dispose]()
112
+ }
113
+
114
+ super.delete(key)
115
+ }
116
+
117
+ public async [Symbol.asyncDispose]() {
118
+ const resourceKeys = Array.from(super.keys()).reverse()
119
+
120
+ for (const resourceKey of resourceKeys) {
121
+ this.close(resourceKey)
122
+ }
123
+
124
+ super.clear()
125
+ }
126
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ /**
8
+ * Given an iterable collection, returns an async iterable, executing the callback on each batch.
9
+ *
10
+ * This is useful for batching asynchronous operations.
11
+ *
12
+ * @param collection The collection to batch.
13
+ * @param batchSize The size of each batch.
14
+ * @param callback The async callback to execute on each batch.
15
+ */
16
+ export async function* takeInParallel<T, C extends (entry: T) => Promise<unknown>>(
17
+ collection: Iterable<T> | AsyncIterable<T>,
18
+ batchSize: number,
19
+ callback: C,
20
+ abortSignal?: AbortSignal
21
+ ): AsyncIterable<Awaited<ReturnType<C>>> {
22
+ const iterator =
23
+ Symbol.asyncIterator in collection ? collection[Symbol.asyncIterator]() : collection[Symbol.iterator]()
24
+
25
+ const runningTasks = new Map<T, Promise<unknown>>()
26
+ const results = new Map<T, ReturnType<C>>()
27
+
28
+ let iterationResult = await iterator.next()
29
+
30
+ while ((!iterationResult.done || results.size) && !abortSignal?.aborted) {
31
+ for (const [key, result] of results) {
32
+ yield result
33
+
34
+ results.delete(key)
35
+ }
36
+
37
+ if (runningTasks.size >= batchSize) {
38
+ await Promise.race(runningTasks.values())
39
+ continue
40
+ }
41
+
42
+ if (iterationResult.done) {
43
+ await Promise.all(runningTasks.values())
44
+
45
+ break
46
+ }
47
+
48
+ const entry = iterationResult.value
49
+
50
+ const futureResult = callback(entry).then((result) => {
51
+ runningTasks.delete(entry)
52
+
53
+ results.set(entry, result as ReturnType<C>)
54
+ })
55
+
56
+ runningTasks.set(entry, futureResult)
57
+
58
+ iterationResult = await iterator.next()
59
+ }
60
+
61
+ if (!abortSignal || !abortSignal.aborted) {
62
+ await Promise.all(runningTasks.values())
63
+
64
+ for (const [key, result] of results) {
65
+ yield result
66
+
67
+ results.delete(key)
68
+ }
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Given an async iterable collection, returns an async iterable, yielding batches of items.
74
+ *
75
+ * This is useful for emitting asynchronous items in batches, such as when processing a stream of data.
76
+ */
77
+ export async function* takeAsync<T>(collection: AsyncIterable<T>, batchSize: number): AsyncIterable<T[]> {
78
+ let buffer: T[] = []
79
+
80
+ for await (const item of collection) {
81
+ buffer.push(item)
82
+
83
+ if (buffer.length === batchSize) {
84
+ yield buffer
85
+
86
+ buffer = []
87
+ }
88
+ }
89
+
90
+ if (buffer.length !== 0) {
91
+ yield buffer
92
+ }
93
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ /**
8
+ * A resource with a display name.
9
+ */
10
+ export type Displayable<T> = T & {
11
+ displayName?: string
12
+ }
13
+
14
+ /**
15
+ * Type predicate to determine if a value is displayable.
16
+ */
17
+ export function isDisplayable<T>(value: T): value is Displayable<T> {
18
+ return typeof value === "object" && value !== null && "displayName" in value
19
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ import { execFile } from "node:child_process"
8
+ import * as fs from "node:fs/promises"
9
+ import { promisify } from "node:util"
10
+
11
+ import { tryStat } from "@mailwoman/core/fs"
12
+ import { PathBuilder, type PathBuilderLike } from "path-ts"
13
+
14
+ const execFileAsync = promisify(execFile)
15
+
16
+ /**
17
+ * Metadata for a repository source.
18
+ */
19
+ export interface RepositorySource {
20
+ name: string
21
+ owner: string
22
+ url: string
23
+ }
24
+
25
+ export async function prepareRepositoryDirectories(
26
+ { name, owner }: RepositorySource,
27
+ localRepoDirectory: PathBuilderLike
28
+ ) {
29
+ const ownerDirectory = PathBuilder.from(localRepoDirectory, owner)
30
+ const repoDirectory = ownerDirectory(name)
31
+
32
+ await fs.mkdir(ownerDirectory.toString(), { recursive: true })
33
+
34
+ const exists = await tryStat(repoDirectory)
35
+
36
+ return { ownerDirectory, repoDirectory, exists }
37
+ }
38
+
39
+ /**
40
+ * Synchronize a repository source, i.e. clone or pull the repository.
41
+ */
42
+ export async function synchronizeRepo(source: RepositorySource, localRepoDirectory: PathBuilderLike): Promise<void> {
43
+ if (source.name.includes("deprecated")) return
44
+
45
+ const { ownerDirectory, repoDirectory, exists } = await prepareRepositoryDirectories(source, localRepoDirectory)
46
+
47
+ if (exists) {
48
+ await execFileAsync("git", ["pull"], { cwd: repoDirectory.toString() })
49
+
50
+ return
51
+ }
52
+
53
+ await execFileAsync("git", ["clone", "--depth=1", source.url], { cwd: ownerDirectory.toString() })
54
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ export * from "./collections.ts"
8
+ export * from "./debugging.ts"
9
+ export * from "./git.ts"
10
+ export * from "./languages/index.ts"
11
+ export * from "./libaddressinput.ts"
12
+ export * from "./libpostal.ts"
13
+ export * from "./locale.ts"
14
+ export * from "./LocaleIndex.ts"
15
+ export * from "./ResourceMapCache.ts"
16
+ export * from "./set.ts"
17
+ export * from "./whosonfirst/index.ts"
@@ -0,0 +1,49 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ export * from "./types.gen.ts"
8
+ import { Alpha2LabelMap, Alpha2LanguageCode, Alpha3bLabelMap, type Alpha3bLanguageCode } from "./types.gen.ts"
9
+
10
+ /**
11
+ * Prefixed languages are those which use a street prefix instead of a suffix.
12
+ */
13
+ export const prefixedLanguages: ReadonlySet<Alpha2LanguageCode | "all"> = new Set([
14
+ Alpha2LanguageCode.French,
15
+ Alpha2LanguageCode.Catalan,
16
+ Alpha2LanguageCode.Spanish,
17
+ Alpha2LanguageCode.Portuguese,
18
+ Alpha2LanguageCode.Romanian,
19
+ Alpha2LanguageCode.Polish,
20
+ ])
21
+
22
+ /**
23
+ * Type-predicate to determine if a string is a valid ISO 639-1 language code.
24
+ */
25
+ export function isAlpha2LanguageCode(value: string): value is Alpha2LanguageCode {
26
+ return Alpha2LabelMap.has(value as Alpha2LanguageCode)
27
+ }
28
+
29
+ /**
30
+ * Type-predicate to determine if a string is a valid ISO 639-2 language code.
31
+ */
32
+ export function isAlpha3bLanguageCode(value: string): value is Alpha3bLanguageCode {
33
+ return Alpha3bLabelMap.has(value as Alpha3bLanguageCode)
34
+ }
35
+
36
+ /**
37
+ * Pluck the language label from the language code.
38
+ */
39
+ export function pluckLanguageLabel(languageCodeLike: string, fallback: string = languageCodeLike): string {
40
+ if (isAlpha2LanguageCode(languageCodeLike)) {
41
+ return Alpha2LabelMap.get(languageCodeLike)![0]!
42
+ }
43
+
44
+ if (isAlpha3bLanguageCode(languageCodeLike)) {
45
+ return Alpha3bLabelMap.get(languageCodeLike)![0]!
46
+ }
47
+
48
+ return fallback
49
+ }