@form-engine-ts/translator-cache 2.6.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 form-engine-ts contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,24 @@
1
+ # @form-engine-ts/translator-cache
2
+
3
+ Cache decorator for any `AsyncTranslationAdapter`. Cache storage is injected, so applications can use memory, Redis,
4
+ durable edge storage, or another TTL-capable backend without coupling the package to a vendor.
5
+
6
+ ## Install
7
+
8
+ ```bash
9
+ pnpm add @form-engine-ts/core @form-engine-ts/translator-cache
10
+ ```
11
+
12
+ ## Usage
13
+
14
+ ```ts
15
+ import { withTranslationCache } from "@form-engine-ts/translator-cache";
16
+
17
+ const translator = withTranslationCache(baseTranslator, cacheStorage, {
18
+ ttlMs: 60 * 60 * 1000,
19
+ keyPrefix: "survey-translations"
20
+ });
21
+ ```
22
+
23
+ Keys isolate source locale, target locale, and a deterministic UTF-8 hash of the source text. Batch misses are deduplicated,
24
+ translated once in source order, cached, and restored to their original positions.
package/dist/index.cjs ADDED
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ hashTranslationText: () => hashTranslationText,
24
+ withTranslationCache: () => withTranslationCache
25
+ });
26
+ module.exports = __toCommonJS(index_exports);
27
+ var FNV_OFFSET_BASIS = 14695981039346656037n;
28
+ var FNV_PRIME = 1099511628211n;
29
+ var UINT64_MASK = 0xffffffffffffffffn;
30
+ function hashTranslationText(text) {
31
+ if (typeof text !== "string") throw new TypeError("text must be a string.");
32
+ let hash = FNV_OFFSET_BASIS;
33
+ for (const byte of new TextEncoder().encode(text)) {
34
+ hash ^= BigInt(byte);
35
+ hash = hash * FNV_PRIME & UINT64_MASK;
36
+ }
37
+ return hash.toString(16).padStart(16, "0");
38
+ }
39
+ function requireLocale(value, name) {
40
+ if (typeof value !== "string" || value.trim().length === 0) throw new TypeError(`${name} must not be empty.`);
41
+ return value.trim();
42
+ }
43
+ function withTranslationCache(baseAdapter, cache, options = {}) {
44
+ if (typeof baseAdapter?.translateBatch !== "function") throw new TypeError("baseAdapter.translateBatch is required.");
45
+ if (typeof cache?.get !== "function" || typeof cache.set !== "function") {
46
+ throw new TypeError("cache must implement get and set.");
47
+ }
48
+ if (options.ttlMs !== void 0 && (!Number.isSafeInteger(options.ttlMs) || options.ttlMs < 0)) {
49
+ throw new TypeError("ttlMs must be a non-negative safe integer.");
50
+ }
51
+ const prefix = options.keyPrefix ?? "form-engine-ts";
52
+ if (prefix.trim().length === 0) throw new TypeError("keyPrefix must not be empty.");
53
+ const translateBatch = async (texts, targetLocale, sourceLocale) => {
54
+ if (!Array.isArray(texts) || texts.some((text) => typeof text !== "string")) {
55
+ throw new TypeError("texts must be an array of strings.");
56
+ }
57
+ const target = requireLocale(targetLocale, "targetLocale");
58
+ const source = sourceLocale === void 0 ? "auto" : requireLocale(sourceLocale, "sourceLocale");
59
+ const keys = texts.map((text) => `${prefix}:${source}:${target}:${hashTranslationText(text)}`);
60
+ const cached = await Promise.all(keys.map((key) => cache.get(key)));
61
+ const missingByKey = /* @__PURE__ */ new Map();
62
+ for (let index = 0; index < texts.length; index += 1) {
63
+ if (cached[index] !== void 0) continue;
64
+ const key = keys[index];
65
+ const text = texts[index];
66
+ if (key === void 0 || text === void 0) throw new Error("Translation cache index is unavailable.");
67
+ const missing = missingByKey.get(key);
68
+ if (missing === void 0) missingByKey.set(key, { text, indices: [index] });
69
+ else missing.indices.push(index);
70
+ }
71
+ if (missingByKey.size > 0) {
72
+ const missing = [...missingByKey.entries()];
73
+ const translated = await baseAdapter.translateBatch(
74
+ missing.map(([, value]) => value.text),
75
+ target,
76
+ sourceLocale
77
+ );
78
+ if (translated.length !== missing.length) {
79
+ throw new Error(`Translation adapter returned ${translated.length} values for ${missing.length} cache misses.`);
80
+ }
81
+ await Promise.all(
82
+ missing.map(async ([key, value], translatedIndex) => {
83
+ const translation = translated[translatedIndex];
84
+ if (translation === void 0) throw new Error("Translation adapter result is unavailable.");
85
+ await cache.set(key, translation, options.ttlMs);
86
+ for (const index of value.indices) cached[index] = translation;
87
+ })
88
+ );
89
+ }
90
+ return cached.map((value) => {
91
+ if (value === void 0) throw new Error("Translation cache result is unavailable.");
92
+ return value;
93
+ });
94
+ };
95
+ return {
96
+ async translateText(text, targetLocale, sourceLocale) {
97
+ const translated = await translateBatch([text], targetLocale, sourceLocale);
98
+ const value = translated[0];
99
+ if (value === void 0) throw new Error("Translation cache returned no translation.");
100
+ return value;
101
+ },
102
+ translateBatch
103
+ };
104
+ }
105
+ // Annotate the CommonJS export names for ESM import in node:
106
+ 0 && (module.exports = {
107
+ hashTranslationText,
108
+ withTranslationCache
109
+ });
@@ -0,0 +1,14 @@
1
+ import { AsyncTranslationAdapter } from '@form-engine-ts/core';
2
+
3
+ interface TranslationCacheStorage {
4
+ get(key: string): Promise<string | undefined> | string | undefined;
5
+ set(key: string, value: string, ttlMs?: number): Promise<void> | void;
6
+ }
7
+ interface TranslationCacheOptions {
8
+ readonly ttlMs?: number;
9
+ readonly keyPrefix?: string;
10
+ }
11
+ declare function hashTranslationText(text: string): string;
12
+ declare function withTranslationCache(baseAdapter: AsyncTranslationAdapter, cache: TranslationCacheStorage, options?: TranslationCacheOptions): AsyncTranslationAdapter;
13
+
14
+ export { type TranslationCacheOptions, type TranslationCacheStorage, hashTranslationText, withTranslationCache };
@@ -0,0 +1,14 @@
1
+ import { AsyncTranslationAdapter } from '@form-engine-ts/core';
2
+
3
+ interface TranslationCacheStorage {
4
+ get(key: string): Promise<string | undefined> | string | undefined;
5
+ set(key: string, value: string, ttlMs?: number): Promise<void> | void;
6
+ }
7
+ interface TranslationCacheOptions {
8
+ readonly ttlMs?: number;
9
+ readonly keyPrefix?: string;
10
+ }
11
+ declare function hashTranslationText(text: string): string;
12
+ declare function withTranslationCache(baseAdapter: AsyncTranslationAdapter, cache: TranslationCacheStorage, options?: TranslationCacheOptions): AsyncTranslationAdapter;
13
+
14
+ export { type TranslationCacheOptions, type TranslationCacheStorage, hashTranslationText, withTranslationCache };
package/dist/index.js ADDED
@@ -0,0 +1,83 @@
1
+ // src/index.ts
2
+ var FNV_OFFSET_BASIS = 14695981039346656037n;
3
+ var FNV_PRIME = 1099511628211n;
4
+ var UINT64_MASK = 0xffffffffffffffffn;
5
+ function hashTranslationText(text) {
6
+ if (typeof text !== "string") throw new TypeError("text must be a string.");
7
+ let hash = FNV_OFFSET_BASIS;
8
+ for (const byte of new TextEncoder().encode(text)) {
9
+ hash ^= BigInt(byte);
10
+ hash = hash * FNV_PRIME & UINT64_MASK;
11
+ }
12
+ return hash.toString(16).padStart(16, "0");
13
+ }
14
+ function requireLocale(value, name) {
15
+ if (typeof value !== "string" || value.trim().length === 0) throw new TypeError(`${name} must not be empty.`);
16
+ return value.trim();
17
+ }
18
+ function withTranslationCache(baseAdapter, cache, options = {}) {
19
+ if (typeof baseAdapter?.translateBatch !== "function") throw new TypeError("baseAdapter.translateBatch is required.");
20
+ if (typeof cache?.get !== "function" || typeof cache.set !== "function") {
21
+ throw new TypeError("cache must implement get and set.");
22
+ }
23
+ if (options.ttlMs !== void 0 && (!Number.isSafeInteger(options.ttlMs) || options.ttlMs < 0)) {
24
+ throw new TypeError("ttlMs must be a non-negative safe integer.");
25
+ }
26
+ const prefix = options.keyPrefix ?? "form-engine-ts";
27
+ if (prefix.trim().length === 0) throw new TypeError("keyPrefix must not be empty.");
28
+ const translateBatch = async (texts, targetLocale, sourceLocale) => {
29
+ if (!Array.isArray(texts) || texts.some((text) => typeof text !== "string")) {
30
+ throw new TypeError("texts must be an array of strings.");
31
+ }
32
+ const target = requireLocale(targetLocale, "targetLocale");
33
+ const source = sourceLocale === void 0 ? "auto" : requireLocale(sourceLocale, "sourceLocale");
34
+ const keys = texts.map((text) => `${prefix}:${source}:${target}:${hashTranslationText(text)}`);
35
+ const cached = await Promise.all(keys.map((key) => cache.get(key)));
36
+ const missingByKey = /* @__PURE__ */ new Map();
37
+ for (let index = 0; index < texts.length; index += 1) {
38
+ if (cached[index] !== void 0) continue;
39
+ const key = keys[index];
40
+ const text = texts[index];
41
+ if (key === void 0 || text === void 0) throw new Error("Translation cache index is unavailable.");
42
+ const missing = missingByKey.get(key);
43
+ if (missing === void 0) missingByKey.set(key, { text, indices: [index] });
44
+ else missing.indices.push(index);
45
+ }
46
+ if (missingByKey.size > 0) {
47
+ const missing = [...missingByKey.entries()];
48
+ const translated = await baseAdapter.translateBatch(
49
+ missing.map(([, value]) => value.text),
50
+ target,
51
+ sourceLocale
52
+ );
53
+ if (translated.length !== missing.length) {
54
+ throw new Error(`Translation adapter returned ${translated.length} values for ${missing.length} cache misses.`);
55
+ }
56
+ await Promise.all(
57
+ missing.map(async ([key, value], translatedIndex) => {
58
+ const translation = translated[translatedIndex];
59
+ if (translation === void 0) throw new Error("Translation adapter result is unavailable.");
60
+ await cache.set(key, translation, options.ttlMs);
61
+ for (const index of value.indices) cached[index] = translation;
62
+ })
63
+ );
64
+ }
65
+ return cached.map((value) => {
66
+ if (value === void 0) throw new Error("Translation cache result is unavailable.");
67
+ return value;
68
+ });
69
+ };
70
+ return {
71
+ async translateText(text, targetLocale, sourceLocale) {
72
+ const translated = await translateBatch([text], targetLocale, sourceLocale);
73
+ const value = translated[0];
74
+ if (value === void 0) throw new Error("Translation cache returned no translation.");
75
+ return value;
76
+ },
77
+ translateBatch
78
+ };
79
+ }
80
+ export {
81
+ hashTranslationText,
82
+ withTranslationCache
83
+ };
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@form-engine-ts/translator-cache",
3
+ "version": "2.6.0",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
7
+ "type": "module",
8
+ "sideEffects": false,
9
+ "files": [
10
+ "dist",
11
+ "README.md",
12
+ "LICENSE"
13
+ ],
14
+ "main": "./dist/index.cjs",
15
+ "module": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js",
21
+ "require": "./dist/index.cjs"
22
+ }
23
+ },
24
+ "license": "MIT",
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/nitta-a/form-engine-ts.git",
28
+ "directory": "packages/translator-cache"
29
+ },
30
+ "bugs": {
31
+ "url": "https://github.com/nitta-a/form-engine-ts/issues"
32
+ },
33
+ "homepage": "https://github.com/nitta-a/form-engine-ts#readme",
34
+ "keywords": [
35
+ "form",
36
+ "translation",
37
+ "cache",
38
+ "typescript"
39
+ ],
40
+ "dependencies": {
41
+ "@form-engine-ts/core": "2.6.0"
42
+ },
43
+ "scripts": {
44
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean --external @form-engine-ts/core",
45
+ "check": "biome check . && tsc --noEmit",
46
+ "test": "vitest run --globals",
47
+ "typecheck": "tsc --noEmit"
48
+ }
49
+ }