@babelize/engine 0.3.13 → 0.3.14

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.
@@ -1,6 +1,7 @@
1
1
  import type { ByokProvider } from '@babelize/types';
2
2
  import type { FormalitySetting } from '../modules/translator/formality';
3
3
  import type { TranslationProvider } from '../providers/types';
4
+ import { type ContentFormatter } from '../local/formatter';
4
5
  export interface DocsConfig {
5
6
  /** Globs of source pages, relative to the project root (`content/docs/**`). */
6
7
  include: string[];
@@ -42,6 +43,11 @@ export interface DocsTranslateDeps {
42
43
  };
43
44
  /** `detail`: a step inside the current one (a batch), not a new step. */
44
45
  onProgress?: (message: string, detail?: boolean) => void;
46
+ /**
47
+ * Formats a translated file before it's compared and written. Default: the
48
+ * project's own prettier/biome (null: leave files as rebuilt).
49
+ */
50
+ format?: ContentFormatter | null;
45
51
  }
46
52
  export interface DocsFailure {
47
53
  file: string;
@@ -58,6 +64,8 @@ export interface DocsTranslateReport {
58
64
  /** Segment translations produced this run (not reused from the lockfile). */
59
65
  translated: number;
60
66
  reused: number;
67
+ /** Lockfile entries dropped because no page has their text any more. */
68
+ pruned: number;
61
69
  failures: DocsFailure[];
62
70
  changes: {
63
71
  added: string[];
@@ -62,6 +62,7 @@ const fast_glob_1 = __importDefault(require("fast-glob"));
62
62
  const translate_1 = require("../modules/translator/translate");
63
63
  const translate_core_1 = require("../local/translate-core");
64
64
  const check_project_1 = require("../qa/check-project");
65
+ const formatter_1 = require("../local/formatter");
65
66
  const locale_files_1 = require("../qa/locale-files");
66
67
  const markdown_segments_1 = require("./markdown-segments");
67
68
  /** `docs` from .babelize/config.json; null when it isn't configured. */
@@ -205,11 +206,15 @@ async function translateDocs(opts, deps = {}) {
205
206
  pages.push(page);
206
207
  }
207
208
  const lock = await readLock(projectDir);
209
+ // Translated files as the project's formatter writes them, so CI format
210
+ // checks pass and an unchanged page isn't rewritten every run.
211
+ const format = deps.format !== undefined ? deps.format : await (0, formatter_1.createContentFormatter)(projectDir);
208
212
  const report = {
209
213
  files: pages.length,
210
214
  segments: pages.reduce((n, p) => n + p.segments.length, 0),
211
215
  translated: 0,
212
216
  reused: 0,
217
+ pruned: 0,
213
218
  failures: [],
214
219
  changes: { added: [], modified: [] },
215
220
  outputs: {},
@@ -311,6 +316,8 @@ async function translateDocs(opts, deps = {}) {
311
316
  if (translations.size === 0 && page.segments.length > 0)
312
317
  continue;
313
318
  const target = targetPath(page.rel, locale, docs);
319
+ if (format)
320
+ content = await format(target, content);
314
321
  report.outputs[target] = content;
315
322
  const existing = await fs_1.promises.readFile(path.join(projectDir, target), 'utf8').catch(() => null);
316
323
  if (existing === content)
@@ -322,6 +329,16 @@ async function translateDocs(opts, deps = {}) {
322
329
  }
323
330
  }
324
331
  }
332
+ // Translations of text no page has any more (an edited paragraph's old
333
+ // version) are dropped. Every configured page was read, so this is complete;
334
+ // locales outside this run keep their translations of current text.
335
+ const live = new Set(pages.flatMap((p) => p.segments.map((s) => hashOf(s.message))));
336
+ for (const h of Object.keys(lock.segments)) {
337
+ if (live.has(h))
338
+ continue;
339
+ delete lock.segments[h];
340
+ report.pruned++;
341
+ }
325
342
  if (!opts.dryRun) {
326
343
  await fs_1.promises.mkdir(path.dirname(path.join(projectDir, exports.DOCS_LOCKFILE)), { recursive: true });
327
344
  await fs_1.promises.writeFile(path.join(projectDir, exports.DOCS_LOCKFILE), `${JSON.stringify(lock, null, 2)}\n`);
@@ -23,4 +23,13 @@ export declare function detectFormatter(projectRoot: string): Promise<(typeof FO
23
23
  export declare function formatChangedFiles(projectDir: string, workDir: string, changedFiles: string[], opts?: {
24
24
  timeoutMs?: number;
25
25
  }): Promise<FormatResult | null>;
26
+ /** Formats one file's new content as the project's formatter would; returns it unchanged when it can't. */
27
+ export type ContentFormatter = (relPath: string, content: string) => Promise<string>;
28
+ /**
29
+ * A formatter for content written straight into the project (translated
30
+ * docs), so it can be compared with what is on disk before writing. Uses the
31
+ * project's own prettier (in process, with its config and .prettierignore) or
32
+ * biome (stdin). Null when the project has neither installed.
33
+ */
34
+ export declare function createContentFormatter(projectDir: string): Promise<ContentFormatter | null>;
26
35
  export {};
@@ -35,8 +35,10 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.detectFormatter = detectFormatter;
37
37
  exports.formatChangedFiles = formatChangedFiles;
38
+ exports.createContentFormatter = createContentFormatter;
38
39
  const node_child_process_1 = require("node:child_process");
39
40
  const promises_1 = require("node:fs/promises");
41
+ const node_module_1 = require("node:module");
40
42
  const path = __importStar(require("node:path"));
41
43
  const node_util_1 = require("node:util");
42
44
  const execFileAsync = (0, node_util_1.promisify)(node_child_process_1.execFile);
@@ -103,3 +105,43 @@ async function formatChangedFiles(projectDir, workDir, changedFiles, opts = {})
103
105
  await (0, promises_1.unlink)(link).catch(() => { });
104
106
  }
105
107
  }
108
+ /**
109
+ * A formatter for content written straight into the project (translated
110
+ * docs), so it can be compared with what is on disk before writing. Uses the
111
+ * project's own prettier (in process, with its config and .prettierignore) or
112
+ * biome (stdin). Null when the project has neither installed.
113
+ */
114
+ async function createContentFormatter(projectDir) {
115
+ const formatter = await detectFormatter(projectDir);
116
+ if (!formatter)
117
+ return null;
118
+ if (formatter.name === 'prettier') {
119
+ let prettier;
120
+ try {
121
+ prettier = (0, node_module_1.createRequire)(path.join(projectDir, 'package.json'))('prettier');
122
+ }
123
+ catch {
124
+ return null;
125
+ }
126
+ const ignorePath = path.join(projectDir, '.prettierignore');
127
+ return async (relPath, content) => {
128
+ const file = path.join(projectDir, relPath);
129
+ try {
130
+ const info = await prettier.getFileInfo(file, { ignorePath });
131
+ if (info.ignored || !info.inferredParser)
132
+ return content;
133
+ return await prettier.format(content, { ...(await prettier.resolveConfig(file)), filepath: file });
134
+ }
135
+ catch {
136
+ return content;
137
+ }
138
+ };
139
+ }
140
+ const bin = path.join(projectDir, 'node_modules', '.bin', formatter.name);
141
+ if (!(await (0, promises_1.lstat)(bin).catch(() => null)))
142
+ return null;
143
+ return (relPath, content) => new Promise((resolve) => {
144
+ const child = (0, node_child_process_1.execFile)(bin, ['format', `--stdin-file-path=${relPath}`], { cwd: projectDir, timeout: 30000, maxBuffer: 16 * 1024 * 1024, env: { ...process.env, NO_COLOR: '1' } }, (err, stdout) => resolve(err || !stdout ? content : stdout));
145
+ child.stdin?.end(content);
146
+ });
147
+ }
@@ -9,6 +9,17 @@ import type { KeyResult, TranslationBatchRequest, TranslationProvider } from '..
9
9
  */
10
10
  /** Server limit on entries per request. */
11
11
  export declare const HOSTED_MAX_BATCH: 100;
12
+ /**
13
+ * Most source characters per request. The hosted model's time grows with the
14
+ * text it gets, and the server gives a batch 90 s: a batch of long docs
15
+ * paragraphs at the entry limit never finished (#406). About 1,200 characters
16
+ * measured at 30–80 s; longer text goes out in more, parallel requests.
17
+ */
18
+ export declare const HOSTED_MAX_BATCH_CHARS = 1200;
19
+ /** Requests of at most `maxEntries` entries and `maxChars` characters (a longer entry goes alone). */
20
+ export declare function chunkEntries<T extends {
21
+ value: string;
22
+ }>(entries: T[], maxEntries: number, maxChars: number): T[][];
12
23
  /**
13
24
  * Per-attempt timeout. Longer than the server's total model budget (90 s),
14
25
  * so the server finishes — or gives up uncharged — before we retry.
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HostedTranslationProvider = exports.HOSTED_MAX_IN_FLIGHT = exports.HostedTranslationError = exports.BILLING_URL = exports.API_KEYS_URL = exports.HOSTED_CREDITS_HEADER = exports.HOSTED_MODEL_HEADER = exports.HOSTED_REQUEST_TIMEOUT_MS = exports.HOSTED_MAX_BATCH = void 0;
3
+ exports.HostedTranslationProvider = exports.HOSTED_MAX_IN_FLIGHT = exports.HostedTranslationError = exports.BILLING_URL = exports.API_KEYS_URL = exports.HOSTED_CREDITS_HEADER = exports.HOSTED_MODEL_HEADER = exports.HOSTED_REQUEST_TIMEOUT_MS = exports.HOSTED_MAX_BATCH_CHARS = exports.HOSTED_MAX_BATCH = void 0;
4
+ exports.chunkEntries = chunkEntries;
4
5
  exports.parseRetryAfterMs = parseRetryAfterMs;
5
6
  const node_crypto_1 = require("node:crypto");
6
7
  const language_codes_1 = require("../modules/translator/language-codes");
@@ -15,6 +16,31 @@ const types_1 = require("@babelize/types");
15
16
  */
16
17
  /** Server limit on entries per request. */
17
18
  exports.HOSTED_MAX_BATCH = types_1.TRANSLATE_BATCH_LIMITS.maxEntries;
19
+ /**
20
+ * Most source characters per request. The hosted model's time grows with the
21
+ * text it gets, and the server gives a batch 90 s: a batch of long docs
22
+ * paragraphs at the entry limit never finished (#406). About 1,200 characters
23
+ * measured at 30–80 s; longer text goes out in more, parallel requests.
24
+ */
25
+ exports.HOSTED_MAX_BATCH_CHARS = 1200;
26
+ /** Requests of at most `maxEntries` entries and `maxChars` characters (a longer entry goes alone). */
27
+ function chunkEntries(entries, maxEntries, maxChars) {
28
+ const chunks = [];
29
+ let current = [];
30
+ let chars = 0;
31
+ for (const e of entries) {
32
+ if (current.length > 0 && (current.length >= maxEntries || chars + e.value.length > maxChars)) {
33
+ chunks.push(current);
34
+ current = [];
35
+ chars = 0;
36
+ }
37
+ current.push(e);
38
+ chars += e.value.length;
39
+ }
40
+ if (current.length > 0)
41
+ chunks.push(current);
42
+ return chunks;
43
+ }
18
44
  /**
19
45
  * Per-attempt timeout. Longer than the server's total model budget (90 s),
20
46
  * so the server finishes — or gives up uncharged — before we retry.
@@ -119,16 +145,18 @@ class HostedTranslationProvider {
119
145
  }
120
146
  return true;
121
147
  });
148
+ // Sent side by side, as many at a time as the in-flight cap allows.
122
149
  const remote = new Map();
123
- for (let i = 0; i < sendable.length; i += exports.HOSTED_MAX_BATCH) {
124
- const entries = sendable.slice(i, i + exports.HOSTED_MAX_BATCH);
150
+ const chunks = chunkEntries(sendable, exports.HOSTED_MAX_BATCH, exports.HOSTED_MAX_BATCH_CHARS);
151
+ const results = await Promise.all(chunks.map((entries) => {
125
152
  const keys = new Set(entries.map((e) => e.key));
126
153
  const hints = request.hints
127
154
  ? Object.fromEntries(Object.entries(request.hints).filter(([k]) => keys.has(k)))
128
155
  : undefined;
129
- for (const r of await this.withSlot(() => this.post({ ...request, entries, hints })))
130
- remote.set(r.key, r);
131
- }
156
+ return this.withSlot(() => this.post({ ...request, entries, hints }));
157
+ }));
158
+ for (const r of results.flat())
159
+ remote.set(r.key, r);
132
160
  return request.entries.flatMap((e) => {
133
161
  const r = local.get(e.key) ?? remote.get(e.key);
134
162
  return r ? [r] : [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@babelize/engine",
3
- "version": "0.3.13",
3
+ "version": "0.3.14",
4
4
  "description": "Babelize translation pipeline (extract, keygen, translate, inject). Infrastructure is injected through provider/store interfaces.",
5
5
  "keywords": [
6
6
  "babelize",