@menapo/vi18n 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -0
- package/dist/{apply-Bre-lY9J.js → apply-Bg-3rB2m.js} +69 -89
- package/dist/{captured-Bj8bO6vd.js → captured-DfLk50Ji.js} +196 -217
- package/dist/{check-BIKEuu6B.js → check-CunekuYs.js} +76 -85
- package/dist/cli.js +2 -3
- package/dist/{collect-Cx4_SKOe.js → collect-CYATDjdo.js} +1 -2
- package/dist/collisions-CDSdtLQm.js +215 -0
- package/dist/{compile-Cc97JaW2.js → compile-DqkofbiO.js} +376 -331
- package/dist/compile-hva0qjhZ.js +240 -0
- package/dist/concurrency-BCY_4zcr.js +1 -0
- package/dist/concurrency-Dy2ny50V.js +107 -0
- package/dist/config.d.ts +1 -5
- package/dist/config.js +4 -5
- package/dist/{types-D3QGM8XO.js → diagnostics-LgIWyeSp.js} +28 -27
- package/dist/{dir-zw6bGMKQ.js → dir-TGLYuOZb.js} +34 -37
- package/dist/{duplicates-yuRljQ6h.js → duplicates-8cudcHNj.js} +10 -27
- package/dist/engine-ecRD8-IE.js +556 -0
- package/dist/engine.d.ts +1 -5
- package/dist/engine.js +297 -168
- package/dist/exchange-DjwlrTQ9.js +41 -0
- package/dist/{exclude-Du-Zd_qI.js → exclude-BFETmvde.js} +2 -3
- package/dist/{export-C9Sy6UWv.js → export-D2tsqWIr.js} +17 -38
- package/dist/{extract-C3S8btx0.js → extract-BxYchVmY.js} +114 -82
- package/dist/{formats-9unqj_fZ.js → formats-BaryZ2N7.js} +352 -276
- package/dist/fs-ezCMZeDV.js +52 -0
- package/dist/i18next-COO6o0tX.js +1907 -0
- package/dist/i18next-Dr7DCQlQ.js +1 -0
- package/dist/{import-nANvQutw.js → import-vSC29Cn4.js} +81 -75
- package/dist/index.d.ts +1 -13
- package/dist/index.js +14 -16
- package/dist/{init-C2ScuW6a.js → init-Cc7A-8VX.js} +466 -501
- package/dist/{library-D5CWvTQs.js → library-tp_xqzSY.js} +975 -451
- package/dist/lingui-BnnlqGXT.js +902 -0
- package/dist/lint.d.ts +0 -4
- package/dist/lint.js +70 -82
- package/dist/{load-gW-oJt1Q.js → load-BSIeGJ5v.js} +275 -148
- package/dist/{load-CQRz4PpM.js → load-SSrAeJVB.js} +1214 -1116
- package/dist/{locales-DX4MOBFE.js → locales-D0U-yVRm.js} +271 -237
- package/dist/{lsp-RMMMc88P.js → lsp-DvC11pBZ.js} +4 -5
- package/dist/{match-BGr8EXB3.js → match-BLDcj610.js} +11 -4
- package/dist/{mcp-CHVwBoRP.js → mcp-D2zzOTBy.js} +4 -5
- package/dist/{merge-driver-BTX87aVm.js → merge-driver-BLI8OtAc.js} +138 -122
- package/dist/migrate-1r43OBfe.js +1 -0
- package/dist/migrate-ChDGhlC-.js +2169 -0
- package/dist/{openai-CTaMDcl-.js → openai-CLn4puY8.js} +128 -87
- package/dist/{output-DWE3SIUA.js → output-D5tAt8q4.js} +15 -9
- package/dist/parse.d.ts +1 -3
- package/dist/parse.js +7 -8
- package/dist/{pipeline-C9Dbotkh.js → pipeline-BJSkkRYC.js} +387 -359
- package/dist/{pipeline-DbX6rlo5.js → pipeline-BeCc441z.js} +1 -1
- package/dist/project-B5KIO0q-.js +544 -0
- package/dist/{pseudo-DRv30iN5.js → pseudo-B2DUpoLu.js} +126 -3
- package/dist/{raw-C4Y6vyGY.js → raw-YsYZMS9n.js} +52 -29
- package/dist/react-intl-C8JehBBL.js +634 -0
- package/dist/rename-ZVGq9ZG1.js +577 -0
- package/dist/repeated-uuI1tUGg.js +85 -0
- package/dist/restore-xlBIrtRt.js +199 -0
- package/dist/rewrite-BwzXoBiA.js +415 -0
- package/dist/{rich-DCUKl5HM.js → rich-ApY1Dm4S.js} +35 -28
- package/dist/rolldown-runtime-C1I3wEg2.js +43 -0
- package/dist/{rolldown-runtime-D7D4PA-g.js → rolldown-runtime-D8jQpDG7.js} +1 -2
- package/dist/run-CQ9pDLSa.js +674 -0
- package/dist/scan-worker.d.ts +2 -4
- package/dist/scan-worker.js +1 -1
- package/dist/{scoped-BMYpSthj.js → scoped-h3KE8XWW.js} +3 -4
- package/dist/{server-Da1Ot9IN.js → server-Br8tAuG2.js} +312 -386
- package/dist/{server-deBOq2vq.js → server-DJRpUQVZ.js} +1059 -333
- package/dist/server.d.ts +1 -17
- package/dist/server.js +419 -379
- package/dist/{sitemap-DJXzKoza.js → sitemap-CSAkm6oi.js} +21 -33
- package/dist/{sources-D19czDSA.js → sources-DNVbYsgs.js} +713 -373
- package/dist/{status-zr4jY59Y.js → status-q6M3rBrh.js} +30 -30
- package/dist/{stdio-FPOKQAgu.js → stdio-D9kTzyqB.js} +2 -4
- package/dist/{stdio-CVaJfxA7.js → stdio-FWIVU3P4.js} +1 -2
- package/dist/sync-BNIAwMhR.js +1352 -0
- package/dist/{t-DC-c9zE5.js → t-gvEXx25s.js} +76 -53
- package/dist/test.d.ts +5 -16
- package/dist/test.js +126 -56
- package/dist/translate-BP4iVhOR.js +336 -0
- package/dist/{ts-BaU5yOf0.js → ts-BX6kwig5.js} +25 -14
- package/dist/{types-DtvQ7UdD.js → types-3kwyaCAm.js} +1 -2
- package/dist/{types-DsdWBG0b.d.ts → types-B4wNX6PA.d.ts} +6 -8
- package/dist/{types-CgUCkFU1.d.ts → types-_4UdFhR9.d.ts} +24 -21
- package/dist/types-xR2exI3L.js +42 -0
- package/dist/{units-CQ5Q99RC.js → units-DPPfCN7j.js} +7 -16
- package/dist/{url-CRfCOhUI.js → url-Bpc6wLea.js} +24 -11
- package/dist/{url-CsBkRaJy.js → url-D2_VlEeH.js} +25 -12
- package/dist/{validate-BxpupdAf.js → validate-CgzaDdOY.js} +690 -377
- package/dist/{validate-D6DJepZv.js → validate-PGgMsasz.js} +3 -5
- package/dist/{version-Byqi2guX.js → version-DC-J5WvV.js} +3 -5
- package/dist/{vite-scan-CT_vsp4g.js → vite-scan-kM8Ta3rO.js} +87 -92
- package/dist/vite.d.ts +2 -6
- package/dist/vite.js +6500 -6032
- package/dist/vue-i18n-_uIXlFVh.js +806 -0
- package/dist/{which-BOemZ5Q8.js → which-DFWk_KwN.js} +44 -37
- package/dist/{worker-84U6uYB3.js → worker-zlhNj4y3.js} +454 -608
- package/package.json +5 -5
- package/dist/check-HsmmpJZg.js +0 -1
- package/dist/codec-DuvU2VQy.js +0 -207
- package/dist/collisions-CfpZU8e4.js +0 -217
- package/dist/compile-BaDh0cHG.js +0 -245
- package/dist/concurrency-C9UUWuDC.js +0 -96
- package/dist/concurrency-DONL7t4V.js +0 -1
- package/dist/engine-C2ENBRJe.js +0 -531
- package/dist/i18next-9HAoxwUI.js +0 -1
- package/dist/i18next-BEJgv_S8.js +0 -1596
- package/dist/lingui-zUiCl9Um.js +0 -833
- package/dist/messages-BfjIExyB.js +0 -166
- package/dist/migrate-IpLDMXmq.js +0 -1484
- package/dist/migrate-rCQuOGsf.js +0 -1
- package/dist/project-Bw9UPIdx.js +0 -1046
- package/dist/project-C4GpaN-n.js +0 -381
- package/dist/react-intl-BP0u-D5m.js +0 -519
- package/dist/restore-CiYv-jxS.js +0 -175
- package/dist/rewrite-EsIw_lsq.js +0 -803
- package/dist/run-BEcnBbu-.js +0 -694
- package/dist/runtime-DTMmliT1.js +0 -64
- package/dist/sync-B9V2KFwb.js +0 -658
- package/dist/translate-CQnJfLjO.js +0 -299
- package/dist/types-wSh9fCBY.js +0 -11
- package/dist/vue-i18n-g0iGy6CZ.js +0 -651
|
@@ -0,0 +1,2169 @@
|
|
|
1
|
+
import { E as entryKey, F as isIncluded, I as listProjectFiles, M as sourceMatches, h as updateCatalogFile, p as serializeCatalog, s as catalogPath } from "./library-tp_xqzSY.js";
|
|
2
|
+
import { n as isDiagnosticError } from "./diagnostics-LgIWyeSp.js";
|
|
3
|
+
import { C as langFromId, w as parseModule } from "./sources-DNVbYsgs.js";
|
|
4
|
+
import { _ as isValidManualId, b as printICU, r as validateTranslation } from "./validate-CgzaDdOY.js";
|
|
5
|
+
import { t as syncCatalog } from "./sync-BNIAwMhR.js";
|
|
6
|
+
import { t as VERSION } from "./version-DC-J5WvV.js";
|
|
7
|
+
import { i as rootRelative, o as errorMessage, r as plural } from "./output-D5tAt8q4.js";
|
|
8
|
+
import { r as writeFileAtomic } from "./fs-ezCMZeDV.js";
|
|
9
|
+
import { a as hasErrors, g as usageError, o as loadCatalogs, r as compareText, s as loadProject } from "./project-B5KIO0q-.js";
|
|
10
|
+
import { s as decodeEntities } from "./worker-zlhNj4y3.js";
|
|
11
|
+
import { r as EXIT } from "./types-xR2exI3L.js";
|
|
12
|
+
import { basename, dirname, extname, join, resolve } from "node:path";
|
|
13
|
+
import { readFile } from "node:fs/promises";
|
|
14
|
+
// src/cli/commands/migrate/js.ts
|
|
15
|
+
/**
|
|
16
|
+
* ESTree analysis for the library codemods (`vi18n migrate --from i18next |
|
|
17
|
+
* react-intl | lingui | vue-i18n`, INTERNALS §2.14): a walker that knows
|
|
18
|
+
* each node's parent and field, the module's imports, every binding with the
|
|
19
|
+
* range it is visible in, and every reference by name. That is enough to
|
|
20
|
+
* tell whether the rewrites consumed every use of a hook result or an import
|
|
21
|
+
* (so it can go), and whether a name is free at a call site (so the vi18n
|
|
22
|
+
* import can take it). Scopes are approximated by source ranges: a wrong
|
|
23
|
+
* answer can only keep a binding or alias an import, never capture a name.
|
|
24
|
+
*/
|
|
25
|
+
function isNode$1(value) {
|
|
26
|
+
return typeof value === "object" && value !== null && typeof value.type === "string";
|
|
27
|
+
}
|
|
28
|
+
/** Children with the field holding them, in source order. */
|
|
29
|
+
function* childEntries(node) {
|
|
30
|
+
for (const key in node) {
|
|
31
|
+
if (key === "type" || key === "start" || key === "end") continue;
|
|
32
|
+
const value = node[key];
|
|
33
|
+
if (Array.isArray(value)) {
|
|
34
|
+
for (const item of value) if (isNode$1(item)) yield [key, item];
|
|
35
|
+
} else if (isNode$1(value)) yield [key, value];
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function unwrap(node) {
|
|
39
|
+
let current = node;
|
|
40
|
+
while (current.type === "TSAsExpression" || current.type === "TSSatisfiesExpression" || current.type === "TSNonNullExpression" || current.type === "TSTypeAssertion" || current.type === "ParenthesizedExpression") current = current.expression;
|
|
41
|
+
return current;
|
|
42
|
+
}
|
|
43
|
+
/** A string literal, a template without substitutions, or a `+` of those; null otherwise. */
|
|
44
|
+
function stringValue(node) {
|
|
45
|
+
if (node === void 0 || node === null) return null;
|
|
46
|
+
const n = unwrap(node);
|
|
47
|
+
if (n.type === "Literal" && typeof n.value === "string") return n.value;
|
|
48
|
+
if (n.type === "TemplateLiteral" && n.expressions.length === 0) {
|
|
49
|
+
const quasi = n.quasis[0];
|
|
50
|
+
return quasi === void 0 ? null : quasi.value.cooked;
|
|
51
|
+
}
|
|
52
|
+
if (n.type === "BinaryExpression" && n.operator === "+") {
|
|
53
|
+
const left = stringValue(n.left);
|
|
54
|
+
const right = stringValue(n.right);
|
|
55
|
+
return left === null || right === null ? null : left + right;
|
|
56
|
+
}
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
function keyName(property) {
|
|
60
|
+
const key = property.key;
|
|
61
|
+
if (property.computed === true) return stringValue(key);
|
|
62
|
+
if (key.type === "Identifier") return key.name;
|
|
63
|
+
if (key.type === "Literal") return String(key.value);
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
/** `name` of an Identifier (after unwrapping), else null. */
|
|
67
|
+
function identifierName(node) {
|
|
68
|
+
if (node === void 0 || node === null) return null;
|
|
69
|
+
const n = unwrap(node);
|
|
70
|
+
return n.type === "Identifier" ? n.name : null;
|
|
71
|
+
}
|
|
72
|
+
/** `object.property` of a non-computed member call's callee, else null. */
|
|
73
|
+
function memberParts(node) {
|
|
74
|
+
const n = unwrap(node);
|
|
75
|
+
if (n.type !== "MemberExpression" || n.computed === true) return null;
|
|
76
|
+
const property = n.property;
|
|
77
|
+
if (property.type !== "Identifier" && property.type !== "PrivateIdentifier") return null;
|
|
78
|
+
return {
|
|
79
|
+
object: n.object,
|
|
80
|
+
property: property.name
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/** The plain properties of an object literal by key; null when a key is computed or a spread is present. */
|
|
84
|
+
function objectProperties(node) {
|
|
85
|
+
const n = unwrap(node);
|
|
86
|
+
if (n.type !== "ObjectExpression") return null;
|
|
87
|
+
const properties = /* @__PURE__ */ new Map();
|
|
88
|
+
const spreads = [];
|
|
89
|
+
const order = [];
|
|
90
|
+
for (const property of n.properties) {
|
|
91
|
+
order.push(property);
|
|
92
|
+
if (property.type === "SpreadElement") {
|
|
93
|
+
spreads.push(property);
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
const key = keyName(property);
|
|
97
|
+
if (key === null) return null;
|
|
98
|
+
properties.set(key, property);
|
|
99
|
+
}
|
|
100
|
+
return {
|
|
101
|
+
properties,
|
|
102
|
+
spreads,
|
|
103
|
+
order
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
const FUNCTIONS = /* @__PURE__ */ new Set([
|
|
107
|
+
"FunctionDeclaration",
|
|
108
|
+
"FunctionExpression",
|
|
109
|
+
"ArrowFunctionExpression"
|
|
110
|
+
]);
|
|
111
|
+
/** Nodes whose range is a block scope for `let`, `const`, `class` and block functions. */
|
|
112
|
+
const BLOCKS = /* @__PURE__ */ new Set([
|
|
113
|
+
"BlockStatement",
|
|
114
|
+
"StaticBlock",
|
|
115
|
+
"ForStatement",
|
|
116
|
+
"ForInStatement",
|
|
117
|
+
"ForOfStatement",
|
|
118
|
+
"SwitchStatement",
|
|
119
|
+
"CatchClause",
|
|
120
|
+
"ClassBody"
|
|
121
|
+
]);
|
|
122
|
+
/** TypeScript signatures whose parameters bind nothing at runtime. */
|
|
123
|
+
const SIGNATURES = /* @__PURE__ */ new Set([
|
|
124
|
+
"TSFunctionType",
|
|
125
|
+
"TSConstructorType",
|
|
126
|
+
"TSMethodSignature",
|
|
127
|
+
"TSCallSignatureDeclaration",
|
|
128
|
+
"TSConstructSignatureDeclaration",
|
|
129
|
+
"TSDeclareFunction",
|
|
130
|
+
"TSEmptyBodyFunctionExpression"
|
|
131
|
+
]);
|
|
132
|
+
function isReferencePosition(node, parent, field) {
|
|
133
|
+
if (parent === null) return true;
|
|
134
|
+
switch (parent.type) {
|
|
135
|
+
case "MemberExpression": return field !== "property" || parent.computed === true;
|
|
136
|
+
case "Property":
|
|
137
|
+
case "MethodDefinition":
|
|
138
|
+
case "PropertyDefinition":
|
|
139
|
+
case "AccessorProperty":
|
|
140
|
+
case "TSAbstractMethodDefinition":
|
|
141
|
+
case "TSAbstractPropertyDefinition":
|
|
142
|
+
case "TSPropertySignature":
|
|
143
|
+
case "TSMethodSignature": return field !== "key" || parent.computed === true;
|
|
144
|
+
case "ImportSpecifier":
|
|
145
|
+
case "ImportDefaultSpecifier":
|
|
146
|
+
case "ImportNamespaceSpecifier":
|
|
147
|
+
case "ImportAttribute":
|
|
148
|
+
case "LabeledStatement":
|
|
149
|
+
case "BreakStatement":
|
|
150
|
+
case "ContinueStatement":
|
|
151
|
+
case "MetaProperty":
|
|
152
|
+
case "TSEnumMember":
|
|
153
|
+
case "TSTypeParameter":
|
|
154
|
+
case "TSImportType": return false;
|
|
155
|
+
case "TSQualifiedName": return field === "left";
|
|
156
|
+
case "ExportSpecifier": return field === "local" && node === parent.local;
|
|
157
|
+
default: return true;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
/** Component names: `<Trans>`, `<Foo.Bar>`'s `Foo`; lowercase names are elements, not bindings. */
|
|
161
|
+
function isJsxReference(node, parent, field) {
|
|
162
|
+
if (parent === null) return false;
|
|
163
|
+
const name = node.name;
|
|
164
|
+
if (parent.type === "JSXMemberExpression") return field === "object";
|
|
165
|
+
if (parent.type === "JSXOpeningElement" || parent.type === "JSXClosingElement") return field === "name" && !/^[a-z]/.test(name) && !name.includes("-");
|
|
166
|
+
return false;
|
|
167
|
+
}
|
|
168
|
+
function analyzeModule(program) {
|
|
169
|
+
const analyzer = new ModuleAnalyzer(program);
|
|
170
|
+
analyzer.visit(program, null, null);
|
|
171
|
+
const { imports, bindings, references, parents } = analyzer;
|
|
172
|
+
return {
|
|
173
|
+
program,
|
|
174
|
+
imports,
|
|
175
|
+
bindings,
|
|
176
|
+
references,
|
|
177
|
+
parentOf: (node) => parents.get(node) ?? null
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
const range = (n) => ({
|
|
181
|
+
start: n.start,
|
|
182
|
+
end: n.end
|
|
183
|
+
});
|
|
184
|
+
/** One walk over a module: its imports, its bindings with their scopes, and every reference. */
|
|
185
|
+
var ModuleAnalyzer = class {
|
|
186
|
+
imports = [];
|
|
187
|
+
bindings = [];
|
|
188
|
+
bindingIds = /* @__PURE__ */ new Set();
|
|
189
|
+
references = /* @__PURE__ */ new Map();
|
|
190
|
+
parents = /* @__PURE__ */ new Map();
|
|
191
|
+
blocks;
|
|
192
|
+
functions;
|
|
193
|
+
program;
|
|
194
|
+
constructor(program) {
|
|
195
|
+
this.program = program;
|
|
196
|
+
this.blocks = [program];
|
|
197
|
+
this.functions = [program];
|
|
198
|
+
}
|
|
199
|
+
declare(pattern, scope, kind, declarator, slot = null) {
|
|
200
|
+
if (!isNode$1(pattern)) return;
|
|
201
|
+
switch (pattern.type) {
|
|
202
|
+
case "Identifier":
|
|
203
|
+
this.bindingIds.add(pattern);
|
|
204
|
+
this.bindings.push({
|
|
205
|
+
name: pattern.name,
|
|
206
|
+
id: pattern,
|
|
207
|
+
scope: range(scope),
|
|
208
|
+
kind,
|
|
209
|
+
declarator,
|
|
210
|
+
slot
|
|
211
|
+
});
|
|
212
|
+
return;
|
|
213
|
+
case "ObjectPattern":
|
|
214
|
+
for (const property of pattern.properties) {
|
|
215
|
+
const target = property.type === "RestElement" ? property : property.value;
|
|
216
|
+
this.declare(target, scope, kind, declarator, property);
|
|
217
|
+
}
|
|
218
|
+
return;
|
|
219
|
+
case "ArrayPattern":
|
|
220
|
+
for (const element of pattern.elements) if (element !== null) this.declare(element, scope, kind, declarator, element);
|
|
221
|
+
return;
|
|
222
|
+
case "AssignmentPattern":
|
|
223
|
+
case "RestElement":
|
|
224
|
+
case "TSParameterProperty": {
|
|
225
|
+
const inner = pattern[PATTERN_INNER[pattern.type]];
|
|
226
|
+
this.declare(inner, scope, kind, declarator, slot);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
importDeclaration(node) {
|
|
232
|
+
const info = {
|
|
233
|
+
node,
|
|
234
|
+
source: node.source.value,
|
|
235
|
+
typeOnly: node.importKind === "type",
|
|
236
|
+
specifiers: []
|
|
237
|
+
};
|
|
238
|
+
for (const specifier of node.specifiers ?? []) {
|
|
239
|
+
const local = specifier.local;
|
|
240
|
+
info.specifiers.push({
|
|
241
|
+
local: local.name,
|
|
242
|
+
imported: importedName(specifier),
|
|
243
|
+
node: specifier,
|
|
244
|
+
typeOnly: info.typeOnly || specifier.importKind === "type"
|
|
245
|
+
});
|
|
246
|
+
this.declare(local, this.program, "import", null, specifier);
|
|
247
|
+
}
|
|
248
|
+
this.imports.push(info);
|
|
249
|
+
}
|
|
250
|
+
/** The bindings `node` itself declares, in the innermost `block` and function `fn`. */
|
|
251
|
+
declarations(node, block, fn) {
|
|
252
|
+
switch (node.type) {
|
|
253
|
+
case "ImportDeclaration": return this.importDeclaration(node);
|
|
254
|
+
case "VariableDeclaration": {
|
|
255
|
+
const isVar = node.kind === "var";
|
|
256
|
+
for (const declarator of node.declarations) this.declare(declarator.id, isVar ? fn : block, isVar ? "var" : "lexical", declarator);
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
case "FunctionDeclaration":
|
|
260
|
+
case "ClassDeclaration":
|
|
261
|
+
case "TSInterfaceDeclaration":
|
|
262
|
+
case "TSTypeAliasDeclaration":
|
|
263
|
+
case "TSEnumDeclaration":
|
|
264
|
+
case "TSModuleDeclaration":
|
|
265
|
+
if (isNode$1(node.id)) this.declare(node.id, block, DECLARED_KIND[node.type], null);
|
|
266
|
+
return;
|
|
267
|
+
case "ClassExpression":
|
|
268
|
+
case "FunctionExpression":
|
|
269
|
+
if (isNode$1(node.id)) this.declare(node.id, node, DECLARED_KIND[node.type], null);
|
|
270
|
+
return;
|
|
271
|
+
case "CatchClause": return this.declare(node.param, node, "catch", null);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
parameters(node) {
|
|
275
|
+
if (FUNCTIONS.has(node.type)) for (const param of node.params) this.declare(param, node, "param", null);
|
|
276
|
+
else if (SIGNATURES.has(node.type)) for (const param of node.params ?? []) this.declare(param, node, "type", null);
|
|
277
|
+
}
|
|
278
|
+
isReference(node, parent, field) {
|
|
279
|
+
if (node.type === "Identifier") return !this.bindingIds.has(node) && isReferencePosition(node, parent, field);
|
|
280
|
+
return node.type === "JSXIdentifier" && isJsxReference(node, parent, field);
|
|
281
|
+
}
|
|
282
|
+
visit(node, parent, field) {
|
|
283
|
+
if (parent !== null && field !== null) this.parents.set(node, {
|
|
284
|
+
node: parent,
|
|
285
|
+
field
|
|
286
|
+
});
|
|
287
|
+
this.declarations(node, this.blocks.at(-1), this.functions.at(-1));
|
|
288
|
+
this.parameters(node);
|
|
289
|
+
if (this.isReference(node, parent, field)) addReference(this.references, node);
|
|
290
|
+
const isFunction = FUNCTIONS.has(node.type);
|
|
291
|
+
const isBlock = BLOCKS.has(node.type) || isFunction;
|
|
292
|
+
if (isFunction) this.functions.push(node);
|
|
293
|
+
if (isBlock) this.blocks.push(node);
|
|
294
|
+
for (const [key, child] of childEntries(node)) this.visit(child, node, key);
|
|
295
|
+
if (isBlock) this.blocks.pop();
|
|
296
|
+
if (isFunction) this.functions.pop();
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
/** The field holding the pattern a wrapping pattern declares through. */
|
|
300
|
+
const PATTERN_INNER = {
|
|
301
|
+
AssignmentPattern: "left",
|
|
302
|
+
RestElement: "argument",
|
|
303
|
+
TSParameterProperty: "parameter"
|
|
304
|
+
};
|
|
305
|
+
/** What a named declaration's name binds. */
|
|
306
|
+
const DECLARED_KIND = {
|
|
307
|
+
FunctionDeclaration: "function",
|
|
308
|
+
FunctionExpression: "function",
|
|
309
|
+
ClassDeclaration: "class",
|
|
310
|
+
ClassExpression: "class",
|
|
311
|
+
TSInterfaceDeclaration: "type",
|
|
312
|
+
TSTypeAliasDeclaration: "type",
|
|
313
|
+
TSEnumDeclaration: "type",
|
|
314
|
+
TSModuleDeclaration: "type"
|
|
315
|
+
};
|
|
316
|
+
function addReference(references, node) {
|
|
317
|
+
const name = node.name;
|
|
318
|
+
let list = references.get(name);
|
|
319
|
+
if (list === void 0) references.set(name, list = []);
|
|
320
|
+
list.push(node);
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Whether every reference to `binding` (a reference to its name inside its
|
|
324
|
+
* scope) is one the rewrites consumed: it can then be removed.
|
|
325
|
+
*/
|
|
326
|
+
function isConsumed(info, binding, consumed, extra = []) {
|
|
327
|
+
const inScope = (offset) => binding.scope.start <= offset && offset < binding.scope.end;
|
|
328
|
+
for (const ref of info.references.get(binding.name) ?? []) if (inScope(ref.start) && !consumed.has(ref.start)) return false;
|
|
329
|
+
return extra.every((offset) => !inScope(offset) || consumed.has(offset));
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Whether an import of `name` at module level would resolve at every offset
|
|
333
|
+
* in `sites` and capture nothing else: no binding left in place declares it
|
|
334
|
+
* at module level or around a site, and no reference the rewrites keep reads
|
|
335
|
+
* a global of that name.
|
|
336
|
+
*/
|
|
337
|
+
function isNameFree(info, name, sites, removed, consumed) {
|
|
338
|
+
const kept = info.bindings.filter((b) => b.name === name && !removed.has(b.id));
|
|
339
|
+
for (const b of kept) {
|
|
340
|
+
if (b.scope.start === info.program.start && b.scope.end === info.program.end) return false;
|
|
341
|
+
if (sites.some((offset) => b.scope.start <= offset && offset < b.scope.end)) return false;
|
|
342
|
+
}
|
|
343
|
+
for (const ref of info.references.get(name) ?? []) {
|
|
344
|
+
if (consumed.has(ref.start)) continue;
|
|
345
|
+
if (!kept.some((b) => b.scope.start <= ref.start && ref.start < b.scope.end)) return false;
|
|
346
|
+
}
|
|
347
|
+
return true;
|
|
348
|
+
}
|
|
349
|
+
/** The name of a JSX element as written (`Trans`, `Foo.Bar`, `div`). */
|
|
350
|
+
function jsxName(element) {
|
|
351
|
+
return printJsxName(element.openingElement.name);
|
|
352
|
+
}
|
|
353
|
+
function printJsxName(name) {
|
|
354
|
+
if (name.type === "JSXMemberExpression") return `${printJsxName(name.object)}.${name.property.name}`;
|
|
355
|
+
if (name.type === "JSXNamespacedName") return `${name.namespace.name}:${name.name.name}`;
|
|
356
|
+
return name.name;
|
|
357
|
+
}
|
|
358
|
+
/** What an import specifier imports: `default`, `*`, or the exported name. */
|
|
359
|
+
function importedName(specifier) {
|
|
360
|
+
if (specifier.type === "ImportDefaultSpecifier") return "default";
|
|
361
|
+
if (specifier.type === "ImportNamespaceSpecifier") return "*";
|
|
362
|
+
const imported = specifier.imported;
|
|
363
|
+
return imported.name ?? imported.value;
|
|
364
|
+
}
|
|
365
|
+
/** JSXIdentifier nodes naming an element (opening and closing), for consumption. */
|
|
366
|
+
function jsxNameNodes(element) {
|
|
367
|
+
const out = [];
|
|
368
|
+
const root = (n) => n.type === "JSXMemberExpression" ? root(n.object) : n;
|
|
369
|
+
out.push(root(element.openingElement.name));
|
|
370
|
+
const closing = element.closingElement;
|
|
371
|
+
if (isNode$1(closing)) out.push(root(closing.name));
|
|
372
|
+
return out;
|
|
373
|
+
}
|
|
374
|
+
function jsxAttributes(element) {
|
|
375
|
+
const named = /* @__PURE__ */ new Map();
|
|
376
|
+
const spreads = [];
|
|
377
|
+
for (const attribute of element.openingElement.attributes) {
|
|
378
|
+
if (attribute.type === "JSXSpreadAttribute") {
|
|
379
|
+
spreads.push(attribute);
|
|
380
|
+
continue;
|
|
381
|
+
}
|
|
382
|
+
const name = attribute.name;
|
|
383
|
+
const key = name.type === "JSXNamespacedName" ? `${name.namespace.name}:${name.name.name}` : name.name;
|
|
384
|
+
named.set(key, {
|
|
385
|
+
attribute,
|
|
386
|
+
value: isNode$1(attribute.value) ? attribute.value : null
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
return {
|
|
390
|
+
named,
|
|
391
|
+
spreads
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
/** An attribute's expression: the literal itself, or what `{…}` holds; null for `{}` and flags. */
|
|
395
|
+
function attributeExpression(value) {
|
|
396
|
+
if (value === null) return null;
|
|
397
|
+
if (value.type === "JSXExpressionContainer") {
|
|
398
|
+
const expression = value.expression;
|
|
399
|
+
return expression.type === "JSXEmptyExpression" ? null : expression;
|
|
400
|
+
}
|
|
401
|
+
return value;
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* A static attribute string (`id="x"`, `id={"x"}`, ``id={`x`}``), else null.
|
|
405
|
+
* Oxc keeps entities as written; JSX decodes them in a quoted attribute (not
|
|
406
|
+
* in a string inside `{…}`), as the old library's Babel or TypeScript build did.
|
|
407
|
+
*/
|
|
408
|
+
function attributeString(value) {
|
|
409
|
+
const expression = attributeExpression(value);
|
|
410
|
+
if (expression === null) return null;
|
|
411
|
+
const text = stringValue(expression);
|
|
412
|
+
return text !== null && value?.type === "Literal" ? decodeEntities(text) : text;
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* JSX text as React's transform reads it: lines trimmed, lines that are
|
|
416
|
+
* only whitespace dropped, the rest joined by one space; entities decoded
|
|
417
|
+
* first (Oxc's `value` keeps them as written; Babel's had them decoded).
|
|
418
|
+
*/
|
|
419
|
+
function cleanJsxText(value) {
|
|
420
|
+
const lines = decodeEntities(value).split(/\r\n|\n|\r/);
|
|
421
|
+
let last = 0;
|
|
422
|
+
for (let i = 0; i < lines.length; i++) if (/[^ \t]/.test(lines[i])) last = i;
|
|
423
|
+
let out = "";
|
|
424
|
+
for (let i = 0; i < lines.length; i++) {
|
|
425
|
+
let line = lines[i].replace(/\t/g, " ");
|
|
426
|
+
if (i !== 0) line = line.replace(/^ +/, "");
|
|
427
|
+
if (i !== lines.length - 1) line = line.replace(/ +$/, "");
|
|
428
|
+
if (line === "") continue;
|
|
429
|
+
out += i === last ? line : line + " ";
|
|
430
|
+
}
|
|
431
|
+
return out;
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* A JSX element's children as React passes them: text cleaned (and dropped
|
|
435
|
+
* when empty), empty expression containers (comments) dropped.
|
|
436
|
+
*/
|
|
437
|
+
function jsxChildren(element) {
|
|
438
|
+
const out = [];
|
|
439
|
+
for (const child of element.children) if (child.type === "JSXText") {
|
|
440
|
+
if (cleanJsxText(child.value) !== "") out.push(child);
|
|
441
|
+
} else if (child.type === "JSXExpressionContainer" && child.expression.type === "JSXEmptyExpression") continue;
|
|
442
|
+
else out.push(child);
|
|
443
|
+
return out;
|
|
444
|
+
}
|
|
445
|
+
/** Whether a node sits where JSX expects children (so a replacement needs `{…}`). */
|
|
446
|
+
function inJsxChildren(info, node) {
|
|
447
|
+
const parent = info.parentOf(node);
|
|
448
|
+
return parent !== null && parent.field === "children" && (parent.node.type === "JSXElement" || parent.node.type === "JSXFragment");
|
|
449
|
+
}
|
|
450
|
+
/** A statement's range widened to whole lines when it stands alone on them, so no blank line is left. */
|
|
451
|
+
function lineRange(text, start, end) {
|
|
452
|
+
let s = start;
|
|
453
|
+
while (s > 0 && (text[s - 1] === " " || text[s - 1] === " ")) s--;
|
|
454
|
+
let e = end;
|
|
455
|
+
while (e < text.length && (text[e] === " " || text[e] === " ")) e++;
|
|
456
|
+
if (!((s === 0 || text[s - 1] === "\n") && (e === text.length || text[e] === "\n" || text[e] === "\r"))) return {
|
|
457
|
+
start,
|
|
458
|
+
end
|
|
459
|
+
};
|
|
460
|
+
if (text[e] === "\r") e++;
|
|
461
|
+
if (text[e] === "\n") e++;
|
|
462
|
+
return {
|
|
463
|
+
start: s,
|
|
464
|
+
end: e
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
/**
|
|
468
|
+
* The range that removes one element of a comma-separated list (`items`,
|
|
469
|
+
* in order) together with its separator: the comma after it, or before it
|
|
470
|
+
* when it is the last.
|
|
471
|
+
*/
|
|
472
|
+
function listItemRange(items, index) {
|
|
473
|
+
const item = items[index];
|
|
474
|
+
const next = items[index + 1];
|
|
475
|
+
if (next !== void 0) return {
|
|
476
|
+
start: item.start,
|
|
477
|
+
end: next.start
|
|
478
|
+
};
|
|
479
|
+
const previous = items[index - 1];
|
|
480
|
+
if (previous !== void 0) return {
|
|
481
|
+
start: previous.end,
|
|
482
|
+
end: item.end
|
|
483
|
+
};
|
|
484
|
+
return {
|
|
485
|
+
start: item.start,
|
|
486
|
+
end: item.end
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
/** Escapes text for a JS string literal in `quote`. */
|
|
490
|
+
function jsString(value, quote = "\"") {
|
|
491
|
+
if (quote === "\"") return JSON.stringify(value);
|
|
492
|
+
return "'" + JSON.stringify(value).slice(1, -1).replace(/\\"/g, "\"").replace(/'/g, "\\'") + "'";
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* The keys a template literal can produce: its static parts in order, any
|
|
496
|
+
* text between them. Null when the parts hold no letters, since
|
|
497
|
+
* `${a}.${b}` would match every key.
|
|
498
|
+
*/
|
|
499
|
+
function templateKeyPattern(quasis) {
|
|
500
|
+
if (!/[A-Za-z]/.test(quasis.join(""))) return null;
|
|
501
|
+
const escaped = quasis.map((q) => q.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
|
|
502
|
+
return new RegExp("^" + escaped.join("[^]+?") + "$");
|
|
503
|
+
}
|
|
504
|
+
/** The keys among `keys` a template literal with these static parts can produce. */
|
|
505
|
+
function templateKeys(quasis, keys) {
|
|
506
|
+
const found = /* @__PURE__ */ new Set();
|
|
507
|
+
const pattern = templateKeyPattern(quasis);
|
|
508
|
+
if (pattern === null) return found;
|
|
509
|
+
for (const key of keys) if (pattern.test(key)) found.add(key);
|
|
510
|
+
return found;
|
|
511
|
+
}
|
|
512
|
+
// src/cli/commands/migrate/report.ts
|
|
513
|
+
/** What both migrators report the same way: translations that do not fit their source, and the summary line. */
|
|
514
|
+
/**
|
|
515
|
+
* A migrated translation checked against its source. One that does not fit
|
|
516
|
+
* is still written (people fix it), but reported now, as a warning.
|
|
517
|
+
*/
|
|
518
|
+
function translationProblems(codec, message, at) {
|
|
519
|
+
const { key, translation } = message;
|
|
520
|
+
const label = `${key} (${at.locale})`;
|
|
521
|
+
try {
|
|
522
|
+
return validateTranslation(codec.parse(translation), codec.parse(message.canonical), {
|
|
523
|
+
locale: at.locale,
|
|
524
|
+
text: translation
|
|
525
|
+
}).filter((d) => d.severity === "error").map((d) => ({
|
|
526
|
+
...d,
|
|
527
|
+
...at,
|
|
528
|
+
code: "catalog-invalid-translation",
|
|
529
|
+
severity: "warning",
|
|
530
|
+
message: `${label}: ${d.message}`
|
|
531
|
+
}));
|
|
532
|
+
} catch (error) {
|
|
533
|
+
if (!isDiagnosticError(error)) throw error;
|
|
534
|
+
return [{
|
|
535
|
+
...error.diagnostic,
|
|
536
|
+
...at,
|
|
537
|
+
severity: "warning",
|
|
538
|
+
message: `${label}: ${error.diagnostic.message}`
|
|
539
|
+
}];
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
/** The last line both migrators print: what was (or would be) rewritten, and what to do next. */
|
|
543
|
+
function rewriteSummary(data, failed) {
|
|
544
|
+
const counts = `${data.write && !failed ? "rewrote" : "would rewrite"} ${plural(data.rewritten, "call")} in ${plural(data.files.length, "file")}`;
|
|
545
|
+
if (!data.write) return `${counts}; run with --write to apply`;
|
|
546
|
+
return failed ? `${counts} (nothing written: fix the errors first)` : counts;
|
|
547
|
+
}
|
|
548
|
+
// src/cli/commands/migrate.ts
|
|
549
|
+
/**
|
|
550
|
+
* `vi18n migrate --from saas-i18n --catalog <file> [--catalog <l>=<file>]…
|
|
551
|
+
* [--write]` (INTERNALS §2.14, PLAN §11): moves a project from `@saas/i18n`'s
|
|
552
|
+
* key catalogue to vi18n manual ids.
|
|
553
|
+
*
|
|
554
|
+
* - `<x>.t("key"[, values])` with a catalogue key becomes
|
|
555
|
+
* `t({ id: "key", message: "<text>" }[, values])`, importing `t` once; so
|
|
556
|
+
* does a call of a local bound to `<x>.t` (`const t = i18nFor(l).t`,
|
|
557
|
+
* `const { t } = i18n`);
|
|
558
|
+
* - computed keys are not rewritten: every catalogue key the expression can
|
|
559
|
+
* produce becomes a `msg()` descriptor in `messages.vi18n.ts` beside the
|
|
560
|
+
* catalogue, and the call site is reported (`migrate-dynamic-key`); so
|
|
561
|
+
* does a key spelled as a string anywhere else (a route table, a helper's
|
|
562
|
+
* argument), so no key the code names is dropped as unused;
|
|
563
|
+
* - other locales' texts become `translated` manual entries.
|
|
564
|
+
*
|
|
565
|
+
* Catalogues are read with the parser, never executed. Without `--write`
|
|
566
|
+
* nothing is written and the plan is printed; any error writes nothing.
|
|
567
|
+
*/
|
|
568
|
+
const RUNTIME = "@menapo/vi18n";
|
|
569
|
+
const MESSAGES_MODULE = "messages.vi18n.ts";
|
|
570
|
+
/** Extensions parsed as modules; everything else (`.astro`, `.vue`, `.svelte`, `.mdx`) is scanned lexically. */
|
|
571
|
+
const MODULE_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
572
|
+
".js",
|
|
573
|
+
".jsx",
|
|
574
|
+
".mjs",
|
|
575
|
+
".cjs",
|
|
576
|
+
".ts",
|
|
577
|
+
".tsx",
|
|
578
|
+
".mts",
|
|
579
|
+
".cts"
|
|
580
|
+
]);
|
|
581
|
+
/** `@saas/i18n` placeholders: `{name}`, `{name:date}`, `{name:number}`, `{name:currency}`. */
|
|
582
|
+
const PLACEHOLDER = /\{(\w+)(?::(date|number|currency))?\}/g;
|
|
583
|
+
function isNode(value) {
|
|
584
|
+
return typeof value === "object" && value !== null && typeof value.type === "string";
|
|
585
|
+
}
|
|
586
|
+
/** Children in source order (ESTree field order is source order for every node vi18n meets). */
|
|
587
|
+
function* children(node) {
|
|
588
|
+
for (const key in node) {
|
|
589
|
+
if (key === "type" || key === "start" || key === "end") continue;
|
|
590
|
+
const value = node[key];
|
|
591
|
+
if (Array.isArray(value)) {
|
|
592
|
+
for (const item of value) if (isNode(item)) yield item;
|
|
593
|
+
} else if (isNode(value)) yield value;
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
function unwrapExpression(node) {
|
|
597
|
+
let current = node;
|
|
598
|
+
for (;;) if (current.type === "TSAsExpression" || current.type === "TSSatisfiesExpression" || current.type === "TSNonNullExpression" || current.type === "TSTypeAssertion" || current.type === "ParenthesizedExpression") current = current.expression;
|
|
599
|
+
else return current;
|
|
600
|
+
}
|
|
601
|
+
/**
|
|
602
|
+
* The value of a string-like expression: a string literal, a template
|
|
603
|
+
* without substitutions, or a `+` concatenation of those; null otherwise.
|
|
604
|
+
*/
|
|
605
|
+
function staticString(node) {
|
|
606
|
+
const n = unwrapExpression(node);
|
|
607
|
+
if (n.type === "Literal" && typeof n.value === "string") return n.value;
|
|
608
|
+
if (n.type === "TemplateLiteral" && n.expressions.length === 0) return n.quasis[0].value.cooked;
|
|
609
|
+
if (n.type === "BinaryExpression" && n.operator === "+") {
|
|
610
|
+
const left = staticString(n.left);
|
|
611
|
+
const right = staticString(n.right);
|
|
612
|
+
return left === null || right === null ? null : left + right;
|
|
613
|
+
}
|
|
614
|
+
return null;
|
|
615
|
+
}
|
|
616
|
+
function propertyKey(property) {
|
|
617
|
+
const key = property.key;
|
|
618
|
+
if (property.computed === true) return staticString(key);
|
|
619
|
+
if (key.type === "Identifier") return key.name;
|
|
620
|
+
if (key.type === "Literal") return String(key.value);
|
|
621
|
+
return null;
|
|
622
|
+
}
|
|
623
|
+
/**
|
|
624
|
+
* The exported object literal of a catalogue module (`export const en = {…}`,
|
|
625
|
+
* with or without a type annotation or `satisfies`, or `export default {…}`),
|
|
626
|
+
* flattened: nested objects join their keys with `.`.
|
|
627
|
+
*/
|
|
628
|
+
function readCatalogue(text, file, locale, display) {
|
|
629
|
+
const diagnostics = [];
|
|
630
|
+
const catalogue = {
|
|
631
|
+
file,
|
|
632
|
+
locale,
|
|
633
|
+
texts: /* @__PURE__ */ new Map()
|
|
634
|
+
};
|
|
635
|
+
const fail = (message, offset = 0) => {
|
|
636
|
+
const diagnostic = {
|
|
637
|
+
code: "catalog-parse",
|
|
638
|
+
severity: "error",
|
|
639
|
+
message,
|
|
640
|
+
file: display
|
|
641
|
+
};
|
|
642
|
+
if (offset > 0) Object.assign(diagnostic, positionOf(text, offset));
|
|
643
|
+
diagnostics.push(diagnostic);
|
|
644
|
+
};
|
|
645
|
+
let program;
|
|
646
|
+
try {
|
|
647
|
+
program = parseModule(text, langFromId(file), file).program;
|
|
648
|
+
} catch (error) {
|
|
649
|
+
if (!isDiagnosticError(error)) throw error;
|
|
650
|
+
diagnostics.push({
|
|
651
|
+
...error.diagnostic,
|
|
652
|
+
file: display
|
|
653
|
+
});
|
|
654
|
+
return {
|
|
655
|
+
catalogue,
|
|
656
|
+
diagnostics
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
const objects = [];
|
|
660
|
+
for (const statement of program.body) if (statement.type === "ExportDefaultDeclaration") {
|
|
661
|
+
const value = unwrapExpression(statement.declaration);
|
|
662
|
+
if (value.type === "ObjectExpression") objects.push(value);
|
|
663
|
+
} else if (statement.type === "ExportNamedDeclaration" && isNode(statement.declaration)) {
|
|
664
|
+
const declaration = statement.declaration;
|
|
665
|
+
if (declaration.type !== "VariableDeclaration") continue;
|
|
666
|
+
for (const declarator of declaration.declarations) {
|
|
667
|
+
if (!isNode(declarator.init)) continue;
|
|
668
|
+
const value = unwrapExpression(declarator.init);
|
|
669
|
+
if (value.type === "ObjectExpression") objects.push(value);
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
if (objects.length !== 1) {
|
|
673
|
+
fail(objects.length === 0 ? `${basename(file)} exports no object literal; a saas-i18n catalogue is a module exporting one object of strings` : `${basename(file)} exports ${objects.length} object literals; a saas-i18n catalogue exports exactly one`);
|
|
674
|
+
return {
|
|
675
|
+
catalogue,
|
|
676
|
+
diagnostics
|
|
677
|
+
};
|
|
678
|
+
}
|
|
679
|
+
const walk = (object, prefix) => {
|
|
680
|
+
for (const property of object.properties) {
|
|
681
|
+
if (property.type !== "Property") {
|
|
682
|
+
fail("spread properties cannot be read without executing the catalogue; inline them", property.start);
|
|
683
|
+
continue;
|
|
684
|
+
}
|
|
685
|
+
const key = propertyKey(property);
|
|
686
|
+
if (key === null) {
|
|
687
|
+
fail("a computed key cannot be read without executing the catalogue", property.start);
|
|
688
|
+
continue;
|
|
689
|
+
}
|
|
690
|
+
const value = unwrapExpression(property.value);
|
|
691
|
+
if (value.type === "ObjectExpression") {
|
|
692
|
+
walk(value, prefix + key + ".");
|
|
693
|
+
continue;
|
|
694
|
+
}
|
|
695
|
+
const textValue = staticString(value);
|
|
696
|
+
if (textValue === null) {
|
|
697
|
+
fail(`the value of "${prefix + key}" is not a string literal`, value.start);
|
|
698
|
+
continue;
|
|
699
|
+
}
|
|
700
|
+
catalogue.texts.set(prefix + key, textValue);
|
|
701
|
+
}
|
|
702
|
+
};
|
|
703
|
+
walk(objects[0], "");
|
|
704
|
+
return {
|
|
705
|
+
catalogue,
|
|
706
|
+
diagnostics
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
/**
|
|
710
|
+
* A saas-i18n message as ICU text. Placeholders become arguments
|
|
711
|
+
* (`{n:number}` → `{n, number}`, `{d:date}` → `{d, date, medium}`, the ICU
|
|
712
|
+
* style nearest saas's `dateStyle: "medium"`, the same text in English only);
|
|
713
|
+
* everything else is literal text, quoted by the
|
|
714
|
+
* canonical printer where ICU would read it as syntax (`{`, `<b`, `'{`).
|
|
715
|
+
*/
|
|
716
|
+
function saasToIcu(text) {
|
|
717
|
+
const nodes = [];
|
|
718
|
+
const currency = [];
|
|
719
|
+
const literal = (value) => {
|
|
720
|
+
if (value === "") return;
|
|
721
|
+
const last = nodes[nodes.length - 1];
|
|
722
|
+
if (last?.type === "literal") last.value += value;
|
|
723
|
+
else nodes.push({
|
|
724
|
+
type: "literal",
|
|
725
|
+
value
|
|
726
|
+
});
|
|
727
|
+
};
|
|
728
|
+
let at = 0;
|
|
729
|
+
for (const match of text.matchAll(PLACEHOLDER)) {
|
|
730
|
+
literal(text.slice(at, match.index));
|
|
731
|
+
at = match.index + match[0].length;
|
|
732
|
+
const name = match[1];
|
|
733
|
+
const format = match[2];
|
|
734
|
+
let node;
|
|
735
|
+
if (format === "number") node = {
|
|
736
|
+
type: "number",
|
|
737
|
+
name,
|
|
738
|
+
style: null,
|
|
739
|
+
options: null
|
|
740
|
+
};
|
|
741
|
+
else if (format === "date") node = {
|
|
742
|
+
type: "date",
|
|
743
|
+
name,
|
|
744
|
+
style: {
|
|
745
|
+
kind: "keyword",
|
|
746
|
+
value: "medium"
|
|
747
|
+
},
|
|
748
|
+
options: null
|
|
749
|
+
};
|
|
750
|
+
else {
|
|
751
|
+
if (format === "currency") currency.push(name);
|
|
752
|
+
node = {
|
|
753
|
+
type: "argument",
|
|
754
|
+
name
|
|
755
|
+
};
|
|
756
|
+
}
|
|
757
|
+
nodes.push(node);
|
|
758
|
+
}
|
|
759
|
+
literal(text.slice(at));
|
|
760
|
+
return {
|
|
761
|
+
icu: printICU(nodes),
|
|
762
|
+
currency
|
|
763
|
+
};
|
|
764
|
+
}
|
|
765
|
+
/** Names of plain `{name}` placeholders (no `:date`, `:number`, `:currency`) in a saas text, deduplicated. */
|
|
766
|
+
function plainPlaceholders(text) {
|
|
767
|
+
const names = /* @__PURE__ */ new Set();
|
|
768
|
+
for (const match of text.matchAll(PLACEHOLDER)) if (match[2] === void 0) names.add(match[1]);
|
|
769
|
+
return [...names];
|
|
770
|
+
}
|
|
771
|
+
/**
|
|
772
|
+
* Whether a name usually holds a date: `date`, `updated`, `expires`, or a
|
|
773
|
+
* camel-case or snake-case suffix (`publishedAt`, `startDate`, `created_on`).
|
|
774
|
+
* Number-like names (`days`, `readingTime`) are left out: saas formatted
|
|
775
|
+
* only `Date` values, so they render the same in vi18n.
|
|
776
|
+
*/
|
|
777
|
+
function isDateName(name) {
|
|
778
|
+
return /^(?:date|datetime|timestamp|when|since|until|deadline|expires|expiry|expiration|created|updated|modified|published|posted|due)$/i.test(name) || /[a-z0-9](?:Date|At|On)$/.test(name) || /^date[A-Z_]/.test(name) || /_(?:date|at|on)$/i.test(name);
|
|
779
|
+
}
|
|
780
|
+
/**
|
|
781
|
+
* The value written for `name` in a call's values object (`{ date: new
|
|
782
|
+
* Date() }`, or `name` itself for `{ date }`); null when the call names no
|
|
783
|
+
* such property. Lexical, so it reads calls in components alike.
|
|
784
|
+
*/
|
|
785
|
+
function valueExpression(call, name) {
|
|
786
|
+
const property = new RegExp(`[{,]\\s*(?:${name}|"${name}"|'${name}')\\s*:\\s*`).exec(call);
|
|
787
|
+
if (property === null) return new RegExp(`[{,]\\s*${name}\\s*[,}]`).test(call) ? name : null;
|
|
788
|
+
const start = property.index + property[0].length;
|
|
789
|
+
for (let i = start; i < call.length; i++) {
|
|
790
|
+
const c = call[i];
|
|
791
|
+
if (c === "," || c === "}" || c === ")") return call.slice(start, i).trim();
|
|
792
|
+
let end = i + 1;
|
|
793
|
+
if (c === "(" || c === "[" || c === "{") end = skipBalanced(call, i);
|
|
794
|
+
else if (c === "\"" || c === "'") end = readString(call, i)?.end ?? null;
|
|
795
|
+
else if (c === "`") end = readTemplate(call, i)?.end ?? null;
|
|
796
|
+
if (end === null) return null;
|
|
797
|
+
i = end - 1;
|
|
798
|
+
}
|
|
799
|
+
return null;
|
|
800
|
+
}
|
|
801
|
+
/** Whether a value expression passes a `Date`: `new Date(…)`, or ends in a date-like name (`post.updatedAt`). */
|
|
802
|
+
function looksLikeDate(expression) {
|
|
803
|
+
const constructed = /^new\s+Date\b\s*/.exec(expression);
|
|
804
|
+
if (constructed !== null) {
|
|
805
|
+
const at = constructed[0].length;
|
|
806
|
+
return at === expression.length || skipBalanced(expression, at) === expression.length;
|
|
807
|
+
}
|
|
808
|
+
const last = /([A-Za-z_$][\w$]*)\s*(\(\s*\))?\s*$/.exec(expression.replace(/[!?]+$/, ""));
|
|
809
|
+
if (last === null) return false;
|
|
810
|
+
const name = last[1];
|
|
811
|
+
if (last[2] !== void 0 && DATE_NUMBER_GETTER.test(name)) return false;
|
|
812
|
+
return isDateName(name);
|
|
813
|
+
}
|
|
814
|
+
/** `Date` methods that return numbers, not dates. */
|
|
815
|
+
const DATE_NUMBER_GETTER = /^(?:get(?:UTC)?(?:Date|Day|FullYear|Month|Hours|Minutes|Seconds|Milliseconds)|getTime|getTimezoneOffset|valueOf)$/;
|
|
816
|
+
/** A key as a valid manual id (INTERNALS §2.2.3): invalid characters → `_`, a key without `.` gets `msg.`. */
|
|
817
|
+
function toManualId(key) {
|
|
818
|
+
if (isValidManualId(key)) return key;
|
|
819
|
+
const segments = key.split(".").map((segment) => segment.replace(/[^A-Za-z0-9_:-]/g, "_") || "_");
|
|
820
|
+
if (segments.length < 2) segments.unshift("msg");
|
|
821
|
+
return segments.join(".");
|
|
822
|
+
}
|
|
823
|
+
/** Why a key the code computes was not rewritten, and where its msg() descriptors are. */
|
|
824
|
+
function dynamicKeyMessage(site, messagesFile) {
|
|
825
|
+
const lookUp = `import { messages } from it and call t(messages[key])`;
|
|
826
|
+
if (site.literal === true) return `${site.expression} names a catalogue key outside a call vi18n migrate rewrites; it is a msg() descriptor in ${messagesFile}: ${lookUp}`;
|
|
827
|
+
if (site.keys.size === 0) return `${site.receiver}.t(${site.expression}) uses a computed key that matches no catalogue key and was not rewritten; pass a msg() descriptor (t(messages[key])) instead`;
|
|
828
|
+
const listed = [...site.keys].sort(compareText);
|
|
829
|
+
const example = listed.slice(0, 3).join(", ") + (listed.length > 3 ? ", …" : "");
|
|
830
|
+
return `${site.expression} is a computed key and was not rewritten; its ${plural(site.keys.size, "key")} (${example}) are msg() descriptors in ${messagesFile}: ${lookUp}`;
|
|
831
|
+
}
|
|
832
|
+
/**
|
|
833
|
+
* Keys searched for as plain strings outside calls: only nested ones
|
|
834
|
+
* (`nav.home`). A one-word key (`quote`) is as likely an ordinary string of
|
|
835
|
+
* the code, and claiming it would only add noise.
|
|
836
|
+
*/
|
|
837
|
+
function isNamedKey(value, keys) {
|
|
838
|
+
return value.includes(".") && keys.has(value);
|
|
839
|
+
}
|
|
840
|
+
function planModule(file, text, keys, keyList, display) {
|
|
841
|
+
const plan = {
|
|
842
|
+
file,
|
|
843
|
+
text,
|
|
844
|
+
rewrites: [],
|
|
845
|
+
dynamic: [],
|
|
846
|
+
importedT: null,
|
|
847
|
+
program: null,
|
|
848
|
+
diagnostics: []
|
|
849
|
+
};
|
|
850
|
+
let program;
|
|
851
|
+
try {
|
|
852
|
+
program = parseModule(text, langFromId(file), file).program;
|
|
853
|
+
} catch (error) {
|
|
854
|
+
if (!isDiagnosticError(error)) throw error;
|
|
855
|
+
plan.diagnostics.push({
|
|
856
|
+
...error.diagnostic,
|
|
857
|
+
file: display
|
|
858
|
+
});
|
|
859
|
+
return plan;
|
|
860
|
+
}
|
|
861
|
+
plan.program = program;
|
|
862
|
+
new ModulePlanner(plan, keys, keyList).visit(program, null);
|
|
863
|
+
return plan;
|
|
864
|
+
}
|
|
865
|
+
/** The runtime's namespace imports, and the local of its `t` import (set on `plan`). */
|
|
866
|
+
function runtimeImports(program, plan) {
|
|
867
|
+
const namespaces = /* @__PURE__ */ new Set();
|
|
868
|
+
for (const statement of program.body) {
|
|
869
|
+
if (statement.type !== "ImportDeclaration") continue;
|
|
870
|
+
if (statement.source.value !== RUNTIME) continue;
|
|
871
|
+
for (const specifier of statement.specifiers) {
|
|
872
|
+
const local = specifier.local.name;
|
|
873
|
+
if (specifier.type === "ImportNamespaceSpecifier") namespaces.add(local);
|
|
874
|
+
else if (specifier.type === "ImportSpecifier") {
|
|
875
|
+
const imported = specifier.imported;
|
|
876
|
+
if ((imported.name ?? imported.value) === "t" && statement.importKind !== "type") plan.importedT = local;
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
return namespaces;
|
|
881
|
+
}
|
|
882
|
+
/** Whether a callee is `<x>.t`, by a non-computed member. */
|
|
883
|
+
const isMemberT = (callee) => callee.type === "MemberExpression" && callee.computed !== true && callee.property.type === "Identifier" && callee.property.name === "t";
|
|
884
|
+
/** One module's saas `t` call sites and the catalogue keys it names elsewhere. */
|
|
885
|
+
var ModulePlanner = class {
|
|
886
|
+
plan;
|
|
887
|
+
text;
|
|
888
|
+
keys;
|
|
889
|
+
keyList;
|
|
890
|
+
runtimeNamespaces;
|
|
891
|
+
bindings;
|
|
892
|
+
/** Literals a call site or descriptor accounts for: not reported again as keys on their own. */
|
|
893
|
+
handled = /* @__PURE__ */ new Set();
|
|
894
|
+
constructor(plan, keys, keyList) {
|
|
895
|
+
this.plan = plan;
|
|
896
|
+
this.text = plan.text;
|
|
897
|
+
this.keys = keys;
|
|
898
|
+
this.keyList = keyList;
|
|
899
|
+
const program = plan.program;
|
|
900
|
+
this.runtimeNamespaces = runtimeImports(program, plan);
|
|
901
|
+
this.bindings = moduleBindings(program, plan.importedT);
|
|
902
|
+
}
|
|
903
|
+
visit(node, parent) {
|
|
904
|
+
if (node.type === "CallExpression") this.call(node);
|
|
905
|
+
if (node.type === "ObjectExpression") this.descriptorIds(node);
|
|
906
|
+
if (node.type === "Literal") this.literal(node, parent);
|
|
907
|
+
if (node.type === "TemplateLiteral") this.template(node);
|
|
908
|
+
for (const child of children(node)) this.visit(child, node);
|
|
909
|
+
}
|
|
910
|
+
/** `<x>` of a `<x>.t(…)` call, or a local bound to a saas `t`; null for other calls. */
|
|
911
|
+
receiver(callee) {
|
|
912
|
+
if (isMemberT(callee)) {
|
|
913
|
+
const object = callee.object;
|
|
914
|
+
if (object.type === "Identifier" && this.runtimeNamespaces.has(object.name)) return null;
|
|
915
|
+
return this.text.slice(object.start, object.end).replace(/\s+/g, "");
|
|
916
|
+
}
|
|
917
|
+
if (callee.type === "Identifier" && this.bindings.has(callee.name)) return callee.name;
|
|
918
|
+
return null;
|
|
919
|
+
}
|
|
920
|
+
call(node) {
|
|
921
|
+
const callee = unwrapExpression(node.callee);
|
|
922
|
+
const first = node.arguments[0];
|
|
923
|
+
const receiver = this.receiver(callee);
|
|
924
|
+
if (receiver === null || first === void 0 || first.type === "SpreadElement") return;
|
|
925
|
+
const { text, plan } = this;
|
|
926
|
+
const key = staticString(first);
|
|
927
|
+
if (key === null) {
|
|
928
|
+
plan.dynamic.push({
|
|
929
|
+
offset: first.start,
|
|
930
|
+
expression: text.slice(first.start, first.end),
|
|
931
|
+
keys: expressionKeys(first, this.keys, this.keyList, this.handled),
|
|
932
|
+
receiver
|
|
933
|
+
});
|
|
934
|
+
return;
|
|
935
|
+
}
|
|
936
|
+
if (!this.keys.has(key)) return;
|
|
937
|
+
const literal = unwrapExpression(first);
|
|
938
|
+
this.handled.add(literal.start);
|
|
939
|
+
const quote = text[literal.start] === "'" ? "'" : "\"";
|
|
940
|
+
plan.rewrites.push({
|
|
941
|
+
key,
|
|
942
|
+
receiver,
|
|
943
|
+
callee: {
|
|
944
|
+
start: callee.start,
|
|
945
|
+
end: callee.end,
|
|
946
|
+
text: ""
|
|
947
|
+
},
|
|
948
|
+
argument: {
|
|
949
|
+
start: first.start,
|
|
950
|
+
end: first.end,
|
|
951
|
+
text: quote
|
|
952
|
+
},
|
|
953
|
+
original: text.slice(node.start, node.end),
|
|
954
|
+
markup: null
|
|
955
|
+
});
|
|
956
|
+
}
|
|
957
|
+
/** A vi18n descriptor (what a migrated call holds) names its id, not a saas key. */
|
|
958
|
+
descriptorIds(node) {
|
|
959
|
+
const properties = node.properties.filter((p) => p.type === "Property");
|
|
960
|
+
if (!properties.some((p) => propertyKey(p) === "message")) return;
|
|
961
|
+
for (const p of properties) if (propertyKey(p) === "id") this.handled.add(p.value.start);
|
|
962
|
+
}
|
|
963
|
+
/** A string equal to a nested key, outside any call vi18n migrate rewrites. */
|
|
964
|
+
literal(node, parent) {
|
|
965
|
+
if (typeof node.value !== "string" || !isNamedKey(node.value, this.keys)) return;
|
|
966
|
+
if (this.handled.has(node.start) || !isKeyPosition(node, parent)) return;
|
|
967
|
+
this.plan.dynamic.push({
|
|
968
|
+
offset: node.start,
|
|
969
|
+
expression: this.text.slice(node.start, node.end),
|
|
970
|
+
keys: /* @__PURE__ */ new Set([node.value]),
|
|
971
|
+
receiver: null,
|
|
972
|
+
literal: true
|
|
973
|
+
});
|
|
974
|
+
}
|
|
975
|
+
/** A template that can produce catalogue keys, outside any call vi18n migrate rewrites. */
|
|
976
|
+
template(node) {
|
|
977
|
+
if (this.handled.has(node.start) || node.expressions.length === 0) return;
|
|
978
|
+
const found = templateKeys(node.quasis.map((q) => q.value.cooked ?? ""), this.keyList);
|
|
979
|
+
if (found.size === 0) return;
|
|
980
|
+
this.plan.dynamic.push({
|
|
981
|
+
offset: node.start,
|
|
982
|
+
expression: this.text.slice(node.start, node.end),
|
|
983
|
+
keys: found,
|
|
984
|
+
receiver: null
|
|
985
|
+
});
|
|
986
|
+
}
|
|
987
|
+
};
|
|
988
|
+
/**
|
|
989
|
+
* Locals bound to a saas `t` (`const t = i18nFor(l).t`, `const { t } =
|
|
990
|
+
* i18n`), whose calls are call sites like `<x>.t(…)`. Scopes are ignored:
|
|
991
|
+
* a call of an unrelated local of the same name only matters when its
|
|
992
|
+
* first argument is a catalogue key.
|
|
993
|
+
*/
|
|
994
|
+
function moduleBindings(program, importedT) {
|
|
995
|
+
const names = /* @__PURE__ */ new Set();
|
|
996
|
+
const visit = (node) => {
|
|
997
|
+
if (node.type === "VariableDeclarator") {
|
|
998
|
+
const id = node.id;
|
|
999
|
+
const init = isNode(node.init) ? unwrapExpression(node.init) : null;
|
|
1000
|
+
if (id.type === "Identifier" && init !== null && init.type === "MemberExpression" && init.computed !== true && init.property.name === "t") names.add(id.name);
|
|
1001
|
+
else if (id.type === "ObjectPattern") for (const property of id.properties) {
|
|
1002
|
+
if (property.type !== "Property" || propertyKey(property) !== "t") continue;
|
|
1003
|
+
let value = property.value;
|
|
1004
|
+
if (value.type === "AssignmentPattern") value = value.left;
|
|
1005
|
+
if (value.type === "Identifier") names.add(value.name);
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
for (const child of children(node)) visit(child);
|
|
1009
|
+
};
|
|
1010
|
+
visit(program);
|
|
1011
|
+
if (importedT !== null) names.delete(importedT);
|
|
1012
|
+
return names;
|
|
1013
|
+
}
|
|
1014
|
+
/**
|
|
1015
|
+
* Whether a string literal equal to a key is a use of that key: not an
|
|
1016
|
+
* object key, a module specifier or a type.
|
|
1017
|
+
*/
|
|
1018
|
+
function isKeyPosition(node, parent) {
|
|
1019
|
+
if (parent === null) return true;
|
|
1020
|
+
switch (parent.type) {
|
|
1021
|
+
case "ImportDeclaration":
|
|
1022
|
+
case "ExportNamedDeclaration":
|
|
1023
|
+
case "ExportAllDeclaration":
|
|
1024
|
+
case "ImportExpression":
|
|
1025
|
+
case "TSLiteralType":
|
|
1026
|
+
case "TSExternalModuleReference": return false;
|
|
1027
|
+
case "Property": return parent.key !== node || parent.computed === true;
|
|
1028
|
+
default: return true;
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
/** Catalogue keys an expression can evaluate to: its string literals and templates that match keys. */
|
|
1032
|
+
function expressionKeys(node, keys, keyList, handled) {
|
|
1033
|
+
const found = /* @__PURE__ */ new Set();
|
|
1034
|
+
const visit = (n) => {
|
|
1035
|
+
if (n.type === "Literal" && typeof n.value === "string" && keys.has(n.value)) {
|
|
1036
|
+
found.add(n.value);
|
|
1037
|
+
handled.add(n.start);
|
|
1038
|
+
}
|
|
1039
|
+
if (n.type === "TemplateLiteral") {
|
|
1040
|
+
handled.add(n.start);
|
|
1041
|
+
const quasis = n.quasis.map((q) => q.value.cooked ?? "");
|
|
1042
|
+
for (const key of templateKeys(quasis, keyList)) found.add(key);
|
|
1043
|
+
}
|
|
1044
|
+
for (const child of children(n)) visit(child);
|
|
1045
|
+
};
|
|
1046
|
+
visit(node);
|
|
1047
|
+
return found;
|
|
1048
|
+
}
|
|
1049
|
+
/** `.t(` or `?.t(`; the receiver before it is found by walking back. */
|
|
1050
|
+
const MEMBER_T = /\??\.\s*t\s*\(/g;
|
|
1051
|
+
/** Words after which `(` opens an expression, not a call: `return (a).t(…)`. */
|
|
1052
|
+
const KEYWORDS = /* @__PURE__ */ new Set([
|
|
1053
|
+
"return",
|
|
1054
|
+
"typeof",
|
|
1055
|
+
"await",
|
|
1056
|
+
"case",
|
|
1057
|
+
"in",
|
|
1058
|
+
"of",
|
|
1059
|
+
"new",
|
|
1060
|
+
"void",
|
|
1061
|
+
"delete",
|
|
1062
|
+
"yield",
|
|
1063
|
+
"else",
|
|
1064
|
+
"do"
|
|
1065
|
+
]);
|
|
1066
|
+
const ESCAPES = {
|
|
1067
|
+
n: "\n",
|
|
1068
|
+
t: " ",
|
|
1069
|
+
r: "\r",
|
|
1070
|
+
b: "\b",
|
|
1071
|
+
f: "\f",
|
|
1072
|
+
v: "\v",
|
|
1073
|
+
0: "\0"
|
|
1074
|
+
};
|
|
1075
|
+
/** A JS string literal starting at `at` (a quote): its value and end, or null when unterminated. */
|
|
1076
|
+
function readString(text, at) {
|
|
1077
|
+
const quote = text[at];
|
|
1078
|
+
let value = "";
|
|
1079
|
+
for (let i = at + 1; i < text.length; i++) {
|
|
1080
|
+
const c = text[i];
|
|
1081
|
+
if (c === quote) return {
|
|
1082
|
+
value,
|
|
1083
|
+
end: i + 1
|
|
1084
|
+
};
|
|
1085
|
+
if (c === "\n") return null;
|
|
1086
|
+
if (c === "\\") {
|
|
1087
|
+
const next = text[++i];
|
|
1088
|
+
if (next === void 0) return null;
|
|
1089
|
+
if (next === "u" || next === "x") {
|
|
1090
|
+
const hex = next === "x" ? text.slice(i + 1, i + 3) : text.slice(i + 1, i + 5);
|
|
1091
|
+
value += String.fromCharCode(Number.parseInt(hex, 16));
|
|
1092
|
+
i += hex.length;
|
|
1093
|
+
} else if (next === "\n") {} else value += ESCAPES[next] ?? next;
|
|
1094
|
+
continue;
|
|
1095
|
+
}
|
|
1096
|
+
value += c;
|
|
1097
|
+
}
|
|
1098
|
+
return null;
|
|
1099
|
+
}
|
|
1100
|
+
/** A template literal starting at `at`: cooked static parts, and its end. */
|
|
1101
|
+
function readTemplate(text, at) {
|
|
1102
|
+
const quasis = [""];
|
|
1103
|
+
for (let i = at + 1; i < text.length; i++) {
|
|
1104
|
+
const c = text[i];
|
|
1105
|
+
if (c === "`") return {
|
|
1106
|
+
quasis,
|
|
1107
|
+
end: i + 1
|
|
1108
|
+
};
|
|
1109
|
+
if (c === "\\") {
|
|
1110
|
+
quasis[quasis.length - 1] += text[++i] ?? "";
|
|
1111
|
+
continue;
|
|
1112
|
+
}
|
|
1113
|
+
if (c === "$" && text[i + 1] === "{") {
|
|
1114
|
+
const end = skipBalanced(text, i + 1);
|
|
1115
|
+
if (end === null) return null;
|
|
1116
|
+
i = end - 1;
|
|
1117
|
+
quasis.push("");
|
|
1118
|
+
continue;
|
|
1119
|
+
}
|
|
1120
|
+
quasis[quasis.length - 1] += c;
|
|
1121
|
+
}
|
|
1122
|
+
return null;
|
|
1123
|
+
}
|
|
1124
|
+
/** From an opening bracket at `at`, the offset after its matching close (strings and templates skipped). */
|
|
1125
|
+
function skipBalanced(text, at) {
|
|
1126
|
+
let depth = 0;
|
|
1127
|
+
for (let i = at; i < text.length; i++) {
|
|
1128
|
+
const c = text[i];
|
|
1129
|
+
if (c === "(" || c === "[" || c === "{") depth++;
|
|
1130
|
+
else if (c === ")" || c === "]" || c === "}") {
|
|
1131
|
+
depth--;
|
|
1132
|
+
if (depth === 0) return i + 1;
|
|
1133
|
+
} else if (c === "\"" || c === "'") {
|
|
1134
|
+
const s = readString(text, i);
|
|
1135
|
+
if (s === null) return null;
|
|
1136
|
+
i = s.end - 1;
|
|
1137
|
+
} else if (c === "`") {
|
|
1138
|
+
const s = readTemplate(text, i);
|
|
1139
|
+
if (s === null) return null;
|
|
1140
|
+
i = s.end - 1;
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
return null;
|
|
1144
|
+
}
|
|
1145
|
+
/** The end of a call argument starting at `at`: the next `,` or `)` at depth 0. */
|
|
1146
|
+
function argumentEnd(text, at) {
|
|
1147
|
+
for (let i = at; i < text.length; i++) {
|
|
1148
|
+
const c = text[i];
|
|
1149
|
+
if (c === "," || c === ")") return i;
|
|
1150
|
+
if (c === "(" || c === "[" || c === "{") {
|
|
1151
|
+
const end = skipBalanced(text, i);
|
|
1152
|
+
if (end === null) return null;
|
|
1153
|
+
i = end - 1;
|
|
1154
|
+
} else if (c === "\"" || c === "'") {
|
|
1155
|
+
const s = readString(text, i);
|
|
1156
|
+
if (s === null) return null;
|
|
1157
|
+
i = s.end - 1;
|
|
1158
|
+
} else if (c === "`") {
|
|
1159
|
+
const s = readTemplate(text, i);
|
|
1160
|
+
if (s === null) return null;
|
|
1161
|
+
i = s.end - 1;
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
return null;
|
|
1165
|
+
}
|
|
1166
|
+
function skipSpace(text, at) {
|
|
1167
|
+
let i = at;
|
|
1168
|
+
while (i < text.length && /\s/.test(text[i])) i++;
|
|
1169
|
+
return i;
|
|
1170
|
+
}
|
|
1171
|
+
/** From a closing bracket at `at`, the offset of its opening one (strings skipped), or null. */
|
|
1172
|
+
function matchBack(text, at) {
|
|
1173
|
+
let depth = 0;
|
|
1174
|
+
for (let i = at; i >= 0; i--) {
|
|
1175
|
+
const c = text[i];
|
|
1176
|
+
if (c === ")" || c === "]" || c === "}") depth++;
|
|
1177
|
+
else if (c === "(" || c === "[" || c === "{") {
|
|
1178
|
+
depth--;
|
|
1179
|
+
if (depth === 0) return i;
|
|
1180
|
+
} else if (c === "\"" || c === "'" || c === "`") {
|
|
1181
|
+
let j = i - 1;
|
|
1182
|
+
while (j >= 0 && !(text[j] === c && text[j - 1] !== "\\")) j--;
|
|
1183
|
+
if (j < 0) return null;
|
|
1184
|
+
i = j;
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
return null;
|
|
1188
|
+
}
|
|
1189
|
+
/**
|
|
1190
|
+
* The start of the receiver ending at `end` (exclusive): identifiers joined
|
|
1191
|
+
* by `.`/`?.`, with calls and indexes (`i18nFor(locale).t`, `a[0].t`).
|
|
1192
|
+
* Null when there is none (`).t(` after an operator, a number).
|
|
1193
|
+
*/
|
|
1194
|
+
function receiverStart(text, end) {
|
|
1195
|
+
const back = (j) => {
|
|
1196
|
+
let k = j;
|
|
1197
|
+
while (k > 0 && /\s/.test(text[k - 1])) k--;
|
|
1198
|
+
return k;
|
|
1199
|
+
};
|
|
1200
|
+
let j = back(end);
|
|
1201
|
+
let start = null;
|
|
1202
|
+
for (;;) {
|
|
1203
|
+
const c = text[j - 1];
|
|
1204
|
+
if (c === ")" || c === "]") {
|
|
1205
|
+
const open = matchBack(text, j - 1);
|
|
1206
|
+
if (open === null) return null;
|
|
1207
|
+
j = open;
|
|
1208
|
+
start = j;
|
|
1209
|
+
const before = text[j - 1];
|
|
1210
|
+
if (before !== void 0 && /[\w$)\]]/.test(before)) {
|
|
1211
|
+
let k = j;
|
|
1212
|
+
while (k > 0 && /[\w$]/.test(text[k - 1])) k--;
|
|
1213
|
+
if (KEYWORDS.has(text.slice(k, j))) return start;
|
|
1214
|
+
continue;
|
|
1215
|
+
}
|
|
1216
|
+
if (before === "." && text[j - 2] === "?") {
|
|
1217
|
+
j -= 2;
|
|
1218
|
+
continue;
|
|
1219
|
+
}
|
|
1220
|
+
return start;
|
|
1221
|
+
}
|
|
1222
|
+
if (c !== void 0 && /[\w$]/.test(c)) {
|
|
1223
|
+
let k = j;
|
|
1224
|
+
while (k > 0 && /[\w$]/.test(text[k - 1])) k--;
|
|
1225
|
+
if (/[0-9]/.test(text[k])) return null;
|
|
1226
|
+
start = k;
|
|
1227
|
+
const dot = back(k);
|
|
1228
|
+
if (text[dot - 1] !== ".") return start;
|
|
1229
|
+
j = text[dot - 2] === "?" ? dot - 2 : dot - 1;
|
|
1230
|
+
j = back(j);
|
|
1231
|
+
continue;
|
|
1232
|
+
}
|
|
1233
|
+
return start;
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
/**
|
|
1237
|
+
* Locals bound to a saas `t` in a component's script or front matter
|
|
1238
|
+
* (`const t = i18nFor(locale).t`, `const { t } = i18n`).
|
|
1239
|
+
*/
|
|
1240
|
+
function componentBindings(text, importedT) {
|
|
1241
|
+
const names = /* @__PURE__ */ new Set();
|
|
1242
|
+
const declaration = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*/g;
|
|
1243
|
+
for (let match = declaration.exec(text); match !== null; match = declaration.exec(text)) {
|
|
1244
|
+
const at = match.index + match[0].length;
|
|
1245
|
+
let end = at;
|
|
1246
|
+
while (end < text.length && !/[;\n,]/.test(text[end])) {
|
|
1247
|
+
const c = text[end];
|
|
1248
|
+
if (c === "(" || c === "[" || c === "{") {
|
|
1249
|
+
const close = skipBalanced(text, end);
|
|
1250
|
+
if (close === null) break;
|
|
1251
|
+
end = close;
|
|
1252
|
+
} else if (c === "\"" || c === "'") {
|
|
1253
|
+
const literal = readString(text, end);
|
|
1254
|
+
if (literal === null) break;
|
|
1255
|
+
end = literal.end;
|
|
1256
|
+
} else end++;
|
|
1257
|
+
}
|
|
1258
|
+
if (/\??\.\s*t\s*$/.test(text.slice(at, end).trimEnd())) names.add(match[1]);
|
|
1259
|
+
}
|
|
1260
|
+
const destructure = /\b(?:const|let|var)\s*\{([^}]*)\}\s*=/g;
|
|
1261
|
+
for (let match = destructure.exec(text); match !== null; match = destructure.exec(text)) for (const part of match[1].split(",")) {
|
|
1262
|
+
const m = /^\s*t\s*(?::\s*([A-Za-z_$][\w$]*))?\s*(?:=.*)?$/.exec(part);
|
|
1263
|
+
if (m !== null) names.add(m[1] ?? "t");
|
|
1264
|
+
}
|
|
1265
|
+
if (importedT !== null) names.delete(importedT);
|
|
1266
|
+
return names;
|
|
1267
|
+
}
|
|
1268
|
+
/**
|
|
1269
|
+
* A Vue SFC's quoted attribute values, outside `<script>` and `<style>`
|
|
1270
|
+
* blocks, and the contents of those blocks (`code`): what lies in neither is
|
|
1271
|
+
* template text.
|
|
1272
|
+
*/
|
|
1273
|
+
function vueRegions(text) {
|
|
1274
|
+
const values = [];
|
|
1275
|
+
const code = [];
|
|
1276
|
+
let i = 0;
|
|
1277
|
+
while (i < text.length) {
|
|
1278
|
+
if (text.startsWith("<!--", i)) {
|
|
1279
|
+
const end = text.indexOf("-->", i + 4);
|
|
1280
|
+
i = end === -1 ? text.length : end + 3;
|
|
1281
|
+
continue;
|
|
1282
|
+
}
|
|
1283
|
+
if (text[i] !== "<" || !/[A-Za-z]/.test(text[i + 1] ?? "")) {
|
|
1284
|
+
i++;
|
|
1285
|
+
continue;
|
|
1286
|
+
}
|
|
1287
|
+
const name = /^<([A-Za-z][\w-]*)/.exec(text.slice(i, i + 64))?.[1]?.toLowerCase() ?? "";
|
|
1288
|
+
i += name.length + 1;
|
|
1289
|
+
while (i < text.length && text[i] !== ">") {
|
|
1290
|
+
const c = text[i];
|
|
1291
|
+
if (c === "\"" || c === "'") {
|
|
1292
|
+
const end = text.indexOf(c, i + 1);
|
|
1293
|
+
if (end === -1) return {
|
|
1294
|
+
attributes: values,
|
|
1295
|
+
code
|
|
1296
|
+
};
|
|
1297
|
+
if (/=\s*$/.test(text.slice(Math.max(0, i - 16), i))) values.push({
|
|
1298
|
+
start: i + 1,
|
|
1299
|
+
end,
|
|
1300
|
+
quote: c
|
|
1301
|
+
});
|
|
1302
|
+
i = end + 1;
|
|
1303
|
+
} else i++;
|
|
1304
|
+
}
|
|
1305
|
+
i++;
|
|
1306
|
+
if (name === "script" || name === "style") {
|
|
1307
|
+
const close = text.indexOf(`</${name}`, i);
|
|
1308
|
+
const end = close === -1 ? text.length : close;
|
|
1309
|
+
code.push({
|
|
1310
|
+
start: i,
|
|
1311
|
+
end
|
|
1312
|
+
});
|
|
1313
|
+
i = end;
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
return {
|
|
1317
|
+
attributes: values,
|
|
1318
|
+
code
|
|
1319
|
+
};
|
|
1320
|
+
}
|
|
1321
|
+
function planComponent(file, text, keys, keyList) {
|
|
1322
|
+
const plan = {
|
|
1323
|
+
file,
|
|
1324
|
+
text,
|
|
1325
|
+
rewrites: [],
|
|
1326
|
+
dynamic: [],
|
|
1327
|
+
importedT: componentImportedT(text),
|
|
1328
|
+
program: null,
|
|
1329
|
+
diagnostics: []
|
|
1330
|
+
};
|
|
1331
|
+
const planner = new ComponentPlanner({
|
|
1332
|
+
plan,
|
|
1333
|
+
text,
|
|
1334
|
+
keys,
|
|
1335
|
+
keyList,
|
|
1336
|
+
templatesSeen: /* @__PURE__ */ new Set(),
|
|
1337
|
+
covered: []
|
|
1338
|
+
}, extname(file) === ".vue" ? vueRegions(text) : null);
|
|
1339
|
+
planner.calls();
|
|
1340
|
+
planner.templates();
|
|
1341
|
+
planner.strayKeys();
|
|
1342
|
+
plan.dynamic.sort((a, b) => a.offset - b.offset);
|
|
1343
|
+
plan.rewrites.sort((a, b) => a.callee.start - b.callee.start);
|
|
1344
|
+
return plan;
|
|
1345
|
+
}
|
|
1346
|
+
/** The local of a component's existing `t` import from the runtime, or null. */
|
|
1347
|
+
function componentImportedT(text) {
|
|
1348
|
+
const existing = new RegExp(String.raw`import\s*\{([^}]*)\}\s*from\s*["']${RUNTIME.replace("/", "\\/")}["']`).exec(text);
|
|
1349
|
+
let local = null;
|
|
1350
|
+
for (const specifier of (existing?.[1] ?? "").split(",")) {
|
|
1351
|
+
const m = /^\s*t(?:\s+as\s+([A-Za-z_$][\w$]*))?\s*$/.exec(specifier);
|
|
1352
|
+
if (m !== null) local = m[1] ?? "t";
|
|
1353
|
+
}
|
|
1354
|
+
return existing === null ? null : local;
|
|
1355
|
+
}
|
|
1356
|
+
/** A component's call sites, found lexically: `<x>.t(…)`, calls of locals bound to `t`, and stray keys. */
|
|
1357
|
+
var ComponentPlanner = class {
|
|
1358
|
+
scan;
|
|
1359
|
+
regions;
|
|
1360
|
+
constructor(scan, regions) {
|
|
1361
|
+
this.scan = scan;
|
|
1362
|
+
this.regions = regions;
|
|
1363
|
+
}
|
|
1364
|
+
markupAt(offset) {
|
|
1365
|
+
const { regions } = this;
|
|
1366
|
+
if (regions === null) return null;
|
|
1367
|
+
if (regions.code.some((r) => r.start <= offset && offset < r.end)) return null;
|
|
1368
|
+
return { quote: regions.attributes.find((a) => a.start <= offset && offset < a.end)?.quote ?? null };
|
|
1369
|
+
}
|
|
1370
|
+
/** `<x>.t(…)` calls, then calls of locals bound to a saas `t`. */
|
|
1371
|
+
calls() {
|
|
1372
|
+
const { text, plan } = this.scan;
|
|
1373
|
+
MEMBER_T.lastIndex = 0;
|
|
1374
|
+
for (let match = MEMBER_T.exec(text); match !== null; match = MEMBER_T.exec(text)) {
|
|
1375
|
+
const start = receiverStart(text, match.index);
|
|
1376
|
+
if (start === null) continue;
|
|
1377
|
+
const receiver = text.slice(start, match.index).replace(/\s+/g, "");
|
|
1378
|
+
const open = match.index + match[0].length;
|
|
1379
|
+
const calleeEnd = text.lastIndexOf("t", open - 1) + 1;
|
|
1380
|
+
this.call({
|
|
1381
|
+
start,
|
|
1382
|
+
end: calleeEnd
|
|
1383
|
+
}, open, receiver);
|
|
1384
|
+
}
|
|
1385
|
+
for (const name of componentBindings(text, plan.importedT)) {
|
|
1386
|
+
const pattern = new RegExp(String.raw`(?<![\w$.])${name.replace(/\$/g, "\\$")}\s*\(`, "g");
|
|
1387
|
+
for (let match = pattern.exec(text); match !== null; match = pattern.exec(text)) {
|
|
1388
|
+
if (/\bfunction\s*$/.test(text.slice(Math.max(0, match.index - 12), match.index))) continue;
|
|
1389
|
+
const callee = {
|
|
1390
|
+
start: match.index,
|
|
1391
|
+
end: match.index + name.length
|
|
1392
|
+
};
|
|
1393
|
+
this.call(callee, match.index + match[0].length, name);
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
/** A call whose `(` ends at `open`: rewritten for a literal key, reported for a computed one. */
|
|
1398
|
+
call(callee, open, receiver) {
|
|
1399
|
+
const { text, keys, templatesSeen } = this.scan;
|
|
1400
|
+
const at = skipSpace(text, open);
|
|
1401
|
+
const c = text[at];
|
|
1402
|
+
if (c === ")") return;
|
|
1403
|
+
if (c === "\"" || c === "'") return this.stringCall(callee, open, receiver);
|
|
1404
|
+
const end = argumentEnd(text, at);
|
|
1405
|
+
if (end === null) return;
|
|
1406
|
+
const template = c === "`" ? readTemplate(text, at) : null;
|
|
1407
|
+
if (template !== null && template.quasis.length === 1 && skipSpace(text, template.end) === end) {
|
|
1408
|
+
const key = template.quasis[0];
|
|
1409
|
+
templatesSeen.add(at);
|
|
1410
|
+
if (keys.has(key)) this.rewrite(callee, open, {
|
|
1411
|
+
key,
|
|
1412
|
+
at,
|
|
1413
|
+
end: template.end,
|
|
1414
|
+
quote: "\""
|
|
1415
|
+
}, receiver);
|
|
1416
|
+
return;
|
|
1417
|
+
}
|
|
1418
|
+
pushDynamic(this.scan, at, end, receiver);
|
|
1419
|
+
}
|
|
1420
|
+
/** A call whose first argument is a string: a key alone, or a computed one (`i18n.t("a" + x)`). */
|
|
1421
|
+
stringCall(callee, open, receiver) {
|
|
1422
|
+
const { text, keys } = this.scan;
|
|
1423
|
+
const at = skipSpace(text, open);
|
|
1424
|
+
const literal = readString(text, at);
|
|
1425
|
+
if (literal === null) return;
|
|
1426
|
+
const after = skipSpace(text, literal.end);
|
|
1427
|
+
if (text[after] !== "," && text[after] !== ")") {
|
|
1428
|
+
const end = argumentEnd(text, at);
|
|
1429
|
+
if (end !== null) pushDynamic(this.scan, at, end, receiver);
|
|
1430
|
+
return;
|
|
1431
|
+
}
|
|
1432
|
+
if (!keys.has(literal.value)) return;
|
|
1433
|
+
const argument = {
|
|
1434
|
+
key: literal.value,
|
|
1435
|
+
at,
|
|
1436
|
+
end: literal.end,
|
|
1437
|
+
quote: text[at]
|
|
1438
|
+
};
|
|
1439
|
+
this.rewrite(callee, open, argument, receiver);
|
|
1440
|
+
}
|
|
1441
|
+
rewrite(callee, open, { key, at, end, quote }, receiver) {
|
|
1442
|
+
const { text, plan, covered } = this.scan;
|
|
1443
|
+
const close = skipBalanced(text, open - 1) ?? end + 1;
|
|
1444
|
+
covered.push([at, end]);
|
|
1445
|
+
plan.rewrites.push({
|
|
1446
|
+
key,
|
|
1447
|
+
receiver,
|
|
1448
|
+
callee: {
|
|
1449
|
+
...callee,
|
|
1450
|
+
text: ""
|
|
1451
|
+
},
|
|
1452
|
+
argument: {
|
|
1453
|
+
start: at,
|
|
1454
|
+
end,
|
|
1455
|
+
text: quote
|
|
1456
|
+
},
|
|
1457
|
+
original: text.slice(callee.start, close),
|
|
1458
|
+
markup: this.markupAt(at)
|
|
1459
|
+
});
|
|
1460
|
+
}
|
|
1461
|
+
/** Templates elsewhere (`labelFor(i18n, \`feature.${k}.title\`)`). */
|
|
1462
|
+
templates() {
|
|
1463
|
+
const { text, plan, keyList, templatesSeen } = this.scan;
|
|
1464
|
+
for (let at = text.indexOf("`"); at !== -1; at = text.indexOf("`", at + 1)) {
|
|
1465
|
+
if (templatesSeen.has(at)) continue;
|
|
1466
|
+
const template = readTemplate(text, at);
|
|
1467
|
+
if (template === null) continue;
|
|
1468
|
+
const found = template.quasis.length > 1 ? templateKeys(template.quasis, keyList) : null;
|
|
1469
|
+
if (found !== null && found.size > 0) {
|
|
1470
|
+
const expression = text.slice(at, template.end);
|
|
1471
|
+
plan.dynamic.push({
|
|
1472
|
+
offset: at,
|
|
1473
|
+
expression,
|
|
1474
|
+
keys: found,
|
|
1475
|
+
receiver: null
|
|
1476
|
+
});
|
|
1477
|
+
}
|
|
1478
|
+
at = template.end - 1;
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
/** Keys spelled anywhere else (`{ href: "/", label: "nav.home" }`). */
|
|
1482
|
+
strayKeys() {
|
|
1483
|
+
const { text, plan, keys, keyList, covered } = this.scan;
|
|
1484
|
+
const inCovered = (offset) => covered.some(([a, b]) => a <= offset && offset < b);
|
|
1485
|
+
for (const key of keyList.filter((k) => isNamedKey(k, keys))) for (const quote of [
|
|
1486
|
+
"\"",
|
|
1487
|
+
"'",
|
|
1488
|
+
"`"
|
|
1489
|
+
]) {
|
|
1490
|
+
const needle = quote + key + quote;
|
|
1491
|
+
for (let at = text.indexOf(needle); at !== -1; at = text.indexOf(needle, at + 1)) {
|
|
1492
|
+
if (inCovered(at) || /\bid\s*:\s*$/.test(text.slice(Math.max(0, at - 16), at))) continue;
|
|
1493
|
+
const site = {
|
|
1494
|
+
offset: at,
|
|
1495
|
+
expression: needle,
|
|
1496
|
+
keys: /* @__PURE__ */ new Set([key]),
|
|
1497
|
+
receiver: null
|
|
1498
|
+
};
|
|
1499
|
+
plan.dynamic.push({
|
|
1500
|
+
...site,
|
|
1501
|
+
literal: true
|
|
1502
|
+
});
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
};
|
|
1507
|
+
function pushDynamic(scan, start, end, receiver) {
|
|
1508
|
+
const { plan, text, keys, keyList, templatesSeen, covered } = scan;
|
|
1509
|
+
covered.push([start, end]);
|
|
1510
|
+
const expression = text.slice(start, end).trim();
|
|
1511
|
+
const found = /* @__PURE__ */ new Set();
|
|
1512
|
+
for (let i = start; i < end; i++) {
|
|
1513
|
+
const c = text[i];
|
|
1514
|
+
if (c === "\"" || c === "'") {
|
|
1515
|
+
const s = readString(text, i);
|
|
1516
|
+
if (s === null) break;
|
|
1517
|
+
if (keys.has(s.value)) found.add(s.value);
|
|
1518
|
+
i = s.end - 1;
|
|
1519
|
+
} else if (c === "`") {
|
|
1520
|
+
const s = readTemplate(text, i);
|
|
1521
|
+
if (s === null) break;
|
|
1522
|
+
templatesSeen.add(i);
|
|
1523
|
+
for (const key of templateKeys(s.quasis, keyList)) found.add(key);
|
|
1524
|
+
i = s.end - 1;
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
plan.dynamic.push({
|
|
1528
|
+
offset: start,
|
|
1529
|
+
expression,
|
|
1530
|
+
keys: found,
|
|
1531
|
+
receiver
|
|
1532
|
+
});
|
|
1533
|
+
}
|
|
1534
|
+
/**
|
|
1535
|
+
* `{ id, message }` in the quote style of the key it replaces, encoded for
|
|
1536
|
+
* where it lands. A Vue template decodes entities in attribute values and in
|
|
1537
|
+
* `{{ }}` before compiling the expression, so catalogue text there is written
|
|
1538
|
+
* as markup: `&` as `&` (else `'` in a message would end its string
|
|
1539
|
+
* literal and run the rest as code), an attribute value's own quote as an
|
|
1540
|
+
* entity, and in text the `}` of a `}}` as `}`, since `}}` would end the
|
|
1541
|
+
* interpolation inside the message (an ICU plural ends with one).
|
|
1542
|
+
*/
|
|
1543
|
+
function descriptor(info, quote, markup = null) {
|
|
1544
|
+
const style = quote === "\"" ? "\"" : "'";
|
|
1545
|
+
return encodeMarkup(`{ id: ${jsString(info.id, style)}, message: ${jsString(info.canonical, style)} }`, markup);
|
|
1546
|
+
}
|
|
1547
|
+
/** Code for where it lands in a Vue template (see {@link descriptor}); unchanged in code. */
|
|
1548
|
+
function encodeMarkup(code, markup) {
|
|
1549
|
+
if (markup === null) return code;
|
|
1550
|
+
const html = code.replaceAll("&", "&");
|
|
1551
|
+
if (markup.quote === null) return html.replaceAll("}}", "}}");
|
|
1552
|
+
return html.replaceAll(markup.quote, markup.quote === "\"" ? """ : "'");
|
|
1553
|
+
}
|
|
1554
|
+
/** A local name for `t` the file does not already use. */
|
|
1555
|
+
function localName(text) {
|
|
1556
|
+
for (const name of [
|
|
1557
|
+
"t",
|
|
1558
|
+
"vt",
|
|
1559
|
+
"vi18nT"
|
|
1560
|
+
]) if (!new RegExp(String.raw`(?<![.\w$])${name}(?![\w$])`).test(text)) return name;
|
|
1561
|
+
return "vi18nT_";
|
|
1562
|
+
}
|
|
1563
|
+
function importLine(local) {
|
|
1564
|
+
return local === "t" ? `import { t } from "${RUNTIME}";` : `import { t as ${local} } from "${RUNTIME}";`;
|
|
1565
|
+
}
|
|
1566
|
+
/** Where the import goes, per file kind, creating the script block or front matter a component lacks. */
|
|
1567
|
+
function importEdit(file, text, local, program) {
|
|
1568
|
+
return importLineEdit(file, text, importLine(local), program);
|
|
1569
|
+
}
|
|
1570
|
+
/** {@link importEdit} for any import line (several names, a type import). */
|
|
1571
|
+
function importLineEdit(file, text, line, program) {
|
|
1572
|
+
const ext = extname(file);
|
|
1573
|
+
if (program !== null) return moduleImportEdit(text, line, program);
|
|
1574
|
+
if (ext === ".astro") {
|
|
1575
|
+
const fence = /^\s*---[ \t]*\r?\n/.exec(text);
|
|
1576
|
+
if (fence !== null) return {
|
|
1577
|
+
start: fence[0].length,
|
|
1578
|
+
end: fence[0].length,
|
|
1579
|
+
text: line + "\n"
|
|
1580
|
+
};
|
|
1581
|
+
return {
|
|
1582
|
+
start: 0,
|
|
1583
|
+
end: 0,
|
|
1584
|
+
text: `---\n${line}\n---\n`
|
|
1585
|
+
};
|
|
1586
|
+
}
|
|
1587
|
+
if (ext === ".vue" || ext === ".svelte") return scriptImportEdit(ext, text, line);
|
|
1588
|
+
const front = /^---\r?\n[\s\S]*?\r?\n---[ \t]*\r?\n/.exec(text);
|
|
1589
|
+
const at = front === null ? 0 : front[0].length;
|
|
1590
|
+
return {
|
|
1591
|
+
start: at,
|
|
1592
|
+
end: at,
|
|
1593
|
+
text: line + "\n\n"
|
|
1594
|
+
};
|
|
1595
|
+
}
|
|
1596
|
+
/** In a module: after the last import, else after a hashbang and the directive prologue. */
|
|
1597
|
+
function moduleImportEdit(text, line, program) {
|
|
1598
|
+
let end = -1;
|
|
1599
|
+
for (const statement of program.body) if (statement.type === "ImportDeclaration") end = statement.end;
|
|
1600
|
+
if (end !== -1) return {
|
|
1601
|
+
start: end,
|
|
1602
|
+
end,
|
|
1603
|
+
text: "\n" + line
|
|
1604
|
+
};
|
|
1605
|
+
let at = 0;
|
|
1606
|
+
if (text.startsWith("#!")) at = text.indexOf("\n") + 1;
|
|
1607
|
+
for (const statement of program.body) {
|
|
1608
|
+
if (statement.type !== "ExpressionStatement" || typeof statement.directive !== "string") break;
|
|
1609
|
+
at = text.indexOf("\n", statement.end) + 1 || statement.end;
|
|
1610
|
+
}
|
|
1611
|
+
return {
|
|
1612
|
+
start: at,
|
|
1613
|
+
end: at,
|
|
1614
|
+
text: line + "\n"
|
|
1615
|
+
};
|
|
1616
|
+
}
|
|
1617
|
+
/** In a `.vue` or `.svelte` component: its instance script, created when it has none. */
|
|
1618
|
+
function scriptImportEdit(ext, text, line) {
|
|
1619
|
+
const usable = [...text.matchAll(/<script\b([^>]*)>/g)].filter((m) => {
|
|
1620
|
+
const attrs = m[1];
|
|
1621
|
+
if (/\bsrc\s*=/.test(attrs)) return false;
|
|
1622
|
+
if (ext === ".svelte") return !/\bcontext\s*=\s*["']module["']|\bmodule\b/.test(attrs);
|
|
1623
|
+
return true;
|
|
1624
|
+
});
|
|
1625
|
+
const tag = ext === ".vue" ? usable.find((m) => /\bsetup\b/.test(m[1])) : usable[0];
|
|
1626
|
+
if (tag !== void 0) {
|
|
1627
|
+
const at = tag.index + tag[0].length;
|
|
1628
|
+
return {
|
|
1629
|
+
start: at,
|
|
1630
|
+
end: at,
|
|
1631
|
+
text: "\n" + line
|
|
1632
|
+
};
|
|
1633
|
+
}
|
|
1634
|
+
const options = ext === ".vue" ? usable[0] : void 0;
|
|
1635
|
+
const close = options === void 0 ? -1 : text.indexOf("<\/script>", options.index);
|
|
1636
|
+
if (options !== void 0 && close !== -1) {
|
|
1637
|
+
const lang = /\blang\s*=\s*["']([^"']+)["']/.exec(options[1])?.[1];
|
|
1638
|
+
const at = close + 9;
|
|
1639
|
+
return {
|
|
1640
|
+
start: at,
|
|
1641
|
+
end: at,
|
|
1642
|
+
text: `\n${lang === void 0 ? "<script setup>" : `<script setup lang="${lang}">`}\n${line}\n<\/script>`
|
|
1643
|
+
};
|
|
1644
|
+
}
|
|
1645
|
+
return {
|
|
1646
|
+
start: 0,
|
|
1647
|
+
end: 0,
|
|
1648
|
+
text: `${ext === ".vue" ? "<script setup>" : "<script>"}\n${line}\n<\/script>\n\n`
|
|
1649
|
+
};
|
|
1650
|
+
}
|
|
1651
|
+
function applyEdits(text, edits) {
|
|
1652
|
+
const sorted = [...edits].sort((a, b) => b.start - a.start || b.end - a.end);
|
|
1653
|
+
let out = text;
|
|
1654
|
+
for (const edit of sorted) out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
|
|
1655
|
+
return out;
|
|
1656
|
+
}
|
|
1657
|
+
function positionOf(text, offset) {
|
|
1658
|
+
let line = 1;
|
|
1659
|
+
let lineStart = 0;
|
|
1660
|
+
for (let i = text.indexOf("\n"); i !== -1 && i < offset; i = text.indexOf("\n", i + 1)) {
|
|
1661
|
+
line++;
|
|
1662
|
+
lineStart = i + 1;
|
|
1663
|
+
}
|
|
1664
|
+
return {
|
|
1665
|
+
line,
|
|
1666
|
+
column: offset - lineStart + 1
|
|
1667
|
+
};
|
|
1668
|
+
}
|
|
1669
|
+
async function migrate(ctx, flags) {
|
|
1670
|
+
if (flags.from !== "saas-i18n") {
|
|
1671
|
+
const { migrateLibrary } = await import("./engine-ecRD8-IE.js");
|
|
1672
|
+
return migrateLibrary(ctx, {
|
|
1673
|
+
...flags,
|
|
1674
|
+
from: flags.from
|
|
1675
|
+
});
|
|
1676
|
+
}
|
|
1677
|
+
return new SaasRun(ctx, flags, await loadProject(ctx)).run();
|
|
1678
|
+
}
|
|
1679
|
+
/**
|
|
1680
|
+
* The last step of every migration: plans the catalogs, reports, writes the
|
|
1681
|
+
* files and catalogs when asked and nothing failed, and prints the plan.
|
|
1682
|
+
*/
|
|
1683
|
+
async function finishMigration(ctx, project, write, { diagnostics, data, outputs, messages, translations, notes }, print) {
|
|
1684
|
+
const { config } = project;
|
|
1685
|
+
const rel = (file) => rootRelative(config.root, file);
|
|
1686
|
+
const loaded = await loadCatalogs(project);
|
|
1687
|
+
diagnostics.push(...loaded.diagnostics.filter((d) => d.code === "catalog-parse" && d.severity === "error"));
|
|
1688
|
+
const catalogPlans = planCatalogs(project, loaded.set, messages, translations, notes);
|
|
1689
|
+
diagnostics.push(...catalogPlans.diagnostics);
|
|
1690
|
+
for (const [locale, count] of catalogPlans.counts) if (locale !== config.sourceLocale) data.entries[locale] = count;
|
|
1691
|
+
ctx.out.report(diagnostics);
|
|
1692
|
+
const failed = hasErrors(diagnostics);
|
|
1693
|
+
data.files = [...outputs.map((o) => rel(o.file)), ...catalogPlans.changed.map((locale) => rel(catalogPath(config, locale)))];
|
|
1694
|
+
if (write && !failed) {
|
|
1695
|
+
for (const output of outputs) await writeFileAtomic(output.file, output.text);
|
|
1696
|
+
for (const locale of catalogPlans.changed) {
|
|
1697
|
+
const texts = {
|
|
1698
|
+
translations: translations.get(locale),
|
|
1699
|
+
notes: notes?.get(locale)
|
|
1700
|
+
};
|
|
1701
|
+
await updateCatalogFile(catalogPath(config, locale), loaded.set.get(locale)?.hash ?? null, (current) => plannedCatalog(project, locale, {
|
|
1702
|
+
current,
|
|
1703
|
+
sourceCatalog: catalogPlans.sourceCatalog
|
|
1704
|
+
}, messages, texts).catalog, {
|
|
1705
|
+
locale,
|
|
1706
|
+
layout: project.layout,
|
|
1707
|
+
isSourceLocale: locale === config.sourceLocale,
|
|
1708
|
+
version: VERSION
|
|
1709
|
+
});
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
1712
|
+
print(ctx, data, failed);
|
|
1713
|
+
return {
|
|
1714
|
+
exitCode: failed ? EXIT.failure : EXIT.ok,
|
|
1715
|
+
data
|
|
1716
|
+
};
|
|
1717
|
+
}
|
|
1718
|
+
/** Whether a file may hold saas-i18n call sites: a `.t`, a template or a nested key in quotes. */
|
|
1719
|
+
function mayUseSaas(text, keyList) {
|
|
1720
|
+
return /\.\s*t\b|\{[^}]*\bt\b[^}]*\}\s*=/.test(text) || text.includes("`") || keyList.some((key) => key.includes(".") && text.includes(key));
|
|
1721
|
+
}
|
|
1722
|
+
/** One `vi18n migrate --from saas-i18n` run. */
|
|
1723
|
+
var SaasRun = class {
|
|
1724
|
+
ctx;
|
|
1725
|
+
flags;
|
|
1726
|
+
project;
|
|
1727
|
+
config;
|
|
1728
|
+
diagnostics = [];
|
|
1729
|
+
data;
|
|
1730
|
+
keys = /* @__PURE__ */ new Map();
|
|
1731
|
+
/** Each used key, and the files that use it. */
|
|
1732
|
+
used = /* @__PURE__ */ new Map();
|
|
1733
|
+
dynamicKeys = /* @__PURE__ */ new Set();
|
|
1734
|
+
constructor(ctx, flags, project) {
|
|
1735
|
+
this.ctx = ctx;
|
|
1736
|
+
this.flags = flags;
|
|
1737
|
+
this.project = project;
|
|
1738
|
+
this.config = project.config;
|
|
1739
|
+
this.data = {
|
|
1740
|
+
from: flags.from,
|
|
1741
|
+
write: flags.write,
|
|
1742
|
+
files: [],
|
|
1743
|
+
rewritten: 0,
|
|
1744
|
+
renamed: [],
|
|
1745
|
+
manualIds: [],
|
|
1746
|
+
messagesModule: null,
|
|
1747
|
+
entries: {},
|
|
1748
|
+
edits: [],
|
|
1749
|
+
unused: []
|
|
1750
|
+
};
|
|
1751
|
+
}
|
|
1752
|
+
rel(file) {
|
|
1753
|
+
return rootRelative(this.config.root, file);
|
|
1754
|
+
}
|
|
1755
|
+
async run() {
|
|
1756
|
+
const catalogues = await this.catalogues();
|
|
1757
|
+
const source = catalogues[0];
|
|
1758
|
+
this.readKeys(source);
|
|
1759
|
+
const keyList = [...this.keys.keys()];
|
|
1760
|
+
const messagesPath = join(dirname(source.file), MESSAGES_MODULE);
|
|
1761
|
+
const plans = await this.planFiles(/* @__PURE__ */ new Set([messagesPath, ...catalogues.map((c) => c.file)]), keyList);
|
|
1762
|
+
this.collectUses(plans, messagesPath);
|
|
1763
|
+
for (const key of keyList) if (!this.used.has(key)) this.data.unused.push(key);
|
|
1764
|
+
this.diagnostics.push(...datePlaceholders(source, this.keys, this.used, plans, (file) => this.rel(file)));
|
|
1765
|
+
const outputs = this.render(plans, messagesPath);
|
|
1766
|
+
return finishMigration(this.ctx, this.project, this.flags.write, {
|
|
1767
|
+
diagnostics: this.diagnostics,
|
|
1768
|
+
data: this.data,
|
|
1769
|
+
outputs,
|
|
1770
|
+
messages: this.messages(),
|
|
1771
|
+
translations: this.translations(catalogues.slice(1))
|
|
1772
|
+
}, printPlan);
|
|
1773
|
+
}
|
|
1774
|
+
/** The `--catalog` files, read; the first is the source locale's, the rest other configured locales. */
|
|
1775
|
+
async catalogues() {
|
|
1776
|
+
const { config, flags } = this;
|
|
1777
|
+
const [first, ...others] = flags.catalogs;
|
|
1778
|
+
if (first.locale !== null && first.locale !== config.sourceLocale) throw usageError(`the first --catalog is the source locale's (${config.sourceLocale}), not ${first.locale}`);
|
|
1779
|
+
for (const other of others) if (other.locale === config.sourceLocale || !config.locales.includes(other.locale)) throw usageError(`--catalog ${other.locale}=${other.file}: ${other.locale} must be a configured locale other than the source (${config.locales.join(", ")})`);
|
|
1780
|
+
const catalogues = [];
|
|
1781
|
+
for (const entry of flags.catalogs) {
|
|
1782
|
+
const file = resolve(this.ctx.global.cwd, entry.file);
|
|
1783
|
+
let text;
|
|
1784
|
+
try {
|
|
1785
|
+
text = await readFile(file, "utf8");
|
|
1786
|
+
} catch (error) {
|
|
1787
|
+
throw usageError(`--catalog ${entry.file}: ${errorMessage(error)}`);
|
|
1788
|
+
}
|
|
1789
|
+
const read = readCatalogue(text, file, entry.locale ?? config.sourceLocale, this.rel(file));
|
|
1790
|
+
this.diagnostics.push(...read.diagnostics);
|
|
1791
|
+
catalogues.push(read.catalogue);
|
|
1792
|
+
}
|
|
1793
|
+
return catalogues;
|
|
1794
|
+
}
|
|
1795
|
+
/** The source catalogue's keys with their ids and ICU text. */
|
|
1796
|
+
readKeys(source) {
|
|
1797
|
+
const takenIds = /* @__PURE__ */ new Map();
|
|
1798
|
+
for (const key of source.texts.keys()) if (isValidManualId(key)) takenIds.set(key, key);
|
|
1799
|
+
for (const [key, text] of source.texts) {
|
|
1800
|
+
const canonical = this.canonical(source, key, text);
|
|
1801
|
+
if (canonical === null) continue;
|
|
1802
|
+
const id = repairedId(key, takenIds);
|
|
1803
|
+
if (id !== key) this.data.renamed.push({
|
|
1804
|
+
from: key,
|
|
1805
|
+
to: id
|
|
1806
|
+
});
|
|
1807
|
+
this.keys.set(key, {
|
|
1808
|
+
key,
|
|
1809
|
+
id,
|
|
1810
|
+
canonical
|
|
1811
|
+
});
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
/** A key's text as canonical ICU; null (reported) when it is not valid ICU. */
|
|
1815
|
+
canonical(source, key, text) {
|
|
1816
|
+
const converted = saasToIcu(text);
|
|
1817
|
+
for (const name of converted.currency) this.diagnostics.push({
|
|
1818
|
+
code: "icu-unknown-currency",
|
|
1819
|
+
severity: "warning",
|
|
1820
|
+
message: `${key}: {${name}:currency} became {${name}}; format the amount with fmt.currencyMinor and pass the string`,
|
|
1821
|
+
file: this.rel(source.file),
|
|
1822
|
+
id: key
|
|
1823
|
+
});
|
|
1824
|
+
try {
|
|
1825
|
+
return this.project.codec.canonicalize(converted.icu);
|
|
1826
|
+
} catch (error) {
|
|
1827
|
+
if (!isDiagnosticError(error)) throw error;
|
|
1828
|
+
this.diagnostics.push({
|
|
1829
|
+
...error.diagnostic,
|
|
1830
|
+
file: this.rel(source.file),
|
|
1831
|
+
id: key
|
|
1832
|
+
});
|
|
1833
|
+
return null;
|
|
1834
|
+
}
|
|
1835
|
+
}
|
|
1836
|
+
async planFiles(skip, keyList) {
|
|
1837
|
+
const listed = await listProjectFiles(this.config);
|
|
1838
|
+
const plans = [];
|
|
1839
|
+
for (const file of listed.files.slice().sort(compareText)) {
|
|
1840
|
+
if (skip.has(file)) continue;
|
|
1841
|
+
const text = await readFile(file, "utf8");
|
|
1842
|
+
if (!mayUseSaas(text, keyList)) continue;
|
|
1843
|
+
const plan = MODULE_EXTENSIONS.has(extname(file)) ? planModule(file, text, this.keys, keyList, this.rel(file)) : planComponent(file, text, this.keys, keyList);
|
|
1844
|
+
this.diagnostics.push(...plan.diagnostics);
|
|
1845
|
+
if (plan.rewrites.length > 0 || plan.dynamic.length > 0) plans.push(plan);
|
|
1846
|
+
}
|
|
1847
|
+
return plans;
|
|
1848
|
+
}
|
|
1849
|
+
use(key, file) {
|
|
1850
|
+
let files = this.used.get(key);
|
|
1851
|
+
if (files === void 0) this.used.set(key, files = /* @__PURE__ */ new Set());
|
|
1852
|
+
files.add(this.rel(file));
|
|
1853
|
+
}
|
|
1854
|
+
/**
|
|
1855
|
+
* The keys each plan uses, and its computed keys reported. A computed key on
|
|
1856
|
+
* a receiver that also calls `.t("key")` somewhere is saas-i18n's; one that
|
|
1857
|
+
* matches catalogue keys is too.
|
|
1858
|
+
*/
|
|
1859
|
+
collectUses(plans, messagesPath) {
|
|
1860
|
+
const receivers = /* @__PURE__ */ new Set();
|
|
1861
|
+
for (const plan of plans) for (const r of plan.rewrites) receivers.add(r.receiver);
|
|
1862
|
+
for (const plan of plans) {
|
|
1863
|
+
for (const r of plan.rewrites) this.use(r.key, plan.file);
|
|
1864
|
+
for (const site of plan.dynamic) {
|
|
1865
|
+
if (site.keys.size === 0 && (site.receiver === null || !receivers.has(site.receiver))) continue;
|
|
1866
|
+
for (const key of site.keys) {
|
|
1867
|
+
this.dynamicKeys.add(key);
|
|
1868
|
+
this.use(key, messagesPath);
|
|
1869
|
+
}
|
|
1870
|
+
const where = positionOf(plan.text, site.offset);
|
|
1871
|
+
this.diagnostics.push({
|
|
1872
|
+
code: "migrate-dynamic-key",
|
|
1873
|
+
severity: "warning",
|
|
1874
|
+
message: dynamicKeyMessage(site, this.rel(messagesPath)),
|
|
1875
|
+
file: this.rel(plan.file),
|
|
1876
|
+
line: where.line,
|
|
1877
|
+
column: where.column
|
|
1878
|
+
});
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
}
|
|
1882
|
+
/** The rewritten files, and the `msg()` table when the code computes keys. */
|
|
1883
|
+
render(plans, messagesPath) {
|
|
1884
|
+
const outputs = [];
|
|
1885
|
+
for (const plan of plans) {
|
|
1886
|
+
if (plan.rewrites.length === 0) continue;
|
|
1887
|
+
outputs.push({
|
|
1888
|
+
file: plan.file,
|
|
1889
|
+
text: this.renderPlan(plan)
|
|
1890
|
+
});
|
|
1891
|
+
}
|
|
1892
|
+
if (this.dynamicKeys.size === 0) return outputs;
|
|
1893
|
+
outputs.push({
|
|
1894
|
+
file: messagesPath,
|
|
1895
|
+
text: messagesModule(this.dynamicKeys, this.keys)
|
|
1896
|
+
});
|
|
1897
|
+
this.data.messagesModule = this.rel(messagesPath);
|
|
1898
|
+
if (!isIncluded(messagesPath, this.config)) this.diagnostics.push({
|
|
1899
|
+
code: "extract-outside-include",
|
|
1900
|
+
severity: "warning",
|
|
1901
|
+
message: `${this.rel(messagesPath)} is outside project.include, so vi18n extract will not see its msg() descriptors; add its directory to project.include`,
|
|
1902
|
+
file: this.rel(messagesPath)
|
|
1903
|
+
});
|
|
1904
|
+
return outputs;
|
|
1905
|
+
}
|
|
1906
|
+
/** One file's rewrites applied, each listed in the report, and the `t` import added. */
|
|
1907
|
+
renderPlan(plan) {
|
|
1908
|
+
const local = plan.importedT ?? localName(plan.text);
|
|
1909
|
+
const edits = [];
|
|
1910
|
+
for (const r of plan.rewrites) {
|
|
1911
|
+
const replacement = descriptor(this.keys.get(r.key), r.argument.text, r.markup);
|
|
1912
|
+
edits.push({
|
|
1913
|
+
...r.callee,
|
|
1914
|
+
text: local
|
|
1915
|
+
}, {
|
|
1916
|
+
...r.argument,
|
|
1917
|
+
text: replacement
|
|
1918
|
+
});
|
|
1919
|
+
const where = positionOf(plan.text, r.callee.start);
|
|
1920
|
+
const to = applyEdits(r.original, [{
|
|
1921
|
+
start: 0,
|
|
1922
|
+
end: r.callee.end - r.callee.start,
|
|
1923
|
+
text: local
|
|
1924
|
+
}, {
|
|
1925
|
+
start: r.argument.start - r.callee.start,
|
|
1926
|
+
end: r.argument.end - r.callee.start,
|
|
1927
|
+
text: replacement
|
|
1928
|
+
}]);
|
|
1929
|
+
const { line, column } = where;
|
|
1930
|
+
this.data.edits.push({
|
|
1931
|
+
file: this.rel(plan.file),
|
|
1932
|
+
line,
|
|
1933
|
+
column,
|
|
1934
|
+
from: r.original,
|
|
1935
|
+
to
|
|
1936
|
+
});
|
|
1937
|
+
}
|
|
1938
|
+
if (plan.importedT === null) edits.push(importEdit(plan.file, plan.text, local, plan.program));
|
|
1939
|
+
this.data.rewritten += plan.rewrites.length;
|
|
1940
|
+
return applyEdits(plan.text, edits);
|
|
1941
|
+
}
|
|
1942
|
+
/** The used keys as catalog messages, under their ids. */
|
|
1943
|
+
messages() {
|
|
1944
|
+
const { codec } = this.project;
|
|
1945
|
+
const messages = /* @__PURE__ */ new Map();
|
|
1946
|
+
for (const [key, files] of this.used) {
|
|
1947
|
+
const info = this.keys.get(key);
|
|
1948
|
+
messages.set(info.id, {
|
|
1949
|
+
id: info.id,
|
|
1950
|
+
manual: true,
|
|
1951
|
+
canonical: info.canonical,
|
|
1952
|
+
sourceHash: codec.sourceHash(info.canonical),
|
|
1953
|
+
label: codec.label(info.canonical),
|
|
1954
|
+
contexts: [],
|
|
1955
|
+
refs: [...files].sort(compareText),
|
|
1956
|
+
sources: [info.canonical],
|
|
1957
|
+
locations: []
|
|
1958
|
+
});
|
|
1959
|
+
}
|
|
1960
|
+
return messages;
|
|
1961
|
+
}
|
|
1962
|
+
/** The other catalogues' texts of used keys, as ICU by id, per locale. */
|
|
1963
|
+
translations(others) {
|
|
1964
|
+
const translations = /* @__PURE__ */ new Map();
|
|
1965
|
+
for (const catalogue of others) {
|
|
1966
|
+
const map = /* @__PURE__ */ new Map();
|
|
1967
|
+
for (const [key, text] of catalogue.texts) {
|
|
1968
|
+
const info = this.keys.get(key);
|
|
1969
|
+
if (info === void 0 || !this.used.has(key)) continue;
|
|
1970
|
+
const converted = saasToIcu(text).icu;
|
|
1971
|
+
map.set(info.id, converted);
|
|
1972
|
+
this.diagnostics.push(...translationProblems(this.project.codec, {
|
|
1973
|
+
key: info.key,
|
|
1974
|
+
canonical: info.canonical,
|
|
1975
|
+
translation: converted
|
|
1976
|
+
}, {
|
|
1977
|
+
file: this.rel(catalogue.file),
|
|
1978
|
+
locale: catalogue.locale,
|
|
1979
|
+
id: info.id
|
|
1980
|
+
}));
|
|
1981
|
+
}
|
|
1982
|
+
translations.set(catalogue.locale, map);
|
|
1983
|
+
}
|
|
1984
|
+
return translations;
|
|
1985
|
+
}
|
|
1986
|
+
};
|
|
1987
|
+
/** A key's manual id: the key when valid, else its repair, suffixed when another key took it. */
|
|
1988
|
+
function repairedId(key, takenIds) {
|
|
1989
|
+
let id = toManualId(key);
|
|
1990
|
+
if (id === key) return id;
|
|
1991
|
+
if (takenIds.has(id)) {
|
|
1992
|
+
let n = 2;
|
|
1993
|
+
while (takenIds.has(`${id}_${n}`)) n++;
|
|
1994
|
+
id = `${id}_${n}`;
|
|
1995
|
+
}
|
|
1996
|
+
takenIds.set(id, key);
|
|
1997
|
+
return id;
|
|
1998
|
+
}
|
|
1999
|
+
/**
|
|
2000
|
+
* saas formatted a `Date` in any placeholder with `dateStyle: "medium"`;
|
|
2001
|
+
* `migrate` keeps a plain `{x}` as it is, where a `Date` still renders that
|
|
2002
|
+
* way but a date string never formats, and the catalogue does not say a date
|
|
2003
|
+
* is expected. The value's type is not visible here, so a placeholder is
|
|
2004
|
+
* reported when a call passes it something that looks like a `Date`, or when
|
|
2005
|
+
* its name says it holds one.
|
|
2006
|
+
*/
|
|
2007
|
+
function datePlaceholders(source, keys, used, plans, rel) {
|
|
2008
|
+
const seen = /* @__PURE__ */ new Map();
|
|
2009
|
+
for (const plan of plans) for (const r of plan.rewrites) for (const name of plainPlaceholders(source.texts.get(r.key) ?? "")) {
|
|
2010
|
+
const at = `${r.key}\0${name}`;
|
|
2011
|
+
if (seen.has(at)) continue;
|
|
2012
|
+
const value = valueExpression(r.original.slice(r.argument.end - r.callee.start), name);
|
|
2013
|
+
if (value === null || !looksLikeDate(value)) continue;
|
|
2014
|
+
const { line } = positionOf(plan.text, r.callee.start);
|
|
2015
|
+
seen.set(at, {
|
|
2016
|
+
expression: value,
|
|
2017
|
+
file: rel(plan.file),
|
|
2018
|
+
line
|
|
2019
|
+
});
|
|
2020
|
+
}
|
|
2021
|
+
const out = [];
|
|
2022
|
+
for (const [key, text] of source.texts) {
|
|
2023
|
+
if (!keys.has(key) || !used.has(key)) continue;
|
|
2024
|
+
for (const name of plainPlaceholders(text)) {
|
|
2025
|
+
const passed = seen.get(`${key}\0${name}`);
|
|
2026
|
+
if (passed === void 0 && !isDateName(name)) continue;
|
|
2027
|
+
const why = passed === void 0 ? "its name says it holds a date" : `${passed.file}:${passed.line} passes ${passed.expression}`;
|
|
2028
|
+
out.push({
|
|
2029
|
+
code: "migrate-date-placeholder",
|
|
2030
|
+
severity: "warning",
|
|
2031
|
+
message: `${key}: {${name}} may receive a Date (${why}); saas formatted it with dateStyle "medium": write {${name}, date, medium} (the same text in English, not in every locale) and pass a Date or epoch milliseconds (new Date(value) for a string), or pass fmt.date(value, { dateStyle: "medium" }) for saas's exact text`,
|
|
2032
|
+
file: rel(source.file),
|
|
2033
|
+
id: key
|
|
2034
|
+
});
|
|
2035
|
+
}
|
|
2036
|
+
}
|
|
2037
|
+
return out;
|
|
2038
|
+
}
|
|
2039
|
+
/**
|
|
2040
|
+
* A locale's catalog after migration: the migrated messages added the way
|
|
2041
|
+
* the dev writer adds them (`add-only`, so nothing else changes), then the
|
|
2042
|
+
* catalogue's texts set on entries that have no translation yet — a
|
|
2043
|
+
* translation someone already made in vi18n is never replaced. `notes` are
|
|
2044
|
+
* translator comments for entries left empty (a text the codemod could not
|
|
2045
|
+
* convert, kept for a person to finish).
|
|
2046
|
+
*/
|
|
2047
|
+
function plannedCatalog(project, locale, { current, sourceCatalog }, messages, { translations, notes }) {
|
|
2048
|
+
const { config, codec, layout } = project;
|
|
2049
|
+
const synced = syncCatalog({
|
|
2050
|
+
config,
|
|
2051
|
+
codec,
|
|
2052
|
+
messages,
|
|
2053
|
+
locale,
|
|
2054
|
+
catalog: current,
|
|
2055
|
+
sourceCatalog,
|
|
2056
|
+
options: {
|
|
2057
|
+
mode: "add-only",
|
|
2058
|
+
yes: false
|
|
2059
|
+
}
|
|
2060
|
+
});
|
|
2061
|
+
let translated = 0;
|
|
2062
|
+
let catalog = synced.catalog;
|
|
2063
|
+
if (translations !== void 0 && translations.size > 0 || notes !== void 0 && notes.size > 0) {
|
|
2064
|
+
let changed = false;
|
|
2065
|
+
const entries = catalog.entries.map((entry) => {
|
|
2066
|
+
const key = entryKey(entry, layout, codec);
|
|
2067
|
+
if (key === null) return entry;
|
|
2068
|
+
const message = messages.get(key);
|
|
2069
|
+
if (message === void 0 || entry.manualId !== (message.manual ? key : null)) return entry;
|
|
2070
|
+
if (entry.translation !== "" || !sourceMatches(entry, layout, message, codec)) return entry;
|
|
2071
|
+
const text = translations?.get(key);
|
|
2072
|
+
if (text !== void 0) {
|
|
2073
|
+
translated++;
|
|
2074
|
+
changed = true;
|
|
2075
|
+
return {
|
|
2076
|
+
...entry,
|
|
2077
|
+
translation: text,
|
|
2078
|
+
state: "translated",
|
|
2079
|
+
fuzzy: false
|
|
2080
|
+
};
|
|
2081
|
+
}
|
|
2082
|
+
const added = (notes?.get(key) ?? []).filter((note) => !entry.comments.includes(note));
|
|
2083
|
+
if (added.length === 0) return entry;
|
|
2084
|
+
changed = true;
|
|
2085
|
+
return {
|
|
2086
|
+
...entry,
|
|
2087
|
+
comments: [...entry.comments, ...added]
|
|
2088
|
+
};
|
|
2089
|
+
});
|
|
2090
|
+
if (changed) catalog = {
|
|
2091
|
+
...catalog,
|
|
2092
|
+
entries
|
|
2093
|
+
};
|
|
2094
|
+
}
|
|
2095
|
+
return {
|
|
2096
|
+
catalog,
|
|
2097
|
+
added: synced.stats.added,
|
|
2098
|
+
translated,
|
|
2099
|
+
diagnostics: synced.diagnostics
|
|
2100
|
+
};
|
|
2101
|
+
}
|
|
2102
|
+
function planCatalogs(project, set, messages, translations, notes) {
|
|
2103
|
+
const { config } = project;
|
|
2104
|
+
const sourceCatalog = set.get(config.sourceLocale)?.catalog ?? null;
|
|
2105
|
+
const changed = [];
|
|
2106
|
+
const counts = /* @__PURE__ */ new Map();
|
|
2107
|
+
const diagnostics = [];
|
|
2108
|
+
if (messages.size === 0) return {
|
|
2109
|
+
changed,
|
|
2110
|
+
counts,
|
|
2111
|
+
sourceCatalog,
|
|
2112
|
+
diagnostics
|
|
2113
|
+
};
|
|
2114
|
+
for (const locale of config.locales) {
|
|
2115
|
+
const current = set.get(locale)?.catalog ?? null;
|
|
2116
|
+
const planned = plannedCatalog(project, locale, {
|
|
2117
|
+
current,
|
|
2118
|
+
sourceCatalog
|
|
2119
|
+
}, messages, {
|
|
2120
|
+
translations: translations.get(locale),
|
|
2121
|
+
notes: notes?.get(locale)
|
|
2122
|
+
});
|
|
2123
|
+
for (const d of planned.diagnostics) diagnostics.push({
|
|
2124
|
+
...d,
|
|
2125
|
+
locale: d.locale ?? locale,
|
|
2126
|
+
file: d.file ?? rootRelative(config.root, catalogPath(config, locale))
|
|
2127
|
+
});
|
|
2128
|
+
counts.set(locale, planned.translated);
|
|
2129
|
+
if ((current === null ? null : serializeCatalog(current, {
|
|
2130
|
+
isSourceLocale: locale === config.sourceLocale,
|
|
2131
|
+
version: VERSION
|
|
2132
|
+
})) !== serializeCatalog(planned.catalog, {
|
|
2133
|
+
isSourceLocale: locale === config.sourceLocale,
|
|
2134
|
+
version: VERSION
|
|
2135
|
+
})) changed.push(locale);
|
|
2136
|
+
}
|
|
2137
|
+
return {
|
|
2138
|
+
changed,
|
|
2139
|
+
counts,
|
|
2140
|
+
sourceCatalog,
|
|
2141
|
+
diagnostics
|
|
2142
|
+
};
|
|
2143
|
+
}
|
|
2144
|
+
/** `export const messages = { "<key>": msg({ id, message }) }`, keyed by the catalogue key the code computes. */
|
|
2145
|
+
function messagesModule(dynamicKeys, keys) {
|
|
2146
|
+
const lines = [
|
|
2147
|
+
"// Generated by vi18n migrate --from saas-i18n: catalogue keys the code computes at",
|
|
2148
|
+
"// runtime, as msg() descriptors so vi18n extracts them. Look one up with",
|
|
2149
|
+
"// t(messages[key]); keys stay the catalogue's, ids are vi18n manual ids.",
|
|
2150
|
+
`import { msg } from "${RUNTIME}";`,
|
|
2151
|
+
"",
|
|
2152
|
+
"export const messages = {"
|
|
2153
|
+
];
|
|
2154
|
+
for (const key of [...dynamicKeys].sort(compareText)) {
|
|
2155
|
+
const info = keys.get(key);
|
|
2156
|
+
lines.push(` ${JSON.stringify(key)}: msg(${descriptor(info, "\"")}),`);
|
|
2157
|
+
}
|
|
2158
|
+
lines.push("} as const;", "");
|
|
2159
|
+
return lines.join("\n");
|
|
2160
|
+
}
|
|
2161
|
+
function printPlan(ctx, data, failed) {
|
|
2162
|
+
for (const edit of data.edits) ctx.out.result(`${edit.file}:${edit.line}:${edit.column}\n - ${edit.from}\n + ${edit.to}`);
|
|
2163
|
+
if (data.renamed.length > 0) ctx.out.result(`renamed to valid manual ids: ${data.renamed.map((r) => `${r.from} → ${r.to}`).join(", ")}`);
|
|
2164
|
+
if (data.messagesModule !== null) ctx.out.result(`msg() table for computed keys: ${data.messagesModule}`);
|
|
2165
|
+
for (const [locale, count] of Object.entries(data.entries)) ctx.out.result(`${locale}: ${plural(count, "translation")} for the vi18n catalog`);
|
|
2166
|
+
if (data.unused.length > 0) ctx.out.result(`${plural(data.unused.length, "catalogue key")} no code uses: ${data.unused.join(", ")}`);
|
|
2167
|
+
ctx.out.result(rewriteSummary(data, failed));
|
|
2168
|
+
}
|
|
2169
|
+
export { isNode$1 as A, objectProperties as B, attributeString as C, inJsxChildren as D, identifierName as E, jsxNameNodes as F, templateKeyPattern as H, keyName as I, lineRange as L, jsxAttributes as M, jsxChildren as N, isConsumed as O, jsxName as P, listItemRange as R, attributeExpression as S, cleanJsxText as T, templateKeys as U, stringValue as V, unwrap as W, toManualId as _, finishMigration as a, translationProblems as b, migrate as c, positionOf as d, readString as f, skipSpace as g, skipBalanced as h, encodeMarkup as i, jsString as j, isNameFree as k, planCatalogs as l, saasToIcu as m, applyEdits as n, importLineEdit as o, readTemplate as p, argumentEnd as r, isDateName as s, MESSAGES_MODULE as t, plannedCatalog as u, vueRegions as v, childEntries as w, analyzeModule as x, rewriteSummary as y, memberParts as z };
|