@babelize/engine 0.3.7 → 0.3.9

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.
Files changed (50) hide show
  1. package/dist/analysis/analyze.d.ts +3 -0
  2. package/dist/analysis/analyze.js +1 -0
  3. package/dist/index.d.ts +4 -0
  4. package/dist/index.js +16 -1
  5. package/dist/local/hosted-provider.js +1 -0
  6. package/dist/local/translate-core.d.ts +19 -2
  7. package/dist/local/translate-core.js +28 -9
  8. package/dist/local/translate-messages.d.ts +5 -0
  9. package/dist/local/translate-messages.js +1 -1
  10. package/dist/modules/extractor/extract.js +22 -5
  11. package/dist/modules/finalization/finalize.d.ts +6 -0
  12. package/dist/modules/finalization/finalize.js +25 -5
  13. package/dist/modules/finalization/nextjs-finalize.d.ts +63 -6
  14. package/dist/modules/finalization/nextjs-finalize.js +339 -26
  15. package/dist/modules/format-injection/index.js +3 -2
  16. package/dist/modules/injection/inject.js +2 -1
  17. package/dist/modules/locale-builder/adopted.d.ts +29 -2
  18. package/dist/modules/locale-builder/adopted.js +185 -16
  19. package/dist/modules/locale-builder/locales.js +11 -2
  20. package/dist/modules/locale-builder/message-modules.d.ts +40 -0
  21. package/dist/modules/locale-builder/message-modules.js +263 -0
  22. package/dist/modules/sync-detector/sync-detector.js +4 -1
  23. package/dist/modules/translator/client/byok.provider.js +8 -2
  24. package/dist/modules/translator/formality.d.ts +40 -0
  25. package/dist/modules/translator/formality.js +313 -0
  26. package/dist/modules/translator/translate.d.ts +18 -0
  27. package/dist/modules/translator/translate.js +78 -11
  28. package/dist/modules/workspace/existing-setup.d.ts +3 -1
  29. package/dist/modules/workspace/existing-setup.js +32 -15
  30. package/dist/modules/workspace/validate.js +7 -0
  31. package/dist/orchestrator.js +51 -7
  32. package/dist/providers/default-translation-provider.js +2 -2
  33. package/dist/providers/types.d.ts +5 -0
  34. package/dist/qa/check-project.d.ts +7 -0
  35. package/dist/qa/check-project.js +12 -2
  36. package/dist/qa/locale-files.d.ts +8 -5
  37. package/dist/qa/locale-files.js +37 -9
  38. package/dist/qa/locale-qa.d.ts +10 -1
  39. package/dist/qa/locale-qa.js +9 -0
  40. package/dist/qa/review.js +1 -1
  41. package/dist/runtime/types.d.ts +29 -1
  42. package/dist/types.d.ts +2 -0
  43. package/dist/utils/ast-helpers.js +35 -4
  44. package/dist/utils/source-scope.d.ts +30 -0
  45. package/dist/utils/source-scope.js +112 -0
  46. package/dist/utils/translator-caller.d.ts +19 -0
  47. package/dist/utils/translator-caller.js +55 -21
  48. package/dist/utils/ui-copy.d.ts +14 -0
  49. package/dist/utils/ui-copy.js +51 -0
  50. package/package.json +4 -2
@@ -1,6 +1,40 @@
1
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
+ })();
2
35
  Object.defineProperty(exports, "__esModule", { value: true });
3
36
  exports.readAdoptedLocales = readAdoptedLocales;
37
+ exports.readAdoptedLocale = readAdoptedLocale;
4
38
  exports.seedLockfileFromLocaleFiles = seedLockfileFromLocaleFiles;
5
39
  exports.missingKeysByLocale = missingKeysByLocale;
6
40
  exports.adoptedLocaleFile = adoptedLocaleFile;
@@ -8,36 +42,94 @@ exports.adoptedSetupNotes = adoptedSetupNotes;
8
42
  exports.hardcodedStrings = hardcodedStrings;
9
43
  /**
10
44
  * Locale files of an adopted i18n setup (#367): the app's own `<locale>.json`
11
- * files in its own locale directory. Their translations are the project's —
45
+ * files in its own locale directory, or a folder per locale of namespace
46
+ * files — JSON, or TypeScript/JS message modules (#370). Their translations are the project's —
12
47
  * kept, never re-translated while their source text is unchanged — and a run
13
48
  * writes them back in the file's own key order and indentation, with nothing
14
49
  * Babelize-specific (`_meta`) added.
15
50
  */
16
51
  const fs_1 = require("fs");
52
+ const path = __importStar(require("path"));
17
53
  const i18n_1 = require("../../detection/i18n");
18
54
  const file_utils_1 = require("../../utils/file-utils");
19
55
  const keygen_1 = require("../keygen");
20
56
  const hasher_1 = require("../lockfile/hasher");
21
57
  const language_codes_1 = require("../translator/language-codes");
58
+ const message_modules_1 = require("./message-modules");
22
59
  /** The locale files as they are before the run (the translator writes to the same paths). */
23
60
  async function readAdoptedLocales(workspace, locales) {
24
61
  const out = {};
25
- for (const locale of locales) {
26
- const raw = await fs_1.promises.readFile((0, file_utils_1.workspaceLocaleFile)(workspace, locale).file, 'utf8').catch(() => null);
27
- let data = null;
28
- if (raw !== null) {
62
+ for (const locale of locales)
63
+ out[locale] = await readAdoptedLocale(workspace, locale);
64
+ return out;
65
+ }
66
+ async function readAdoptedLocale(workspace, locale) {
67
+ const setup = workspace.existingSetup;
68
+ if (setup?.layout && setup.layout !== 'flat')
69
+ return readLocaleFolder(workspace, locale);
70
+ const raw = await fs_1.promises.readFile((0, file_utils_1.workspaceLocaleFile)(workspace, locale).file, 'utf8').catch(() => null);
71
+ if (raw === null)
72
+ return null;
73
+ const data = parseJsonObject(raw, (0, file_utils_1.workspaceLocaleFile)(workspace, locale).relativeFile);
74
+ return data ? { data, raw } : null;
75
+ }
76
+ /** A locale's folder of namespace files: those the source language has. */
77
+ async function readLocaleFolder(workspace, locale) {
78
+ const setup = workspace.existingSetup;
79
+ const parts = {};
80
+ const data = {};
81
+ for (const file of setup.namespaces ?? []) {
82
+ const rel = adoptedFilePath(setup.localeDir, locale, file);
83
+ const raw = await fs_1.promises.readFile(path.join(workspace.path, rel), 'utf8').catch(() => null);
84
+ if (raw === null)
85
+ continue;
86
+ const ns = namespaceOf(file);
87
+ if (setup.layout === 'modules') {
88
+ let module;
29
89
  try {
30
- const parsed = JSON.parse(raw);
31
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))
32
- data = parsed;
90
+ module = (0, message_modules_1.parseMessageModule)(raw, rel);
33
91
  }
34
- catch {
35
- throw new Error(`${(0, file_utils_1.workspaceLocaleFile)(workspace, locale).relativeFile} is not valid JSON. Fix it and run again. Nothing was changed.`);
92
+ catch (err) {
93
+ if (!(err instanceof message_modules_1.MessageModuleError))
94
+ throw err;
95
+ throw new Error(`Babelize can't read the ${i18n_1.I18N_LIBRARY_NAMES[setup.library]} messages in ${setup.localeDir}/<locale>/*${path.extname(file)}: ${err.message} ` +
96
+ `Messages must be an exported object of plain text values. Nothing was changed.`);
36
97
  }
98
+ // Not a catalog (types, helpers): left alone.
99
+ if (!module)
100
+ continue;
101
+ parts[ns] = { file, raw, data: module.data, module };
37
102
  }
38
- out[locale] = data && raw !== null ? { data, raw } : null;
103
+ else {
104
+ const parsed = parseJsonObject(raw, rel);
105
+ if (!parsed)
106
+ continue;
107
+ parts[ns] = { file, raw, data: parsed };
108
+ }
109
+ data[ns] = parts[ns].data;
110
+ }
111
+ if (Object.keys(parts).length === 0)
112
+ return null;
113
+ const indexRaw = setup.indexFile
114
+ ? await fs_1.promises.readFile(path.join(workspace.path, adoptedFilePath(setup.localeDir, locale, setup.indexFile)), 'utf8').catch(() => undefined)
115
+ : undefined;
116
+ return { data, raw: '', parts, ...(indexRaw !== undefined ? { indexRaw } : {}) };
117
+ }
118
+ function parseJsonObject(raw, rel) {
119
+ try {
120
+ const parsed = JSON.parse(raw);
121
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
122
+ }
123
+ catch {
124
+ throw new Error(`${rel} is not valid JSON. Fix it and run again. Nothing was changed.`);
39
125
  }
40
- return out;
126
+ }
127
+ /** `messages/fr/auth.ts`, relative to the workspace (posix). */
128
+ function adoptedFilePath(localeDir, locale, file) {
129
+ return path.posix.join(localeDir, locale, file);
130
+ }
131
+ function namespaceOf(file) {
132
+ return file.slice(0, file.length - path.extname(file).length);
41
133
  }
42
134
  /**
43
135
  * Record the translations already in the project's locale files in the
@@ -45,7 +137,7 @@ async function readAdoptedLocales(workspace, locales) {
45
137
  * over the lockfile's (someone edited the file); a key whose source text
46
138
  * changed since the lockfile recorded it is left for re-translation.
47
139
  */
48
- function seedLockfileFromLocaleFiles(lockfile, flatKeys, targets) {
140
+ function seedLockfileFromLocaleFiles(lockfile, flatKeys, targets, options = {}) {
49
141
  const next = JSON.parse(JSON.stringify(lockfile));
50
142
  const now = new Date().toISOString();
51
143
  for (const [locale, file] of Object.entries(targets)) {
@@ -59,6 +151,11 @@ function seedLockfileFromLocaleFiles(lockfile, flatKeys, targets) {
59
151
  const entry = next.keys[key] ?? { sourceHash: hash, translatedAt: now, languages: {}, metadata: {} };
60
152
  if (entry.sourceHash !== hash)
61
153
  continue;
154
+ if (options.onlyOverRecorded) {
155
+ const recorded = entry.languages[locale];
156
+ if (!recorded || recorded === source)
157
+ continue;
158
+ }
62
159
  if (entry.languages[locale] !== value) {
63
160
  // Not what Babelize wrote: the project's own, kept through glossary edits too.
64
161
  entry.metadata = { ...(entry.metadata ?? {}), [locale]: { external: true } };
@@ -83,8 +180,13 @@ function missingKeysByLocale(flatKeys, targets) {
83
180
  * extra keys, non-string values) with `values` filled in, or — for a new
84
181
  * file — the source file's structure and order. Serialized like the source
85
182
  * file (indentation, trailing newline) and handed to hosts as exact content.
183
+ * `others` are the setup's other locales, whose modules can serve as the
184
+ * template for a new language's (they already import the source and say
185
+ * `satisfies`).
86
186
  */
87
- function adoptedLocaleFile(workspace, locale, source, values, existing) {
187
+ function adoptedLocaleFile(workspace, locale, source, values, existing, others = {}) {
188
+ if (source.parts)
189
+ return adoptedLocaleFolder(workspace, locale, source, values, existing, others);
88
190
  const data = (fill(existing ? clone(existing.data) : {}, source.data, values, '', !existing) ?? {});
89
191
  const style = existing ?? source;
90
192
  const { relativeFile } = (0, file_utils_1.workspaceLocaleFile)(workspace, locale);
@@ -96,9 +198,67 @@ function adoptedLocaleFile(workspace, locale, source, values, existing) {
96
198
  data,
97
199
  isNew: !existing,
98
200
  isRTL: (0, language_codes_1.isRTL)(locale),
99
- content: unchanged ? existing.raw : `${JSON.stringify(data, null, indentOf(style.raw))}${style.raw.endsWith('\n') ? '\n' : ''}`,
201
+ content: unchanged ? existing.raw : serializeJson(data, style.raw),
100
202
  };
101
203
  }
204
+ /** A folder-per-locale target: one file per source namespace (plus the index module for a new language). */
205
+ function adoptedLocaleFolder(workspace, locale, source, values, existing, others) {
206
+ const setup = workspace.existingSetup;
207
+ const files = [];
208
+ const data = {};
209
+ for (const [ns, sourcePart] of Object.entries(source.parts)) {
210
+ const before = existing?.parts?.[ns];
211
+ // Each file on its own: a namespace file new to this language gets the source's non-text values.
212
+ const partData = fill(before ? clone(before.data) : {}, sourcePart.data, values, ns, !before);
213
+ if (!partData || typeof partData !== 'object' || Array.isArray(partData))
214
+ continue;
215
+ // No translation for a file this language doesn't have: not created.
216
+ if (!before && Object.keys((0, keygen_1.flattenLocaleData)(partData)).length === 0)
217
+ continue;
218
+ data[ns] = partData;
219
+ const rel = adoptedFilePath(setup.localeDir, locale, sourcePart.file);
220
+ if (before && JSON.stringify(partData) === JSON.stringify(before.data)) {
221
+ files.push({ path: rel, content: before.raw });
222
+ continue;
223
+ }
224
+ if (!sourcePart.module) {
225
+ files.push({ path: rel, content: serializeJson(partData, (before ?? sourcePart).raw) });
226
+ continue;
227
+ }
228
+ const flat = (0, keygen_1.flattenLocaleData)(partData);
229
+ const template = moduleTemplate(ns, Object.keys(flat), before, others, sourcePart);
230
+ files.push({ path: rel, content: (0, message_modules_1.writeMessageModule)(template.raw, template.module, flat) });
231
+ }
232
+ // A new language's folder gets the combining module too, copied from a sibling.
233
+ if (setup.indexFile && !existing) {
234
+ const from = Object.entries(others).find(([, o]) => o?.indexRaw !== undefined)?.[1]?.indexRaw ?? source.indexRaw;
235
+ if (from !== undefined)
236
+ files.push({ path: adoptedFilePath(setup.localeDir, locale, setup.indexFile), content: from });
237
+ }
238
+ return {
239
+ locale,
240
+ path: path.posix.join(setup.localeDir, locale),
241
+ data,
242
+ isNew: !existing,
243
+ isRTL: (0, language_codes_1.isRTL)(locale),
244
+ files,
245
+ };
246
+ }
247
+ /**
248
+ * The module to write a target's from: the target's own (new keys are added
249
+ * to it), else another language's that has every key (written as a
250
+ * translation of the source, e.g. `satisfies MessageShape<typeof english>`),
251
+ * else any other language's, else the source's.
252
+ */
253
+ function moduleTemplate(ns, keys, own, others, sourcePart) {
254
+ if (own?.module)
255
+ return own;
256
+ const siblings = Object.keys(others).sort().map((l) => others[l]?.parts?.[ns]).filter((p) => p?.module);
257
+ return siblings.find((p) => keys.every((k) => p.module.leaves[k])) ?? siblings[0] ?? sourcePart;
258
+ }
259
+ function serializeJson(data, styleRaw) {
260
+ return `${JSON.stringify(data, null, indentOf(styleRaw))}${styleRaw.endsWith('\n') ? '\n' : ''}`;
261
+ }
102
262
  /**
103
263
  * Walk the source structure, writing translated leaves into `target` (new
104
264
  * keys land in source order). Undefined: nothing to write at this path.
@@ -153,15 +313,24 @@ function adoptedSetupNotes(workspace, sourceLocale, targetLocales, hardcoded) {
153
313
  const notes = [`Used the project's existing ${library} setup: translations are in ${setup.localeDir}/. No code or i18n config was changed.`];
154
314
  if (hardcoded.length > 0) {
155
315
  const files = new Set(hardcoded.map((h) => h.file)).size;
156
- notes.push(`${hardcoded.length} hardcoded string(s) in ${files} file(s) look translatable but aren't in ${setup.localeDir}/${sourceLocale}.json. ` +
316
+ notes.push(`${hardcoded.length} hardcoded string(s) in ${files} file(s) look translatable but aren't in ${sourceFiles(setup, sourceLocale)}. ` +
157
317
  `They were left as they are: add them to your ${library} setup to translate them.`);
158
318
  }
159
319
  const added = targetLocales.filter((l) => !workspace.existingLocales.includes(l));
160
320
  if (added.length > 0 && setup.languageLists.length > 0) {
161
321
  notes.push(`New language(s) ${added.join(', ')}: add them where the app lists its languages (${setup.languageLists.join(', ')}), or the app won't offer them.`);
162
322
  }
323
+ else if (added.length > 0 && setup.layout && setup.layout !== 'flat') {
324
+ notes.push(`New language(s) ${added.join(', ')}: register them where the app loads ${setup.localeDir}/<locale>/ (its list of locales and message imports), or the app won't offer them.`);
325
+ }
163
326
  return notes;
164
327
  }
328
+ /** Where an adopted setup's source text is, for messages. */
329
+ function sourceFiles(setup, sourceLocale) {
330
+ if (!setup.layout || setup.layout === 'flat')
331
+ return `${setup.localeDir}/${sourceLocale}.json`;
332
+ return `${setup.localeDir}/${sourceLocale}/`;
333
+ }
165
334
  const COMPONENT_FILE = /\.(?:vue|jsx|tsx|html?)$/;
166
335
  /**
167
336
  * Strings found in code that an adopted setup leaves alone (reported, never
@@ -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
- const exists = await (0, file_utils_1.pathExists)(localeFilePathTarget);
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 (exists) {
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
+ }
@@ -43,6 +43,7 @@ const types_1 = require("../../runtime/types");
43
43
  const types_2 = require("@babelize/types");
44
44
  const extraction_options_1 = require("../../utils/extraction-options");
45
45
  const validate_1 = require("../workspace/validate");
46
+ const source_scope_1 = require("../../utils/source-scope");
46
47
  /**
47
48
  * Extraction options the project's engine runs use (sentence grouping, ICU
48
49
  * plurals, data-literal rules), so a sync check compares like with like and
@@ -148,9 +149,11 @@ async function detectSyncIssues(projectId, workspacePath, changedFiles, commitSh
148
149
  // 1. Filter changed files to only source files
149
150
  const extractOptions = await runExtractionOptions(workspacePath, options);
150
151
  const frameworkExcludes = types_2.FRAMEWORK_CONFIGS[extractOptions.framework]?.excludedPatterns ?? [];
152
+ // Files outside the project's include/exclude are never translated, so changing them can't drift.
153
+ const inScope = (0, source_scope_1.createScopeMatcher)(await (0, source_scope_1.readSourceScope)(workspacePath));
151
154
  const sourceFiles = [];
152
155
  for (const file of changedFiles) {
153
- if (isSourceFile(file, frameworkExcludes)) {
156
+ if (isSourceFile(file, frameworkExcludes) && inScope(file)) {
154
157
  sourceFiles.push(file);
155
158
  }
156
159
  else {