@babelize/engine 0.3.7 → 0.3.8
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/dist/index.d.ts +2 -0
- package/dist/index.js +11 -1
- package/dist/local/hosted-provider.js +1 -0
- package/dist/local/translate-core.d.ts +13 -2
- package/dist/local/translate-core.js +27 -9
- package/dist/local/translate-messages.d.ts +5 -0
- package/dist/local/translate-messages.js +1 -1
- package/dist/modules/finalization/nextjs-finalize.d.ts +19 -2
- package/dist/modules/finalization/nextjs-finalize.js +46 -4
- package/dist/modules/locale-builder/adopted.d.ts +29 -2
- package/dist/modules/locale-builder/adopted.js +185 -16
- package/dist/modules/locale-builder/locales.js +11 -2
- package/dist/modules/locale-builder/message-modules.d.ts +40 -0
- package/dist/modules/locale-builder/message-modules.js +263 -0
- package/dist/modules/translator/client/byok.provider.js +8 -2
- package/dist/modules/translator/formality.d.ts +40 -0
- package/dist/modules/translator/formality.js +313 -0
- package/dist/modules/translator/translate.d.ts +18 -0
- package/dist/modules/translator/translate.js +78 -11
- package/dist/modules/workspace/existing-setup.d.ts +3 -1
- package/dist/modules/workspace/existing-setup.js +32 -15
- package/dist/orchestrator.js +51 -7
- package/dist/providers/default-translation-provider.js +2 -2
- package/dist/providers/types.d.ts +5 -0
- package/dist/qa/check-project.d.ts +7 -0
- package/dist/qa/check-project.js +12 -2
- package/dist/qa/locale-files.d.ts +8 -5
- package/dist/qa/locale-files.js +37 -9
- package/dist/qa/locale-qa.d.ts +10 -1
- package/dist/qa/locale-qa.js +9 -0
- package/dist/qa/review.js +1 -1
- package/dist/runtime/types.d.ts +21 -1
- package/dist/types.d.ts +2 -0
- package/dist/utils/translator-caller.d.ts +19 -0
- package/dist/utils/translator-caller.js +55 -21
- package/package.json +2 -2
|
@@ -6,6 +6,7 @@ exports.checkExistingTargetLocales = checkExistingTargetLocales;
|
|
|
6
6
|
const file_utils_1 = require("../../utils/file-utils");
|
|
7
7
|
const keygen_1 = require("../keygen");
|
|
8
8
|
const language_codes_1 = require("../translator/language-codes");
|
|
9
|
+
const adopted_1 = require("./adopted");
|
|
9
10
|
function assertSafeLocale(locale) {
|
|
10
11
|
// Allow common locale identifiers only (examples: en, en-US, pt_BR, zh-Hant).
|
|
11
12
|
// Disallow path separators and other special characters to prevent path traversal.
|
|
@@ -26,10 +27,16 @@ async function handleBaseLocale(workspace, generatedKeys, sourceLocale = 'en', d
|
|
|
26
27
|
const adopted = !!workspace.existingSetup;
|
|
27
28
|
if (!dryRun && !adopted)
|
|
28
29
|
await (0, file_utils_1.ensureDir)(localesDir);
|
|
29
|
-
|
|
30
|
+
// An adopted setup's source may be a folder of namespace files or modules.
|
|
31
|
+
const adoptedSource = adopted ? await (0, adopted_1.readAdoptedLocale)(workspace, sourceLocale) : null;
|
|
32
|
+
const exists = adopted ? !!adoptedSource : await (0, file_utils_1.pathExists)(localeFilePathTarget);
|
|
30
33
|
let existingData = {};
|
|
31
34
|
let existingKeysCount = 0;
|
|
32
|
-
if (
|
|
35
|
+
if (adoptedSource) {
|
|
36
|
+
existingData = adoptedSource.data;
|
|
37
|
+
existingKeysCount = countKeys(existingData);
|
|
38
|
+
}
|
|
39
|
+
else if (exists) {
|
|
33
40
|
if (workspace.localeFormat !== 'json') {
|
|
34
41
|
throw new Error(`Locale format '${workspace.localeFormat}' not yet supported for base locale handling`);
|
|
35
42
|
}
|
|
@@ -115,6 +122,8 @@ async function readLocaleFile(workspace, locale) {
|
|
|
115
122
|
if (workspace.localeFormat !== 'json') {
|
|
116
123
|
throw new Error(`Locale format '${workspace.localeFormat}' reading not yet implemented`);
|
|
117
124
|
}
|
|
125
|
+
if (workspace.existingSetup)
|
|
126
|
+
return (await (0, adopted_1.readAdoptedLocale)(workspace, locale))?.data ?? null;
|
|
118
127
|
const { file } = (0, file_utils_1.workspaceLocaleFile)(workspace, locale);
|
|
119
128
|
return (0, file_utils_1.readJsonFile)(file);
|
|
120
129
|
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { LocaleData } from '../../runtime/types';
|
|
2
|
+
export declare const MESSAGE_MODULE_EXTENSIONS: readonly [".ts", ".js", ".mts", ".mjs", ".cts", ".cjs"];
|
|
3
|
+
/** A string value in a module, by flat key path, with where it sits in the source. */
|
|
4
|
+
interface Leaf {
|
|
5
|
+
start: number;
|
|
6
|
+
end: number;
|
|
7
|
+
quote: "'" | '"' | '`';
|
|
8
|
+
}
|
|
9
|
+
/** An object literal in a module, by key path, with where new entries go. */
|
|
10
|
+
interface ObjectSite {
|
|
11
|
+
/** After the last entry (and its trailing comma, if any); after `{` when empty. */
|
|
12
|
+
insertAt: number;
|
|
13
|
+
trailingComma: boolean;
|
|
14
|
+
empty: boolean;
|
|
15
|
+
/** Entries on their own lines: their indentation, and one level of it. */
|
|
16
|
+
indent: string | null;
|
|
17
|
+
step: string;
|
|
18
|
+
}
|
|
19
|
+
export interface MessageModule {
|
|
20
|
+
data: LocaleData;
|
|
21
|
+
leaves: Record<string, Leaf>;
|
|
22
|
+
objects: Record<string, ObjectSite>;
|
|
23
|
+
}
|
|
24
|
+
export declare class MessageModuleError extends Error {
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The messages object a module exports. Null: the module exports no object
|
|
28
|
+
* literal (a type-only module, a helper), so it isn't a catalog.
|
|
29
|
+
* Throws MessageModuleError when the object holds something that can't be
|
|
30
|
+
* read without running the code (spreads, computed keys, function calls).
|
|
31
|
+
*/
|
|
32
|
+
export declare function parseMessageModule(code: string, file: string): MessageModule | null;
|
|
33
|
+
/**
|
|
34
|
+
* `template` (a module of the same catalog, parsed) with each string leaf
|
|
35
|
+
* found in `values` replaced. Leaves without a value keep the template's
|
|
36
|
+
* text; values the template has no leaf for are added as new entries of the
|
|
37
|
+
* object they belong in, after its last one.
|
|
38
|
+
*/
|
|
39
|
+
export declare function writeMessageModule(template: string, parsed: MessageModule, values: Record<string, string>): string;
|
|
40
|
+
export {};
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.MessageModuleError = exports.MESSAGE_MODULE_EXTENSIONS = void 0;
|
|
37
|
+
exports.parseMessageModule = parseMessageModule;
|
|
38
|
+
exports.writeMessageModule = writeMessageModule;
|
|
39
|
+
/**
|
|
40
|
+
* Locale catalogs written as TypeScript/JavaScript modules (#370):
|
|
41
|
+
*
|
|
42
|
+
* // messages/fr/auth.ts
|
|
43
|
+
* import { auth as english } from '../en/auth';
|
|
44
|
+
* export const auth = { signIn: 'Se connecter', … } satisfies MessageShape<typeof english>;
|
|
45
|
+
*
|
|
46
|
+
* Read by AST (an object literal of string leaves; nothing is evaluated) and
|
|
47
|
+
* written by replacing only the string literals of a template module, so the
|
|
48
|
+
* export, imports, `satisfies`/`as const` suffix and comments stay as written.
|
|
49
|
+
*/
|
|
50
|
+
const parser = __importStar(require("@babel/parser"));
|
|
51
|
+
const t = __importStar(require("@babel/types"));
|
|
52
|
+
exports.MESSAGE_MODULE_EXTENSIONS = ['.ts', '.js', '.mts', '.mjs', '.cts', '.cjs'];
|
|
53
|
+
class MessageModuleError extends Error {
|
|
54
|
+
}
|
|
55
|
+
exports.MessageModuleError = MessageModuleError;
|
|
56
|
+
/**
|
|
57
|
+
* The messages object a module exports. Null: the module exports no object
|
|
58
|
+
* literal (a type-only module, a helper), so it isn't a catalog.
|
|
59
|
+
* Throws MessageModuleError when the object holds something that can't be
|
|
60
|
+
* read without running the code (spreads, computed keys, function calls).
|
|
61
|
+
*/
|
|
62
|
+
function parseMessageModule(code, file) {
|
|
63
|
+
let ast;
|
|
64
|
+
try {
|
|
65
|
+
ast = parser.parse(code, { sourceType: 'module', plugins: ['typescript'], errorRecovery: false });
|
|
66
|
+
}
|
|
67
|
+
catch (err) {
|
|
68
|
+
throw new MessageModuleError(`${file} could not be parsed: ${err.message}`);
|
|
69
|
+
}
|
|
70
|
+
const consts = new Map();
|
|
71
|
+
for (const stmt of ast.program.body) {
|
|
72
|
+
const decl = t.isExportNamedDeclaration(stmt) ? stmt.declaration : stmt;
|
|
73
|
+
if (t.isVariableDeclaration(decl)) {
|
|
74
|
+
for (const d of decl.declarations)
|
|
75
|
+
if (t.isIdentifier(d.id) && d.init)
|
|
76
|
+
consts.set(d.id.name, d.init);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const exported = [];
|
|
80
|
+
const add = (expr) => {
|
|
81
|
+
let e = expr ? unwrap(expr) : null;
|
|
82
|
+
if (e && t.isIdentifier(e))
|
|
83
|
+
e = consts.has(e.name) ? unwrap(consts.get(e.name)) : null;
|
|
84
|
+
if (e && t.isObjectExpression(e) && !exported.includes(e))
|
|
85
|
+
exported.push(e);
|
|
86
|
+
};
|
|
87
|
+
for (const stmt of ast.program.body) {
|
|
88
|
+
if (t.isExportNamedDeclaration(stmt)) {
|
|
89
|
+
if (t.isVariableDeclaration(stmt.declaration))
|
|
90
|
+
for (const d of stmt.declaration.declarations)
|
|
91
|
+
add(d.init);
|
|
92
|
+
for (const s of stmt.specifiers)
|
|
93
|
+
if (t.isExportSpecifier(s) && !stmt.source)
|
|
94
|
+
add(s.local);
|
|
95
|
+
}
|
|
96
|
+
else if (t.isExportDefaultDeclaration(stmt)) {
|
|
97
|
+
add(stmt.declaration);
|
|
98
|
+
}
|
|
99
|
+
else if (t.isExpressionStatement(stmt) && isModuleExportsAssignment(stmt.expression)) {
|
|
100
|
+
add(stmt.expression.right);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (exported.length === 0)
|
|
104
|
+
return null;
|
|
105
|
+
if (exported.length > 1) {
|
|
106
|
+
throw new MessageModuleError(`${file} exports ${exported.length} message objects; Babelize reads one per file.`);
|
|
107
|
+
}
|
|
108
|
+
const leaves = {};
|
|
109
|
+
const objects = {};
|
|
110
|
+
const data = readObject(exported[0], '', { leaves, objects }, code, file);
|
|
111
|
+
return { data, leaves, objects };
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* `template` (a module of the same catalog, parsed) with each string leaf
|
|
115
|
+
* found in `values` replaced. Leaves without a value keep the template's
|
|
116
|
+
* text; values the template has no leaf for are added as new entries of the
|
|
117
|
+
* object they belong in, after its last one.
|
|
118
|
+
*/
|
|
119
|
+
function writeMessageModule(template, parsed, values) {
|
|
120
|
+
const edits = Object.entries(parsed.leaves)
|
|
121
|
+
.filter(([key]) => values[key] !== undefined)
|
|
122
|
+
.map(([key, leaf]) => ({ start: leaf.start, end: leaf.end, text: quote(values[key], leaf.quote) }));
|
|
123
|
+
// New keys, grouped under the deepest object the template already has.
|
|
124
|
+
const q = Object.values(parsed.leaves)[0]?.quote === '"' ? '"' : "'";
|
|
125
|
+
const missing = new Map();
|
|
126
|
+
for (const [key, value] of Object.entries(values)) {
|
|
127
|
+
if (parsed.leaves[key])
|
|
128
|
+
continue;
|
|
129
|
+
const segments = key.split('.');
|
|
130
|
+
let at = segments.length - 1;
|
|
131
|
+
while (at > 0 && !parsed.objects[segments.slice(0, at).join('.')])
|
|
132
|
+
at--;
|
|
133
|
+
const owner = segments.slice(0, at).join('.');
|
|
134
|
+
if (!parsed.objects[owner])
|
|
135
|
+
continue;
|
|
136
|
+
const rest = segments.slice(at);
|
|
137
|
+
// Under an array or a string in the template: nothing sensible to add.
|
|
138
|
+
if (rest.length > 1 && parsed.leaves[segments.slice(0, at + 1).join('.')])
|
|
139
|
+
continue;
|
|
140
|
+
const group = missing.get(owner) ?? {};
|
|
141
|
+
group[rest.join('.')] = value;
|
|
142
|
+
missing.set(owner, group);
|
|
143
|
+
}
|
|
144
|
+
for (const [owner, group] of missing) {
|
|
145
|
+
const site = parsed.objects[owner];
|
|
146
|
+
const entries = renderEntries(nest(group), site.indent, site.step, q);
|
|
147
|
+
if (site.indent === null) {
|
|
148
|
+
edits.push({ start: site.insertAt, end: site.insertAt, text: site.empty ? ` ${entries.join(', ')} ` : `, ${entries.join(', ')}` });
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
const lines = entries.map((e) => `\n${site.indent}${e}`);
|
|
152
|
+
const text = site.trailingComma || site.empty ? lines.map((l) => `${l},`).join('') : `,${lines.join(',')}`;
|
|
153
|
+
edits.push({ start: site.insertAt, end: site.insertAt, text });
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
let out = template;
|
|
157
|
+
for (const e of edits.sort((a, b) => b.start - a.start))
|
|
158
|
+
out = out.slice(0, e.start) + e.text + out.slice(e.end);
|
|
159
|
+
return out;
|
|
160
|
+
}
|
|
161
|
+
function nest(flat) {
|
|
162
|
+
const out = {};
|
|
163
|
+
for (const [key, value] of Object.entries(flat)) {
|
|
164
|
+
const parts = key.split('.');
|
|
165
|
+
let node = out;
|
|
166
|
+
for (const p of parts.slice(0, -1))
|
|
167
|
+
node = (typeof node[p] === 'object' ? node[p] : (node[p] = {}));
|
|
168
|
+
node[parts[parts.length - 1]] = value;
|
|
169
|
+
}
|
|
170
|
+
return out;
|
|
171
|
+
}
|
|
172
|
+
/** `key: 'text'` / `key: { … }` entries, indented under `indent` (null: on one line). */
|
|
173
|
+
function renderEntries(tree, indent, step, q) {
|
|
174
|
+
return Object.entries(tree).map(([k, v]) => {
|
|
175
|
+
const name = /^[A-Za-z_$][\w$]*$/.test(k) ? k : quote(k, q);
|
|
176
|
+
if (typeof v === 'string')
|
|
177
|
+
return `${name}: ${quote(v, q)}`;
|
|
178
|
+
const inner = renderEntries(v, indent === null ? null : indent + step, step, q);
|
|
179
|
+
if (indent === null)
|
|
180
|
+
return `${name}: { ${inner.join(', ')} }`;
|
|
181
|
+
return `${name}: {${inner.map((e) => `\n${indent}${step}${e},`).join('')}\n${indent}}`;
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
function unwrap(node) {
|
|
185
|
+
let n = node;
|
|
186
|
+
while (t.isTSAsExpression(n) || t.isTSSatisfiesExpression(n) || t.isTSTypeAssertion(n) ||
|
|
187
|
+
t.isTSNonNullExpression(n) || t.isParenthesizedExpression(n)) {
|
|
188
|
+
n = n.expression;
|
|
189
|
+
}
|
|
190
|
+
return n;
|
|
191
|
+
}
|
|
192
|
+
function isModuleExportsAssignment(e) {
|
|
193
|
+
return t.isAssignmentExpression(e) && t.isMemberExpression(e.left) &&
|
|
194
|
+
t.isIdentifier(e.left.object, { name: 'module' }) && t.isIdentifier(e.left.property, { name: 'exports' });
|
|
195
|
+
}
|
|
196
|
+
function readObject(node, prefix, sites, code, file) {
|
|
197
|
+
const { leaves } = sites;
|
|
198
|
+
const n = unwrap(node);
|
|
199
|
+
const where = () => `${file}:${n.loc?.start.line ?? '?'}`;
|
|
200
|
+
if (t.isStringLiteral(n)) {
|
|
201
|
+
leaves[prefix] = { start: n.start, end: n.end, quote: code[n.start] === "'" ? "'" : '"' };
|
|
202
|
+
return n.value;
|
|
203
|
+
}
|
|
204
|
+
if (t.isTemplateLiteral(n)) {
|
|
205
|
+
if (n.expressions.length > 0)
|
|
206
|
+
throw new MessageModuleError(`${where()}: a template literal with \${…} can't be translated as text.`);
|
|
207
|
+
leaves[prefix] = { start: n.start, end: n.end, quote: '`' };
|
|
208
|
+
return n.quasis[0].value.cooked ?? n.quasis[0].value.raw;
|
|
209
|
+
}
|
|
210
|
+
if (t.isNumericLiteral(n) || t.isBooleanLiteral(n))
|
|
211
|
+
return n.value;
|
|
212
|
+
if (t.isNullLiteral(n))
|
|
213
|
+
return null;
|
|
214
|
+
if (t.isArrayExpression(n)) {
|
|
215
|
+
return n.elements.map((el, i) => {
|
|
216
|
+
if (!el || t.isSpreadElement(el))
|
|
217
|
+
throw new MessageModuleError(`${where()}: spreads and holes in arrays aren't supported.`);
|
|
218
|
+
return readObject(el, join(prefix, String(i)), sites, code, file);
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
if (t.isObjectExpression(n)) {
|
|
222
|
+
const out = {};
|
|
223
|
+
for (const p of n.properties) {
|
|
224
|
+
if (!t.isObjectProperty(p) || p.computed) {
|
|
225
|
+
throw new MessageModuleError(`${file}:${p.loc?.start.line ?? '?'}: only plain \`key: 'text'\` entries can be read (found ${t.isSpreadElement(p) ? 'a spread' : t.isObjectMethod(p) ? 'a method' : 'a computed key'}).`);
|
|
226
|
+
}
|
|
227
|
+
const k = t.isIdentifier(p.key) ? p.key.name : t.isStringLiteral(p.key) || t.isNumericLiteral(p.key) ? String(p.key.value) : null;
|
|
228
|
+
if (k === null)
|
|
229
|
+
throw new MessageModuleError(`${file}:${p.loc?.start.line ?? '?'}: unsupported key.`);
|
|
230
|
+
out[k] = readObject(p.value, join(prefix, k), sites, code, file);
|
|
231
|
+
}
|
|
232
|
+
sites.objects[prefix] = objectSite(n, code);
|
|
233
|
+
return out;
|
|
234
|
+
}
|
|
235
|
+
throw new MessageModuleError(`${where()}: a ${n.type} can't be read as message text without running the code.`);
|
|
236
|
+
}
|
|
237
|
+
function objectSite(n, code) {
|
|
238
|
+
const last = n.properties[n.properties.length - 1];
|
|
239
|
+
const lineIndent = (pos) => /^[ \t]*/.exec(code.slice(code.lastIndexOf('\n', pos - 1) + 1))[0];
|
|
240
|
+
if (!last)
|
|
241
|
+
return { insertAt: n.start + 1, trailingComma: false, empty: true, indent: null, step: ' ' };
|
|
242
|
+
let after = last.end;
|
|
243
|
+
while (/\s/.test(code[after] ?? ''))
|
|
244
|
+
after++;
|
|
245
|
+
const trailingComma = code[after] === ',';
|
|
246
|
+
const first = n.properties[0];
|
|
247
|
+
const ownLine = code.slice(n.start, first.start).includes('\n');
|
|
248
|
+
const indent = ownLine ? lineIndent(first.start) : null;
|
|
249
|
+
const outer = lineIndent(n.start);
|
|
250
|
+
const step = indent !== null && indent.startsWith(outer) && indent.length > outer.length ? indent.slice(outer.length) : ' ';
|
|
251
|
+
return { insertAt: trailingComma ? after + 1 : last.end, trailingComma, empty: false, indent, step };
|
|
252
|
+
}
|
|
253
|
+
function join(prefix, k) {
|
|
254
|
+
return prefix ? `${prefix}.${k}` : k;
|
|
255
|
+
}
|
|
256
|
+
function quote(value, q) {
|
|
257
|
+
if (q === '"')
|
|
258
|
+
return JSON.stringify(value);
|
|
259
|
+
if (q === '`')
|
|
260
|
+
return `\`${value.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$\{/g, '\\${')}\``;
|
|
261
|
+
const body = JSON.stringify(value).slice(1, -1).replace(/\\"/g, '"').replace(/'/g, "\\'");
|
|
262
|
+
return `'${body}'`;
|
|
263
|
+
}
|
|
@@ -17,6 +17,7 @@ exports.parseTranslations = parseTranslations;
|
|
|
17
17
|
const types_1 = require("@babelize/types");
|
|
18
18
|
const retry_1 = require("./retry");
|
|
19
19
|
const language_codes_1 = require("../language-codes");
|
|
20
|
+
const formality_1 = require("../formality");
|
|
20
21
|
const icu_message_1 = require("../../../utils/icu-message");
|
|
21
22
|
// Rough character to token ratio
|
|
22
23
|
const CHAR_TO_TOKEN_RATIO = 4;
|
|
@@ -241,6 +242,7 @@ function buildSystemPrompt(req, entries) {
|
|
|
241
242
|
const targetCode = req.targetLocale || safeFromFlores(req.targetLang);
|
|
242
243
|
const source = languageName(safeFromFlores(req.sourceLang));
|
|
243
244
|
const target = languageName(targetCode);
|
|
245
|
+
const address = (0, formality_1.formalityInstruction)(targetCode, req.formality, target);
|
|
244
246
|
const rules = [
|
|
245
247
|
`You are a professional software localizer. Translate the user-interface strings of a web application from ${source} into ${target}.`,
|
|
246
248
|
'',
|
|
@@ -251,7 +253,9 @@ function buildSystemPrompt(req, entries) {
|
|
|
251
253
|
'Rules:',
|
|
252
254
|
'1. Tokens such as [#VAR_0#] stand for variables, markup tags, links or brand names. Copy every token exactly once and unchanged; move it if the target grammar needs a different word order. Never translate, add, merge or drop tokens.',
|
|
253
255
|
'2. Write natural, idiomatic UI text as a native speaker would — not a word-for-word rendering. Keep it concise: buttons, labels and menu items should stay short.',
|
|
254
|
-
|
|
256
|
+
req.formality && address
|
|
257
|
+
? `3. Use consistent terminology across all entries. ${address}`
|
|
258
|
+
: `3. Use one consistent formality level and terminology across all entries, matching what is conventional for modern software in the target language.${address ? ` ${address}` : ''}`,
|
|
255
259
|
"4. Follow the target language's punctuation, capitalization and spacing conventions. Keep any leading or trailing whitespace.",
|
|
256
260
|
'5. If a text is a proper name, a code identifier, or is already correct in the target language (e.g. "OK", "Email" where that is the norm), return it unchanged.',
|
|
257
261
|
'6. Never explain, never add quotes or notes, never leave text in the source language unless rule 5 applies.',
|
|
@@ -270,7 +274,9 @@ function buildSystemPrompt(req, entries) {
|
|
|
270
274
|
rules.push(`- "${g.term}" → "${g.translation}"`);
|
|
271
275
|
}
|
|
272
276
|
if (req.brandVoice) {
|
|
273
|
-
rules.push('',
|
|
277
|
+
rules.push('', req.formality && address
|
|
278
|
+
? 'Brand voice — follow this tone and style; it takes priority over rule 3, except for the form of address, which is fixed:'
|
|
279
|
+
: 'Brand voice — follow this tone and style; it takes priority over rule 3:', req.brandVoice);
|
|
274
280
|
}
|
|
275
281
|
return rules.join('\n');
|
|
276
282
|
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Formal vs informal address per target language (#371): the forms the
|
|
3
|
+
* translator is told to use, and the marker words that tell which form a
|
|
4
|
+
* translated string uses (detection from an existing catalog, QA for mixed
|
|
5
|
+
* forms). Languages without a T–V distinction have no entry and get no
|
|
6
|
+
* instruction.
|
|
7
|
+
*/
|
|
8
|
+
export type FormalityLevel = 'formal' | 'informal';
|
|
9
|
+
export type FormalitySetting = FormalityLevel | 'auto';
|
|
10
|
+
/** True when the language distinguishes formal and informal address. */
|
|
11
|
+
export declare function hasFormalitySplit(locale: string): boolean;
|
|
12
|
+
/**
|
|
13
|
+
* The formality configured for `locale`: the exact locale, else its base
|
|
14
|
+
* language (`de` covers `de-AT`). `auto` and unlisted locales: undefined.
|
|
15
|
+
*/
|
|
16
|
+
export declare function formalityFor(settings: Record<string, FormalitySetting> | null | undefined, locale: string): FormalityLevel | undefined;
|
|
17
|
+
/**
|
|
18
|
+
* The prompt rule for the form of address. With a level set, it names the
|
|
19
|
+
* concrete forms to use and to avoid; on `auto` it still forbids mixing them.
|
|
20
|
+
* Undefined for languages without the distinction (and `auto`): the generic
|
|
21
|
+
* consistency rule applies.
|
|
22
|
+
*/
|
|
23
|
+
export declare function formalityInstruction(locale: string, level: FormalityLevel | undefined, languageName: string): string | undefined;
|
|
24
|
+
/** Which form a single string uses: undefined when it addresses no one (or both forms appear). */
|
|
25
|
+
export declare function formalityOf(text: string, locale: string): FormalityLevel | undefined;
|
|
26
|
+
/**
|
|
27
|
+
* The form an existing catalog uses, when it clearly uses one: at least
|
|
28
|
+
* three strings address the user and 80% of them use the same form.
|
|
29
|
+
*/
|
|
30
|
+
export declare function detectFormality(values: Iterable<string>, locale: string): FormalityLevel | undefined;
|
|
31
|
+
/**
|
|
32
|
+
* Strings of one locale that break its form of address: with `expected`, the
|
|
33
|
+
* ones using the other form; without it, the minority form when both appear
|
|
34
|
+
* (all of them on a tie). Key → message.
|
|
35
|
+
*/
|
|
36
|
+
export declare function formalityIssues(values: Record<string, string>, locale: string, expected?: FormalityLevel): Record<string, string>;
|
|
37
|
+
/** Parse `de=formal,it=informal` (CLI flag values); throws on a malformed item. */
|
|
38
|
+
export declare function parseFormalityList(items: string[]): Record<string, FormalitySetting>;
|
|
39
|
+
/** Keep valid `locale → formal|informal|auto` entries of untrusted input (config files, DB rows). */
|
|
40
|
+
export declare function sanitizeFormality(raw: unknown): Record<string, FormalitySetting> | undefined;
|