@happyvertical/smrt-languages 0.74.6 → 0.75.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.
- package/AGENTS.md +16 -8
- package/README.md +171 -0
- package/dist/chunks/language-authorization-JB74PQtk.js +11 -0
- package/dist/chunks/language-authorization-JB74PQtk.js.map +1 -0
- package/dist/chunks/{language-registry-Btq3nkPD.js → language-mutations-CK2hhO1Z.js} +144 -41
- package/dist/chunks/language-mutations-CK2hhO1Z.js.map +1 -0
- package/dist/chunks/{translation-job-DtabwjO-.js → translation-job-BvLyuWvG.js} +143 -79
- package/dist/chunks/translation-job-BvLyuWvG.js.map +1 -0
- package/dist/cli.js +2 -2
- package/dist/fill-catalog.d.ts +33 -0
- package/dist/fill-catalog.d.ts.map +1 -0
- package/dist/fill-catalog.js +61 -0
- package/dist/fill-catalog.js.map +1 -0
- package/dist/i18n/catalog.d.ts +9 -0
- package/dist/i18n/catalog.d.ts.map +1 -0
- package/dist/i18n/catalog.generated.d.ts +3 -0
- package/dist/i18n/catalog.generated.d.ts.map +1 -0
- package/dist/i18n/catalog.js +404 -0
- package/dist/i18n/catalog.js.map +1 -0
- package/dist/index.d.ts +14 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +590 -10
- package/dist/index.js.map +1 -1
- package/dist/jobs/translation-job.d.ts +14 -4
- package/dist/jobs/translation-job.d.ts.map +1 -1
- package/dist/jobs.d.ts +2 -0
- package/dist/jobs.d.ts.map +1 -1
- package/dist/jobs.js +132 -2
- package/dist/jobs.js.map +1 -0
- package/dist/language-authorization.d.ts +6 -0
- package/dist/language-authorization.d.ts.map +1 -0
- package/dist/language-fill.d.ts +77 -0
- package/dist/language-fill.d.ts.map +1 -0
- package/dist/language-mutations.d.ts +30 -0
- package/dist/language-mutations.d.ts.map +1 -0
- package/dist/language-resolver.d.ts +7 -1
- package/dist/language-resolver.d.ts.map +1 -1
- package/dist/language-settings.d.ts +47 -0
- package/dist/language-settings.d.ts.map +1 -0
- package/dist/manifest.json +401 -47
- package/dist/models/LanguageMutationRevision.d.ts +11 -0
- package/dist/models/LanguageMutationRevision.d.ts.map +1 -0
- package/dist/models/LanguageOverride.d.ts.map +1 -1
- package/dist/models/LanguagePreferences.d.ts +9 -0
- package/dist/models/LanguagePreferences.d.ts.map +1 -0
- package/dist/operations.d.ts +291 -0
- package/dist/operations.d.ts.map +1 -0
- package/dist/settings-types.d.ts +57 -0
- package/dist/settings-types.d.ts.map +1 -0
- package/dist/smrt-knowledge.json +151 -166
- package/dist/svelte/LanguageSettingsPanel.svelte +134 -0
- package/dist/svelte/LanguageSettingsPanel.svelte.d.ts +16 -0
- package/dist/svelte/LanguageSettingsPanel.svelte.d.ts.map +1 -0
- package/dist/svelte/components/LanguageFillPanel.svelte +246 -0
- package/dist/svelte/components/LanguageFillPanel.svelte.d.ts +46 -0
- package/dist/svelte/components/LanguageFillPanel.svelte.d.ts.map +1 -0
- package/dist/svelte/components/fill-messages.d.ts +23 -0
- package/dist/svelte/components/fill-messages.d.ts.map +1 -0
- package/dist/svelte/components/fill-messages.js +23 -0
- package/dist/svelte/index.d.ts +4 -0
- package/dist/svelte/index.d.ts.map +1 -0
- package/dist/svelte/index.js +2 -0
- package/dist/svelte/messages.d.ts +31 -0
- package/dist/svelte/messages.d.ts.map +1 -0
- package/dist/svelte/messages.js +31 -0
- package/dist/types.d.ts +24 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +41 -14
- package/dist/chunks/language-registry-Btq3nkPD.js.map +0 -1
- package/dist/chunks/translation-job-DtabwjO-.js.map +0 -1
package/AGENTS.md
CHANGED
|
@@ -11,6 +11,9 @@ auto-translation for missing locales.
|
|
|
11
11
|
- `resolveLanguageString(key, options)` walks the 5-layer chain (code → file
|
|
12
12
|
config → app override → tenant override → runtime override) and falls back
|
|
13
13
|
through the locale chain (`fr-CA` → `fr` → default) before giving up.
|
|
14
|
+
- `resolveLanguageStrings(keys, options)` is read-only bulk resolution: one app
|
|
15
|
+
list and at most one supplied-tenant list, request-local maps, no shared cache
|
|
16
|
+
or jobs. It preserves the single-key fallback order and caller DB/transaction.
|
|
14
17
|
- `LanguageOverride` stores app-level and tenant-level overrides in
|
|
15
18
|
`_smrt_language_overrides`. `auto_generated`, `source_hash`, `ai_model`,
|
|
16
19
|
`reviewed_at`, `reviewed_by` fields support the AI auto-translation pipeline
|
|
@@ -30,22 +33,27 @@ When `resolveLanguageString` cannot find an exact `(key, locale, tenantId)`:
|
|
|
30
33
|
2. Return the first hit — same call returns immediately with
|
|
31
34
|
`source: 'fallback'`.
|
|
32
35
|
3. Fire-and-forget `enqueueTranslationJob` for the missing target, scoped to
|
|
33
|
-
the current tenant
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
4. Subsequent requests hit the new app-level row and resolve at the requested
|
|
36
|
+
the current tenant. Tenant glossary, prompt bindings, billing and output
|
|
37
|
+
remain in that tenant; app jobs use app inputs and write `tenantId: null`.
|
|
38
|
+
4. Subsequent requests hit the new scoped row and resolve at the requested
|
|
37
39
|
locale.
|
|
38
40
|
|
|
39
41
|
The translation job:
|
|
40
42
|
|
|
41
43
|
- Honors the `smrt-languages.auto_translate` feature flag (kill switch).
|
|
42
44
|
- Skips locales outside `supportedLocales` when configured.
|
|
43
|
-
-
|
|
44
|
-
|
|
45
|
+
- Fills exact-locale gaps only; an existing override remains intact. The source
|
|
46
|
+
hash records which shipped template produced generated wording.
|
|
45
47
|
- Never overwrites a row with `auto_generated: false` — human edits win
|
|
46
48
|
permanently.
|
|
47
|
-
-
|
|
48
|
-
|
|
49
|
+
- Captures the tenant's glossary with a digest at enqueue, so auto-translations
|
|
50
|
+
match tenant voice without crossing scopes.
|
|
51
|
+
- Captures durable key/scope mutation revisions. Human saves, reviews and RESET
|
|
52
|
+
invalidate queued output; generated writeback claims revisions atomically.
|
|
53
|
+
Language management also checks inherited app revisions for tenant jobs.
|
|
54
|
+
- `LanguageFillCoordinator` (`/jobs`) binds authenticated settings scope to
|
|
55
|
+
exact-gap preview, enqueue/retry, and sanitized scoped progress. The callback
|
|
56
|
+
`LanguageFillPanel` lives under `src/svelte/components/`.
|
|
49
57
|
|
|
50
58
|
## Conventions
|
|
51
59
|
|
package/README.md
CHANGED
|
@@ -191,3 +191,174 @@ negotiation HTTP middleware, XLIFF/PO TM-tool integration, and richer quality
|
|
|
191
191
|
scoring of AI translations are all v1.1+ concerns. v1 sticks to plain
|
|
192
192
|
`{var}` substitution and the resolution chain above so adoption stays a
|
|
193
193
|
mechanical refactor across consumer packages.
|
|
194
|
+
|
|
195
|
+
## Settings → Languages
|
|
196
|
+
|
|
197
|
+
Import `LanguageSettingsService` from the package root and
|
|
198
|
+
`LanguageSettingsPanel` from `@happyvertical/smrt-languages/svelte`. The panel is
|
|
199
|
+
presentation only: bind its callbacks to authenticated server endpoints and
|
|
200
|
+
refresh `inventory` after each successful mutation. `children` accepts a snippet
|
|
201
|
+
for an AI-fill control, receiving `{ keys, search, packageName }` for the currently
|
|
202
|
+
visible filtered inventory so the host can preview or enqueue exactly that subset. Never expose the model collection directly over HTTP.
|
|
203
|
+
|
|
204
|
+
```ts
|
|
205
|
+
const settings = await LanguageSettingsService.create({ db }, {
|
|
206
|
+
// Derive this from verified server session context, never a posted tenant ID.
|
|
207
|
+
scope: { type: 'tenant', tenantId: session.tenantId },
|
|
208
|
+
catalogs: applicationCatalogs, // explicit package and lazy-route catalogs
|
|
209
|
+
authorize: ({ operation, scope }) => permissions.allow(session, operation, scope),
|
|
210
|
+
defaults: { defaultLocale: 'en', enabledLocales: ['en', 'es'] },
|
|
211
|
+
});
|
|
212
|
+
const inventory = await settings.list({ locale: 'es', search: 'invoice' });
|
|
213
|
+
await settings.saveOverride('commerce.invoice.dueText', 'es', 'Vence {date}');
|
|
214
|
+
await settings.resetOverride('commerce.invoice.dueText', 'es');
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
Every method checks the host's authorizer before accessing scoped data, including
|
|
218
|
+
reads, previews and review. Missing, throwing and false authorizers deny access.
|
|
219
|
+
Bind a service to exactly one trusted scope per request. An app administrator may
|
|
220
|
+
create an app-scoped service; tenant administrators should only receive their
|
|
221
|
+
active, verified tenant scope. Public SSR may explicitly authorize `read` for
|
|
222
|
+
`getPreferences()`; this does not authorize any mutation. Generated override
|
|
223
|
+
HTTP/CLI/MCP CRUD is closed because it cannot enforce these scope decisions.
|
|
224
|
+
`LanguageSettingsAuthorizationError.status` is 403; invalid input throws before
|
|
225
|
+
writing. The host should map input errors to its 400 response convention.
|
|
226
|
+
|
|
227
|
+
Default/enabled locale preferences are a single atomic document in
|
|
228
|
+
`_smrt_language_preferences`, inherited app → tenant. `setPreferences()` requires
|
|
229
|
+
the default locale to be enabled. `resetPreferences()` removes only the bound
|
|
230
|
+
scope's preferences. Disabling a locale never deletes wording. Include the new
|
|
231
|
+
model in the application's migration discovery and run normal migrations before
|
|
232
|
+
serving the panel; runtime reads never create schema.
|
|
233
|
+
|
|
234
|
+
Inventory enumerates explicit catalogs without registering strings, resolving
|
|
235
|
+
strings, creating overrides, or enqueueing jobs. It includes lazy route keys,
|
|
236
|
+
shipped and effective wording, the supplying scope and locale, the value revealed
|
|
237
|
+
by reset, exact coverage, and generated text awaiting review. Regional fallback
|
|
238
|
+
counts as missing an exact translation. Search matches key, package, shipped and
|
|
239
|
+
effective text. Package upgrades replace shipped catalogs while persisted keys
|
|
240
|
+
retain administrator wording. Keys are durable identifiers; renaming requires a
|
|
241
|
+
migration.
|
|
242
|
+
|
|
243
|
+
`preview`, `saveOverride`, `resetOverride` and `reviewOverride` operate on only
|
|
244
|
+
the bound scope. A tenant reset reveals app wording; an app reset reveals shipped
|
|
245
|
+
wording. Saving validates named placeholder parity and marks the value as a human
|
|
246
|
+
edit. `reviewOverride` only approves a generated row in that scope; derive its
|
|
247
|
+
reviewer ID from the authenticated session. Human changes and reset use a durable
|
|
248
|
+
transaction revision shared with AI writeback so a stale job cannot undo them.
|
|
249
|
+
|
|
250
|
+
The service is tested with in-process SQLite, DuckDB and PostgreSQL through
|
|
251
|
+
PGlite. Preferences write both fields in one row and respect the supplied
|
|
252
|
+
transaction executor, including rollback. AI/human mutation coordination requires
|
|
253
|
+
a transaction-capable database. Pass `codeDefaults` and `suppressAutoTranslate`
|
|
254
|
+
to `resolveLanguageString` for request-local explicit snapshots; these do not
|
|
255
|
+
mutate the global registry or enqueue jobs.
|
|
256
|
+
|
|
257
|
+
The Languages panel uses registered `languages.settings.*` messages throughout,
|
|
258
|
+
including accessible names, coverage and error states. Compose the pure
|
|
259
|
+
`messageCatalog` from `@happyvertical/smrt-languages/i18n/catalog` into the app's
|
|
260
|
+
explicit catalog before its first request; it includes reviewed English and
|
|
261
|
+
Spanish. Standalone components fall back to registered English. Regenerate the
|
|
262
|
+
English snapshot with `node scripts/generate-message-catalogs.mjs languages`
|
|
263
|
+
after changing `src/svelte/messages.ts`.
|
|
264
|
+
|
|
265
|
+
Manual wording and AI results use the shared catalog placeholder validator.
|
|
266
|
+
Reordering and repeating names are allowed; the exact set of renderer-recognized
|
|
267
|
+
names (including hyphens, dots and spaces) must match the source. Review also
|
|
268
|
+
checks this contract before approving older generated wording. Reset remains
|
|
269
|
+
available to remove invalid overrides.
|
|
270
|
+
|
|
271
|
+
### Scoped AI fill
|
|
272
|
+
|
|
273
|
+
Import `LanguageFillCoordinator` from `@happyvertical/smrt-languages/jobs` on
|
|
274
|
+
servers only. Construct it with the authenticated `LanguageSettingsService`, its
|
|
275
|
+
DB options and immutable scope, and trusted source-locale catalog definitions.
|
|
276
|
+
Never accept a scope or source template from the browser. `preview(selection)`
|
|
277
|
+
returns the scope and eligible count; `enqueue(selection)` rechecks authorization
|
|
278
|
+
and exact coverage, queues eligible entries, and reports per-entry enqueue
|
|
279
|
+
failures. `retry(selection)` uses the same eligibility checks. `progress(ids)`
|
|
280
|
+
queries only jobs in the bound scope and returns sanitized errors. Use the
|
|
281
|
+
settings service's review action to approve generated overrides.
|
|
282
|
+
|
|
283
|
+
An APP owner can fill installation-wide strings while a tenant is active. The
|
|
284
|
+
coordinator completes authorization in that original request context, then uses
|
|
285
|
+
public `withSystemContext` only for APP job persistence; native job ownership
|
|
286
|
+
stays `tenantId: null`. Tenant operations and callers without an active tenant
|
|
287
|
+
keep their existing context. Preparation, feature checks, revisions and tenant
|
|
288
|
+
glossary reads remain outside elevation, and the original context is restored
|
|
289
|
+
on success or failure. Progress retains its explicit ownership, queue, task,
|
|
290
|
+
method and payload-scope filters.
|
|
291
|
+
|
|
292
|
+
The enqueuer's optional `runJobPersistence` callback is a trusted in-process
|
|
293
|
+
boundary supplied by this already-authorized APP coordinator. It is not a
|
|
294
|
+
request/JSON option or a caller-controlled bypass flag, and is never persisted
|
|
295
|
+
in job arguments, options or deduplication identity. Direct enqueuer callers keep
|
|
296
|
+
the normal Job tenant guards unless their trusted host supplies a context.
|
|
297
|
+
|
|
298
|
+
An inherited regional fallback is still an exact-locale gap. Existing exact
|
|
299
|
+
translations, including human overrides, are excluded. The translation feature
|
|
300
|
+
flag and supported locale allowlist apply at enqueue and execution. Active jobs
|
|
301
|
+
share a durable tenant/scope/key/locale dedup slot; a completed or failed job can
|
|
302
|
+
be retried. Generated rows stay pending review. The callback-only
|
|
303
|
+
`LanguageFillPanel` uses registered `languages.fill.*` messages from the full
|
|
304
|
+
`@happyvertical/smrt-languages/i18n/catalog` (English and Spanish). It previews the selected count and scope before enqueueing and
|
|
305
|
+
exposes progress refresh, failures, retry preview, and review navigation.
|
|
306
|
+
The generated panel sends search/package selectors, omitting explicit keys for
|
|
307
|
+
all missing strings. Catalog size does not truncate selection: the server
|
|
308
|
+
rechecks every matching gap. Explicit API/MCP key selections remain bounded to
|
|
309
|
+
1,000 keys; progress reads use batches of at most 1,000 job IDs and retain all
|
|
310
|
+
accepted IDs for refresh if any batch fails.
|
|
311
|
+
|
|
312
|
+
Resolver jobs now keep tenant glossary, prompt bindings, billing, dedup identity
|
|
313
|
+
and output in that tenant. App jobs use app inputs and write app overrides.
|
|
314
|
+
Queued work captures a durable mutation revision: administrator save, review,
|
|
315
|
+
and RESET (even when there is no override) invalidate that revision. The worker
|
|
316
|
+
claims it and inserts the generated override in one transaction. A human change
|
|
317
|
+
made during the AI call wins; stale or duplicate work skips persistence. Revision
|
|
318
|
+
tombstones must survive RESET. Run migrations for `LanguageMutationRevision`
|
|
319
|
+
before enabling language management; the worker never creates application tables.
|
|
320
|
+
|
|
321
|
+
### Read-only bulk interface resolution
|
|
322
|
+
|
|
323
|
+
`resolveLanguageStrings(keys, options)` resolves a request's interface dictionary
|
|
324
|
+
with one public app-override list read and at most one list read for its supplied
|
|
325
|
+
tenant. It uses the caller's database/transaction, builds maps only for that call,
|
|
326
|
+
and never queues jobs or shares a catalog/locale/tenant cache. At each locale in
|
|
327
|
+
the fallback chain it preserves tenant → app → file config → shipped code order.
|
|
328
|
+
Runtime overrides, interpolation, strict misses and empty templates match the
|
|
329
|
+
single-key resolver. The existing `resolveLanguageString` worker/enqueue behavior
|
|
330
|
+
is unchanged. Pass explicit `codeDefaults` for application/version isolation.
|
|
331
|
+
|
|
332
|
+
### Authorized management transports
|
|
333
|
+
|
|
334
|
+
`createLanguageOperationExecutor` and `languageOperationDefinitions` provide the
|
|
335
|
+
closed, transport-neutral management contract. The host supplies authorization,
|
|
336
|
+
request-bound `LanguageSettingsService`/`LanguageFillCoordinator` factories and
|
|
337
|
+
the verified reviewer. Inputs select `scope: 'tenant' | 'app'`; they never carry
|
|
338
|
+
tenant IDs, session IDs, source templates, glossaries, or review actors. Unknown
|
|
339
|
+
fields (including nested preference fields), invalid locales and oversized
|
|
340
|
+
selections are refused before service creation. Progress rejects any unknown or
|
|
341
|
+
foreign job ID, including a mixed selection. Importing the root keeps jobs/AI off
|
|
342
|
+
the runtime import graph; only the host imports the `/jobs` coordinator.
|
|
343
|
+
|
|
344
|
+
### Persisted pre-scope translation jobs
|
|
345
|
+
|
|
346
|
+
Pending or retryable jobs emitted by the baseline producer remain executable.
|
|
347
|
+
Compatibility accepts only its exact seven-field payload and old deterministic
|
|
348
|
+
identity, inside authentic runner dispatch with matching native tenant ownership,
|
|
349
|
+
`languages` queue, task and method. A fresh, bounded native-row read also
|
|
350
|
+
requires null object ID/dedup key and the exact raw payload, including fields
|
|
351
|
+
that dispatch strips. Scoped jobs cannot shed JSON markers to become legacy.
|
|
352
|
+
Mixed/new snapshot, scope, model, token or
|
|
353
|
+
unknown fields cannot downgrade a job into this compatibility path. New scoped
|
|
354
|
+
identities retain their strict checks and may use explicitly configured queues.
|
|
355
|
+
Legacy jobs preserve their stored arguments on retry and adopt missing revision
|
|
356
|
+
snapshots only when both their own scope and inherited APP history are provably
|
|
357
|
+
pristine. Initial captures share a durable pristine marker; human and generated
|
|
358
|
+
mutations rotate it to an opaque UUID. Existing unknown UUID history is never
|
|
359
|
+
rewritten or guessed from timestamps: snapshotless work skips before the provider
|
|
360
|
+
when history cannot be proven. Explicitly queued scoped UUID snapshots remain
|
|
361
|
+
valid. The exact adopted pristine token participates in CAS, so resets racing
|
|
362
|
+
the check still win. Legacy jobs retain source/exact-gap guards and write tenant
|
|
363
|
+
results into that tenant without inventing historical enqueue snapshots. Unknown/malformed jobs fail closed; use
|
|
364
|
+
the authorized fill workflow to enqueue a new scoped job instead.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
//#region src/language-authorization.ts
|
|
2
|
+
var LanguageSettingsAuthorizationError = class extends Error {
|
|
3
|
+
status = 403;
|
|
4
|
+
constructor() {
|
|
5
|
+
super("Language settings access denied");
|
|
6
|
+
}
|
|
7
|
+
};
|
|
8
|
+
//#endregion
|
|
9
|
+
export { LanguageSettingsAuthorizationError as t };
|
|
10
|
+
|
|
11
|
+
//# sourceMappingURL=language-authorization-JB74PQtk.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"language-authorization-JB74PQtk.js","names":[],"sources":["../../src/language-authorization.ts"],"sourcesContent":["/** Shared safe denial without importing the management persistence service into workers. */\nexport class LanguageSettingsAuthorizationError extends Error {\n readonly status = 403;\n constructor() {\n super('Language settings access denied');\n }\n}\n"],"mappings":";AACO,IAAM,qCAAN,cAAiD,MAAM;CACnD,SAAS;CAClB,cAAc;EACZ,MAAM,iCAAiC;CACzC;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { RuntimeError, SmrtCollection, SmrtObject, field, smrt } from "@happyvertical/smrt-core";
|
|
2
|
-
import { createHash } from "node:crypto";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
3
|
//#region src/utils.ts
|
|
4
4
|
function isPlainObject(value) {
|
|
5
5
|
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
@@ -129,21 +129,21 @@ function clearLanguageCache() {
|
|
|
129
129
|
}
|
|
130
130
|
//#endregion
|
|
131
131
|
//#region src/models/LanguageOverride.ts
|
|
132
|
-
var __defProp = Object.defineProperty;
|
|
133
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
134
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
|
|
132
|
+
var __defProp$1 = Object.defineProperty;
|
|
133
|
+
var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
|
|
134
|
+
var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, {
|
|
135
135
|
enumerable: true,
|
|
136
136
|
configurable: true,
|
|
137
137
|
writable: true,
|
|
138
138
|
value
|
|
139
139
|
}) : obj[key] = value;
|
|
140
|
-
var __decorateClass = (decorators, target, key, kind) => {
|
|
141
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
140
|
+
var __decorateClass$1 = (decorators, target, key, kind) => {
|
|
141
|
+
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1(target, key) : target;
|
|
142
142
|
for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
143
|
-
if (kind && result) __defProp(target, key, result);
|
|
143
|
+
if (kind && result) __defProp$1(target, key, result);
|
|
144
144
|
return result;
|
|
145
145
|
};
|
|
146
|
-
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
146
|
+
var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
147
147
|
var LanguageOverride = class extends SmrtObject {
|
|
148
148
|
key = "";
|
|
149
149
|
locale = "";
|
|
@@ -246,7 +246,8 @@ var LanguageOverride = class extends SmrtObject {
|
|
|
246
246
|
}
|
|
247
247
|
async getPersistedIdentity() {
|
|
248
248
|
if (!this.id) return null;
|
|
249
|
-
const
|
|
249
|
+
const { rows } = await this.db.query(`SELECT key, locale, CAST(tenant_id AS VARCHAR) AS tenant_id FROM ${this.tableName} WHERE id = ?`, this.id);
|
|
250
|
+
const existing = rows[0];
|
|
250
251
|
if (!existing) return null;
|
|
251
252
|
const row = existing;
|
|
252
253
|
return {
|
|
@@ -256,67 +257,51 @@ var LanguageOverride = class extends SmrtObject {
|
|
|
256
257
|
};
|
|
257
258
|
}
|
|
258
259
|
};
|
|
259
|
-
__publicField(LanguageOverride, "__smrtPackage__", "@happyvertical/smrt-languages");
|
|
260
|
-
__decorateClass([field({
|
|
260
|
+
__publicField$1(LanguageOverride, "__smrtPackage__", "@happyvertical/smrt-languages");
|
|
261
|
+
__decorateClass$1([field({
|
|
261
262
|
required: true,
|
|
262
263
|
requiredFor: "identity"
|
|
263
264
|
})], LanguageOverride.prototype, "key", 2);
|
|
264
|
-
__decorateClass([field({
|
|
265
|
+
__decorateClass$1([field({
|
|
265
266
|
required: true,
|
|
266
267
|
requiredFor: "identity"
|
|
267
268
|
})], LanguageOverride.prototype, "locale", 2);
|
|
268
|
-
__decorateClass([field({
|
|
269
|
+
__decorateClass$1([field({
|
|
269
270
|
sqlType: "UUID",
|
|
270
271
|
nullable: true
|
|
271
272
|
})], LanguageOverride.prototype, "tenantId", 2);
|
|
272
|
-
__decorateClass([field({ type: "text" })], LanguageOverride.prototype, "template", 2);
|
|
273
|
-
__decorateClass([field({
|
|
273
|
+
__decorateClass$1([field({ type: "text" })], LanguageOverride.prototype, "template", 2);
|
|
274
|
+
__decorateClass$1([field({
|
|
274
275
|
type: "boolean",
|
|
275
276
|
required: true,
|
|
276
277
|
default: false
|
|
277
278
|
})], LanguageOverride.prototype, "auto_generated", 2);
|
|
278
|
-
__decorateClass([field({
|
|
279
|
+
__decorateClass$1([field({
|
|
279
280
|
type: "text",
|
|
280
281
|
nullable: true
|
|
281
282
|
})], LanguageOverride.prototype, "source_hash", 2);
|
|
282
|
-
__decorateClass([field({
|
|
283
|
+
__decorateClass$1([field({
|
|
283
284
|
type: "text",
|
|
284
285
|
nullable: true
|
|
285
286
|
})], LanguageOverride.prototype, "ai_model", 2);
|
|
286
|
-
__decorateClass([field({
|
|
287
|
+
__decorateClass$1([field({
|
|
287
288
|
type: "text",
|
|
288
289
|
nullable: true
|
|
289
290
|
})], LanguageOverride.prototype, "reviewed_at", 2);
|
|
290
|
-
__decorateClass([field({
|
|
291
|
+
__decorateClass$1([field({
|
|
291
292
|
type: "text",
|
|
292
293
|
nullable: true
|
|
293
294
|
})], LanguageOverride.prototype, "reviewed_by", 2);
|
|
294
|
-
LanguageOverride = __decorateClass([smrt({
|
|
295
|
+
LanguageOverride = __decorateClass$1([smrt({
|
|
295
296
|
tableName: "_smrt_language_overrides",
|
|
296
297
|
conflictColumns: [
|
|
297
298
|
"key",
|
|
298
299
|
"locale",
|
|
299
300
|
"context"
|
|
300
301
|
],
|
|
301
|
-
api:
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
"create",
|
|
305
|
-
"update",
|
|
306
|
-
"delete"
|
|
307
|
-
] },
|
|
308
|
-
cli: {
|
|
309
|
-
include: [
|
|
310
|
-
"list",
|
|
311
|
-
"get",
|
|
312
|
-
"create",
|
|
313
|
-
"update",
|
|
314
|
-
"delete",
|
|
315
|
-
"approve"
|
|
316
|
-
],
|
|
317
|
-
skipApiCheck: true
|
|
318
|
-
},
|
|
319
|
-
mcp: { include: [] }
|
|
302
|
+
api: false,
|
|
303
|
+
cli: false,
|
|
304
|
+
mcp: false
|
|
320
305
|
})], LanguageOverride);
|
|
321
306
|
function withoutRevisionGuard(options) {
|
|
322
307
|
if (!options || options.expectedUpdatedAt === void 0) return options;
|
|
@@ -468,6 +453,124 @@ function defineLanguageString(input) {
|
|
|
468
453
|
return LanguageRegistry.register(input);
|
|
469
454
|
}
|
|
470
455
|
//#endregion
|
|
471
|
-
|
|
456
|
+
//#region src/models/LanguageMutationRevision.ts
|
|
457
|
+
var __defProp = Object.defineProperty;
|
|
458
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
459
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
|
|
460
|
+
enumerable: true,
|
|
461
|
+
configurable: true,
|
|
462
|
+
writable: true,
|
|
463
|
+
value
|
|
464
|
+
}) : obj[key] = value;
|
|
465
|
+
var __decorateClass = (decorators, target, key, kind) => {
|
|
466
|
+
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
467
|
+
for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
468
|
+
if (kind && result) __defProp(target, key, result);
|
|
469
|
+
return result;
|
|
470
|
+
};
|
|
471
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
472
|
+
var LanguageMutationRevision = class extends SmrtObject {
|
|
473
|
+
key = "";
|
|
474
|
+
locale = "";
|
|
475
|
+
revision = "";
|
|
476
|
+
};
|
|
477
|
+
__publicField(LanguageMutationRevision, "__smrtPackage__", "@happyvertical/smrt-languages");
|
|
478
|
+
__decorateClass([field({
|
|
479
|
+
required: true,
|
|
480
|
+
requiredFor: "identity"
|
|
481
|
+
})], LanguageMutationRevision.prototype, "key", 2);
|
|
482
|
+
__decorateClass([field({
|
|
483
|
+
required: true,
|
|
484
|
+
requiredFor: "identity"
|
|
485
|
+
})], LanguageMutationRevision.prototype, "locale", 2);
|
|
486
|
+
__decorateClass([field({
|
|
487
|
+
required: true,
|
|
488
|
+
requiredFor: "idempotency"
|
|
489
|
+
})], LanguageMutationRevision.prototype, "revision", 2);
|
|
490
|
+
LanguageMutationRevision = __decorateClass([smrt({
|
|
491
|
+
tableName: "_smrt_language_mutation_revisions",
|
|
492
|
+
conflictColumns: [
|
|
493
|
+
"key",
|
|
494
|
+
"locale",
|
|
495
|
+
"context"
|
|
496
|
+
],
|
|
497
|
+
api: false,
|
|
498
|
+
cli: false,
|
|
499
|
+
mcp: false
|
|
500
|
+
})], LanguageMutationRevision);
|
|
501
|
+
var LanguageMutationRevisionCollection = class extends SmrtCollection {
|
|
502
|
+
static _itemClass = LanguageMutationRevision;
|
|
503
|
+
};
|
|
504
|
+
//#endregion
|
|
505
|
+
//#region src/language-mutations.ts
|
|
506
|
+
function scopeContext(scope) {
|
|
507
|
+
if (scope.type === "app") return "__app__";
|
|
508
|
+
if (scope.type !== "tenant" || !scope.tenantId || scope.tenantId === "__app__") throw new TypeError("Invalid language mutation scope");
|
|
509
|
+
return scope.tenantId;
|
|
510
|
+
}
|
|
511
|
+
async function database(options) {
|
|
512
|
+
return (await LanguageMutationRevisionCollection.create(options)).db;
|
|
513
|
+
}
|
|
514
|
+
async function ensureRevision(db, scope, key, locale) {
|
|
515
|
+
const id = randomUUID();
|
|
516
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
517
|
+
await db.query(`INSERT INTO _smrt_language_mutation_revisions
|
|
518
|
+
(id, slug, context, created_at, updated_at, key, locale, revision)
|
|
519
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (key, locale, context) DO NOTHING`, id, id, scopeContext(scope), now, now, key, normalizeLocale(locale), `pristine:${id}`);
|
|
520
|
+
}
|
|
521
|
+
async function captureLanguageRevision(options, scope, key, locale) {
|
|
522
|
+
const db = await database(options);
|
|
523
|
+
await ensureRevision(db, scope, key, locale);
|
|
524
|
+
const revision = (await db.query("SELECT revision FROM _smrt_language_mutation_revisions WHERE key = ? AND locale = ? AND context = ?", key, normalizeLocale(locale), scopeContext(scope))).rows[0]?.revision;
|
|
525
|
+
if (typeof revision !== "string") throw new Error("Missing language revision");
|
|
526
|
+
return revision;
|
|
527
|
+
}
|
|
528
|
+
async function capturePristineLanguageRevision(options, scope, key, locale) {
|
|
529
|
+
const db = await database(options);
|
|
530
|
+
await ensureRevision(db, scope, key, locale);
|
|
531
|
+
const row = (await db.query("SELECT CAST(id AS TEXT) AS revision_id, revision FROM _smrt_language_mutation_revisions WHERE key = ? AND locale = ? AND context = ?", key, normalizeLocale(locale), scopeContext(scope))).rows[0];
|
|
532
|
+
return row && row.revision === `pristine:${String(row.revision_id)}` ? String(row.revision) : null;
|
|
533
|
+
}
|
|
534
|
+
async function withLanguageMutation(options, scope, key, locale, fn) {
|
|
535
|
+
const db = await database(options);
|
|
536
|
+
if (!db.transaction) throw new Error("Language mutations require transactions");
|
|
537
|
+
const result = await db.transaction(async (tx) => {
|
|
538
|
+
await ensureRevision(tx, scope, key, locale);
|
|
539
|
+
await tx.query("UPDATE _smrt_language_mutation_revisions SET revision = ?, updated_at = ? WHERE key = ? AND locale = ? AND context = ?", randomUUID(), (/* @__PURE__ */ new Date()).toISOString(), key, normalizeLocale(locale), scopeContext(scope));
|
|
540
|
+
return fn(tx);
|
|
541
|
+
});
|
|
542
|
+
invalidateLanguageCache(key, normalizeLocale(locale), scope.type === "tenant" ? scope.tenantId : null, db);
|
|
543
|
+
return result;
|
|
544
|
+
}
|
|
545
|
+
async function commitGeneratedLanguage(options, scope, input) {
|
|
546
|
+
const db = await database(options);
|
|
547
|
+
if (!db.transaction) throw new Error("Language mutations require transactions");
|
|
548
|
+
const result = await db.transaction(async (tx) => {
|
|
549
|
+
if (scope.type === "tenant") {
|
|
550
|
+
if (!input.expectedAppRevision) return false;
|
|
551
|
+
if ((await tx.query("UPDATE _smrt_language_mutation_revisions SET updated_at = updated_at WHERE key = ? AND locale = ? AND context = ? AND revision = ? RETURNING id", input.key, normalizeLocale(input.locale), "__app__", input.expectedAppRevision)).rows.length !== 1) return false;
|
|
552
|
+
}
|
|
553
|
+
if ((await tx.query(`UPDATE _smrt_language_mutation_revisions SET revision = ?, updated_at = ?
|
|
554
|
+
WHERE key = ? AND locale = ? AND context = ? AND revision = ? RETURNING id`, randomUUID(), (/* @__PURE__ */ new Date()).toISOString(), input.key, normalizeLocale(input.locale), scopeContext(scope), input.expectedRevision)).rows.length !== 1) return false;
|
|
555
|
+
const overrides = await LanguageOverrideCollection.create({ db: tx });
|
|
556
|
+
if ((scope.type === "tenant" ? await overrides.getTenantOverride(input.key, input.locale, scope.tenantId) : await overrides.getAppOverride(input.key, input.locale)) || scope.type === "tenant" && await overrides.getAppOverride(input.key, input.locale)) return false;
|
|
557
|
+
await overrides.create({
|
|
558
|
+
key: input.key,
|
|
559
|
+
locale: input.locale,
|
|
560
|
+
tenantId: scope.type === "tenant" ? scope.tenantId : null,
|
|
561
|
+
template: input.template,
|
|
562
|
+
auto_generated: true,
|
|
563
|
+
source_hash: input.sourceHash,
|
|
564
|
+
ai_model: input.aiModel,
|
|
565
|
+
reviewed_at: null,
|
|
566
|
+
reviewed_by: null
|
|
567
|
+
});
|
|
568
|
+
return true;
|
|
569
|
+
});
|
|
570
|
+
if (result) invalidateLanguageCache(input.key, normalizeLocale(input.locale), scope.type === "tenant" ? scope.tenantId : null, db);
|
|
571
|
+
return result;
|
|
572
|
+
}
|
|
573
|
+
//#endregion
|
|
574
|
+
export { buildLocaleFallbackChain as _, LanguageMutationRevision as a, normalizeLocale as b, buildTenantGlossary as c, clearLanguageCache as d, getCachedLanguage as f, setCachedLanguage as g, invalidateLanguageCache as h, withLanguageMutation as i, LanguageOverrideCollection as l, getLanguageCacheTtlMs as m, capturePristineLanguageRevision as n, LanguageRegistry as o, getLanguageCacheGeneration as p, commitGeneratedLanguage as r, defineLanguageString as s, captureLanguageRevision as t, LanguageOverride as u, buildTranslationJobId as v, renderTemplate as x, computeSourceHash as y };
|
|
472
575
|
|
|
473
|
-
//# sourceMappingURL=language-
|
|
576
|
+
//# sourceMappingURL=language-mutations-CK2hhO1Z.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"language-mutations-CK2hhO1Z.js","names":[],"sources":["../../src/utils.ts","../../src/cache.ts","../../src/models/LanguageOverride.ts","../../src/collections/LanguageOverrideCollection.ts","../../src/glossary.ts","../../src/language-registry.ts","../../src/models/LanguageMutationRevision.ts","../../src/language-mutations.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport type { LanguageVariables } from './types.js';\n\nexport function isPlainObject(\n value: unknown,\n): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\n/** Stable hash used to gate auto-translation re-runs against a specific source. */\nexport function computeSourceHash(template: string): string {\n return `sha256:${createHash('sha256').update(template, 'utf8').digest('hex')}`;\n}\n\n/**\n * Normalize a BCP-47-ish locale tag for consistent matching across the\n * registry, the cache, and DB lookups.\n *\n * Lowercases the language subtag and uppercases everything after it so\n * `fr-ca`, `fr-CA`, and `Fr-Ca` collapse to the same key. This is **not**\n * canonical BCP-47 casing (proper BCP-47 lower-cases variants and uses\n * Title-case for script subtags like `Hans`); it is an internal\n * normalization shared by every layer in this package and intentionally\n * stricter than what BCP-47 mandates.\n */\nexport function normalizeLocale(locale: string): string {\n if (!locale) return '';\n const trimmed = locale.trim();\n if (!trimmed) return '';\n const [language, ...rest] = trimmed.split('-');\n if (rest.length === 0) {\n return language.toLowerCase();\n }\n return [\n language.toLowerCase(),\n ...rest.map((part) => part.toUpperCase()),\n ].join('-');\n}\n\n/**\n * Build the locale fallback chain for a requested locale.\n *\n * Example: `fr-CA` with default `en` → `['fr-CA', 'fr', 'en']`.\n * Duplicates and empty segments are removed.\n */\nexport function buildLocaleFallbackChain(\n requested: string,\n defaultLocale: string,\n): string[] {\n const chain: string[] = [];\n const push = (value: string) => {\n const normalized = normalizeLocale(value);\n if (normalized && !chain.includes(normalized)) {\n chain.push(normalized);\n }\n };\n\n if (requested) {\n let current = normalizeLocale(requested);\n while (current) {\n push(current);\n const idx = current.lastIndexOf('-');\n if (idx === -1) break;\n current = current.slice(0, idx);\n }\n }\n\n if (defaultLocale) {\n push(defaultLocale);\n }\n\n return chain;\n}\n\n/**\n * Render `{var}` placeholders against the supplied variables.\n *\n * When at least one variable is provided, every `{...}` placeholder in the\n * template is replaced; missing or `undefined`/`null` variables collapse to\n * empty strings (callers that pass `name` but not `title` get the `{title}`\n * placeholder removed).\n *\n * When `variables` is `undefined` or `{}` the template is returned unchanged\n * — that fast path avoids the regex pass for the common \"no interpolation\n * needed\" case. If you need every placeholder collapsed regardless, pass at\n * least one variable (e.g. `{ __forceRender: true }`).\n */\nexport function renderTemplate(\n template: string,\n variables?: LanguageVariables,\n): string {\n if (!variables || Object.keys(variables).length === 0) {\n return template;\n }\n\n return template.replace(/\\{([^{}]+)\\}/g, (_match, rawKey: string) => {\n const key = rawKey.trim();\n const value = variables[key];\n\n if (value === undefined || value === null) {\n return '';\n }\n\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n if (Array.isArray(value) || isPlainObject(value)) {\n try {\n return JSON.stringify(value);\n } catch {\n return '';\n }\n }\n\n return String(value);\n });\n}\n\n/** Deterministic translation-job ID — used for stampede protection. */\nexport function buildTranslationJobId(\n key: string,\n targetLocale: string,\n): string {\n return `smrt-languages.translate:${key}:${normalizeLocale(targetLocale)}`;\n}\n","import type { DatabaseInterface } from '@happyvertical/sql';\nimport type { LanguageCacheValue } from './types.js';\nimport { normalizeLocale } from './utils.js';\n\nconst LANGUAGE_CACHE_TTL_MS = 30_000;\n\ntype CacheEntry = {\n expiresAt: number;\n value: LanguageCacheValue;\n};\n\nconst languageCache = new Map<string, CacheEntry>();\n/**\n * Monotonic per-`(db, key, locale)` invalidation counter; see\n * getLanguageCacheGeneration.\n */\nconst cacheGenerations = new Map<string, number>();\n/**\n * Source of every generation value. Drawing from one counter instead of\n * incrementing each entry independently makes a generation unique across every\n * `(key, locale)` and every clear, which is what lets `clearedThrough` work as\n * a floor.\n */\nlet nextGeneration = 1;\n/**\n * Floor that `clearLanguageCache()` raises for *every* `(key, locale)`,\n * including pairs with no map entry. A pair that has never been invalidated in\n * this process reads as generation 0, so a resolution that captured 0 before a\n * clear would still see 0 after it and write its pre-clear value back — the\n * flush would be silently undone for the rest of the TTL.\n */\nlet clearedThrough = 0;\nconst dbInstanceIds = new WeakMap<object, string>();\nlet nextDbId = 1;\n\nfunction getDbNamespace(db: unknown): string {\n if (!db) {\n return 'no-db';\n }\n\n if (typeof db === 'string') {\n return `db:${db}`;\n }\n\n if (typeof db === 'object') {\n const dbObject = db as Record<string, unknown>;\n if (typeof dbObject.query === 'function') {\n if (!dbInstanceIds.has(dbObject)) {\n dbInstanceIds.set(dbObject, `db-instance:${nextDbId++}`);\n }\n const namespace = dbInstanceIds.get(dbObject);\n if (namespace) {\n return namespace;\n }\n\n return 'db-instance:unknown';\n }\n\n try {\n return `db-config:${JSON.stringify(dbObject)}`;\n } catch {\n return 'db-config:opaque';\n }\n }\n\n return 'db:unknown';\n}\n\nfunction buildCacheKey(\n key: string,\n locale: string,\n tenantId: string | null | undefined,\n db: unknown,\n): string {\n return `${getDbNamespace(db)}::${key}::${normalizeLocale(locale)}::${\n tenantId ?? 'app'\n }`;\n}\n\nfunction buildGenerationKey(\n key: string,\n locale: string,\n db: DatabaseInterface | unknown,\n): string {\n return `${getDbNamespace(db)}::${key}::${normalizeLocale(locale)}`;\n}\n\nfunction bumpGeneration(\n key: string,\n locale: string,\n db: DatabaseInterface | unknown,\n): void {\n cacheGenerations.set(buildGenerationKey(key, locale, db), nextGeneration++);\n}\n\nexport function getLanguageCacheTtlMs(): number {\n return LANGUAGE_CACHE_TTL_MS;\n}\n\nexport function getCachedLanguage(\n key: string,\n locale: string,\n tenantId: string | null | undefined,\n db: DatabaseInterface | unknown,\n): LanguageCacheValue | null {\n const cacheKey = buildCacheKey(key, locale, tenantId, db);\n const cached = languageCache.get(cacheKey);\n\n if (!cached) {\n return null;\n }\n\n if (cached.expiresAt <= Date.now()) {\n languageCache.delete(cacheKey);\n return null;\n }\n\n return cached.value;\n}\n\n/**\n * Reads the current invalidation generation for a `(key, locale)` pair.\n *\n * A resolution captures this *before* its asynchronous layer loads and hands\n * it back to {@link setCachedLanguage}. Any write that lands while those loads\n * are in flight bumps the generation, so the in-flight resolution — which read\n * the pre-write layers — is refused the cache write instead of repopulating\n * the entry the write just invalidated. Without this, a read that raced a\n * write served the pre-write value for the full TTL, and a raced `delete()`\n * resurrected the deleted override.\n *\n * Granularity is `(db, key, locale)`, not `(db, key)` as in smrt-playbooks and\n * smrt-prompts, and not `(db, key, locale, tenantId)`:\n *\n * - `locale` is part of the key because every layer a cached entry is built\n * from is read at exactly the locale it is cached under. `resolveLanguageString`\n * walks a fallback chain (`fr-CA` → `fr` → `en`), but each attempt reads its\n * own locale's rows (`getTenantOverride`/`getAppOverride` are called with\n * that locale) and caches the result under that same locale; an attempt that\n * resolves nothing caches nothing, so a fallback hit is never stored under\n * the requested locale. Every writer — `LanguageOverride.save()`/`delete()`\n * (both identities, when one changes) and the translation job — invalidates\n * the same `(key, locale)` it wrote. A per-locale generation therefore still\n * covers every write that can change what a cached entry was built from.\n * - `tenantId` is deliberately *not* part of the key, because an app-level row\n * (tenantId null) is inherited by every tenant, so a write to any scope of a\n * `(key, locale)` must be able to refuse an in-flight write for any other\n * scope of it. This matches the coarsest fan-out of\n * {@link invalidateLanguageCache}.\n *\n * A pair with no entry of its own reports the {@link clearLanguageCache} floor\n * rather than a bare 0, so a clear refuses in-flight writes for pairs that have\n * never been invalidated too.\n */\nexport function getLanguageCacheGeneration(\n key: string,\n locale: string,\n db: DatabaseInterface | unknown,\n): number {\n const generation =\n cacheGenerations.get(buildGenerationKey(key, locale, db)) ?? 0;\n return generation > clearedThrough ? generation : clearedThrough;\n}\n\nexport function setCachedLanguage(\n key: string,\n locale: string,\n tenantId: string | null | undefined,\n db: DatabaseInterface | unknown,\n value: LanguageCacheValue,\n loadedAtGeneration: number,\n): void {\n if (getLanguageCacheGeneration(key, locale, db) !== loadedAtGeneration) {\n // A write landed while this resolution was loading. Its value is already\n // stale, so drop it rather than poison the entry for the whole TTL.\n return;\n }\n\n languageCache.set(buildCacheKey(key, locale, tenantId, db), {\n expiresAt: Date.now() + LANGUAGE_CACHE_TTL_MS,\n value,\n });\n}\n\n/**\n * Drop cached entries that match the given (key, locale).\n *\n * - When `tenantId` is provided, only that tenant's entries for this DB are dropped.\n * - When `tenantId` is null/undefined, every (key, locale, *) entry across tenants\n * is dropped — used for app-level writes that affect all tenants.\n */\nexport function invalidateLanguageCache(\n key: string,\n locale: string,\n tenantId: string | null | undefined,\n db: DatabaseInterface | unknown,\n): void {\n const dbNamespace = getDbNamespace(db);\n const normalizedLocale = normalizeLocale(locale);\n bumpGeneration(key, normalizedLocale, db);\n\n if (tenantId !== null && tenantId !== undefined) {\n languageCache.delete(buildCacheKey(key, normalizedLocale, tenantId, db));\n return;\n }\n\n const keyPrefix = `${dbNamespace}::${key}::${normalizedLocale}::`;\n for (const cacheKey of languageCache.keys()) {\n if (cacheKey.startsWith(keyPrefix)) {\n languageCache.delete(cacheKey);\n }\n }\n}\n\nexport function clearLanguageCache(): void {\n languageCache.clear();\n // Raise the floor instead of resetting counters: a resolution that started\n // before the clear must be refused its write, and raising a single floor\n // covers pairs with no generation entry, which a per-entry bump cannot reach.\n // With the floor carrying the refusal, the per-entry values can be dropped.\n clearedThrough = nextGeneration++;\n cacheGenerations.clear();\n}\n","import {\n field,\n RuntimeError,\n SmrtObject,\n type SmrtObjectOptions,\n type SmrtSaveOptions,\n smrt,\n} from '@happyvertical/smrt-core';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { invalidateLanguageCache } from '../cache.js';\nimport type { LanguageOverrideOptions } from '../types.js';\nimport { normalizeLocale } from '../utils.js';\n\ntype LanguageTransactionHandle = DatabaseInterface & {\n commit: () => Promise<void>;\n rollback: () => Promise<void>;\n};\n\nexport interface LanguageOverrideCtorOptions\n extends SmrtObjectOptions,\n LanguageOverrideOptions {}\n\n@smrt({\n tableName: '_smrt_language_overrides',\n conflictColumns: ['key', 'locale', 'context'],\n // Scope-bound LanguageSettingsService is the server management boundary.\n api: false,\n cli: false,\n mcp: false,\n})\nexport class LanguageOverride extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-languages\";\n @field({ required: true, requiredFor: 'identity' })\n key: string = '';\n\n @field({ required: true, requiredFor: 'identity' })\n locale: string = '';\n\n // Not tenant-scoped (any scope is writable), but the value is a tenant id:\n // uuid on Postgres, so it compares with every other tenant_id column.\n @field({ sqlType: 'UUID', nullable: true })\n tenantId: string | null = null;\n\n @field({ type: 'text' })\n template: string = '';\n\n /** True when this row was produced by the AI translation job. */\n @field({ type: 'boolean', required: true, default: false })\n auto_generated: boolean = false;\n\n /** sha256 of the source template at translation time, for re-translation gating. */\n @field({ type: 'text', nullable: true })\n source_hash: string | null = null;\n\n /** AI model identifier (null for human-edited rows). */\n @field({ type: 'text', nullable: true })\n ai_model: string | null = null;\n\n /** ISO timestamp marking admin review of an auto-generated row. */\n @field({ type: 'text', nullable: true })\n reviewed_at: string | null = null;\n\n /** User ID of the reviewer. */\n @field({ type: 'text', nullable: true })\n reviewed_by: string | null = null;\n\n constructor(options: LanguageOverrideCtorOptions = {}) {\n super(options);\n\n if (options.key !== undefined) this.key = options.key;\n if (options.locale !== undefined)\n this.locale = normalizeLocale(options.locale);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.template !== undefined) this.template = options.template;\n if (options.auto_generated !== undefined) {\n this.auto_generated = options.auto_generated;\n }\n if (options.source_hash !== undefined)\n this.source_hash = options.source_hash;\n if (options.ai_model !== undefined) this.ai_model = options.ai_model;\n if (options.reviewed_at !== undefined)\n this.reviewed_at = options.reviewed_at;\n if (options.reviewed_by !== undefined)\n this.reviewed_by = options.reviewed_by;\n }\n\n override async save(options?: SmrtSaveOptions): Promise<this> {\n if (!this.key || this.key.trim() === '') {\n throw new Error('LanguageOverride.key is required');\n }\n if (!this.locale || this.locale.trim() === '') {\n throw new Error('LanguageOverride.locale is required');\n }\n if (typeof this.template !== 'string') {\n throw new Error('LanguageOverride.template must be a string');\n }\n\n this.locale = normalizeLocale(this.locale);\n // `context` is the conflictColumn-friendly scope: '__app__' for nullable\n // tenant, tenantId otherwise. Mirrors the prompt-override convention.\n this.context = this.tenantId ?? '__app__';\n\n const previousIdentity = await this.getPersistedIdentity();\n const identityChanged =\n !!previousIdentity &&\n (previousIdentity.key !== this.key ||\n previousIdentity.locale !== this.locale ||\n previousIdentity.tenantId !== this.tenantId);\n\n // Persistence upserts on `(key, locale, context)`, so changing any of\n // those on an existing row makes a plain `super.save(options)` write the old\n // primary key under a new conflict identity — that hits the PK\n // constraint instead of moving the override. Use the same\n // delete-then-insert dance as PromptOverride: prefer a transaction when\n // the driver supports it; otherwise stage a replacement row first and\n // delete the old one only after the new one is durable.\n const result =\n identityChanged && previousIdentity\n ? await this.saveAfterIdentityChange(options)\n : await super.save(options);\n\n if (identityChanged && previousIdentity) {\n invalidateLanguageCache(\n previousIdentity.key,\n previousIdentity.locale,\n previousIdentity.tenantId,\n this.db,\n );\n }\n invalidateLanguageCache(this.key, this.locale, this.tenantId, this.db);\n return result;\n }\n\n private async saveAfterIdentityChange(\n options?: SmrtSaveOptions,\n ): Promise<this> {\n if (typeof this.db.beginTransaction === 'function') {\n return this.saveAfterIdentityChangeInTransaction(options);\n }\n return this.saveAfterIdentityChangeWithDeferredDelete(options);\n }\n\n private async saveAfterIdentityChangeInTransaction(\n options?: SmrtSaveOptions,\n ): Promise<this> {\n const originalDb = this._db;\n const originalOptionsDb = this.options.db;\n const tx = (await this.db.beginTransaction?.()) as\n | LanguageTransactionHandle\n | undefined;\n\n if (!tx) {\n return this.saveAfterIdentityChangeWithDeferredDelete(options);\n }\n\n try {\n this._db = tx;\n this.options.db = tx;\n // The caller's revision guards the ORIGINAL row (checked by the delete);\n // the replacement is a fresh insert and must not carry the update guard.\n await super.delete(\n options?.expectedUpdatedAt === undefined\n ? undefined\n : { expectedUpdatedAt: options.expectedUpdatedAt },\n );\n const result = await super.save(withoutRevisionGuard(options));\n await tx.commit();\n return result;\n } catch (error) {\n try {\n await tx.rollback();\n } catch {\n // Preserve the original save error; rollback failures are secondary.\n }\n throw error;\n } finally {\n this._db = originalDb;\n this.options.db = originalOptionsDb;\n }\n }\n\n private async saveAfterIdentityChangeWithDeferredDelete(\n options?: SmrtSaveOptions,\n ): Promise<this> {\n const previousId = this.id;\n if (!previousId) {\n return super.save(options);\n }\n\n // Without a transaction, a check here and the later unguarded delete are\n // not atomic: a concurrent update could be deleted. Fail closed rather\n // than accept a revision guard that cannot be honoured (#4408).\n if (options?.expectedUpdatedAt !== undefined) {\n throw new RuntimeError(\n `${this.constructor.name} identity changes honour expectedUpdatedAt only inside a transaction`,\n 'RUNTIME_REVISION_GUARD_REQUIRES_TRANSACTION',\n { className: this.constructor.name, id: previousId },\n );\n }\n\n const replacementId = crypto.randomUUID();\n let replacementSaved = false;\n this.id = replacementId;\n\n try {\n const result = await super.save(withoutRevisionGuard(options));\n replacementSaved = true;\n await this.db.delete(this.tableName, { id: previousId });\n return result;\n } catch (error) {\n if (replacementSaved) {\n try {\n await this.db.delete(this.tableName, { id: replacementId });\n } catch {\n // Best effort cleanup keeps the original row as the source of truth.\n }\n }\n this.id = previousId;\n throw error;\n }\n }\n\n override async delete(): Promise<void> {\n const key = this.key;\n const locale = this.locale;\n const tenantId = this.tenantId;\n await super.delete();\n invalidateLanguageCache(key, locale, tenantId, this.db);\n }\n\n /**\n * Mark this auto-generated row as reviewed by an admin. Useful for the\n * admin review queue surfaced via `smrt languages approve <id>`.\n */\n async approve(reviewerId: string): Promise<this> {\n this.reviewed_at = new Date().toISOString();\n this.reviewed_by = reviewerId;\n return this.save();\n }\n\n private async getPersistedIdentity(): Promise<{\n key: string;\n locale: string;\n tenantId: string | null;\n } | null> {\n if (!this.id) {\n return null;\n }\n\n // Raw DuckDB UUID values are native wrappers; compare canonical text.\n const { rows } = await this.db.query(\n `SELECT key, locale, CAST(tenant_id AS VARCHAR) AS tenant_id FROM ${this.tableName} WHERE id = ?`,\n this.id,\n );\n const existing = rows[0];\n if (!existing) {\n return null;\n }\n\n const row = existing as Record<string, unknown>;\n return {\n key: String(row.key ?? this.key),\n locale: String(row.locale ?? this.locale),\n tenantId:\n row.tenantId !== undefined\n ? (row.tenantId as string | null)\n : (((row.tenant_id as string | null | undefined) ?? null) as\n | string\n | null),\n };\n }\n}\n\nexport type { LanguageOverrideOptions } from '../types.js';\n\n/** The replacement row of an identity change is an insert, not a guarded update. */\nfunction withoutRevisionGuard(\n options: SmrtSaveOptions | undefined,\n): SmrtSaveOptions | undefined {\n if (!options || options.expectedUpdatedAt === undefined) return options;\n const { expectedUpdatedAt: _expected, ...rest } = options;\n return rest;\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { LanguageOverride } from '../models/LanguageOverride.js';\nimport { normalizeLocale } from '../utils.js';\n\nexport class LanguageOverrideCollection extends SmrtCollection<LanguageOverride> {\n static readonly _itemClass = LanguageOverride;\n\n /**\n * Look up the app-level (tenantId = null) override for a (key, locale) pair.\n * App-level rows hold AI auto-translations and ops-curated app-wide strings.\n */\n async getAppOverride(\n key: string,\n locale: string,\n ): Promise<LanguageOverride | null> {\n const items = await this.list({\n where: { key, locale: normalizeLocale(locale), tenantId: null },\n });\n return items[0] ?? null;\n }\n\n async getTenantOverride(\n key: string,\n locale: string,\n tenantId: string,\n ): Promise<LanguageOverride | null> {\n const items = await this.list({\n where: { key, locale: normalizeLocale(locale), tenantId },\n });\n return items[0] ?? null;\n }\n\n /**\n * Convenience helper for the resolver: returns the app and (optional) tenant\n * override rows for a (key, locale).\n */\n async getResolutionLayers(\n key: string,\n locale: string,\n tenantId?: string | null,\n ): Promise<{\n app: LanguageOverride | null;\n tenant: LanguageOverride | null;\n }> {\n const [app, tenant] = await Promise.all([\n this.getAppOverride(key, locale),\n tenantId != null\n ? this.getTenantOverride(key, locale, tenantId)\n : Promise.resolve(null),\n ]);\n return { app, tenant };\n }\n\n /** All overrides for a tenant (used to build the AI translation glossary). */\n async listTenantOverrides(tenantId: string): Promise<LanguageOverride[]> {\n return this.list({ where: { tenantId } });\n }\n\n /** Auto-generated overrides that no admin has approved yet. */\n async listUnreviewedAutoTranslations(\n options: { locale?: string; limit?: number } = {},\n ): Promise<LanguageOverride[]> {\n const where: Record<string, unknown> = {\n auto_generated: true,\n reviewed_at: null,\n };\n if (options.locale) {\n where.locale = normalizeLocale(options.locale);\n }\n return this.list({\n where,\n orderBy: 'createdAt ASC',\n limit: options.limit,\n });\n }\n}\n","import type { LanguageOverride } from './models/LanguageOverride.js';\nimport { normalizeLocale } from './utils.js';\n\n/**\n * Build a glossary string suitable for inclusion in an AI translation prompt.\n *\n * Pulls the tenant's existing language overrides for the source/target locales\n * and renders them as a concise list of \"source → target\" pairs, restricted to\n * keys that actually have both sides. The intent is \"make AI auto-translations\n * match tenant voice\", not bulk dump every override.\n *\n * Returns an empty string when there is nothing useful to add.\n */\nexport function buildTenantGlossary(\n overrides: LanguageOverride[],\n options: { sourceLocale: string; targetLocale: string; max?: number },\n): string {\n const sourceLocale = normalizeLocale(options.sourceLocale);\n const targetLocale = normalizeLocale(options.targetLocale);\n const max = options.max ?? 25;\n\n const sourceByKey = new Map<string, string>();\n const targetByKey = new Map<string, string>();\n\n for (const override of overrides) {\n if (!override.template) continue;\n const locale = normalizeLocale(override.locale);\n if (locale === sourceLocale) {\n sourceByKey.set(override.key, override.template);\n } else if (locale === targetLocale) {\n targetByKey.set(override.key, override.template);\n }\n }\n\n const pairs: string[] = [];\n for (const [key, source] of sourceByKey.entries()) {\n const target = targetByKey.get(key);\n if (target) {\n pairs.push(`- \"${source}\" → \"${target}\"`);\n if (pairs.length >= max) break;\n }\n }\n\n return pairs.join('\\n');\n}\n","import type {\n LanguageStringDefinition,\n LanguageStringDefinitionInput,\n} from './types.js';\nimport { computeSourceHash, normalizeLocale } from './utils.js';\n\ndeclare global {\n // eslint-disable-next-line no-var\n var __smrtLanguageRegistry:\n | Map<string, Map<string, LanguageStringDefinition>>\n | undefined;\n}\n\nfunction getRegistry(): Map<string, Map<string, LanguageStringDefinition>> {\n if (!globalThis.__smrtLanguageRegistry) {\n globalThis.__smrtLanguageRegistry = new Map();\n }\n return globalThis.__smrtLanguageRegistry;\n}\n\nfunction buildIndex(\n key: string,\n locale: string,\n): { key: string; locale: string } {\n return { key, locale: normalizeLocale(locale) };\n}\n\nexport const LanguageRegistry = {\n register(input: LanguageStringDefinitionInput): LanguageStringDefinition {\n if (!input.key || input.key.trim() === '') {\n throw new Error('Language string definitions require a non-empty key');\n }\n if (!input.locale || input.locale.trim() === '') {\n throw new Error(\n `Language string \"${input.key}\" requires a non-empty locale`,\n );\n }\n if (typeof input.template !== 'string') {\n throw new Error(\n `Language string \"${input.key}\" template must be a string`,\n );\n }\n\n const { key, locale } = buildIndex(input.key, input.locale);\n const definition: LanguageStringDefinition = {\n key,\n locale,\n template: input.template,\n sourceHash: computeSourceHash(input.template),\n };\n\n const registry = getRegistry();\n let byLocale = registry.get(key);\n if (!byLocale) {\n byLocale = new Map();\n registry.set(key, byLocale);\n }\n\n const existing = byLocale.get(locale);\n if (existing) {\n if (existing.template !== definition.template) {\n throw new Error(\n `Language string \"${key}\" is already registered for locale \"${locale}\" with a different template`,\n );\n }\n return existing;\n }\n\n byLocale.set(locale, definition);\n return definition;\n },\n\n get(key: string, locale: string): LanguageStringDefinition | undefined {\n return getRegistry().get(key)?.get(normalizeLocale(locale));\n },\n\n has(key: string, locale: string): boolean {\n return Boolean(this.get(key, locale));\n },\n\n hasKey(key: string): boolean {\n return getRegistry().has(key);\n },\n\n /** Return the locales that have a registered code default for the given key. */\n getLocalesForKey(key: string): string[] {\n const byLocale = getRegistry().get(key);\n return byLocale ? Array.from(byLocale.keys()) : [];\n },\n\n /** All registered (key, locale, template) triples. Used by the batch translator. */\n getAll(): LanguageStringDefinition[] {\n const all: LanguageStringDefinition[] = [];\n for (const byLocale of getRegistry().values()) {\n for (const definition of byLocale.values()) {\n all.push(definition);\n }\n }\n return all;\n },\n\n /** Distinct keys currently registered. */\n getKeys(): string[] {\n return Array.from(getRegistry().keys());\n },\n\n clear(): void {\n getRegistry().clear();\n },\n};\n\nexport function defineLanguageString(\n input: LanguageStringDefinitionInput,\n): LanguageStringDefinition {\n return LanguageRegistry.register(input);\n}\n","import {\n field,\n SmrtCollection,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\n\n/** Durable tombstone: RESET must invalidate work even when no override exists. */\n@smrt({\n tableName: '_smrt_language_mutation_revisions',\n conflictColumns: ['key', 'locale', 'context'],\n api: false,\n cli: false,\n mcp: false,\n})\nexport class LanguageMutationRevision extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-languages\";\n @field({ required: true, requiredFor: 'identity' })\n key: string = '';\n\n @field({ required: true, requiredFor: 'identity' })\n locale: string = '';\n\n @field({ required: true, requiredFor: 'idempotency' })\n revision: string = '';\n}\n\nexport class LanguageMutationRevisionCollection extends SmrtCollection<LanguageMutationRevision> {\n static readonly _itemClass = LanguageMutationRevision;\n}\n","import { randomUUID } from 'node:crypto';\nimport type { SmrtClassOptions } from '@happyvertical/smrt-core';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { invalidateLanguageCache } from './cache.js';\nimport { LanguageOverrideCollection } from './collections/LanguageOverrideCollection.js';\nimport { LanguageMutationRevisionCollection } from './models/LanguageMutationRevision.js';\nimport { normalizeLocale } from './utils.js';\n\nexport type LanguageMutationScope =\n | { type: 'app' }\n | { type: 'tenant'; tenantId: string };\n\nfunction scopeContext(scope: LanguageMutationScope): string {\n if (scope.type === 'app') return '__app__';\n if (\n scope.type !== 'tenant' ||\n !scope.tenantId ||\n scope.tenantId === '__app__'\n ) {\n throw new TypeError('Invalid language mutation scope');\n }\n return scope.tenantId;\n}\n\nasync function database(options: SmrtClassOptions): Promise<DatabaseInterface> {\n return (await LanguageMutationRevisionCollection.create(options)).db;\n}\n\nasync function ensureRevision(\n db: DatabaseInterface,\n scope: LanguageMutationScope,\n key: string,\n locale: string,\n): Promise<void> {\n const id = randomUUID();\n const now = new Date().toISOString();\n await db.query(\n `INSERT INTO _smrt_language_mutation_revisions\n (id, slug, context, created_at, updated_at, key, locale, revision)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (key, locale, context) DO NOTHING`,\n id,\n id,\n scopeContext(scope),\n now,\n now,\n key,\n normalizeLocale(locale),\n `pristine:${id}`,\n );\n}\n\n/** Capture at enqueue, never at writeback. This is a durable scope/key tombstone. */\nexport async function captureLanguageRevision(\n options: SmrtClassOptions,\n scope: LanguageMutationScope,\n key: string,\n locale: string,\n): Promise<string> {\n const db = await database(options);\n await ensureRevision(db, scope, key, locale);\n const result = await db.query(\n 'SELECT revision FROM _smrt_language_mutation_revisions WHERE key = ? AND locale = ? AND context = ?',\n key,\n normalizeLocale(locale),\n scopeContext(scope),\n );\n const revision = result.rows[0]?.revision;\n if (typeof revision !== 'string')\n throw new Error('Missing language revision');\n return revision;\n}\n\n/**\n * Snapshotless legacy work may adopt only a provably untouched revision.\n * Old UUID tokens have unknown history and are never rewritten to pristine.\n * Return this exact token to CAS; recapturing later could adopt a raced RESET.\n */\nexport async function capturePristineLanguageRevision(\n options: SmrtClassOptions,\n scope: LanguageMutationScope,\n key: string,\n locale: string,\n): Promise<string | null> {\n const db = await database(options);\n await ensureRevision(db, scope, key, locale);\n const result = await db.query(\n 'SELECT CAST(id AS TEXT) AS revision_id, revision FROM _smrt_language_mutation_revisions WHERE key = ? AND locale = ? AND context = ?',\n key,\n normalizeLocale(locale),\n scopeContext(scope),\n );\n const row = result.rows[0];\n return row && row.revision === `pristine:${String(row.revision_id)}`\n ? String(row.revision)\n : null;\n}\n\n/** All administrator mutations, including absent RESET, share this transaction. */\nexport async function withLanguageMutation<T>(\n options: SmrtClassOptions,\n scope: LanguageMutationScope,\n key: string,\n locale: string,\n fn: (db: DatabaseInterface) => Promise<T>,\n): Promise<T> {\n const db = await database(options);\n if (!db.transaction)\n throw new Error('Language mutations require transactions');\n const result = await db.transaction(async (tx) => {\n await ensureRevision(tx, scope, key, locale);\n await tx.query(\n 'UPDATE _smrt_language_mutation_revisions SET revision = ?, updated_at = ? WHERE key = ? AND locale = ? AND context = ?',\n randomUUID(),\n new Date().toISOString(),\n key,\n normalizeLocale(locale),\n scopeContext(scope),\n );\n return fn(tx);\n });\n invalidateLanguageCache(\n key,\n normalizeLocale(locale),\n scope.type === 'tenant' ? scope.tenantId : null,\n db,\n );\n return result;\n}\n\nexport interface GeneratedLanguageMutation {\n key: string;\n locale: string;\n template: string;\n expectedRevision: string;\n expectedAppRevision?: string;\n sourceHash: string;\n aiModel: string | null;\n}\n\n/** Claim revision and persist in one transaction; rollback retains the old token. */\nexport async function commitGeneratedLanguage(\n options: SmrtClassOptions,\n scope: LanguageMutationScope,\n input: GeneratedLanguageMutation,\n): Promise<boolean> {\n const db = await database(options);\n if (!db.transaction)\n throw new Error('Language mutations require transactions');\n const result = await db.transaction(async (tx) => {\n if (scope.type === 'tenant') {\n if (!input.expectedAppRevision) return false;\n const app = await tx.query(\n 'UPDATE _smrt_language_mutation_revisions SET updated_at = updated_at WHERE key = ? AND locale = ? AND context = ? AND revision = ? RETURNING id',\n input.key,\n normalizeLocale(input.locale),\n '__app__',\n input.expectedAppRevision,\n );\n if (app.rows.length !== 1) return false;\n }\n const claimed = await tx.query(\n `UPDATE _smrt_language_mutation_revisions SET revision = ?, updated_at = ?\n WHERE key = ? AND locale = ? AND context = ? AND revision = ? RETURNING id`,\n randomUUID(),\n new Date().toISOString(),\n input.key,\n normalizeLocale(input.locale),\n scopeContext(scope),\n input.expectedRevision,\n );\n if (claimed.rows.length !== 1) return false;\n const overrides = await LanguageOverrideCollection.create({ db: tx });\n const existing =\n scope.type === 'tenant'\n ? await overrides.getTenantOverride(\n input.key,\n input.locale,\n scope.tenantId,\n )\n : await overrides.getAppOverride(input.key, input.locale);\n // An exact entry is no longer a gap, even if generated by another job.\n if (\n existing ||\n (scope.type === 'tenant' &&\n (await overrides.getAppOverride(input.key, input.locale)))\n )\n return false;\n await overrides.create({\n key: input.key,\n locale: input.locale,\n tenantId: scope.type === 'tenant' ? scope.tenantId : null,\n template: input.template,\n auto_generated: true,\n source_hash: input.sourceHash,\n ai_model: input.aiModel,\n reviewed_at: null,\n reviewed_by: null,\n });\n return true;\n });\n if (result)\n invalidateLanguageCache(\n input.key,\n normalizeLocale(input.locale),\n scope.type === 'tenant' ? scope.tenantId : null,\n db,\n );\n return result;\n}\n"],"mappings":";;;AAGO,SAAS,cACd,OACkC;CAClC,OAAO,CAAC,CAAC,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AACrE;AAGO,SAAS,kBAAkB,UAA0B;CAC1D,OAAO,UAAU,WAAW,QAAQ,CAAA,CAAE,OAAO,UAAU,MAAM,CAAA,CAAE,OAAO,KAAK;AAC7E;AAaO,SAAS,gBAAgB,QAAwB;CACtD,IAAI,CAAC,QAAQ,OAAO;CACpB,MAAM,UAAU,OAAO,KAAK;CAC5B,IAAI,CAAC,SAAS,OAAO;CACrB,MAAM,CAAC,UAAU,GAAG,QAAQ,QAAQ,MAAM,GAAG;CAC7C,IAAI,KAAK,WAAW,GAClB,OAAO,SAAS,YAAY;CAE9B,OAAO,CACL,SAAS,YAAY,GACrB,GAAG,KAAK,KAAK,SAAS,KAAK,YAAY,CAAC,CAC1C,CAAA,CAAE,KAAK,GAAG;AACZ;AAQO,SAAS,yBACd,WACA,eACU;CACV,MAAM,QAAkB,CAAC;CACzB,MAAM,QAAQ,UAAkB;EAC9B,MAAM,aAAa,gBAAgB,KAAK;EACxC,IAAI,cAAc,CAAC,MAAM,SAAS,UAAU,GAC1C,MAAM,KAAK,UAAU;CAEz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