@babelize/engine 0.3.11 → 0.3.13

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.
@@ -0,0 +1,71 @@
1
+ import type { ByokProvider } from '@babelize/types';
2
+ import type { FormalitySetting } from '../modules/translator/formality';
3
+ import type { TranslationProvider } from '../providers/types';
4
+ export interface DocsConfig {
5
+ /** Globs of source pages, relative to the project root (`content/docs/**`). */
6
+ include: string[];
7
+ exclude?: string[];
8
+ /** `dot`: `page.ja.mdx` next to `page.mdx`. `dir`: `<root>/ja/page.mdx`. */
9
+ layout: 'dot' | 'dir';
10
+ /** The docs root for the `dir` layout (`content/docs`). */
11
+ root?: string;
12
+ /**
13
+ * Pin each translated heading's id to the source's (`## Título [#title]`,
14
+ * Fumadocs syntax) so `#anchor` links keep working. Default true.
15
+ */
16
+ anchors?: boolean;
17
+ }
18
+ /** `docs` from .babelize/config.json; null when it isn't configured. */
19
+ export declare function readDocsConfig(raw: unknown): DocsConfig | null;
20
+ /** `docs` from the project's .babelize/config.json; null when it isn't configured. */
21
+ export declare function readProjectDocsConfig(projectDir: string): Promise<DocsConfig | null>;
22
+ export declare const DOCS_LOCKFILE = ".babelize/local/docs-lock.json";
23
+ export interface DocsTranslateOptions {
24
+ projectDir: string;
25
+ sourceLocale: string;
26
+ targetLocales: string[];
27
+ docs: DocsConfig;
28
+ /** Compute everything, write nothing. */
29
+ dryRun: boolean;
30
+ /** Replaces `.babelize/config.json` `brandVoice` (`--brand-voice`). */
31
+ brandVoice?: string;
32
+ /** Merged over `.babelize/config.json` `formality` (`--formality`). */
33
+ formality?: Record<string, FormalitySetting>;
34
+ }
35
+ export interface DocsTranslateDeps {
36
+ /** The translator: hosted, BYOK (via `byok`), or a test double. */
37
+ translator?: TranslationProvider;
38
+ byok?: {
39
+ provider: ByokProvider;
40
+ apiKey: string;
41
+ model?: string;
42
+ };
43
+ /** `detail`: a step inside the current one (a batch), not a new step. */
44
+ onProgress?: (message: string, detail?: boolean) => void;
45
+ }
46
+ export interface DocsFailure {
47
+ file: string;
48
+ locale: string;
49
+ line: number;
50
+ source: string;
51
+ reason: string;
52
+ message: string;
53
+ }
54
+ export interface DocsTranslateReport {
55
+ /** Source files: pages and meta.json files. */
56
+ files: number;
57
+ segments: number;
58
+ /** Segment translations produced this run (not reused from the lockfile). */
59
+ translated: number;
60
+ reused: number;
61
+ failures: DocsFailure[];
62
+ changes: {
63
+ added: string[];
64
+ modified: string[];
65
+ };
66
+ /** Target path → new content (always filled; written unless dryRun). */
67
+ outputs: Record<string, string>;
68
+ }
69
+ /** Where a page's translation goes. */
70
+ export declare function targetPath(rel: string, locale: string, docs: DocsConfig): string;
71
+ export declare function translateDocs(opts: DocsTranslateOptions, deps?: DocsTranslateDeps): Promise<DocsTranslateReport>;
@@ -0,0 +1,330 @@
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
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.DOCS_LOCKFILE = void 0;
40
+ exports.readDocsConfig = readDocsConfig;
41
+ exports.readProjectDocsConfig = readProjectDocsConfig;
42
+ exports.targetPath = targetPath;
43
+ exports.translateDocs = translateDocs;
44
+ /**
45
+ * Translate a project's Markdown / MDX docs (#377): every page under
46
+ * `.babelize/config.json` `docs.include`, segment by segment, written next to
47
+ * it in the docs framework's layout — `page.ja.mdx` (Fumadocs' dot parser)
48
+ * or `ja/page.mdx` under `docs.root` (its dir parser). Fumadocs `meta.json`
49
+ * files get their sidebar labels translated the same way (`meta.ja.json`).
50
+ *
51
+ * Segments go through the same translate pipeline as app strings
52
+ * (glossary, brand voice, formality, placeholder/markup QA). A content-
53
+ * addressed lockfile (`.babelize/local/docs-lock.json`) remembers each
54
+ * segment's translation, so a re-run only translates what changed and an
55
+ * edited paragraph costs one paragraph. A segment that fails keeps its
56
+ * source text and is reported; the next run retries it.
57
+ */
58
+ const fs_1 = require("fs");
59
+ const path = __importStar(require("path"));
60
+ const crypto_1 = require("crypto");
61
+ const fast_glob_1 = __importDefault(require("fast-glob"));
62
+ const translate_1 = require("../modules/translator/translate");
63
+ const translate_core_1 = require("../local/translate-core");
64
+ const check_project_1 = require("../qa/check-project");
65
+ const locale_files_1 = require("../qa/locale-files");
66
+ const markdown_segments_1 = require("./markdown-segments");
67
+ /** `docs` from .babelize/config.json; null when it isn't configured. */
68
+ function readDocsConfig(raw) {
69
+ if (!raw || typeof raw !== 'object')
70
+ return null;
71
+ const r = raw;
72
+ const list = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string' && x.trim() !== '') : []);
73
+ const include = list(r.include);
74
+ if (include.length === 0)
75
+ return null;
76
+ const layout = r.layout === 'dir' ? 'dir' : 'dot';
77
+ const root = typeof r.root === 'string' && r.root.trim() ? r.root.trim().replace(/^\.\//, '').replace(/\/+$/, '') : undefined;
78
+ return { include, exclude: list(r.exclude), layout, ...(root ? { root } : {}), ...(r.anchors === false ? { anchors: false } : {}) };
79
+ }
80
+ /** `docs` from the project's .babelize/config.json; null when it isn't configured. */
81
+ async function readProjectDocsConfig(projectDir) {
82
+ try {
83
+ const raw = JSON.parse(await fs_1.promises.readFile(path.join(projectDir, '.babelize', 'config.json'), 'utf8'));
84
+ return readDocsConfig(raw?.docs);
85
+ }
86
+ catch {
87
+ return null;
88
+ }
89
+ }
90
+ exports.DOCS_LOCKFILE = '.babelize/local/docs-lock.json';
91
+ const hashOf = (message) => (0, crypto_1.createHash)('sha256').update(message).digest('hex').slice(0, 16);
92
+ const toPosix = (p) => p.split(path.sep).join('/');
93
+ /**
94
+ * A Fumadocs `meta.json`'s readable labels: `title`, `description`, and in
95
+ * `pages` the text of `---Separator---` and `[Icon][Text](url)` entries.
96
+ * Page names, icons and URLs stay as they are.
97
+ */
98
+ const META_SEPARATOR = /^(---(?:\[[^\]]*\])?)(.+?)(---)$/;
99
+ const META_LINK = /^((?:external:)?(?:\[[^\]]*\])?\[)([^\]]+)(\]\(.+\))$/;
100
+ function metaLabels(meta) {
101
+ const labels = [];
102
+ for (const field of ['title', 'description']) {
103
+ const v = meta[field];
104
+ if (typeof v === 'string' && v.trim())
105
+ labels.push({ message: v, apply: (m, value) => { m[field] = value; } });
106
+ }
107
+ if (Array.isArray(meta.pages)) {
108
+ meta.pages.forEach((entry, i) => {
109
+ if (typeof entry !== 'string')
110
+ return;
111
+ const m = META_SEPARATOR.exec(entry) ?? META_LINK.exec(entry);
112
+ if (!m || !m[2].trim())
113
+ return;
114
+ labels.push({ message: m[2], apply: (out, value) => { out.pages[i] = `${m[1]}${value.replace(/[[\]]/g, '')}${m[3]}`; } });
115
+ });
116
+ }
117
+ return labels;
118
+ }
119
+ function markdownPage(rel, source, docs) {
120
+ const segments = (0, markdown_segments_1.segmentDocument)(source);
121
+ const options = { anchors: docs.anchors !== false };
122
+ return {
123
+ rel,
124
+ segments,
125
+ rebuild: (translations) => (0, markdown_segments_1.rebuildDocument)(source, segments, translations, options),
126
+ checkOne: (i, value) => void (0, markdown_segments_1.rebuildDocument)(source, [segments[i]], new Map([[0, value]]), options),
127
+ };
128
+ }
129
+ function metaPage(rel, source) {
130
+ let meta;
131
+ try {
132
+ meta = JSON.parse(source);
133
+ }
134
+ catch {
135
+ return null;
136
+ }
137
+ if (!meta || typeof meta !== 'object' || Array.isArray(meta))
138
+ return null;
139
+ const labels = metaLabels(meta);
140
+ // Nothing to translate: Fumadocs falls back to meta.json.
141
+ if (labels.length === 0)
142
+ return null;
143
+ const indent = /\n([ \t]+)"/.exec(source)?.[1] ?? ' ';
144
+ return {
145
+ rel,
146
+ segments: labels.map((l) => ({ message: l.message, line: 1, kind: 'frontmatter' })),
147
+ rebuild: (translations) => {
148
+ const out = JSON.parse(source);
149
+ translations.forEach((value, i) => labels[i].apply(out, value));
150
+ return `${JSON.stringify(out, null, indent)}\n`;
151
+ },
152
+ checkOne: () => undefined,
153
+ };
154
+ }
155
+ const isMeta = (rel) => path.posix.basename(rel) === 'meta.json';
156
+ /** Where a page's translation goes. */
157
+ function targetPath(rel, locale, docs) {
158
+ if (docs.layout === 'dir') {
159
+ const root = docs.root ?? path.posix.dirname(rel);
160
+ const inside = rel.startsWith(`${root}/`) ? rel.slice(root.length + 1) : path.posix.basename(rel);
161
+ return `${root}/${locale}/${inside}`;
162
+ }
163
+ const ext = path.posix.extname(rel);
164
+ return `${rel.slice(0, -ext.length)}.${locale}${ext}`;
165
+ }
166
+ /** A page that is itself a translation (`page.ja.mdx`, `<root>/ja/page.mdx`). */
167
+ function isTranslation(rel, docs) {
168
+ if (docs.layout === 'dir' && docs.root) {
169
+ const first = rel.startsWith(`${docs.root}/`) ? rel.slice(docs.root.length + 1).split('/')[0] : '';
170
+ if (first && (0, locale_files_1.isLocaleCode)(first) && rel.slice(docs.root.length + 1).includes('/'))
171
+ return true;
172
+ }
173
+ const m = /\.([A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*)\.(?:mdx?|json)$/.exec(rel);
174
+ return !!m && (0, locale_files_1.isLocaleCode)(m[1]);
175
+ }
176
+ async function readLock(projectDir) {
177
+ try {
178
+ const raw = JSON.parse(await fs_1.promises.readFile(path.join(projectDir, exports.DOCS_LOCKFILE), 'utf8'));
179
+ if (raw?.version === 1 && raw.segments && typeof raw.segments === 'object')
180
+ return raw;
181
+ }
182
+ catch {
183
+ // none yet
184
+ }
185
+ return { version: 1, segments: {} };
186
+ }
187
+ async function translateDocs(opts, deps = {}) {
188
+ var _a;
189
+ const projectDir = path.resolve(opts.projectDir);
190
+ const docs = opts.docs;
191
+ const files = (await (0, fast_glob_1.default)(docs.include, {
192
+ cwd: projectDir,
193
+ ignore: ['**/node_modules/**', ...(docs.exclude ?? [])],
194
+ onlyFiles: true,
195
+ dot: false,
196
+ }))
197
+ .map(toPosix)
198
+ .filter((f) => (/\.mdx?$/.test(f) || isMeta(f)) && !isTranslation(f, docs))
199
+ .sort();
200
+ const pages = [];
201
+ for (const rel of files) {
202
+ const source = await fs_1.promises.readFile(path.join(projectDir, rel), 'utf8');
203
+ const page = isMeta(rel) ? metaPage(rel, source) : markdownPage(rel, source, docs);
204
+ if (page)
205
+ pages.push(page);
206
+ }
207
+ const lock = await readLock(projectDir);
208
+ const report = {
209
+ files: pages.length,
210
+ segments: pages.reduce((n, p) => n + p.segments.length, 0),
211
+ translated: 0,
212
+ reused: 0,
213
+ failures: [],
214
+ changes: { added: [], modified: [] },
215
+ outputs: {},
216
+ };
217
+ // The translate pipeline only needs a workspace for paths; nothing is written there (dryRun).
218
+ const workspace = {
219
+ path: projectDir, framework: 'unknown', sourceDirs: [], hasLocalesDir: false,
220
+ existingLocales: [], publicDir: '.', localeFormat: 'json',
221
+ };
222
+ const providers = deps.translator ? { translator: deps.translator } : {};
223
+ // .babelize/config.json glossary, brand voice and formality, as for app strings; options win.
224
+ let rules;
225
+ if (opts.brandVoice?.trim() || (opts.formality && Object.keys(opts.formality).length > 0)) {
226
+ const config = await (0, check_project_1.readProjectLocaleConfig)(projectDir);
227
+ const store = (0, translate_core_1.configRulesStore)(config.glossary, {
228
+ brandVoice: opts.brandVoice?.trim() || config.brandVoice,
229
+ formality: { ...config.formality, ...opts.formality },
230
+ });
231
+ rules = await (0, translate_1.loadProjectTranslationRules)('local', store);
232
+ }
233
+ for (const locale of opts.targetLocales) {
234
+ // Unique messages this locale has no translation for yet.
235
+ const todo = new Map();
236
+ for (const page of pages) {
237
+ for (const s of page.segments) {
238
+ const h = hashOf(s.message);
239
+ if (lock.segments[h]?.[locale] !== undefined)
240
+ continue;
241
+ if (!todo.has(h))
242
+ todo.set(h, s.message);
243
+ }
244
+ }
245
+ const failed = new Map();
246
+ if (todo.size > 0) {
247
+ deps.onProgress?.(`Translating ${todo.size} doc segment${todo.size === 1 ? '' : 's'} into ${locale}…`);
248
+ // No per-segment context: a doc paragraph carries its own, and NLLB-based
249
+ // translators prefix the context to the text and can leak it into the output.
250
+ const data = {};
251
+ for (const [h, message] of todo)
252
+ data[`s${h}`] = message;
253
+ const result = await (0, translate_1.translateLocales)(workspace, { locale: opts.sourceLocale, path: exports.DOCS_LOCKFILE, data, isNew: true }, [locale], false, true, undefined, (m) => deps.onProgress?.(m, true), undefined, undefined, deps.byok, undefined, undefined, providers, rules ? { rules } : {});
254
+ const out = (result.translation.locales.find((l) => l.locale === locale)?.data ?? {});
255
+ for (const [h] of todo) {
256
+ const value = out[`s${h}`];
257
+ if (typeof value === 'string' && value.trim()) {
258
+ ((_a = lock.segments)[h] ?? (_a[h] = {}))[locale] = value;
259
+ report.translated++;
260
+ }
261
+ }
262
+ for (const f of result.translation.failures) {
263
+ if (f.locale === locale)
264
+ failed.set(f.key.replace(/^s/, ''), { reason: f.reason, message: f.message ?? f.reason });
265
+ }
266
+ }
267
+ for (const page of pages) {
268
+ const translations = new Map();
269
+ page.segments.forEach((s, i) => {
270
+ const h = hashOf(s.message);
271
+ const value = lock.segments[h]?.[locale];
272
+ if (value === undefined) {
273
+ const why = failed.get(h) ?? { reason: 'missing_from_response', message: 'No translation was produced' };
274
+ report.failures.push({ file: page.rel, locale, line: s.line, source: s.message, ...why });
275
+ return;
276
+ }
277
+ if (!todo.has(h))
278
+ report.reused++;
279
+ translations.set(i, value);
280
+ });
281
+ // A translation whose tags or placeholders don't line up keeps the source text.
282
+ let content;
283
+ for (;;) {
284
+ try {
285
+ content = page.rebuild(translations);
286
+ break;
287
+ }
288
+ catch (err) {
289
+ if (!(err instanceof markdown_segments_1.RestoreError))
290
+ throw err;
291
+ const bad = [...translations.keys()].find((i) => {
292
+ try {
293
+ page.checkOne(i, translations.get(i));
294
+ return false;
295
+ }
296
+ catch {
297
+ return true;
298
+ }
299
+ });
300
+ if (bad === undefined)
301
+ throw err;
302
+ const s = page.segments[bad];
303
+ report.failures.push({ file: page.rel, locale, line: s.line, source: s.message, reason: 'markup_mismatch', message: `Markdown syntax didn't survive translation: ${err.message}` });
304
+ delete lock.segments[hashOf(s.message)]?.[locale];
305
+ translations.delete(bad);
306
+ }
307
+ }
308
+ // Nothing translated (translator down, every segment failed): a copy of the
309
+ // source would pass for a translation. Write nothing; the docs framework
310
+ // falls back to the source page, and the next run retries.
311
+ if (translations.size === 0 && page.segments.length > 0)
312
+ continue;
313
+ const target = targetPath(page.rel, locale, docs);
314
+ report.outputs[target] = content;
315
+ const existing = await fs_1.promises.readFile(path.join(projectDir, target), 'utf8').catch(() => null);
316
+ if (existing === content)
317
+ continue;
318
+ (existing === null ? report.changes.added : report.changes.modified).push(target);
319
+ if (!opts.dryRun) {
320
+ await fs_1.promises.mkdir(path.dirname(path.join(projectDir, target)), { recursive: true });
321
+ await fs_1.promises.writeFile(path.join(projectDir, target), content);
322
+ }
323
+ }
324
+ }
325
+ if (!opts.dryRun) {
326
+ await fs_1.promises.mkdir(path.dirname(path.join(projectDir, exports.DOCS_LOCKFILE)), { recursive: true });
327
+ await fs_1.promises.writeFile(path.join(projectDir, exports.DOCS_LOCKFILE), `${JSON.stringify(lock, null, 2)}\n`);
328
+ }
329
+ return report;
330
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Markdown / MDX documents as translatable segments (#377).
3
+ *
4
+ * A document is split into the text a reader sees — headings, paragraphs,
5
+ * list items, table cells, blockquotes, frontmatter `title`/`description`,
6
+ * and human-readable string props of MDX components (`<Callout title="…">`)
7
+ * — and everything else, which is never touched: fenced code, `import` /
8
+ * `export`, JSX tags and expressions, comments, URLs.
9
+ *
10
+ * Inside a segment, inline syntax becomes what the translate pipeline already
11
+ * protects and validates: numbered tags for spans whose content is
12
+ * translated (`**bold**`, `[link](url)`, `<kbd>Enter</kbd>` → `<1>…</1>`)
13
+ * and `{pN}` placeholders for spans that are copied through (`inline code`,
14
+ * `{expressions}`, `<Icon />`, URLs). A translation is rebuilt by splicing
15
+ * each segment's range, so the rest of the file stays byte-identical.
16
+ */
17
+ export type SegmentKind = 'frontmatter' | 'heading' | 'paragraph' | 'list' | 'table' | 'quote' | 'attribute';
18
+ export interface InlineRestore {
19
+ /** `{pN}` → its original text. */
20
+ placeholders: string[];
21
+ /** Tag n → the syntax around its content (`**` … `**`, `[` … `](url)`). */
22
+ tags: Array<{
23
+ open: string;
24
+ close: string;
25
+ }>;
26
+ }
27
+ export interface DocSegment {
28
+ kind: SegmentKind;
29
+ /** Text sent to the translator: tags `<n>…</n>` and placeholders `{pN}`. */
30
+ message: string;
31
+ /** Range in the source document this segment replaces. */
32
+ start: number;
33
+ end: number;
34
+ restore: InlineRestore;
35
+ /** Frontmatter values and JSX attributes: how the value is quoted in the source. */
36
+ quote?: '"' | "'" | '';
37
+ /** 1-based line of the segment, for reports. */
38
+ line: number;
39
+ /**
40
+ * Headings without an explicit id: the id the source heading gets
41
+ * (github-slugger, as Fumadocs and GitHub), kept on the translation so
42
+ * `#anchor` links still land.
43
+ */
44
+ anchor?: string;
45
+ }
46
+ /** github-slugger's slug of a heading's text: lowercase, punctuation and symbols dropped, spaces → `-`. */
47
+ export declare function headingSlug(markdown: string): string;
48
+ /** Turn inline Markdown/MDX into a translator message with tags and placeholders. */
49
+ export declare function toMessage(text: string): {
50
+ message: string;
51
+ restore: InlineRestore;
52
+ };
53
+ export declare class RestoreError extends Error {
54
+ }
55
+ /**
56
+ * The translated message back as Markdown/MDX: tags and placeholders become
57
+ * their syntax again; characters that would change the structure (`<`, `{`,
58
+ * a `|` in a table cell) are escaped. Throws RestoreError when a tag or
59
+ * placeholder is missing, repeated or unknown.
60
+ */
61
+ export declare function fromMessage(message: string, restore: InlineRestore, opts?: {
62
+ inTable?: boolean;
63
+ }): string;
64
+ /** Every translatable segment of a Markdown / MDX document. */
65
+ export declare function segmentDocument(source: string): DocSegment[];
66
+ /**
67
+ * The document with each translated segment spliced in. `translations`
68
+ * maps a segment's index to its translated message; segments without one
69
+ * keep their source text. A frontmatter value that would need quoting in
70
+ * YAML but wasn't quoted is wrapped in double quotes.
71
+ */
72
+ export interface RebuildOptions {
73
+ /** Pin a translated heading's id to the source's as `[#id]` (Fumadocs syntax). Default true. */
74
+ anchors?: boolean;
75
+ }
76
+ export declare function rebuildDocument(source: string, segments: DocSegment[], translations: Map<number, string>, options?: RebuildOptions): string;
@@ -0,0 +1,565 @@
1
+ "use strict";
2
+ /**
3
+ * Markdown / MDX documents as translatable segments (#377).
4
+ *
5
+ * A document is split into the text a reader sees — headings, paragraphs,
6
+ * list items, table cells, blockquotes, frontmatter `title`/`description`,
7
+ * and human-readable string props of MDX components (`<Callout title="…">`)
8
+ * — and everything else, which is never touched: fenced code, `import` /
9
+ * `export`, JSX tags and expressions, comments, URLs.
10
+ *
11
+ * Inside a segment, inline syntax becomes what the translate pipeline already
12
+ * protects and validates: numbered tags for spans whose content is
13
+ * translated (`**bold**`, `[link](url)`, `<kbd>Enter</kbd>` → `<1>…</1>`)
14
+ * and `{pN}` placeholders for spans that are copied through (`inline code`,
15
+ * `{expressions}`, `<Icon />`, URLs). A translation is rebuilt by splicing
16
+ * each segment's range, so the rest of the file stays byte-identical.
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.RestoreError = void 0;
20
+ exports.headingSlug = headingSlug;
21
+ exports.toMessage = toMessage;
22
+ exports.fromMessage = fromMessage;
23
+ exports.segmentDocument = segmentDocument;
24
+ exports.rebuildDocument = rebuildDocument;
25
+ /** github-slugger's slug of a heading's text: lowercase, punctuation and symbols dropped, spaces → `-`. */
26
+ function headingSlug(markdown) {
27
+ const text = markdown
28
+ .replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1')
29
+ .replace(/<[^>]+>/g, '')
30
+ .replace(/[`*~]/g, '');
31
+ return text.toLowerCase().replace(/[^\p{L}\p{M}\p{N}\p{Pc} -]/gu, '').replace(/ /g, '-');
32
+ }
33
+ /** Slugs seen so far in the document being segmented (github-slugger numbers repeats: `-1`, `-2`). */
34
+ let headingSlugs = null;
35
+ function uniqueSlug(base) {
36
+ const seen = (headingSlugs ?? (headingSlugs = new Map()));
37
+ let slug = base;
38
+ while (seen.has(slug)) {
39
+ const n = seen.get(base) + 1;
40
+ seen.set(base, n);
41
+ slug = `${base}-${n}`;
42
+ }
43
+ seen.set(slug, 0);
44
+ return slug;
45
+ }
46
+ /** Props whose string value people read. */
47
+ const READABLE_PROPS = new Set(['title', 'description', 'label', 'alt', 'placeholder', 'aria-label', 'caption', 'summary', 'heading', 'subtitle']);
48
+ /** Frontmatter keys whose value people read. */
49
+ const READABLE_FRONTMATTER = new Set(['title', 'description', 'summary', 'sidebarTitle', 'label']);
50
+ /** Elements whose content is code, never translated. */
51
+ const CODE_ELEMENTS = new Set(['pre', 'code', 'kbd', 'samp', 'script', 'style']);
52
+ const LETTER = /\p{L}/u;
53
+ // ── Inline syntax ↔ message ────────────────────────────────────────────────
54
+ /** Turn inline Markdown/MDX into a translator message with tags and placeholders. */
55
+ function toMessage(text) {
56
+ const restore = { placeholders: [], tags: [] };
57
+ const message = convert(text, restore);
58
+ return { message, restore };
59
+ }
60
+ function placeholder(restore, original) {
61
+ restore.placeholders.push(original);
62
+ return `{p${restore.placeholders.length - 1}}`;
63
+ }
64
+ function tag(restore, open, close, inner) {
65
+ restore.tags.push({ open, close });
66
+ const n = restore.tags.length;
67
+ return `<${n}>${convert(inner, restore)}</${n}>`;
68
+ }
69
+ /** Index just past the `{…}` starting at `i` (balanced, string-aware), or -1. */
70
+ function matchBrace(text, i) {
71
+ let depth = 0;
72
+ for (let j = i; j < text.length; j++) {
73
+ const c = text[j];
74
+ if (c === '"' || c === "'" || c === '`') {
75
+ const close = text.indexOf(c, j + 1);
76
+ if (close === -1)
77
+ return -1;
78
+ j = close;
79
+ }
80
+ else if (c === '{')
81
+ depth++;
82
+ else if (c === '}') {
83
+ depth--;
84
+ if (depth === 0)
85
+ return j + 1;
86
+ }
87
+ }
88
+ return -1;
89
+ }
90
+ /** End of the JSX/HTML tag starting at `<` (quote- and brace-aware), or -1. */
91
+ function tagEnd(text, i) {
92
+ for (let j = i + 1; j < text.length; j++) {
93
+ const c = text[j];
94
+ if (c === '"' || c === "'") {
95
+ const close = text.indexOf(c, j + 1);
96
+ if (close === -1)
97
+ return -1;
98
+ j = close;
99
+ }
100
+ else if (c === '{') {
101
+ const close = matchBrace(text, j);
102
+ if (close === -1)
103
+ return -1;
104
+ j = close - 1;
105
+ }
106
+ else if (c === '>')
107
+ return j + 1;
108
+ }
109
+ return -1;
110
+ }
111
+ /** Index of the `</name>` closing the element opened before `from`, nesting-aware, or -1. */
112
+ function closingTag(text, name, from) {
113
+ const open = new RegExp(`<${escapeRe(name)}(?=[\\s/>])`, 'g');
114
+ const close = new RegExp(`</${escapeRe(name)}\\s*>`, 'g');
115
+ let depth = 1;
116
+ let pos = from;
117
+ for (;;) {
118
+ close.lastIndex = pos;
119
+ const c = close.exec(text);
120
+ if (!c)
121
+ return -1;
122
+ open.lastIndex = pos;
123
+ let o;
124
+ while ((o = open.exec(text)) && o.index < c.index) {
125
+ const end = tagEnd(text, o.index);
126
+ if (end !== -1 && text[end - 2] !== '/')
127
+ depth++;
128
+ open.lastIndex = Math.max(end, o.index + 1);
129
+ }
130
+ depth--;
131
+ if (depth === 0)
132
+ return c.index;
133
+ pos = c.index + c[0].length;
134
+ }
135
+ }
136
+ function escapeRe(s) {
137
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
138
+ }
139
+ const URL_RE = /^(?:https?:\/\/|mailto:)[^\s<>()]*[^\s<>().,;:!?'"]/;
140
+ function convert(text, restore) {
141
+ let out = '';
142
+ let i = 0;
143
+ while (i < text.length) {
144
+ const c = text[i];
145
+ const rest = text.slice(i);
146
+ // `code` (any backtick run, closed by the same run)
147
+ if (c === '`') {
148
+ const run = /^`+/.exec(rest)[0];
149
+ const close = text.indexOf(run, i + run.length);
150
+ if (close !== -1) {
151
+ out += placeholder(restore, text.slice(i, close + run.length));
152
+ i = close + run.length;
153
+ continue;
154
+ }
155
+ }
156
+ // \escape
157
+ if (c === '\\' && i + 1 < text.length) {
158
+ out += placeholder(restore, text.slice(i, i + 2));
159
+ i += 2;
160
+ continue;
161
+ }
162
+ // ![alt](src) and [text](url) / [text][ref]
163
+ const link = /^(!?)\[((?:[^[\]\\]|\\.|\[[^\]]*\])*)\](\([^()\s]*(?:\([^()]*\))?[^()]*\)|\[[^\]]*\])/.exec(rest);
164
+ if (link) {
165
+ const [whole, bang, inner, target] = link;
166
+ out += inner.trim() ? tag(restore, `${bang}[`, `]${target}`, inner) : placeholder(restore, whole);
167
+ i += whole.length;
168
+ continue;
169
+ }
170
+ // **strong**, __strong__, ~~strike~~, *em* (not _em_: snake_case is common in docs)
171
+ const emph = /^(\*\*|__|~~|\*)(?=\S)([\s\S]*?\S)\1(?!\*)/.exec(rest);
172
+ if (emph && !(emph[1] === '__' && /\w/.test(text[i - 1] ?? ''))) {
173
+ out += tag(restore, emph[1], emph[1], emph[2]);
174
+ i += emph[0].length;
175
+ continue;
176
+ }
177
+ if (c === '<') {
178
+ const auto = /^<(?:https?:\/\/|mailto:)[^>\s]+>/.exec(rest);
179
+ if (auto) {
180
+ out += placeholder(restore, auto[0]);
181
+ i += auto[0].length;
182
+ continue;
183
+ }
184
+ if (rest.startsWith('<!--')) {
185
+ const end = text.indexOf('-->', i);
186
+ const stop = end === -1 ? text.length : end + 3;
187
+ out += placeholder(restore, text.slice(i, stop));
188
+ i = stop;
189
+ continue;
190
+ }
191
+ const name = /^<([A-Za-z][\w.:-]*)/.exec(rest)?.[1];
192
+ const end = name ? tagEnd(text, i) : -1;
193
+ if (name && end !== -1) {
194
+ const openTag = text.slice(i, end);
195
+ if (openTag.endsWith('/>')) {
196
+ out += placeholder(restore, openTag);
197
+ i = end;
198
+ continue;
199
+ }
200
+ const close = closingTag(text, name, end);
201
+ if (close !== -1) {
202
+ const closeTag = /^<\/[^>]*>/.exec(text.slice(close))[0];
203
+ const inner = text.slice(end, close);
204
+ if (CODE_ELEMENTS.has(name) || !LETTER.test(inner))
205
+ out += placeholder(restore, text.slice(i, close + closeTag.length));
206
+ else
207
+ out += tag(restore, openTag, closeTag, inner);
208
+ i = close + closeTag.length;
209
+ continue;
210
+ }
211
+ // An unclosed tag (void HTML like <br>): copy it.
212
+ out += placeholder(restore, openTag);
213
+ i = end;
214
+ continue;
215
+ }
216
+ out += placeholder(restore, '<');
217
+ i++;
218
+ continue;
219
+ }
220
+ // {expression}
221
+ if (c === '{') {
222
+ const end = matchBrace(text, i);
223
+ const stop = end === -1 ? i + 1 : end;
224
+ out += placeholder(restore, text.slice(i, stop));
225
+ i = stop;
226
+ continue;
227
+ }
228
+ if (c === '}' || c === '>') {
229
+ out += placeholder(restore, c);
230
+ i++;
231
+ continue;
232
+ }
233
+ const url = URL_RE.exec(rest);
234
+ if (url && !LETTER.test(text[i - 1] ?? '')) {
235
+ out += placeholder(restore, url[0]);
236
+ i += url[0].length;
237
+ continue;
238
+ }
239
+ out += c;
240
+ i++;
241
+ }
242
+ return out;
243
+ }
244
+ class RestoreError extends Error {
245
+ }
246
+ exports.RestoreError = RestoreError;
247
+ /**
248
+ * The translated message back as Markdown/MDX: tags and placeholders become
249
+ * their syntax again; characters that would change the structure (`<`, `{`,
250
+ * a `|` in a table cell) are escaped. Throws RestoreError when a tag or
251
+ * placeholder is missing, repeated or unknown.
252
+ */
253
+ function fromMessage(message, restore, opts = {}) {
254
+ const seenP = new Set();
255
+ const seenOpen = new Set();
256
+ const seenClose = new Set();
257
+ let out = '';
258
+ const re = /\{p(\d+)\}|<(\/?)(\d+)>/g;
259
+ let last = 0;
260
+ let m;
261
+ const text = (s) => {
262
+ let t = s.replace(/[<{}]/g, (ch) => `\\${ch}`);
263
+ if (opts.inTable)
264
+ t = t.replace(/(?<!\\)\|/g, '\\|');
265
+ return t;
266
+ };
267
+ while ((m = re.exec(message))) {
268
+ out += text(message.slice(last, m.index));
269
+ last = m.index + m[0].length;
270
+ if (m[1] !== undefined) {
271
+ const n = Number(m[1]);
272
+ if (n >= restore.placeholders.length || seenP.has(n))
273
+ throw new RestoreError(`placeholder {p${n}} unknown or repeated`);
274
+ seenP.add(n);
275
+ out += restore.placeholders[n];
276
+ }
277
+ else {
278
+ const n = Number(m[3]);
279
+ const t = restore.tags[n - 1];
280
+ if (!t)
281
+ throw new RestoreError(`tag <${n}> unknown`);
282
+ const seen = m[2] ? seenClose : seenOpen;
283
+ if (seen.has(n))
284
+ throw new RestoreError(`tag <${m[2]}${n}> repeated`);
285
+ seen.add(n);
286
+ out += m[2] ? t.close : t.open;
287
+ }
288
+ }
289
+ out += text(message.slice(last));
290
+ if (seenP.size !== restore.placeholders.length)
291
+ throw new RestoreError('a placeholder was dropped');
292
+ if (seenOpen.size !== restore.tags.length || seenClose.size !== restore.tags.length)
293
+ throw new RestoreError('a tag was dropped');
294
+ return out;
295
+ }
296
+ function linesOf(src, base, firstLine) {
297
+ const lines = [];
298
+ let start = 0;
299
+ let no = firstLine;
300
+ for (;;) {
301
+ const nl = src.indexOf('\n', start);
302
+ const end = nl === -1 ? src.length : nl;
303
+ const text = src.slice(start, end).replace(/\r$/, '');
304
+ lines.push({ text, start: base + start, end: base + start + text.length, no });
305
+ if (nl === -1)
306
+ break;
307
+ start = nl + 1;
308
+ no++;
309
+ }
310
+ return lines;
311
+ }
312
+ const FENCE = /^\s*(`{3,}|~{3,})/;
313
+ const HEADING = /^(\s{0,3}#{1,6}[ \t]+)(.*?)([ \t]*(?:\[#[\w-]+\]|\{#[\w-]+\})?[ \t#]*)$/;
314
+ const LIST = /^(\s*(?:[-*+]|\d{1,9}[.)])[ \t]+(?:\[[ xX]\][ \t]+)?)(.*)$/;
315
+ const QUOTE = /^(\s*(?:>[ \t]?)+)(.*)$/;
316
+ const TABLE_SEP = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
317
+ const RULE = /^\s{0,3}([-*_])(\s*\1){2,}\s*$/;
318
+ function startsBlock(text) {
319
+ const t = text.trimStart();
320
+ return t === '' || FENCE.test(text) || HEADING.test(text) || LIST.test(text) || QUOTE.test(text) ||
321
+ t.startsWith('|') || t.startsWith('<') || t.startsWith('{') || RULE.test(text) ||
322
+ /^(import|export)\s/.test(t);
323
+ }
324
+ /** Every translatable segment of a Markdown / MDX document. */
325
+ function segmentDocument(source) {
326
+ const out = [];
327
+ let body = 0;
328
+ let firstLine = 1;
329
+ const fm = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(source);
330
+ if (fm) {
331
+ for (const line of linesOf(fm[1], fm[0].indexOf(fm[1]), 2)) {
332
+ const kv = /^([A-Za-z_][\w-]*):[ \t]*(.+?)[ \t]*$/.exec(line.text);
333
+ if (!kv || !READABLE_FRONTMATTER.has(kv[1]))
334
+ continue;
335
+ const raw = kv[2];
336
+ const valueStart = line.start + line.text.indexOf(raw, kv[1].length + 1);
337
+ const quoted = /^(["'])(.*)\1$/.exec(raw);
338
+ const quote = (quoted?.[1] ?? '');
339
+ const value = quoted ? quoted[2] : raw;
340
+ const start = valueStart + (quoted ? 1 : 0);
341
+ // The translator sees the text, not YAML escaping (rebuild re-escapes).
342
+ const text = quote === "'" ? value.replace(/''/g, "'") : quote === '"' ? value.replace(/\\(["\\])/g, '$1') : value;
343
+ push(out, 'frontmatter', text, start, start + value.length, line.no, quote);
344
+ }
345
+ body = fm[0].length;
346
+ firstLine = fm[0].split('\n').length;
347
+ }
348
+ headingSlugs = new Map();
349
+ try {
350
+ blocks(source, body, source.length, firstLine, out);
351
+ }
352
+ finally {
353
+ headingSlugs = null;
354
+ }
355
+ return out.sort((a, b) => a.start - b.start);
356
+ }
357
+ function push(out, kind, text, start, end, line, quote) {
358
+ if (!LETTER.test(text))
359
+ return;
360
+ const { message, restore } = toMessage(text);
361
+ // Only syntax and placeholders (a cell that is all `code`): nothing to translate.
362
+ if (!LETTER.test(message.replace(/\{p\d+\}|<\/?\d+>/g, '')))
363
+ return;
364
+ out.push({ kind, message, start, end, restore, line, ...(quote !== undefined ? { quote } : {}) });
365
+ }
366
+ function blocks(source, from, to, firstLine, out) {
367
+ const lines = linesOf(source.slice(from, to), from, firstLine);
368
+ let i = 0;
369
+ while (i < lines.length) {
370
+ const line = lines[i];
371
+ const t = line.text.trimStart();
372
+ if (t === '' || RULE.test(line.text)) {
373
+ i++;
374
+ continue;
375
+ }
376
+ const fence = FENCE.exec(line.text);
377
+ if (fence) {
378
+ const marker = fence[1];
379
+ i++;
380
+ while (i < lines.length && !new RegExp(`^\\s*${marker[0] === '`' ? '`' : '~'}{${marker.length},}\\s*$`).test(lines[i].text))
381
+ i++;
382
+ i++;
383
+ continue;
384
+ }
385
+ // MDX ESM: `import …` / `export …` until a blank line.
386
+ if (/^(import|export)\s/.test(t)) {
387
+ while (i < lines.length && lines[i].text.trim() !== '')
388
+ i++;
389
+ continue;
390
+ }
391
+ // {/* comments */} and other flow expressions.
392
+ if (t.startsWith('{')) {
393
+ const at = line.start + (line.text.length - t.length);
394
+ const end = matchBrace(source, at);
395
+ i = skipTo(lines, i, end === -1 ? line.end : end);
396
+ continue;
397
+ }
398
+ if (t.startsWith('<!--')) {
399
+ const end = source.indexOf('-->', line.start);
400
+ i = skipTo(lines, i, end === -1 ? to : end + 3);
401
+ continue;
402
+ }
403
+ if (/^<[A-Za-z]/.test(t)) {
404
+ i = jsxBlock(source, lines, i, to, out);
405
+ continue;
406
+ }
407
+ const heading = HEADING.exec(line.text);
408
+ if (heading) {
409
+ const start = line.start + heading[1].length;
410
+ const before = out.length;
411
+ push(out, 'heading', heading[2], start, start + heading[2].length, line.no);
412
+ // An explicit id ([#id], {#id}) stays in the source; otherwise remember the generated one.
413
+ if (!/\[#|\{#/.test(heading[3])) {
414
+ const anchor = uniqueSlug(headingSlug(heading[2]));
415
+ if (out.length > before && anchor)
416
+ out[out.length - 1].anchor = anchor;
417
+ }
418
+ i++;
419
+ continue;
420
+ }
421
+ if (t.startsWith('|')) {
422
+ while (i < lines.length && lines[i].text.trimStart().startsWith('|')) {
423
+ if (!TABLE_SEP.test(lines[i].text))
424
+ tableRow(lines[i], out);
425
+ i++;
426
+ }
427
+ continue;
428
+ }
429
+ const quote = QUOTE.exec(line.text);
430
+ if (quote) {
431
+ const text = quote[2].replace(/^\[!\w+\]\s*/, (m) => ' '.repeat(m.length));
432
+ const lead = text.length - text.trimStart().length;
433
+ const start = line.start + quote[1].length + lead;
434
+ push(out, 'quote', text.trim(), start, start + text.trim().length, line.no);
435
+ i++;
436
+ continue;
437
+ }
438
+ const item = LIST.exec(line.text);
439
+ if (item) {
440
+ let text = item[2];
441
+ i++;
442
+ // Lazy continuation lines belong to the item.
443
+ while (i < lines.length && lines[i].text.trim() !== '' && !startsBlock(lines[i].text)) {
444
+ text += `\n${lines[i].text}`;
445
+ i++;
446
+ }
447
+ const start = line.start + item[1].length;
448
+ push(out, 'list', text.trimEnd(), start, start + text.trimEnd().length, line.no);
449
+ continue;
450
+ }
451
+ // Paragraph: lines until a blank line or another block.
452
+ const start = line.start + (line.text.length - t.length);
453
+ let end = line.end;
454
+ let text = t;
455
+ i++;
456
+ while (i < lines.length && lines[i].text.trim() !== '' && !startsBlock(lines[i].text)) {
457
+ text += `\n${lines[i].text}`;
458
+ end = lines[i].end;
459
+ i++;
460
+ }
461
+ push(out, 'paragraph', text.trimEnd(), start, start + text.trimEnd().length, line.no);
462
+ void end;
463
+ }
464
+ }
465
+ /** Index of the first line that starts at or after `offset`. */
466
+ function skipTo(lines, i, offset) {
467
+ while (i < lines.length && lines[i].start < offset)
468
+ i++;
469
+ return i;
470
+ }
471
+ function tableRow(line, out) {
472
+ const text = line.text;
473
+ let cellStart = text.indexOf('|') + 1;
474
+ let inCode = false;
475
+ for (let j = cellStart; j <= text.length; j++) {
476
+ const c = text[j];
477
+ if (c === '`')
478
+ inCode = !inCode;
479
+ if (c === '\\') {
480
+ j++;
481
+ continue;
482
+ }
483
+ if ((c === '|' && !inCode) || j === text.length) {
484
+ const cell = text.slice(cellStart, j);
485
+ const lead = cell.length - cell.trimStart().length;
486
+ const value = cell.trim();
487
+ if (value)
488
+ push(out, 'table', value, line.start + cellStart + lead, line.start + cellStart + lead + value.length, line.no);
489
+ cellStart = j + 1;
490
+ }
491
+ }
492
+ }
493
+ /** A JSX/HTML element starting a block: readable props, then its children as blocks. */
494
+ function jsxBlock(source, lines, i, to, out) {
495
+ const line = lines[i];
496
+ const at = line.start + (line.text.length - line.text.trimStart().length);
497
+ const end = tagEnd(source, at);
498
+ if (end === -1 || end > to)
499
+ return i + 1;
500
+ const name = /^<([A-Za-z][\w.:-]*)/.exec(source.slice(at))[1];
501
+ const openTag = source.slice(at, end);
502
+ // Readable string props: title="…", description='…'.
503
+ const attr = /([\w:-]+)=("([^"]*)"|'([^']*)')/g;
504
+ let a;
505
+ while ((a = attr.exec(openTag))) {
506
+ if (!READABLE_PROPS.has(a[1]))
507
+ continue;
508
+ const value = a[3] ?? a[4];
509
+ const start = at + a.index + a[1].length + 2;
510
+ const lineNo = line.no + openTag.slice(0, a.index).split('\n').length - 1;
511
+ push(out, 'attribute', value, start, start + value.length, lineNo, a[2][0]);
512
+ }
513
+ if (openTag.endsWith('/>'))
514
+ return skipTo(lines, i, end);
515
+ const close = closingTag(source, name, end);
516
+ if (close === -1 || close > to)
517
+ return skipTo(lines, i, end);
518
+ const closeEnd = close + /^<\/[^>]*>/.exec(source.slice(close))[0].length;
519
+ if (!CODE_ELEMENTS.has(name)) {
520
+ const childLine = line.no + source.slice(line.start, end).split('\n').length - 1;
521
+ blocks(source, end, close, childLine, out);
522
+ }
523
+ return skipTo(lines, i, closeEnd);
524
+ }
525
+ // ── Rebuild ────────────────────────────────────────────────────────────────
526
+ /** A frontmatter value / JSX attribute value, quoted the way the source quoted it. */
527
+ function quoteValue(value, segment) {
528
+ if (segment.kind === 'attribute') {
529
+ return segment.quote === "'" ? value.replace(/'/g, '&apos;') : value.replace(/"/g, '&quot;');
530
+ }
531
+ if (segment.quote === '"')
532
+ return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
533
+ if (segment.quote === "'")
534
+ return value.replace(/'/g, "''");
535
+ return value;
536
+ }
537
+ function rebuildDocument(source, segments, translations, options = {}) {
538
+ let out = source;
539
+ const order = segments.map((s, i) => ({ s, i })).sort((a, b) => b.s.start - a.s.start);
540
+ for (const { s, i } of order) {
541
+ const message = translations.get(i);
542
+ if (message === undefined)
543
+ continue;
544
+ let text = fromMessage(message, s.restore, { inTable: s.kind === 'table' });
545
+ if (s.kind === 'frontmatter' || s.kind === 'attribute') {
546
+ // Values are plain text: undo Markdown escapes of < { } added by fromMessage.
547
+ text = text.replace(/\\([<{}|])/g, '$1');
548
+ if (s.kind === 'frontmatter' && s.quote === '' && /^[\s\-?:,[\]{}#&*!|>'"%@`]|:\s|\s#/.test(text)) {
549
+ out = `${out.slice(0, s.start)}"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"${out.slice(s.end)}`;
550
+ continue;
551
+ }
552
+ text = quoteValue(text, s);
553
+ }
554
+ else {
555
+ // Collapse to one line; a translation must not start a new block.
556
+ text = text.replace(/\s*\n\s*/g, ' ');
557
+ if (s.kind === 'paragraph' && /^(#{1,6}\s|[-+*]\s|\d+[.)]\s|>|\|)/.test(text))
558
+ text = `\\${text}`;
559
+ if (s.kind === 'heading' && s.anchor && options.anchors !== false)
560
+ text = `${text} [#${s.anchor}]`;
561
+ }
562
+ out = `${out.slice(0, s.start)}${text}${out.slice(s.end)}`;
563
+ }
564
+ return out;
565
+ }
package/dist/index.d.ts CHANGED
@@ -63,6 +63,9 @@ export type { CheckProjectOptions, LocaleSetReport, ProjectLocaleCheck, ProjectL
63
63
  export { hashText, translationCacheKey, TRANSLATION_CACHE_TTL_SECONDS } from './utils/cache-keys';
64
64
  export { createScopeMatcher, mergeSourceScope, normalizeScopePatterns, readSourceScope } from './utils/source-scope';
65
65
  export { scanStrings } from './analysis/scan';
66
+ export { DOCS_LOCKFILE, readDocsConfig, readProjectDocsConfig, targetPath as docsTargetPath, translateDocs } from './docs/docs-translate';
67
+ export type { DocsConfig, DocsFailure, DocsTranslateDeps, DocsTranslateOptions, DocsTranslateReport } from './docs/docs-translate';
68
+ export { segmentDocument } from './docs/markdown-segments';
66
69
  export type { ScannedFile, ScannedString, ScanStringsOptions } from './analysis/scan';
67
70
  export { extractStringsFromFile } from './modules/extractor/extract';
68
71
  export type { SourceScope } from './utils/source-scope';
package/dist/index.js CHANGED
@@ -22,7 +22,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
22
22
  };
23
23
  Object.defineProperty(exports, "__esModule", { value: true });
24
24
  exports.CircuitBreaker = exports.validateBatchQuality = exports.validateTranslationQuality = exports.translatorLoadBalancer = exports.warmupTranslator = exports.checkTranslatorHealth = exports.callTranslator = exports.requiredPluralCategories = exports.parseIcu = exports.isIcuMessage = exports.compareIcuMessages = exports.sameProtectedSpans = exports.restoreText = exports.protectText = exports.hasNothingToTranslate = exports.checkTokens = exports.validateRawTokens = exports.sanitizeTranslation = exports.restorePlaceholders = exports.protectPlaceholders = exports.hashString = exports.hasICUSyntax = exports.extractPlaceholders = exports.parseCode = exports.I18N_LIBRARY_NAMES = exports.detectI18n = exports.SUPPORTED_SUMMARY = exports.FRAMEWORK_DISPLAY_NAMES = exports.localRepoFiles = exports.detectStack = exports.saveProjectConfig = exports.saveCachedStrings = exports.getProjectInfo = exports.getBabelizeSummary = exports.detectProjectInfo = exports.addBabelToHistory = exports.formatSyncNotificationMessage = exports.detectSyncIssues = exports.matchFromMemory = exports.setLocaleValue = exports.applyTranslationOverrides = exports.setEngineLogger = exports.runWithEngineLogger = exports.validateWorkspace = exports.scanKeyReferences = exports.RunAbortedError = exports.validateEngineConfigV2 = exports.runEngineV2 = exports.loadBabelizeConfig = exports.BabelizeEngine = void 0;
25
- exports.extractStringsFromFile = exports.scanStrings = exports.readSourceScope = exports.normalizeScopePatterns = exports.mergeSourceScope = exports.createScopeMatcher = exports.TRANSLATION_CACHE_TTL_SECONDS = exports.translationCacheKey = exports.hashText = exports.readProjectLocaleConfig = exports.localeIssueFile = exports.checkProjectLocales = exports.ReviewError = exports.reviewLocaleChanges = exports.loadLocale = exports.isLocaleCode = exports.isIgnoredLocalePath = exports.groupLocaleFiles = exports.findLocaleFileSets = exports.DEFAULT_LOCALE_IGNORE_DIRS = exports.sanitizeFormality = exports.parseFormalityList = exports.hasFormalitySplit = exports.formalityOf = exports.formalityIssues = exports.formalityInstruction = exports.formalityFor = exports.detectFormality = exports.glossaryFingerprint = exports.normalizeGlossary = exports.localeValue = exports.containsTerm = exports.canonicalizeLocaleKeys = exports.canonicalLocale = exports.tallyLocaleIssues = exports.flattenLocaleMessages = exports.checkLocalePair = exports.frameworkSupport = exports.analyzeWorkspace = exports.analyzeProject = exports.localeExtension = exports.getCircuitBreaker = exports.CircuitState = void 0;
25
+ exports.extractStringsFromFile = exports.segmentDocument = exports.translateDocs = exports.docsTargetPath = exports.readProjectDocsConfig = exports.readDocsConfig = exports.DOCS_LOCKFILE = exports.scanStrings = exports.readSourceScope = exports.normalizeScopePatterns = exports.mergeSourceScope = exports.createScopeMatcher = exports.TRANSLATION_CACHE_TTL_SECONDS = exports.translationCacheKey = exports.hashText = exports.readProjectLocaleConfig = exports.localeIssueFile = exports.checkProjectLocales = exports.ReviewError = exports.reviewLocaleChanges = exports.loadLocale = exports.isLocaleCode = exports.isIgnoredLocalePath = exports.groupLocaleFiles = exports.findLocaleFileSets = exports.DEFAULT_LOCALE_IGNORE_DIRS = exports.sanitizeFormality = exports.parseFormalityList = exports.hasFormalitySplit = exports.formalityOf = exports.formalityIssues = exports.formalityInstruction = exports.formalityFor = exports.detectFormality = exports.glossaryFingerprint = exports.normalizeGlossary = exports.localeValue = exports.containsTerm = exports.canonicalizeLocaleKeys = exports.canonicalLocale = exports.tallyLocaleIssues = exports.flattenLocaleMessages = exports.checkLocalePair = exports.frameworkSupport = exports.analyzeWorkspace = exports.analyzeProject = exports.localeExtension = exports.getCircuitBreaker = exports.CircuitState = void 0;
26
26
  var BabelizeEngine_1 = require("./BabelizeEngine");
27
27
  Object.defineProperty(exports, "BabelizeEngine", { enumerable: true, get: function () { return BabelizeEngine_1.BabelizeEngine; } });
28
28
  var config_1 = require("./config");
@@ -160,6 +160,14 @@ Object.defineProperty(exports, "normalizeScopePatterns", { enumerable: true, get
160
160
  Object.defineProperty(exports, "readSourceScope", { enumerable: true, get: function () { return source_scope_1.readSourceScope; } });
161
161
  var scan_1 = require("./analysis/scan");
162
162
  Object.defineProperty(exports, "scanStrings", { enumerable: true, get: function () { return scan_1.scanStrings; } });
163
+ var docs_translate_1 = require("./docs/docs-translate");
164
+ Object.defineProperty(exports, "DOCS_LOCKFILE", { enumerable: true, get: function () { return docs_translate_1.DOCS_LOCKFILE; } });
165
+ Object.defineProperty(exports, "readDocsConfig", { enumerable: true, get: function () { return docs_translate_1.readDocsConfig; } });
166
+ Object.defineProperty(exports, "readProjectDocsConfig", { enumerable: true, get: function () { return docs_translate_1.readProjectDocsConfig; } });
167
+ Object.defineProperty(exports, "docsTargetPath", { enumerable: true, get: function () { return docs_translate_1.targetPath; } });
168
+ Object.defineProperty(exports, "translateDocs", { enumerable: true, get: function () { return docs_translate_1.translateDocs; } });
169
+ var markdown_segments_1 = require("./docs/markdown-segments");
170
+ Object.defineProperty(exports, "segmentDocument", { enumerable: true, get: function () { return markdown_segments_1.segmentDocument; } });
163
171
  var extract_1 = require("./modules/extractor/extract");
164
172
  Object.defineProperty(exports, "extractStringsFromFile", { enumerable: true, get: function () { return extract_1.extractStringsFromFile; } });
165
173
  // ── Local translation runner (CLI `babelize translate`, MCP `babelize_translate`) ──
@@ -356,6 +356,13 @@ async function extractStringsFromFile(content, filePath, detectFormats, options)
356
356
  };
357
357
  (0, ast_helpers_1.traverse)(ast, {
358
358
  'JSXElement|JSXFragment'(path) {
359
+ // Code shown on the page (<pre>, <code>) is never copy: `import`,
360
+ // `return` and prop names translated into Japanese break the sample (#399).
361
+ if (path.isJSXElement() && ast_helpers_1.t.isJSXIdentifier(path.node.openingElement.name) && CODE_ELEMENTS.has(path.node.openingElement.name.name)) {
362
+ consumed.add(path.node);
363
+ path.traverse({ enter(inner) { consumed.add(inner.node); } });
364
+ return;
365
+ }
359
366
  if (!groupSentences || consumed.has(path.node))
360
367
  return;
361
368
  if ((0, ast_helpers_1.isAlreadyTranslated)(path.node, path))
@@ -470,6 +477,8 @@ async function extractStringsFromFile(content, filePath, detectFormats, options)
470
477
  }
471
478
  },
472
479
  JSXAttribute(path) {
480
+ if (consumed.has(path.node))
481
+ return;
473
482
  const name = path.node.name;
474
483
  if (!ast_helpers_1.t.isJSXIdentifier(name))
475
484
  return;
@@ -617,6 +626,8 @@ async function extractStringsFromFile(content, filePath, detectFormats, options)
617
626
  return { strings, warnings, notInjected: unwired };
618
627
  }
619
628
  /** A string that names something rather than being shown: a property key, or part of a TypeScript type. */
629
+ /** Elements whose content is code, not copy. */
630
+ const CODE_ELEMENTS = new Set(['pre', 'code', 'kbd', 'samp']);
620
631
  /** SVG attributes whose value is geometry (`d`, `viewBox`, `points`, …). */
621
632
  const SVG_GEOMETRY_ATTRS = new Set(['d', 'viewBox', 'points', 'transform', 'gradientTransform', 'patternTransform', 'strokeDasharray', 'stroke-dasharray', 'pathLength']);
622
633
  function isSvgGeometry(path) {
@@ -58,6 +58,7 @@ export declare function buildRequestConfig(opts: {
58
58
  export declare function buildProxy(opts: {
59
59
  kind: 'proxy' | 'middleware';
60
60
  typescript: boolean;
61
+ sourceOnly?: string[];
61
62
  }): string;
62
63
  /**
63
64
  * Give the root layout's <html> the active locale's `lang` and `dir`
@@ -68,6 +69,15 @@ export declare function buildProxy(opts: {
68
69
  export declare function setHtmlLocale(content: string, typescript: boolean, localesImport: string): string | null;
69
70
  /** Next.js major version from package.json (`^16.1.0` → 16); null when unknown. */
70
71
  export declare function nextMajor(packageJson: Record<string, any> | undefined): number | null;
72
+ /**
73
+ * `routing` from .babelize/config.json: `"cookie"` keeps one URL for every
74
+ * language; `"prefix"` (default) or `{ "sourceOnly": ["/docs"] }` gives each
75
+ * language its own URL, except the listed sections.
76
+ */
77
+ export declare function readRouting(workspacePath: string): Promise<{
78
+ mode: NextRouting;
79
+ sourceOnly: string[];
80
+ }>;
71
81
  /** Wrap the next.config default export / module.exports with next-intl's plugin. */
72
82
  export declare function wrapNextConfig(content: string, requestConfigPath: string, typescript: boolean): string | null;
73
83
  /**
@@ -39,6 +39,7 @@ exports.buildRequestConfig = buildRequestConfig;
39
39
  exports.buildProxy = buildProxy;
40
40
  exports.setHtmlLocale = setHtmlLocale;
41
41
  exports.nextMajor = nextMajor;
42
+ exports.readRouting = readRouting;
42
43
  exports.wrapNextConfig = wrapNextConfig;
43
44
  exports.usesCacheComponents = usesCacheComponents;
44
45
  exports.wrapRootLayout = wrapRootLayout;
@@ -159,10 +160,25 @@ import { locales, sourceLocale } from './locales';
159
160
 
160
161
  export { locales, sourceLocale };
161
162
 
162
- async function messagesFor(locale${ts ? ': string' : ''}) {
163
+ ${ts ? 'type Messages = { [key: string]: string | Messages };\n\n' : ''}async function load(locale${ts ? ': string' : ''})${ts ? ': Promise<Messages>' : ''} {
163
164
  return (await import(\`${importPath}\`)).default;
164
165
  }
165
166
 
167
+ /** \`base\` with \`over\` on top, key by key: a string a locale doesn't have yet shows the source text. */
168
+ function withFallback(base${ts ? ': Messages' : ''}, over${ts ? ': Messages' : ''})${ts ? ': Messages' : ''} {
169
+ const merged${ts ? ': Messages' : ''} = { ...base };
170
+ for (const [key, value] of Object.entries(over)) {
171
+ const fallback = base[key];
172
+ merged[key] = typeof value === 'object' && typeof fallback === 'object' ? withFallback(fallback, value) : value;
173
+ }
174
+ return merged;
175
+ }
176
+
177
+ async function messagesFor(locale${ts ? ': string' : ''}) {
178
+ const source = await load(sourceLocale);
179
+ return locale === sourceLocale ? source : withFallback(source, await load(locale));
180
+ }
181
+
166
182
  function pickLocale(candidates${ts ? ': Array<string | undefined>' : ''})${ts ? ': string' : ''} {
167
183
  for (const candidate of candidates) {
168
184
  if (!candidate) continue;
@@ -196,6 +212,33 @@ ${routed} // Otherwise the NEXT_LOCALE cookie, then the browser's Accept-Langua
196
212
  function buildProxy(opts) {
197
213
  const ts = opts.typescript;
198
214
  const req = ts ? 'request: NextRequest' : 'request';
215
+ const sourceOnly = opts.sourceOnly ?? [];
216
+ // Sections that exist in the source language only (routing.sourceOnly): no
217
+ // /<locale>/ version, no redirect to one, no hreflang alternates (#399).
218
+ const sourceOnlyDecl = sourceOnly.length
219
+ ? `
220
+ /** Served in the source language only (routing.sourceOnly in .babelize/config.json). */
221
+ const SOURCE_ONLY = ${JSON.stringify(sourceOnly)};
222
+
223
+ function isSourceOnly(pathname${ts ? ': string' : ''}) {
224
+ return SOURCE_ONLY.some((p) => pathname === p || pathname.startsWith(\`\${p}/\`));
225
+ }
226
+ `
227
+ : '';
228
+ const prefixedSourceOnly = sourceOnly.length
229
+ ? ` // No translated version of this section: serve the source language.
230
+ if (isSourceOnly(url.pathname)) return NextResponse.redirect(url);
231
+ `
232
+ : '';
233
+ const unprefixedSourceOnly = sourceOnly.length
234
+ ? ` if (isSourceOnly(pathname)) {
235
+ const headers = new Headers(request.headers);
236
+ headers.set('${exports.LOCALE_HEADER}', sourceLocale);
237
+ return NextResponse.next({ request: { headers } });
238
+ }
239
+
240
+ `
241
+ : '';
199
242
  return `// ${PROXY_MARKER}
200
243
  // Babelize regenerates this file while the line above is present. Remove that
201
244
  // line to take it over (keep the ${exports.LOCALE_HEADER} header and the matcher).
@@ -203,7 +246,7 @@ import { NextResponse${ts ? ', type NextRequest' : ''} } from 'next/server';
203
246
  import { locales, sourceLocale } from './i18n/locales';
204
247
 
205
248
  const ONE_YEAR = 60 * 60 * 24 * 365;
206
-
249
+ ${sourceOnlyDecl}
207
250
  function localized(pathname${ts ? ': string' : ''}, locale${ts ? ': string' : ''}) {
208
251
  if (locale === sourceLocale) return pathname;
209
252
  return pathname === '/' ? \`/\${locale}\` : \`/\${locale}\${pathname}\`;
@@ -226,7 +269,7 @@ export ${opts.kind === 'proxy' ? 'function proxy' : 'function middleware'}(${req
226
269
  // /ja/docs is app/docs, in Japanese.
227
270
  const url = request.nextUrl.clone();
228
271
  url.pathname = \`/\${rest.join('/')}\`;
229
- const headers = new Headers(request.headers);
272
+ ${prefixedSourceOnly} const headers = new Headers(request.headers);
230
273
  headers.set('${exports.LOCALE_HEADER}', prefixed);
231
274
  const response = NextResponse.rewrite(url, { request: { headers } });
232
275
  response.cookies.set('NEXT_LOCALE', prefixed, { path: '/', maxAge: ONE_YEAR, sameSite: 'lax' });
@@ -234,7 +277,7 @@ export ${opts.kind === 'proxy' ? 'function proxy' : 'function middleware'}(${req
234
277
  return response;
235
278
  }
236
279
 
237
- // An unprefixed URL is the source language, unless the visitor chose another.
280
+ ${unprefixedSourceOnly} // An unprefixed URL is the source language, unless the visitor chose another.
238
281
  const chosen = request.cookies.get('NEXT_LOCALE')?.value;
239
282
  if (chosen && chosen !== sourceLocale && locales.includes(chosen)) {
240
283
  const url = request.nextUrl.clone();
@@ -345,15 +388,29 @@ function nextMajor(packageJson) {
345
388
  const m = typeof range === 'string' ? /(\d+)/.exec(range) : null;
346
389
  return m ? Number(m[1]) : null;
347
390
  }
348
- /** `routing` from .babelize/config.json: `cookie` opts out of locale URLs. */
391
+ /**
392
+ * `routing` from .babelize/config.json: `"cookie"` keeps one URL for every
393
+ * language; `"prefix"` (default) or `{ "sourceOnly": ["/docs"] }` gives each
394
+ * language its own URL, except the listed sections.
395
+ */
349
396
  async function readRouting(workspacePath) {
397
+ let raw;
350
398
  try {
351
- const raw = JSON.parse(await fs.promises.readFile(path.join(workspacePath, '.babelize', 'config.json'), 'utf8'));
352
- return raw?.routing === 'cookie' ? 'cookie' : 'prefix';
399
+ raw = JSON.parse(await fs.promises.readFile(path.join(workspacePath, '.babelize', 'config.json'), 'utf8'))?.routing;
353
400
  }
354
401
  catch {
355
- return 'prefix';
402
+ raw = undefined;
356
403
  }
404
+ if (raw === 'cookie')
405
+ return { mode: 'cookie', sourceOnly: [] };
406
+ const list = raw && typeof raw === 'object' && Array.isArray(raw.sourceOnly)
407
+ ? raw.sourceOnly
408
+ : [];
409
+ const sourceOnly = list
410
+ .filter((p) => typeof p === 'string' && p.trim().length > 0)
411
+ .map((p) => `/${p.trim().replace(/^\/+|\/+$/g, '')}`)
412
+ .filter((p) => p !== '/');
413
+ return { mode: 'prefix', sourceOnly: [...new Set(sourceOnly)] };
357
414
  }
358
415
  /** Wrap the next.config default export / module.exports with next-intl's plugin. */
359
416
  function wrapNextConfig(content, requestConfigPath, typescript) {
@@ -515,7 +572,7 @@ writer = new writes_1.FinalizationWriter(workspace.path, dryRun)) {
515
572
  // the content's syntax always matches its extension and next.config points
516
573
  // at a file that exists.
517
574
  const requestDir = path.join(path.dirname(appDir), 'i18n');
518
- const routing = await readRouting(workspace.path);
575
+ const { mode: routing, sourceOnly } = await readRouting(workspace.path);
519
576
  const locales = await availableLocales(workspace, options);
520
577
  const sourceLocale = options.sourceLocale ?? 'en';
521
578
  // 0. i18n/locales — the locale list the request config, proxy and layout share.
@@ -591,7 +648,7 @@ writer = new writes_1.FinalizationWriter(workspace.path, dryRun)) {
591
648
  const proxyFile = existingProxy
592
649
  ?? path.join(proxyDir, `${(nextMajor(workspace.packageJson) ?? 16) >= 16 ? 'proxy' : 'middleware'}.${typescript ? 'ts' : 'js'}`);
593
650
  const kind = path.basename(proxyFile).startsWith('proxy') ? 'proxy' : 'middleware';
594
- const content = buildProxy({ kind, typescript: /\.ts$/.test(proxyFile) });
651
+ const content = buildProxy({ kind, typescript: /\.ts$/.test(proxyFile), sourceOnly });
595
652
  if (content !== proxyContent) {
596
653
  await writer.write(proxyFile, content);
597
654
  configFileCreated = true;
@@ -35,6 +35,8 @@ exports.FALLBACK_QA_WARNING = 'translated with the backup translator; will be re
35
35
  /** Keys re-sent after failing validation go in small batches with per-key notes. */
36
36
  const REPAIR_BATCH_SIZE = 5;
37
37
  const TRANSLATE_CONCURRENCY = 3; // Max concurrent locales/batches
38
+ /** Fragments of placeholder tokens ([#VAR_0#], the translator's {#0}) left in a translation. */
39
+ const PLACEHOLDER_DEBRIS = /\[#|#\]|\[\{#|\{#\d+\}|#VAR_\d+/;
38
40
  /**
39
41
  * ICU branches sent to a plain-text translator go in requests of up to this
40
42
  * many sentences (the translator service's batch limit).
@@ -748,6 +750,12 @@ configuredFormality) {
748
750
  // ("eng_Latn"), which the sanitizer strips to nothing: no translation.
749
751
  if (!value.trim())
750
752
  return fail('empty_value', true, 'The translator returned no usable text');
753
+ // A token mangled on the way back ("[{#0} ダーク") survives restoring:
754
+ // never write placeholder debris the source doesn't have.
755
+ const debris = PLACEHOLDER_DEBRIS.exec(value)?.[0];
756
+ if (debris && !entry.value.includes(debris)) {
757
+ return fail('placeholder_lost', true, `Placeholder problem: leftover token fragment "${debris}"`);
758
+ }
751
759
  const warnings = [];
752
760
  // A plural added for a count placeholder is validated as ICU too.
753
761
  if (entry.icu || (0, icu_message_1.isIcuMessage)(value)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@babelize/engine",
3
- "version": "0.3.11",
3
+ "version": "0.3.13",
4
4
  "description": "Babelize translation pipeline (extract, keygen, translate, inject). Infrastructure is injected through provider/store interfaces.",
5
5
  "keywords": [
6
6
  "babelize",
@@ -48,6 +48,7 @@
48
48
  "devDependencies": {
49
49
  "@eslint/js": "^9.39.2",
50
50
  "@jest/globals": "^30.3.0",
51
+ "@mdx-js/mdx": "^3.1.1",
51
52
  "@types/babel__generator": "^7.27.0",
52
53
  "@types/babel__traverse": "^7.28.0",
53
54
  "@types/fs-extra": "^11.0.4",