@mailwoman/core 7.1.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 (149) 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/out/layers/index.d.ts +12 -0
  67. package/out/layers/index.d.ts.map +1 -0
  68. package/out/layers/index.js +12 -0
  69. package/out/layers/index.js.map +1 -0
  70. package/out/layers/manifest.d.ts +64 -0
  71. package/out/layers/manifest.d.ts.map +1 -0
  72. package/out/layers/manifest.js +102 -0
  73. package/out/layers/manifest.js.map +1 -0
  74. package/out/layers/schema.d.ts +72 -0
  75. package/out/layers/schema.d.ts.map +1 -0
  76. package/out/layers/schema.js +61 -0
  77. package/out/layers/schema.js.map +1 -0
  78. package/out/pipeline/index.d.ts +1 -1
  79. package/out/pipeline/index.d.ts.map +1 -1
  80. package/out/pipeline/runtime-pipeline.d.ts.map +1 -1
  81. package/out/pipeline/runtime-pipeline.js +27 -0
  82. package/out/pipeline/runtime-pipeline.js.map +1 -1
  83. package/out/pipeline/types.d.ts +74 -4
  84. package/out/pipeline/types.d.ts.map +1 -1
  85. package/out/pipeline/types.js.map +1 -1
  86. package/package.json +21 -21
  87. package/pipeline/index.ts +46 -0
  88. package/pipeline/reconcile-lookups.ts +108 -0
  89. package/pipeline/reconcile.ts +542 -0
  90. package/pipeline/runtime-pipeline.ts +732 -0
  91. package/pipeline/span-logit-aggregation.ts +151 -0
  92. package/pipeline/span-proposer.ts +587 -0
  93. package/pipeline/types.ts +348 -0
  94. package/policy/defaults.ts +35 -0
  95. package/policy/index.ts +10 -0
  96. package/policy/policy.ts +60 -0
  97. package/policy/proposal-collection.ts +64 -0
  98. package/policy/registry.ts +149 -0
  99. package/resolver/index.ts +29 -0
  100. package/resolver/types.ts +584 -0
  101. package/resources/LocaleIndex.ts +124 -0
  102. package/resources/ResourceMapCache.ts +126 -0
  103. package/resources/collections.ts +93 -0
  104. package/resources/debugging.ts +19 -0
  105. package/resources/git.ts +54 -0
  106. package/resources/index.ts +17 -0
  107. package/resources/languages/index.ts +49 -0
  108. package/resources/languages/types.gen.ts +1368 -0
  109. package/resources/libaddressinput.ts +105 -0
  110. package/resources/libpostal.ts +182 -0
  111. package/resources/locale.ts +23 -0
  112. package/resources/set.ts +179 -0
  113. package/resources/whosonfirst/DataSourceCache.ts +72 -0
  114. package/resources/whosonfirst/PlacetypeDataSource.ts +199 -0
  115. package/resources/whosonfirst/index.ts +10 -0
  116. package/resources/whosonfirst/loader.ts +157 -0
  117. package/resources/whosonfirst/placetypes/Placetype.ts +438 -0
  118. package/resources/whosonfirst/placetypes/admin.ts +173 -0
  119. package/resources/whosonfirst/placetypes/definition.ts +135 -0
  120. package/resources/whosonfirst/placetypes/graph.ts +0 -0
  121. package/resources/whosonfirst/placetypes/index.ts +12 -0
  122. package/resources/whosonfirst/placetypes/mermaid.ts +168 -0
  123. package/resources/whosonfirst/placetypes/tree.ts +46 -0
  124. package/routing/index.ts +208 -0
  125. package/scripting/index.ts +40 -0
  126. package/scripting/utils/index.ts +106 -0
  127. package/tokenization/Graph.ts +50 -0
  128. package/tokenization/Span.ts +297 -0
  129. package/tokenization/index.ts +9 -0
  130. package/tokenization/normalizer.ts +123 -0
  131. package/tools/download-libpostal-resources.ts +98 -0
  132. package/tools/download-ssl-address.ts +99 -0
  133. package/tools/generate-language-types.ts +194 -0
  134. package/tools/index.ts +13 -0
  135. package/types/Classification.ts +211 -0
  136. package/types/classifier.ts +133 -0
  137. package/types/component.ts +75 -0
  138. package/types/index.ts +10 -0
  139. package/types/mapping.ts +81 -0
  140. package/utils/data-root.ts +56 -0
  141. package/utils/hash.ts +27 -0
  142. package/utils/index.ts +14 -0
  143. package/utils/jsonl.ts +43 -0
  144. package/utils/python-json.ts +105 -0
  145. package/utils/python-random.ts +90 -0
  146. package/utils/repo.ts +118 -0
  147. package/utils/sealed-db.ts +85 -0
  148. package/utils/stats.ts +32 -0
  149. package/vitest.config.ts +53 -0
package/env/schema.ts ADDED
@@ -0,0 +1,125 @@
1
+ import { z } from "zod"
2
+
3
+ /**
4
+ * Non-secret operational config, exposed via `$public`. Add a key here to make it visible to the runtime; anything not
5
+ * listed is stripped from `process.env` on parse.
6
+ */
7
+ export const PublicEnvSchema = z.object({
8
+ // `.catch` (not `.default`) so an unknown value never throws — vitest sets NODE_ENV=test, CI may set others.
9
+ NODE_ENV: z.enum(["development", "production", "test"]).catch("development"),
10
+ CI: z.coerce.boolean().default(false),
11
+
12
+ // Gazetteer / resolver database paths. CLI flags (`--resolve-db`, …) override these at the call site.
13
+ MAILWOMAN_WOF_DB: z.string().optional(),
14
+ MAILWOMAN_WOF_ADMIN_DB: z.string().optional(),
15
+ MAILWOMAN_WOF_POLYGONS_DB: z.string().optional(),
16
+ MAILWOMAN_CANDIDATE_DB: z.string().optional(),
17
+ MAILWOMAN_POSTAL_CITY_ALIAS_DB: z.string().optional(),
18
+ MAILWOMAN_FST_BIN: z.string().optional(),
19
+ MAILWOMAN_MODEL_CARD: z.string().optional(),
20
+ MAILWOMAN_COARSE_PLACER_DIR: z.string().optional(),
21
+ WOF_DATA_DIR: z.string().optional(),
22
+
23
+ // Geocode server batch row cap (`POST /v1/batch`).
24
+ //
25
+ // `MAILWOMAN_BATCH_CONCURRENCY` was REMOVED 2026-07-16 — it was inert. In-process concurrency
26
+ // cannot overlap a geocode: `onnxruntime-node`'s `session.run()` blocks the JS thread instead of
27
+ // releasing to the libuv pool, and `node:sqlite` reads are synchronous. Measured 1.00x flat from
28
+ // 1→16 workers on both parse and full geocode. Don't reintroduce it without re-measuring; worker
29
+ // threads (see `mailwoman/geocode-stream.ts`) are the only lever that moves this in Node.
30
+ // Receipts: `docs/articles/plan/reference/performance.mdx`.
31
+ MAILWOMAN_BATCH_MAX: z.coerce.number().int().positive().default(1000),
32
+
33
+ // The gazetteer/model data root (`core/utils/data-root.ts`, `scripts/copy-weights.ts`).
34
+ MAILWOMAN_DATA_ROOT: z.string().optional(),
35
+
36
+ // Corpus source-fetch tools (`corpus/src/tools/fetch/*` — env knobs are now command flags; these remain for compat). Callers do their own numeric/boolean parsing on these,
37
+ // so they stay raw strings — the schema only gates which keys surface, not how they're coerced.
38
+ OUT_ROOT: z.string().optional(),
39
+ NAD_MODE: z.string().optional(),
40
+ NAD_URL: z.string().optional(),
41
+ FS_END_OID: z.string().optional(),
42
+ FS_START_OID: z.string().optional(),
43
+ FS_CHUNK_SIZE: z.string().optional(),
44
+ FS_PAGE_SIZE: z.string().optional(),
45
+ FS_CONCURRENCY: z.string().optional(),
46
+ SKIP_STATE_FIPS: z.string().optional(),
47
+ RATE_SLEEP: z.string().optional(),
48
+ MAX_PARALLEL: z.string().optional(),
49
+ DRY_RUN: z.string().optional(),
50
+
51
+ // Python training driver (`corpus-python/scripts/train_with_resume.ts`) + build resume (`corpus/src/build.ts`).
52
+ MAX_ATTEMPTS: z.string().optional(),
53
+ LOG: z.string().optional(),
54
+ CONFIG: z.string().optional(),
55
+ PYTHON: z.string().optional(),
56
+ MAILWOMAN_RESUME: z.string().optional(),
57
+
58
+ // Weights dev-linking + release copy (`neural-weights-*/scripts/link-dev-weights.ts`, `scripts/copy-weights.ts`).
59
+ MAILWOMAN_DEV_MODEL: z.string().optional(),
60
+ MAILWOMAN_DEV_TOKENIZER: z.string().optional(),
61
+ MAILWOMAN_PUBLISH_MODEL: z.string().optional(),
62
+ MAILWOMAN_PUBLISH_TOKENIZER: z.string().optional(),
63
+ MAILWOMAN_SKIP_WEIGHTS_COPY: z.string().optional(),
64
+
65
+ // Release-it publish flow (`scripts/publish-workspace.ts`). The OTP is a secret — see `$private`.
66
+ MAILWOMAN_SKIP_WEIGHTS: z.string().optional(),
67
+ MAILWOMAN_NPM_PROVENANCE: z.string().optional(),
68
+ RELEASE_IT_WORKSPACES_PATH_TO_WORKSPACE: z.string().optional(),
69
+ RELEASE_IT_WORKSPACES_TAG: z.string().optional(),
70
+ RELEASE_IT_WORKSPACES_ACCESS: z.string().optional(),
71
+ RELEASE_IT_WORKSPACES_DRY_RUN: z.string().optional(),
72
+
73
+ // Demo resolver (`docs/plugins/demo-assets/resolve.ts`) + docs driver.
74
+ PLAYPEN_WOF_ADMIN_DB: z.string().optional(),
75
+ PLAYPEN_WOF_POSTCODE_DB: z.string().optional(),
76
+ SLIM_COUNTRIES: z.string().optional(),
77
+ MAILWOMAN_DOCS_URL: z.string().optional(),
78
+
79
+ // Eval scripts (`scripts/eval/*`) — diagnostic toggles + DB/probe overrides.
80
+ MAILWOMAN_WOF_HOT_DB: z.string().optional(),
81
+ /** Override the admin gazetteer used by the default-country test panel. */
82
+ MAILWOMAN_WOF_GLOBAL_DB: z.string().optional(),
83
+ /** Deployed demo URL for the docs e2e suite (skips the local build+serve machinery). */
84
+ MAILWOMAN_DEMO_URL: z.string().optional(),
85
+ /** Override the ONNX model exercised by the neural test suites. */
86
+ MAILWOMAN_TEST_ONNX_MODEL: z.string().optional(),
87
+ /** Override the ONNX model exercised by the capability gate. */
88
+ MAILWOMAN_CAPABILITY_ONNX_MODEL: z.string().optional(),
89
+ MAILWOMAN_DIAG_INTERP: z.string().optional(),
90
+ MAILWOMAN_DUMP_MISS_TAG: z.string().optional(),
91
+ MAILWOMAN_WORD_CONSISTENCY: z.string().optional(),
92
+ MW_DUMP_REGRESSIONS: z.string().optional(),
93
+ PROBE_N: z.string().optional(),
94
+ DEBUG: z.string().optional(),
95
+ })
96
+
97
+ /**
98
+ * Secrets and credentials, exposed via `$private`. Never log these. Add a key here to make it available; anything not
99
+ * listed is stripped from `process.env` on parse.
100
+ */
101
+ export const PrivateEnvSchema = z.object({
102
+ HF_BUCKET_URI: z.string().optional(),
103
+ HF_ORG_NAME: z.string().optional(),
104
+ HF_BUCKET_NAME: z.string().optional(),
105
+ HF_BUCKET_RESOLVE_URL: z.url().optional(),
106
+ HF_TOKEN: z.string().min(1, "HF_TOKEN required").optional(),
107
+
108
+ CF_AUTH_TOKEN: z.string().optional(),
109
+ GEOCODE_EARTH_API_KEY: z.string().optional(),
110
+
111
+ // LLM API keys for the corpus golden-expansion tooling.
112
+ DEEPSEEK_API_KEY: z.string().optional(),
113
+ ANTHROPIC_API_KEY: z.string().optional(),
114
+
115
+ // R2/S3 upload credentials for `tiles publish` (rclone `:s3:` remote).
116
+ RCLONE_S3_ENDPOINT: z.string().optional(),
117
+ RCLONE_S3_ACCESS_KEY_ID: z.string().optional(),
118
+ RCLONE_S3_SECRET_ACCESS_KEY: z.string().optional(),
119
+
120
+ // OpenAddresses batch-download API token (`corpus/src/tools/fetch/openaddresses.ts`).
121
+ OA_BATCH_TOKEN: z.string().optional(),
122
+
123
+ // npm 2FA OTP for the release publish flow (`scripts/publish-workspace.ts`).
124
+ RELEASE_IT_WORKSPACES_OTP: z.string().optional(),
125
+ })
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @copyright Sister Software.
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Utilities for working with errors.
7
+ */
8
+
9
+ export * from "./schema.ts"
@@ -0,0 +1,155 @@
1
+ /**
2
+ * @copyright Sister Software.
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ import type { StatusCodes } from "http-status-codes"
8
+
9
+ /**
10
+ * Type-helper to extract the status code from a `ResourceError`.
11
+ */
12
+ export type ExtractResourceErrorStatusCode<T> = T extends ResourceError<infer S> ? S : never
13
+
14
+ const kResourceError = "_kResourceError"
15
+
16
+ /**
17
+ * An entity registered with the Federal Communications Commission (FCC) that provides telecommunications services.
18
+ */
19
+ export class ResourceError<S extends StatusCodes = StatusCodes> extends Error {
20
+ static DefaultStatus = 500
21
+ static DefaultMessage = "An unknown error occurred."
22
+
23
+ // public readonly $schema = $ResourceError.pathname
24
+
25
+ public [kResourceError] = true
26
+
27
+ static override [Symbol.hasInstance](input: unknown): input is ResourceError {
28
+ if (!input) return false
29
+
30
+ if (typeof input !== "object") return false
31
+
32
+ if (kResourceError in input) return true
33
+
34
+ return false
35
+ }
36
+
37
+ static from<S extends StatusCodes = StatusCodes>(
38
+ statusCode: S,
39
+ message: string,
40
+ ...urnSegments: string[]
41
+ ): ResourceError<S> {
42
+ return new ResourceError(statusCode, urnSegments.length ? urnSegments.join(":") : "unknown", message)
43
+ }
44
+
45
+ /**
46
+ * Given an error, wraps it in a ResourceError instance.
47
+ */
48
+ static wrap<E extends Error>(
49
+ error: E,
50
+ message?: string,
51
+ ...urnSegments: string[]
52
+ ): E extends ResourceError<infer ActualStatusCode> ? ResourceError<ActualStatusCode> : ResourceError
53
+ /**
54
+ * Given a possible instance of `Error`, wraps it in a `ResourceError` instance.
55
+ *
56
+ * Note that if the error is already an instance of `ResourceError`, it will be returned as-is.
57
+ */
58
+ static wrap<S extends StatusCodes>(error: unknown, message?: string, ...urnSegments: string[]): ResourceError<S>
59
+
60
+ /**
61
+ * Given a possible instance of `Error`, wraps it in a `ResourceError` instance.
62
+ *
63
+ * Note that if the error is already an instance of `ResourceError`, it will be returned as-is.
64
+ */
65
+
66
+ static wrap(error: unknown, message: string, ...urnSegments: string[]) {
67
+ if (error instanceof ResourceError) {
68
+ return error as ResourceError
69
+ }
70
+
71
+ let status = this.DefaultStatus
72
+
73
+ if (error instanceof Error) {
74
+ message ||= error.message || this.DefaultMessage
75
+
76
+ if ("status" in error) {
77
+ switch (typeof error.status) {
78
+ case "number":
79
+ status = error.status
80
+ break
81
+ case "string":
82
+ status = parseInt(error.status, 10) || this.DefaultStatus
83
+ break
84
+ }
85
+ }
86
+ } else {
87
+ message ||= this.DefaultMessage
88
+ }
89
+
90
+ const wrapper = this.from(status, message, ...urnSegments)
91
+ wrapper.cause = error
92
+
93
+ return wrapper
94
+ }
95
+
96
+ public get [Symbol.toStringTag]() {
97
+ return `ResourceError<${this.name}>`
98
+ }
99
+
100
+ /**
101
+ * @title HTTP status code.
102
+ *
103
+ * A numeric status code conforming to the HTTP standard.
104
+ */
105
+ status: S
106
+ /**
107
+ * @title Error message.
108
+ *
109
+ * A human-readable error message explaining the error.
110
+ */
111
+ override message!: string
112
+
113
+ /**
114
+ * @title URN identifier.
115
+ *
116
+ * A unique identifier for the error, used to reference it in logs and other systems.
117
+ *
118
+ * @format uri
119
+ */
120
+ override name: string
121
+
122
+ constructor(status: S = 500 as S, urn: string, message = "An unknown error occurred.") {
123
+ super(message)
124
+
125
+ this.message = message
126
+ this.name = urn || [status, "nexus", "isp"].join(":")
127
+ this.status = status
128
+ }
129
+
130
+ public toJSON() {
131
+ return {
132
+ name: this.name,
133
+ status: this.status,
134
+ message: this.message,
135
+ }
136
+ }
137
+
138
+ public override toString(): string {
139
+ const messageSegments: string[] = [`[${this.status}] (${this.name}) ${this.message}`]
140
+
141
+ if (this.cause instanceof Error && this.cause.message && this.cause !== this) {
142
+ messageSegments.push(`\nCaused by: ${this.cause.message}`)
143
+ }
144
+
145
+ return messageSegments.join("\n")
146
+ }
147
+ }
148
+
149
+ /**
150
+ * @public
151
+ * @title Resource Error
152
+ *
153
+ * An error response from a resource, such as an API, database, or file.
154
+ */
155
+ export type ResourceErrorSchema = Pick<ResourceError, "status" | "message" | "name">
package/fs/node.ts ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ import type { PathLike, Stats } from "node:fs"
8
+ import { existsSync } from "node:fs"
9
+ import { stat } from "node:fs/promises"
10
+
11
+ import type { PathBuilderLike } from "path-ts"
12
+
13
+ /**
14
+ * Attempts to stat a file or directory.
15
+ *
16
+ * @throws If the path exists but cannot be statted for some reason other than non-existence.
17
+ */
18
+ export function tryStat(pathBuilderLike: PathBuilderLike): Promise<Stats | null> {
19
+ return stat(pathBuilderLike.toString()).catch((err) => {
20
+ if (err.code === "ENOENT") return null
21
+
22
+ throw err
23
+ })
24
+ }
25
+
26
+ /**
27
+ * Whether a path exists and is a directory.
28
+ */
29
+ export async function isDirectory(path: PathBuilderLike): Promise<boolean> {
30
+ return tryStat(path)
31
+ .then((stats) => stats?.isDirectory() ?? false)
32
+ .catch((err) => {
33
+ if (err.code === "ENOENT") return false
34
+ throw err
35
+ })
36
+ }
37
+
38
+ export { existsSync }
package/identifiers.ts ADDED
@@ -0,0 +1,58 @@
1
+ /**
2
+ * @copyright Sister Software.
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+ import { camelCase, capitalCase, snakeCase } from "change-case"
7
+ import type { CamelCase, SnakeCase } from "type-fest"
8
+
9
+ /**
10
+ * Converts a name to snake_case, unless the name is already in all caps.
11
+ */
12
+ export function smartSnakeCase<T extends string>(name: T): T extends Uppercase<T> ? T : SnakeCase<T> {
13
+ const normalizedName = name
14
+ // Remove periods after capital letters, e.g. "U.S.A." -> "USA"
15
+ .replace(/([A-Z])(\.+)/g, "$1")
16
+ .trim()
17
+
18
+ if (normalizedName.toUpperCase() === normalizedName) {
19
+ return (
20
+ normalizedName
21
+ // Replace all non-word characters with underscores...
22
+ .replace(/\W{1,}/g, "_")
23
+ // ...and then replace all sequences of underscores with a single underscore.
24
+ .replace(/_{2,}/g, "_") as T extends Uppercase<T> ? T : SnakeCase<T>
25
+ )
26
+ }
27
+
28
+ return snakeCase(normalizedName) as T extends Uppercase<T> ? T : SnakeCase<T>
29
+ }
30
+
31
+ /**
32
+ * Converts a name to camelCase, unless the name is already in all caps.
33
+ */
34
+ export function smartCamelCase<T extends string>(name: T): T extends Uppercase<T> ? T : CamelCase<T> {
35
+ if (name.toUpperCase() === name) {
36
+ return name as T extends Uppercase<T> ? T : CamelCase<T>
37
+ }
38
+
39
+ return camelCase(name) as T extends Uppercase<T> ? T : CamelCase<T>
40
+ }
41
+
42
+ /**
43
+ * Predicate to determine if a given string is uniformly cased, i.e. all uppercase or all lowercase.
44
+ */
45
+ export function isUniformlyCased(input: string | null): boolean {
46
+ return Boolean(input && (input === input.toUpperCase() || input === input.toLowerCase()))
47
+ }
48
+
49
+ /**
50
+ * Capitalizes a string, unless the string is uniformly cased, or an email address.
51
+ */
52
+ export function smartCapitalCase(input: string): string {
53
+ if (input.includes("@")) return input
54
+
55
+ if (isUniformlyCased(input)) return input
56
+
57
+ return capitalCase(input)
58
+ }
package/index.ts ADDED
@@ -0,0 +1,13 @@
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 "./decoder/index.ts"
9
+ export * from "./identifiers.ts"
10
+ export * from "./pipeline/index.ts"
11
+ export * from "./resources/index.ts"
12
+ export * from "./tokenization/index.ts"
13
+ export * from "./types/index.ts"
@@ -0,0 +1,29 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ import { DialectAdapterBase, Kysely, type MigrationLockOptions } from "kysely"
8
+
9
+ export class SqliteAdapter extends DialectAdapterBase {
10
+ override get supportsTransactionalDdl(): boolean {
11
+ return false
12
+ }
13
+
14
+ override get supportsReturning(): boolean {
15
+ return true
16
+ }
17
+
18
+ override async acquireMigrationLock(_db: Kysely<unknown>, _opt: MigrationLockOptions): Promise<void> {
19
+ // SQLite only has one connection that's reserved by the migration system
20
+ // for the whole time between acquireMigrationLock and releaseMigrationLock.
21
+ // We don't need to do anything here.
22
+ }
23
+
24
+ override async releaseMigrationLock(_db: Kysely<unknown>, _opt: MigrationLockOptions): Promise<void> {
25
+ // SQLite only has one connection that's reserved by the migration system
26
+ // for the whole time between acquireMigrationLock and releaseMigrationLock.
27
+ // We don't need to do anything here.
28
+ }
29
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ import { Kysely, type KyselyConfig } from "kysely"
8
+
9
+ import type { Database } from "../db/schema.ts"
10
+ import type { SqliteDialectConfig } from "./dialect-config.ts"
11
+ import { SqliteDialect } from "./dialect.ts"
12
+
13
+ /**
14
+ * A Kysely client for SQLite that uses the `node:sqlite` library.
15
+ *
16
+ * Generic over the schema: pass a concrete `Database` interface (`new DatabaseClient<MySchema>(...)`) for compile-time
17
+ * table typing, or omit it for the empty default. See `core/db/schema.ts`.
18
+ */
19
+ export class DatabaseClient<DB = Database> extends Kysely<DB> implements Disposable {
20
+ constructor(dialectConfig: SqliteDialectConfig, config?: Partial<KyselyConfig>) {
21
+ super({
22
+ ...config,
23
+ dialect: new SqliteDialect(dialectConfig),
24
+ })
25
+ }
26
+
27
+ [Symbol.dispose](): void {
28
+ this.destroy()
29
+ }
30
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ import type { DatabaseSync } from "node:sqlite"
8
+
9
+ import type { DatabaseConnection } from "kysely"
10
+
11
+ /**
12
+ * Config for the SQLite dialect.
13
+ */
14
+ export interface SqliteDialectConfig {
15
+ /**
16
+ * A node:sqlite DatabaseSync instance or a function that returns one.
17
+ *
18
+ * If a function is provided, it's called once when the first query is executed.
19
+ *
20
+ * https://nodejs.org/api/sqlite.html#class-databasesync
21
+ */
22
+ database: InstanceType<typeof DatabaseSync> | (() => Promise<InstanceType<typeof DatabaseSync>>)
23
+
24
+ /**
25
+ * Called once when the first query is executed.
26
+ *
27
+ * This is a Kysely specific feature and does not come from the `node:sqlite` module.
28
+ */
29
+ onCreateConnection?: (connection: DatabaseConnection) => Promise<void>
30
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ import {
8
+ SqliteAdapter,
9
+ SqliteIntrospector,
10
+ SqliteQueryCompiler,
11
+ type DatabaseIntrospector,
12
+ type Dialect,
13
+ type DialectAdapter,
14
+ type Driver,
15
+ type Kysely,
16
+ type QueryCompiler,
17
+ } from "kysely"
18
+
19
+ import type { SqliteDialectConfig } from "./dialect-config.ts"
20
+ import { SqliteDriver } from "./driver.ts"
21
+
22
+ /**
23
+ * SQLite dialect that uses the [`node:sqlite`](https://nodejs.org/api/sqlite.html) library.
24
+ *
25
+ * The constructor takes an instance of {@link SqliteDialectConfig}.
26
+ *
27
+ * ```ts
28
+ * import { DatabaseSync } from "node:sqlite"
29
+ *
30
+ * new SqliteDialect({
31
+ * database: new DatabaseSync("db.sqlite"),
32
+ * })
33
+ * ```
34
+ *
35
+ * If you want the pool to only be created once it's first used, `database` can be a function:
36
+ *
37
+ * ```ts
38
+ * import { DatabaseSync } from "node:sqlite"
39
+ *
40
+ * new SqliteDialect({
41
+ * database: async () => new DatabaseSync("db.sqlite"),
42
+ * })
43
+ * ```
44
+ */
45
+ export class SqliteDialect implements Dialect {
46
+ protected config: SqliteDialectConfig
47
+
48
+ constructor(config: SqliteDialectConfig) {
49
+ this.config = Object.freeze({ ...config })
50
+ }
51
+
52
+ createDriver(): Driver {
53
+ return new SqliteDriver(this.config)
54
+ }
55
+
56
+ createQueryCompiler(): QueryCompiler {
57
+ return new SqliteQueryCompiler()
58
+ }
59
+
60
+ createAdapter(): DialectAdapter {
61
+ return new SqliteAdapter()
62
+ }
63
+
64
+ createIntrospector(db: Kysely<unknown>): DatabaseIntrospector {
65
+ return new SqliteIntrospector(db)
66
+ }
67
+ }