cc-translate 1.3.0 → 1.3.3
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/README.md +128 -10
- package/index.d.ts +5 -4
- package/index.js +417 -119
- package/lib/cache/index.d.ts +9 -3
- package/lib/cache/index.d.ts.map +1 -1
- package/lib/cache/index.js +87 -4
- package/lib/log/index.d.ts +1 -1
- package/lib/log/index.d.ts.map +1 -1
- package/lib/support.d.ts +1 -1
- package/lib/support.d.ts.map +1 -1
- package/lib/translation-format.d.ts +5 -0
- package/lib/translation-format.d.ts.map +1 -0
- package/lib/translation-format.js +31 -0
- package/lib/translation-metadata.d.ts +12 -0
- package/lib/translation-metadata.d.ts.map +1 -0
- package/lib/translation-metadata.js +94 -0
- package/lib/translation-reference.d.ts +4 -2
- package/lib/translation-reference.d.ts.map +1 -1
- package/lib/translation-reference.js +52 -35
- package/lib/translation-response.d.ts +9 -0
- package/lib/translation-response.d.ts.map +1 -0
- package/lib/translation-response.js +169 -0
- package/lib/utils.d.ts +1 -1
- package/lib/utils.d.ts.map +1 -1
- package/package.json +3 -2
- package/types/index.d.ts +46 -10
- package/types/index.d.ts.map +1 -1
- package/CHANGELOG.md +0 -41
package/lib/cache/index.d.ts
CHANGED
|
@@ -1,17 +1,23 @@
|
|
|
1
|
-
import { IDeleteSingleCacheParams, IGenerateCacheParams, IJson, IRegisterLanguageCacheFile } from "../../types";
|
|
1
|
+
import { IDeleteSingleCacheParams, IGenerateCacheParams, IJson, IRegisterLanguageCacheFile, MissingReferenceIds, ReferenceCacheState, ReferenceSnapshot, SourceCache } from "../../types/index.js";
|
|
2
2
|
/**
|
|
3
3
|
* 和翻译缓存json文件对比 返回存在更改的json文件
|
|
4
4
|
* @param {object} cacheObject 已经缓存的对象
|
|
5
5
|
* @param {object} translateObject 需要翻译的对象
|
|
6
6
|
* @returns {object} 存在修改的对象
|
|
7
7
|
*/
|
|
8
|
-
export declare const translateJSONDiffToJson: (cacheObject:
|
|
8
|
+
export declare const translateJSONDiffToJson: (cacheObject: SourceCache, translateObject: IJson) => IJson;
|
|
9
9
|
/**
|
|
10
10
|
* 获取缓存文件
|
|
11
11
|
* @param {string} filePath 缓存文件路径
|
|
12
12
|
* @returns {Promise<{key:value}>}
|
|
13
13
|
*/
|
|
14
|
-
export declare const getCacheFileSync: (filePath: string) => Promise<
|
|
14
|
+
export declare const getCacheFileSync: (filePath: string) => Promise<SourceCache>;
|
|
15
|
+
export declare const readReferenceCache: (filePath: string, previouslyMissing?: Map<string, Set<string>>) => Map<string, ReferenceSnapshot>;
|
|
16
|
+
export declare const writeReferenceCache: ({ filePath, observed }: ReferenceCacheState) => void;
|
|
17
|
+
export declare const referenceDigest: (snapshot: ReferenceSnapshot) => string;
|
|
18
|
+
export declare const getRejectedReferences: (cache: SourceCache) => IJson;
|
|
19
|
+
export declare const getMissingReferenceIds: (cache: SourceCache) => MissingReferenceIds;
|
|
20
|
+
export declare const writeMissingReferenceIds: (filePath: string, updates: MissingReferenceIds) => Promise<void>;
|
|
15
21
|
/**
|
|
16
22
|
* 注册语言缓存文件
|
|
17
23
|
* @param {string} language
|
package/lib/cache/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/lib/cache/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/lib/cache/index.ts"],"names":[],"mappings":"AAQA,OAAO,EAEL,wBAAwB,EACxB,oBAAoB,EACpB,KAAK,EACL,0BAA0B,EAC1B,mBAAmB,EACnB,mBAAmB,EACnB,iBAAiB,EACjB,WAAW,EACZ,MAAM,sBAAsB,CAAC;AAE9B;;;;;GAKG;AACH,eAAO,MAAM,uBAAuB,gBACrB,WAAW,mBACP,KAAK,UAiBvB,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,aAAoB,MAAM,KAAG,OAAO,CAAC,WAAW,CAM5E,CAAC;AAGF,eAAO,MAAM,kBAAkB,aACnB,MAAM,sBACI,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,KAC3C,GAAG,CAAC,MAAM,EAAE,iBAAiB,CAmB/B,CAAC;AAaF,eAAO,MAAM,mBAAmB,2BAA4B,mBAAmB,SAG9E,CAAC;AAGF,eAAO,MAAM,eAAe,aAAc,iBAAiB,KAAG,MAC8B,CAAC;AAE7F,eAAO,MAAM,qBAAqB,UAAW,WAAW,KAAG,KAI1D,CAAC;AAEF,eAAO,MAAM,sBAAsB,UAAW,WAAW,KAAG,mBAI3D,CAAC;AAWF,eAAO,MAAM,wBAAwB,aAAoB,MAAM,WAAW,mBAAmB,kBAI5F,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,yBAAyB,WAC5B,0BAA0B,kBA+BnC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,aAAa,WAAkB,oBAAoB,kBAwC/D,CAAC;AAwCF;;;GAGG;AACH,eAAO,MAAM,gBAAgB,WAAY,wBAAwB,SAmChE,CAAC"}
|
package/lib/cache/index.js
CHANGED
|
@@ -9,6 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
9
9
|
};
|
|
10
10
|
import path from "path";
|
|
11
11
|
import fs from "fs";
|
|
12
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
12
13
|
import { intersection, notExistsToCreateFile, readJsonFileSync, } from "../utils.js";
|
|
13
14
|
/**
|
|
14
15
|
* 和翻译缓存json文件对比 返回存在更改的json文件
|
|
@@ -46,18 +47,95 @@ export const getCacheFileSync = (filePath) => __awaiter(void 0, void 0, void 0,
|
|
|
46
47
|
return {};
|
|
47
48
|
}
|
|
48
49
|
});
|
|
50
|
+
// 参考快照单独存储,保留现有源文案缓存的格式。
|
|
51
|
+
export const readReferenceCache = (filePath, previouslyMissing) => {
|
|
52
|
+
const snapshots = new Map();
|
|
53
|
+
if (!fs.existsSync(filePath))
|
|
54
|
+
return snapshots;
|
|
55
|
+
const stored = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
56
|
+
for (const [key, snapshot] of Object.entries(stored)) {
|
|
57
|
+
const entries = Object.entries(snapshot);
|
|
58
|
+
// 旧格式中的 null 只参与本次变更判断,不再写入参考缓存。
|
|
59
|
+
const missing = entries.filter(([, value]) => value === null).map(([id]) => id);
|
|
60
|
+
if (missing.length)
|
|
61
|
+
previouslyMissing === null || previouslyMissing === void 0 ? void 0 : previouslyMissing.set(key, new Set(missing));
|
|
62
|
+
const matched = entries.filter((entry) => typeof entry[1] === "string" && entry[1].trim() !== "");
|
|
63
|
+
if (matched.length)
|
|
64
|
+
snapshots.set(key, Object.fromEntries(matched));
|
|
65
|
+
}
|
|
66
|
+
return snapshots;
|
|
67
|
+
};
|
|
68
|
+
const writeCacheJson = (filePath, value) => {
|
|
69
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
70
|
+
const temporaryPath = `${filePath}.${randomUUID()}.tmp`;
|
|
71
|
+
try {
|
|
72
|
+
fs.writeFileSync(temporaryPath, JSON.stringify(value, null, 2));
|
|
73
|
+
fs.renameSync(temporaryPath, filePath);
|
|
74
|
+
}
|
|
75
|
+
finally {
|
|
76
|
+
fs.rmSync(temporaryPath, { force: true });
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
export const writeReferenceCache = ({ filePath, observed }) => {
|
|
80
|
+
if (observed.size)
|
|
81
|
+
writeCacheJson(filePath, Object.fromEntries(observed));
|
|
82
|
+
else
|
|
83
|
+
fs.rmSync(filePath, { force: true });
|
|
84
|
+
};
|
|
85
|
+
// 普通缓存仅保存未采用参考的摘要,供下次按 key 比较变化,不保存参考原文。
|
|
86
|
+
export const referenceDigest = (snapshot) => createHash("sha256").update(JSON.stringify(Object.entries(snapshot).sort())).digest("hex");
|
|
87
|
+
export const getRejectedReferences = (cache) => {
|
|
88
|
+
const metadata = cache._meta;
|
|
89
|
+
const rejected = metadata && typeof metadata === "object" ? metadata.rejectedReferences : undefined;
|
|
90
|
+
return Object.assign(Object.create(null), rejected);
|
|
91
|
+
};
|
|
92
|
+
export const getMissingReferenceIds = (cache) => {
|
|
93
|
+
const metadata = cache._meta;
|
|
94
|
+
const missing = metadata && typeof metadata === "object" ? metadata.missingReferenceIds : undefined;
|
|
95
|
+
return Object.assign(Object.create(null), missing);
|
|
96
|
+
};
|
|
97
|
+
const setSourceCacheMetadata = (cache, rejected, missing) => {
|
|
98
|
+
const metadata = Object.assign(Object.assign({}, (Object.keys(rejected).length ? { rejectedReferences: rejected } : {})), (Object.keys(missing).length ? { missingReferenceIds: missing } : {}));
|
|
99
|
+
if (Object.keys(metadata).length)
|
|
100
|
+
cache._meta = metadata;
|
|
101
|
+
else
|
|
102
|
+
delete cache._meta;
|
|
103
|
+
};
|
|
104
|
+
export const writeMissingReferenceIds = (filePath, updates) => __awaiter(void 0, void 0, void 0, function* () {
|
|
105
|
+
const cache = yield getCacheFileSync(filePath);
|
|
106
|
+
setSourceCacheMetadata(cache, getRejectedReferences(cache), Object.assign(Object.assign({}, getMissingReferenceIds(cache)), updates));
|
|
107
|
+
writeCacheJson(filePath, cache);
|
|
108
|
+
});
|
|
49
109
|
/**
|
|
50
110
|
* 注册语言缓存文件
|
|
51
111
|
* @param {string} language
|
|
52
112
|
*/
|
|
53
113
|
export const registerLanguageCacheFile = (params) => __awaiter(void 0, void 0, void 0, function* () {
|
|
114
|
+
var _a;
|
|
54
115
|
const { jsonMap, sourceFilePath, fileName, language, folderName } = params;
|
|
55
116
|
const cacheFilePath = path.join(folderName, language, fileName);
|
|
56
117
|
const sourceObject = yield readJsonFileSync(sourceFilePath);
|
|
57
|
-
const cacheObject = yield
|
|
58
|
-
|
|
118
|
+
const cacheObject = yield getCacheFileSync(cacheFilePath);
|
|
119
|
+
const rejectedReferences = getRejectedReferences(cacheObject);
|
|
120
|
+
const missingReferenceIds = getMissingReferenceIds(cacheObject);
|
|
121
|
+
for (const key of Object.keys(jsonMap)) {
|
|
122
|
+
if (key === "_meta")
|
|
123
|
+
continue;
|
|
59
124
|
cacheObject[key] = sourceObject[key];
|
|
60
|
-
|
|
125
|
+
const digest = (_a = params.rejectedReferences) === null || _a === void 0 ? void 0 : _a[key];
|
|
126
|
+
if (digest)
|
|
127
|
+
rejectedReferences[key] = digest;
|
|
128
|
+
else
|
|
129
|
+
delete rejectedReferences[key];
|
|
130
|
+
if (params.usedReferenceId && missingReferenceIds[key]) {
|
|
131
|
+
const remaining = missingReferenceIds[key].filter((id) => id !== params.usedReferenceId);
|
|
132
|
+
if (remaining.length)
|
|
133
|
+
missingReferenceIds[key] = remaining;
|
|
134
|
+
else
|
|
135
|
+
delete missingReferenceIds[key];
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
setSourceCacheMetadata(cacheObject, rejectedReferences, missingReferenceIds);
|
|
61
139
|
if (Object.values(jsonMap).length === 0)
|
|
62
140
|
return;
|
|
63
141
|
notExistsToCreateFile(folderName);
|
|
@@ -85,7 +163,7 @@ export const generateCache = (params) => __awaiter(void 0, void 0, void 0, funct
|
|
|
85
163
|
const translated = {};
|
|
86
164
|
// 遍历文件中的已经翻译的内容
|
|
87
165
|
Object.entries(data).forEach(([key, value]) => {
|
|
88
|
-
if (value) {
|
|
166
|
+
if (key !== "_meta" && value) {
|
|
89
167
|
translated[key] = sourceFileMap[fileName].data[key];
|
|
90
168
|
}
|
|
91
169
|
});
|
|
@@ -152,9 +230,14 @@ export const deleteBatchCache = (params) => {
|
|
|
152
230
|
deleteLanguages.forEach((language) => {
|
|
153
231
|
const jsonData = fs.readFileSync(path.resolve(cacheFolderPath, language, cacheFileName), "utf-8");
|
|
154
232
|
const data = JSON.parse(jsonData);
|
|
233
|
+
const rejectedReferences = getRejectedReferences(data);
|
|
234
|
+
const missingReferenceIds = getMissingReferenceIds(data);
|
|
155
235
|
keys.forEach((key) => {
|
|
156
236
|
delete data[key];
|
|
237
|
+
delete rejectedReferences[key];
|
|
238
|
+
delete missingReferenceIds[key];
|
|
157
239
|
});
|
|
240
|
+
setSourceCacheMetadata(data, rejectedReferences, missingReferenceIds);
|
|
158
241
|
fs.writeFileSync(path.resolve(cacheFolderPath, language, cacheFileName), JSON.stringify(data, null, 2), "utf-8");
|
|
159
242
|
});
|
|
160
243
|
};
|
package/lib/log/index.d.ts
CHANGED
package/lib/log/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/lib/log/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/lib/log/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAG/D,wBAAgB,cAAc,CAAC,MAAM,EAAE,kBAAkB,iBAWxD"}
|
package/lib/support.d.ts
CHANGED
package/lib/support.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"support.d.ts","sourceRoot":"","sources":["../src/lib/support.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"support.d.ts","sourceRoot":"","sources":["../src/lib/support.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,eAAO,MAAM,oBAAoB,EAAE,kBA6GlC,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"translation-format.d.ts","sourceRoot":"","sources":["../src/lib/translation-format.ts"],"names":[],"mappings":"AAMA,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM;UACvB,MAAM;iBAAe,OAAO;IAwBrD"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// 支持 i18next 插值、React Intl 参数、富文本标签和常见 printf 占位符。
|
|
2
|
+
const formatStart = /[%$]?\{|<\/?[\p{L}\p{N}_][\p{L}\p{N}_.:-]*(?:\s+(?:"[^"]*"|'[^']*'|[^<>"'])*)?\s*\/?>|%(?:\d+\$|\([\p{L}\p{N}_.-]+\))?[sdif@](?![\p{L}\p{N}_])/gu;
|
|
3
|
+
const argumentStart = /^\{(?:\{\s*-?)?\s*[\p{L}\p{N}_][\p{L}\p{N}_.-]*\s*(?=[,}])/u;
|
|
4
|
+
export function splitTranslationText(text) {
|
|
5
|
+
const segments = [];
|
|
6
|
+
let offset = 0;
|
|
7
|
+
for (const match of text.matchAll(formatStart)) {
|
|
8
|
+
const start = match.index;
|
|
9
|
+
if (start < offset)
|
|
10
|
+
continue;
|
|
11
|
+
let end = start + match[0].length;
|
|
12
|
+
if (match[0].endsWith("{")) {
|
|
13
|
+
if (!argumentStart.test(text.slice(end - 1)))
|
|
14
|
+
continue;
|
|
15
|
+
let depth = 1;
|
|
16
|
+
while (end < text.length && depth) {
|
|
17
|
+
const char = text[end++];
|
|
18
|
+
if (char === "{")
|
|
19
|
+
depth++;
|
|
20
|
+
else if (char === "}")
|
|
21
|
+
depth--;
|
|
22
|
+
}
|
|
23
|
+
if (depth)
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
segments.push({ text: text.slice(offset, start), placeholder: false }, { text: text.slice(start, end), placeholder: true });
|
|
27
|
+
offset = end;
|
|
28
|
+
}
|
|
29
|
+
segments.push({ text: text.slice(offset), placeholder: false });
|
|
30
|
+
return segments;
|
|
31
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { FileTranslationMetadata } from "../types/index.js";
|
|
2
|
+
export declare const readProtectedTerms: (value: unknown) => readonly string[] | undefined;
|
|
3
|
+
export declare const readTranslationMetadata: (value: unknown) => FileTranslationMetadata | undefined;
|
|
4
|
+
export declare const protectTerms: (text: string, localTerms?: readonly string[], globalTerms?: readonly string[], sourceLiterals?: (text: string) => {
|
|
5
|
+
start: number;
|
|
6
|
+
end: number;
|
|
7
|
+
}[]) => {
|
|
8
|
+
text: string;
|
|
9
|
+
restore(translation: string): string;
|
|
10
|
+
} | undefined;
|
|
11
|
+
export declare const isProtectedText: (text: string, localTerms?: readonly string[], globalTerms?: readonly string[]) => boolean;
|
|
12
|
+
//# sourceMappingURL=translation-metadata.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"translation-metadata.d.ts","sourceRoot":"","sources":["../src/lib/translation-metadata.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAGjE,eAAO,MAAM,kBAAkB,UAAW,OAAO,KAAG,SAAS,MAAM,EAAE,GAAG,SAQvE,CAAC;AAEF,eAAO,MAAM,uBAAuB,UAAW,OAAO,KAAG,uBAAuB,GAAG,SASlF,CAAC;AAcF,eAAO,MAAM,YAAY,SACjB,MAAM,eACC,SAAS,MAAM,EAAE,gBAChB,SAAS,MAAM,EAAE,mBACd,CAAC,IAAI,EAAE,MAAM,KAAK;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,EAAE;;yBA8C5C,MAAM;aAW9B,CAAC;AAEF,eAAO,MAAM,eAAe,SACpB,MAAM,eACC,SAAS,MAAM,EAAE,gBAChB,SAAS,MAAM,EAAE,YAKhC,CAAC"}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { splitTranslationText } from "./translation-format.js";
|
|
2
|
+
export const readProtectedTerms = (value) => {
|
|
3
|
+
if (Array.isArray(value) &&
|
|
4
|
+
value.length > 0 &&
|
|
5
|
+
value.every((term) => typeof term === "string" && term.trim() !== "")) {
|
|
6
|
+
return [...new Set(value.map((term) => term.trim()))];
|
|
7
|
+
}
|
|
8
|
+
};
|
|
9
|
+
export const readTranslationMetadata = (value) => {
|
|
10
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
11
|
+
return;
|
|
12
|
+
const { context, noTranslate } = value;
|
|
13
|
+
const fileContext = typeof context === "string" ? context.trim() : "";
|
|
14
|
+
const protectedTerms = readProtectedTerms(noTranslate);
|
|
15
|
+
if (fileContext || protectedTerms) {
|
|
16
|
+
return { context: fileContext || undefined, noTranslate: protectedTerms };
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
const protectedTermPattern = (terms) => {
|
|
20
|
+
if (!(terms === null || terms === void 0 ? void 0 : terms.length))
|
|
21
|
+
return;
|
|
22
|
+
const alternatives = [...terms]
|
|
23
|
+
.sort((first, second) => second.length - first.length)
|
|
24
|
+
.map((term) => term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
|
|
25
|
+
const wordCharacters = "[\\p{L}\\p{M}\\p{N}_]";
|
|
26
|
+
return new RegExp(`(?<!${wordCharacters})(?:${alternatives.join("|")})(?!${wordCharacters})`, "gu");
|
|
27
|
+
};
|
|
28
|
+
export const protectTerms = (text, localTerms, globalTerms, sourceLiterals) => {
|
|
29
|
+
var _a;
|
|
30
|
+
const localPattern = protectedTermPattern(localTerms);
|
|
31
|
+
const globalPattern = protectedTermPattern(globalTerms);
|
|
32
|
+
if (!localPattern && !globalPattern && !sourceLiterals)
|
|
33
|
+
return;
|
|
34
|
+
let prefix = "{__CC_PROTECTED_";
|
|
35
|
+
while (text.includes(prefix))
|
|
36
|
+
prefix += "_";
|
|
37
|
+
const placeholders = new Map();
|
|
38
|
+
const segments = splitTranslationText(text);
|
|
39
|
+
for (const segment of segments) {
|
|
40
|
+
if (segment.placeholder)
|
|
41
|
+
continue;
|
|
42
|
+
const matches = (_a = sourceLiterals === null || sourceLiterals === void 0 ? void 0 : sourceLiterals(segment.text)) !== null && _a !== void 0 ? _a : [];
|
|
43
|
+
// 先匹配局部词,再匹配全局词。两次都使用原文,避免占位符改变词边界。
|
|
44
|
+
for (const pattern of [localPattern, globalPattern]) {
|
|
45
|
+
if (!pattern)
|
|
46
|
+
continue;
|
|
47
|
+
for (const match of segment.text.matchAll(pattern)) {
|
|
48
|
+
matches.push({ start: match.index, end: match.index + match[0].length });
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
matches.sort((first, second) => first.start - second.start);
|
|
52
|
+
// 包含或重叠的匹配合并成一个范围,独立的匹配各自保留。
|
|
53
|
+
const merged = [];
|
|
54
|
+
for (const match of matches) {
|
|
55
|
+
const previous = merged[merged.length - 1];
|
|
56
|
+
if (previous && match.start < previous.end) {
|
|
57
|
+
previous.end = Math.max(previous.end, match.end);
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
merged.push(match);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
let offset = 0;
|
|
64
|
+
let masked = "";
|
|
65
|
+
for (const { start, end } of merged) {
|
|
66
|
+
const placeholder = `${prefix}${placeholders.size}__}`;
|
|
67
|
+
placeholders.set(placeholder, segment.text.slice(start, end));
|
|
68
|
+
masked += segment.text.slice(offset, start) + placeholder;
|
|
69
|
+
offset = end;
|
|
70
|
+
}
|
|
71
|
+
segment.text = masked + segment.text.slice(offset);
|
|
72
|
+
}
|
|
73
|
+
if (placeholders.size === 0)
|
|
74
|
+
return;
|
|
75
|
+
return {
|
|
76
|
+
text: segments.map(({ text }) => text).join(""),
|
|
77
|
+
restore(translation) {
|
|
78
|
+
for (const [placeholder, term] of placeholders) {
|
|
79
|
+
const parts = translation.split(placeholder);
|
|
80
|
+
if (parts.length !== 2) {
|
|
81
|
+
throw new Error(`Translation must preserve protected placeholder ${placeholder} exactly once`);
|
|
82
|
+
}
|
|
83
|
+
translation = parts.join(term);
|
|
84
|
+
}
|
|
85
|
+
return translation;
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
};
|
|
89
|
+
export const isProtectedText = (text, localTerms, globalTerms) => {
|
|
90
|
+
if (!(localTerms === null || localTerms === void 0 ? void 0 : localTerms.length) && !(globalTerms === null || globalTerms === void 0 ? void 0 : globalTerms.length))
|
|
91
|
+
return false;
|
|
92
|
+
const value = text.trim();
|
|
93
|
+
return Boolean((localTerms === null || localTerms === void 0 ? void 0 : localTerms.includes(value)) || (globalTerms === null || globalTerms === void 0 ? void 0 : globalTerms.includes(value)));
|
|
94
|
+
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ISingleTranslate, SupportLanguageType } from "../types";
|
|
1
|
+
import type { ISingleTranslate, SupportLanguageType } from "../types/index.js";
|
|
2
2
|
export interface TranslationReferenceOptions {
|
|
3
3
|
language: SupportLanguageType;
|
|
4
4
|
directory: string;
|
|
@@ -9,12 +9,14 @@ interface ReferenceMatch {
|
|
|
9
9
|
translation: string;
|
|
10
10
|
}
|
|
11
11
|
export type ReferenceMatches = Map<string, Map<string, ReferenceMatch>>;
|
|
12
|
+
export type ReferenceFiles = ReadonlyMap<string, ReadonlyMap<string, string>>;
|
|
12
13
|
export declare class TranslationReferencePlugin {
|
|
13
14
|
readonly language: SupportLanguageType;
|
|
14
15
|
readonly directory: string;
|
|
15
16
|
readonly checkConflicts: boolean;
|
|
16
17
|
constructor({ language, directory, checkConflicts, }: TranslationReferenceOptions);
|
|
17
|
-
|
|
18
|
+
readFiles(sourceFiles: Iterable<string>, writableDirectories: string[]): ReferenceFiles;
|
|
19
|
+
prepare(tasks: readonly Pick<ISingleTranslate, "fileName" | "translateJson" | "metadata">[], writableDirectories: string[], globalNoTranslate?: readonly string[], references?: ReferenceFiles): Promise<ReferenceMatches | undefined>;
|
|
18
20
|
}
|
|
19
21
|
export {};
|
|
20
22
|
//# sourceMappingURL=translation-reference.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translation-reference.d.ts","sourceRoot":"","sources":["../src/lib/translation-reference.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"translation-reference.d.ts","sourceRoot":"","sources":["../src/lib/translation-reference.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAG/E,MAAM,WAAW,2BAA2B;IAC1C,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,UAAU,cAAc;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,MAAM,gBAAgB,GAAG,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC,CAAC;AACxE,MAAM,MAAM,cAAc,GAAG,WAAW,CAAC,MAAM,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;AAE9E,qBAAa,0BAA0B;IACrC,QAAQ,CAAC,QAAQ,EAAE,mBAAmB,CAAC;IACvC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,cAAc,EAAE,OAAO,CAAC;gBAErB,EACV,QAAQ,EACR,SAAS,EACT,cAAsB,GACvB,EAAE,2BAA2B;IAM9B,SAAS,CAAC,WAAW,EAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,mBAAmB,EAAE,MAAM,EAAE,GAAG,cAAc;IAwCjF,OAAO,CACX,KAAK,EAAE,SAAS,IAAI,CAAC,gBAAgB,EAAE,UAAU,GAAG,eAAe,GAAG,UAAU,CAAC,EAAE,EACnF,mBAAmB,EAAE,MAAM,EAAE,EAC7B,iBAAiB,CAAC,EAAE,SAAS,MAAM,EAAE,EACrC,UAAU,CAAC,EAAE,cAAc;CAuE9B"}
|
|
@@ -10,66 +10,83 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
10
10
|
import fs from "fs";
|
|
11
11
|
import path from "path";
|
|
12
12
|
import { createInterface } from "node:readline";
|
|
13
|
+
import { isProtectedText } from "./translation-metadata.js";
|
|
13
14
|
export class TranslationReferencePlugin {
|
|
14
15
|
constructor({ language, directory, checkConflicts = false, }) {
|
|
15
16
|
this.language = language;
|
|
16
17
|
this.directory = path.resolve(directory);
|
|
17
18
|
this.checkConflicts = checkConflicts;
|
|
18
19
|
}
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
20
|
+
readFiles(sourceFiles, writableDirectories) {
|
|
21
|
+
let fileNames;
|
|
22
|
+
let referenceDirectory;
|
|
23
|
+
try {
|
|
24
|
+
fileNames = new Set(fs.readdirSync(this.directory));
|
|
25
|
+
referenceDirectory = fs.realpathSync(this.directory);
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
throw new Error(`Cannot read reference directory ${this.directory}: ${error}`);
|
|
29
|
+
}
|
|
30
|
+
for (const directory of writableDirectories) {
|
|
31
|
+
if (fs.existsSync(directory) &&
|
|
32
|
+
fs.realpathSync(directory) === referenceDirectory) {
|
|
33
|
+
throw new Error(`Reference directory is read-only for translation: ${this.directory}`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const references = new Map();
|
|
37
|
+
for (const fileName of sourceFiles) {
|
|
38
|
+
if (!fileNames.has(fileName))
|
|
39
|
+
continue;
|
|
40
|
+
const referencePath = path.join(this.directory, fileName);
|
|
24
41
|
try {
|
|
25
|
-
|
|
26
|
-
|
|
42
|
+
const data = JSON.parse(fs.readFileSync(referencePath, "utf8"));
|
|
43
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) {
|
|
44
|
+
throw new Error("Expected a JSON object");
|
|
45
|
+
}
|
|
46
|
+
const entries = new Map();
|
|
47
|
+
for (const [key, value] of Object.entries(data)) {
|
|
48
|
+
if (typeof value === "string" && value.trim())
|
|
49
|
+
entries.set(key, value);
|
|
50
|
+
}
|
|
51
|
+
references.set(fileName, entries);
|
|
27
52
|
}
|
|
28
53
|
catch (error) {
|
|
29
|
-
throw new Error(`Cannot read reference
|
|
30
|
-
}
|
|
31
|
-
for (const directory of writableDirectories) {
|
|
32
|
-
if (fs.existsSync(directory) &&
|
|
33
|
-
fs.realpathSync(directory) === referenceDirectory) {
|
|
34
|
-
throw new Error(`Reference directory is read-only for translation: ${this.directory}`);
|
|
35
|
-
}
|
|
54
|
+
throw new Error(`Cannot read reference file ${referencePath}: ${error}`);
|
|
36
55
|
}
|
|
56
|
+
}
|
|
57
|
+
return references;
|
|
58
|
+
}
|
|
59
|
+
prepare(tasks, writableDirectories, globalNoTranslate, references) {
|
|
60
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
61
|
+
var _a;
|
|
37
62
|
const pending = new Map();
|
|
38
|
-
for (const { fileName, translateJson } of tasks) {
|
|
63
|
+
for (const { fileName, translateJson, metadata } of tasks) {
|
|
39
64
|
let entries = pending.get(fileName);
|
|
40
|
-
if (!entries) {
|
|
41
|
-
entries = new Map();
|
|
42
|
-
pending.set(fileName, entries);
|
|
43
|
-
}
|
|
44
65
|
for (const [key, source] of Object.entries(translateJson)) {
|
|
66
|
+
if (isProtectedText(source, metadata === null || metadata === void 0 ? void 0 : metadata.noTranslate, globalNoTranslate))
|
|
67
|
+
continue;
|
|
68
|
+
if (!entries) {
|
|
69
|
+
entries = new Map();
|
|
70
|
+
pending.set(fileName, entries);
|
|
71
|
+
}
|
|
45
72
|
entries.set(key, source);
|
|
46
73
|
}
|
|
47
74
|
}
|
|
48
75
|
const matches = new Map();
|
|
49
76
|
const report = [];
|
|
50
77
|
let hasUnmatched = false;
|
|
78
|
+
const referenceFiles = references !== null && references !== void 0 ? references : this.readFiles(pending.keys(), writableDirectories);
|
|
51
79
|
for (const [fileName, entries] of pending) {
|
|
52
|
-
|
|
80
|
+
const reference = referenceFiles.get(fileName);
|
|
81
|
+
if (!reference) {
|
|
53
82
|
report.push(` ${fileName}: missing reference file (0/${entries.size} matched)`);
|
|
54
83
|
hasUnmatched = true;
|
|
55
84
|
continue;
|
|
56
85
|
}
|
|
57
|
-
const referencePath = path.join(this.directory, fileName);
|
|
58
|
-
let reference;
|
|
59
|
-
try {
|
|
60
|
-
const data = JSON.parse(fs.readFileSync(referencePath, "utf8"));
|
|
61
|
-
if (!data || typeof data !== "object" || Array.isArray(data)) {
|
|
62
|
-
throw new Error("Expected a JSON object");
|
|
63
|
-
}
|
|
64
|
-
reference = data;
|
|
65
|
-
}
|
|
66
|
-
catch (error) {
|
|
67
|
-
throw new Error(`Cannot read reference file ${referencePath}: ${error}`);
|
|
68
|
-
}
|
|
69
86
|
const fileMatches = new Map();
|
|
70
87
|
for (const [key, source] of entries) {
|
|
71
|
-
const translation = reference
|
|
72
|
-
if (
|
|
88
|
+
const translation = reference.get(key);
|
|
89
|
+
if (translation !== undefined) {
|
|
73
90
|
fileMatches.set(key, { source, translation });
|
|
74
91
|
}
|
|
75
92
|
}
|
|
@@ -86,7 +103,7 @@ export class TranslationReferencePlugin {
|
|
|
86
103
|
console.log("All pending entries have matching references.");
|
|
87
104
|
return matches;
|
|
88
105
|
}
|
|
89
|
-
console.log("Unmatched entries will
|
|
106
|
+
console.log("Unmatched entries will omit the reference from this directory.");
|
|
90
107
|
if (!process.stdin.isTTY || !process.stdout.isTTY || process.env.CI) {
|
|
91
108
|
console.warn("Translation cancelled: confirmation requires an interactive terminal.");
|
|
92
109
|
return;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { SupportLanguageType, TranslationReference } from "../types/index.js";
|
|
2
|
+
export declare function readTranslationResponse(content: string | null | undefined, source: string): string;
|
|
3
|
+
export declare const englishSourceLiterals: (text: string) => {
|
|
4
|
+
start: number;
|
|
5
|
+
end: number;
|
|
6
|
+
}[];
|
|
7
|
+
export declare function isNonEnglishSource(source: string): boolean;
|
|
8
|
+
export declare function hasUnexpectedTranslationLanguage(translation: string, source: TranslationReference, targetLanguage: SupportLanguageType, references: readonly TranslationReference[]): boolean;
|
|
9
|
+
//# sourceMappingURL=translation-response.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"translation-response.d.ts","sourceRoot":"","sources":["../src/lib/translation-response.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAYnF,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAClC,MAAM,EAAE,MAAM,GACb,MAAM,CA6CR;AA0ED,eAAO,MAAM,qBAAqB,SAAU,MAAM;WA3BzB,MAAM;SAAO,MAAM;GAgC3C,CAAC;AAEF,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAO1D;AAED,wBAAgB,gCAAgC,CAC9C,WAAW,EAAE,MAAM,EACnB,MAAM,EAAE,oBAAoB,EAC5B,cAAc,EAAE,mBAAmB,EACnC,UAAU,EAAE,SAAS,oBAAoB,EAAE,GAC1C,OAAO,CA2BT"}
|