@customyai/cli 0.7.2 → 0.11.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.
@@ -0,0 +1,387 @@
1
+ import { utf8ByteLength, I18nToolsError, compareCodeUnits } from './chunk-BYMLRMNS.mjs';
2
+ import { CATALOG_LOCALE, CATALOG_DOC_VERSION, CATALOG_KEY, CATALOG_NAMESPACE } from './chunk-QKIF4C5R.mjs';
3
+ import { pluralCategories, parseIcu, unparseIcu } from './chunk-3M6ZLCSN.mjs';
4
+
5
+ // src/vendor/i18n-tools/po.ts
6
+ var DEFAULT_PO_MAX_BYTES = 4 * 1024 * 1024;
7
+ var bad = (line, text) => {
8
+ throw new I18nToolsError("malformed-po", `${text} (l\xEDnea ${line})`);
9
+ };
10
+ var SIMPLE_ESC = { n: "\n", t: " ", r: "\r", "\\": "\\", '"': '"', a: "\x07", b: "\b", f: "\f", v: "\v" };
11
+ function parseQuoted(rest, line) {
12
+ let i = 0;
13
+ let out = "";
14
+ let count = 0;
15
+ for (; ; ) {
16
+ while (rest[i] === " " || rest[i] === " ") i += 1;
17
+ if (i >= rest.length) break;
18
+ if (rest[i] !== '"') return bad(line, "se esperaba una cadena entre comillas");
19
+ i += 1;
20
+ let closed = false;
21
+ while (i < rest.length) {
22
+ const c = rest[i];
23
+ if (c === '"') {
24
+ closed = true;
25
+ i += 1;
26
+ break;
27
+ }
28
+ if (c !== "\\") {
29
+ out += c;
30
+ i += 1;
31
+ continue;
32
+ }
33
+ const e = rest[i + 1];
34
+ if (e === void 0) return bad(line, "escape incompleto");
35
+ if (Object.hasOwn(SIMPLE_ESC, e)) {
36
+ out += SIMPLE_ESC[e];
37
+ i += 2;
38
+ continue;
39
+ }
40
+ if (e >= "0" && e <= "7") {
41
+ let j = i + 1;
42
+ let digits = "";
43
+ while (digits.length < 3 && rest[j] !== void 0 && rest[j] >= "0" && rest[j] <= "7") {
44
+ digits += rest[j];
45
+ j += 1;
46
+ }
47
+ const v = Number.parseInt(digits, 8);
48
+ if (v > 255) return bad(line, "escape octal fuera de rango");
49
+ out += String.fromCharCode(v);
50
+ i = j;
51
+ continue;
52
+ }
53
+ if (e === "x") {
54
+ const m = /^[0-9A-Fa-f]{1,2}/.exec(rest.slice(i + 2));
55
+ if (!m) return bad(line, "escape \\x sin d\xEDgitos");
56
+ out += String.fromCharCode(Number.parseInt(m[0], 16));
57
+ i += 2 + m[0].length;
58
+ continue;
59
+ }
60
+ return bad(line, `escape desconocido \\${e}`);
61
+ }
62
+ if (!closed) return bad(line, "cadena sin cerrar");
63
+ count += 1;
64
+ }
65
+ if (count === 0) return bad(line, "se esperaba una cadena entre comillas");
66
+ return out;
67
+ }
68
+ function escapePo(s) {
69
+ let out = "";
70
+ for (const c of s) {
71
+ if (c === "\\") out += "\\\\";
72
+ else if (c === '"') out += '\\"';
73
+ else if (c === "\n") out += "\\n";
74
+ else if (c === " ") out += "\\t";
75
+ else if (c === "\r") out += "\\r";
76
+ else {
77
+ const cp = c.codePointAt(0) ?? 0;
78
+ out += cp < 32 || cp === 127 ? `\\${cp.toString(8).padStart(3, "0")}` : c;
79
+ }
80
+ }
81
+ return out;
82
+ }
83
+ function emitField(lines, prefix, keyword, value) {
84
+ if (!value.includes("\n")) {
85
+ lines.push(`${prefix}${keyword} "${escapePo(value)}"`);
86
+ return;
87
+ }
88
+ lines.push(`${prefix}${keyword} ""`);
89
+ let start = 0;
90
+ while (start < value.length) {
91
+ const nl = value.indexOf("\n", start);
92
+ const end = nl === -1 ? value.length : nl + 1;
93
+ lines.push(`${prefix}"${escapePo(value.slice(start, end))}"`);
94
+ start = end;
95
+ }
96
+ }
97
+ var newDraft = () => ({ msgctxt: null, msgid: null, msgidPlural: null, msgstr: [], plainStr: false, tc: [], ec: [], refs: [], flags: [], prev: [], obsolete: false, started: false });
98
+ function parsePo(input, options = {}) {
99
+ const maxBytes = options.maxBytes ?? DEFAULT_PO_MAX_BYTES;
100
+ if (input.length > maxBytes || utf8ByteLength(input) > maxBytes) throw new I18nToolsError("too-large", `el archivo PO pasa de ${maxBytes} bytes`);
101
+ const text = (input.charCodeAt(0) === 65279 ? input.slice(1) : input).replace(/\r\n?/g, "\n");
102
+ const lines = text.split("\n");
103
+ const entries = [];
104
+ let headerComments = [];
105
+ let headers = [];
106
+ let headerSeen = false;
107
+ const seen = /* @__PURE__ */ new Set();
108
+ let cur = newDraft();
109
+ let field = null;
110
+ let curLine = 0;
111
+ const append = (kind, index, add, replace) => {
112
+ if (kind === "msgctxt") cur.msgctxt = replace ? add : (cur.msgctxt ?? "") + add;
113
+ else if (kind === "msgid") cur.msgid = replace ? add : (cur.msgid ?? "") + add;
114
+ else if (kind === "msgid_plural") cur.msgidPlural = replace ? add : (cur.msgidPlural ?? "") + add;
115
+ else cur.msgstr[index] = replace ? add : (cur.msgstr[index] ?? "") + add;
116
+ };
117
+ const finish = () => {
118
+ if (!cur.started) {
119
+ cur = newDraft();
120
+ field = null;
121
+ return;
122
+ }
123
+ if (cur.msgid === null) bad(curLine, "entrada sin msgid");
124
+ const plural = cur.msgidPlural !== null;
125
+ let msgstr;
126
+ if (plural) {
127
+ if (cur.plainStr) bad(curLine, "una entrada con msgid_plural necesita msgstr[n]");
128
+ if (cur.msgstr.length === 0) bad(curLine, "falta msgstr[0]");
129
+ msgstr = [];
130
+ for (let k = 0; k < cur.msgstr.length; k += 1) {
131
+ const v = cur.msgstr[k];
132
+ if (v === void 0) return bad(curLine, `falta msgstr[${k}]`);
133
+ msgstr.push(v);
134
+ }
135
+ } else {
136
+ if (cur.msgstr.length !== 1 || !cur.plainStr) bad(curLine, "se esperaba un \xFAnico msgstr");
137
+ msgstr = [cur.msgstr[0] ?? ""];
138
+ }
139
+ const msgid = cur.msgid;
140
+ if (!headerSeen && cur.msgctxt === null && msgid === "" && !plural) {
141
+ headerSeen = true;
142
+ headerComments = cur.tc;
143
+ headers = [];
144
+ for (const raw of (msgstr[0] ?? "").split("\n")) {
145
+ if (raw === "") continue;
146
+ const colon = raw.indexOf(":");
147
+ if (colon <= 0) bad(curLine, `l\xEDnea de cabecera no v\xE1lida \xAB${raw}\xBB`);
148
+ headers.push({ name: raw.slice(0, colon), value: raw.slice(colon + 1).replace(/^[ \t]+/, "") });
149
+ }
150
+ } else {
151
+ const id = cur.msgctxt === null ? `n:${msgid}` : `c:${cur.msgctxt}${msgid}`;
152
+ if (seen.has(id)) throw new I18nToolsError("duplicate-entry", `entrada repetida \xAB${msgid}\xBB${cur.msgctxt !== null ? ` (contexto \xAB${cur.msgctxt}\xBB)` : ""}`);
153
+ seen.add(id);
154
+ entries.push({
155
+ msgctxt: cur.msgctxt,
156
+ msgid,
157
+ msgidPlural: cur.msgidPlural,
158
+ msgstr,
159
+ translatorComments: cur.tc,
160
+ extractedComments: cur.ec,
161
+ references: cur.refs,
162
+ flags: cur.flags,
163
+ previous: cur.prev,
164
+ obsolete: cur.obsolete
165
+ });
166
+ }
167
+ cur = newDraft();
168
+ field = null;
169
+ };
170
+ for (let ln = 0; ln < lines.length; ln += 1) {
171
+ curLine = ln + 1;
172
+ let line = lines[ln].trimStart();
173
+ if (line === "") {
174
+ finish();
175
+ continue;
176
+ }
177
+ let obsoleteLine = false;
178
+ if (line.startsWith("#~") && line[2] !== "|") {
179
+ obsoleteLine = true;
180
+ line = line.slice(2).trimStart();
181
+ if (line === "") continue;
182
+ }
183
+ if (line[0] === "#" && !obsoleteLine) {
184
+ if (field !== null && cur.msgstr.length > 0) finish();
185
+ const kind = line[1];
186
+ const body = line.slice(2);
187
+ const strip = (b) => b.startsWith(" ") ? b.slice(1) : b;
188
+ if (kind === void 0) cur.tc.push("");
189
+ else if (kind === " ") cur.tc.push(body);
190
+ else if (kind === ".") cur.ec.push(strip(body));
191
+ else if (kind === ":") cur.refs.push(strip(body));
192
+ else if (kind === ",") for (const f of body.split(",")) {
193
+ const t = f.trim();
194
+ if (t) cur.flags.push(t);
195
+ }
196
+ else if (kind === "|") cur.prev.push(strip(body));
197
+ else bad(curLine, `comentario no reconocido \xAB${line.slice(0, 2)}\xBB`);
198
+ continue;
199
+ }
200
+ if (line[0] === '"') {
201
+ if (field === null) bad(curLine, "cadena sin palabra clave");
202
+ append(field.kind, field.index, parseQuoted(line, curLine), false);
203
+ continue;
204
+ }
205
+ const m = /^(msgctxt|msgid_plural|msgid|msgstr)(?:\[(\d{1,3})\])?[ \t]*(.*)$/.exec(line);
206
+ if (!m) {
207
+ bad(curLine, `l\xEDnea no reconocida \xAB${line.slice(0, 30)}\xBB`);
208
+ continue;
209
+ }
210
+ const keyword = m[1];
211
+ const index = m[2] === void 0 ? 0 : Number.parseInt(m[2], 10);
212
+ if (m[2] !== void 0 && keyword !== "msgstr") bad(curLine, `${keyword} no lleva \xEDndice`);
213
+ if ((keyword === "msgctxt" || keyword === "msgid") && cur.msgstr.length > 0) finish();
214
+ const value = parseQuoted(m[3] ?? "", curLine);
215
+ cur.started = true;
216
+ if (obsoleteLine) cur.obsolete = true;
217
+ if (keyword === "msgstr") {
218
+ if (m[2] === void 0) {
219
+ if (cur.msgstr.length > 0) bad(curLine, "msgstr repetido");
220
+ cur.plainStr = true;
221
+ } else if (cur.plainStr) bad(curLine, "mezcla de msgstr y msgstr[n]");
222
+ if (cur.msgstr[index] !== void 0) bad(curLine, `msgstr[${index}] repetido`);
223
+ if (index > 99) bad(curLine, "\xEDndice de plural fuera de rango");
224
+ } else {
225
+ if (keyword === "msgctxt" && (cur.msgctxt !== null || cur.msgid !== null)) bad(curLine, "msgctxt fuera de lugar");
226
+ if (keyword === "msgid" && cur.msgid !== null) bad(curLine, "msgid repetido");
227
+ if (keyword === "msgid_plural" && (cur.msgid === null || cur.msgidPlural !== null)) bad(curLine, "msgid_plural fuera de lugar");
228
+ }
229
+ append(keyword, index, value, true);
230
+ field = { kind: keyword, index };
231
+ }
232
+ finish();
233
+ return { headerComments, headers, entries };
234
+ }
235
+ function stringifyPo(file) {
236
+ const blocks = [];
237
+ if (file.headers.length > 0 || file.headerComments.length > 0) {
238
+ const lines = [];
239
+ for (const c of file.headerComments) lines.push(c === "" ? "#" : `# ${c}`);
240
+ lines.push('msgid ""');
241
+ emitField(lines, "", "msgstr", file.headers.map((h) => `${h.name}: ${h.value}
242
+ `).join(""));
243
+ blocks.push(lines.join("\n"));
244
+ }
245
+ for (const e of file.entries) {
246
+ const lines = [];
247
+ for (const c of e.translatorComments) lines.push(c === "" ? "#" : `# ${c}`);
248
+ for (const c of e.extractedComments) lines.push(c === "" ? "#." : `#. ${c}`);
249
+ for (const c of e.references) lines.push(c === "" ? "#:" : `#: ${c}`);
250
+ if (e.flags.length > 0) lines.push(`#, ${e.flags.join(", ")}`);
251
+ for (const c of e.previous) lines.push(c === "" ? "#|" : `#| ${c}`);
252
+ const prefix = e.obsolete ? "#~ " : "";
253
+ if (e.msgctxt !== null) emitField(lines, prefix, "msgctxt", e.msgctxt);
254
+ emitField(lines, prefix, "msgid", e.msgid);
255
+ if (e.msgidPlural !== null) {
256
+ emitField(lines, prefix, "msgid_plural", e.msgidPlural);
257
+ e.msgstr.forEach((s, k) => emitField(lines, prefix, `msgstr[${k}]`, s));
258
+ } else emitField(lines, prefix, "msgstr", e.msgstr[0] ?? "");
259
+ blocks.push(lines.join("\n"));
260
+ }
261
+ return blocks.length === 0 ? "" : `${blocks.join("\n\n")}
262
+ `;
263
+ }
264
+ var poHeader = (file, name) => file.headers.find((h) => h.name.toLowerCase() === name.toLowerCase())?.value ?? null;
265
+ var PLURAL_VAR = "customy-plural-var: ";
266
+ var GETTEXT_FORMS = {
267
+ en: "nplurals=2; plural=(n != 1);",
268
+ de: "nplurals=2; plural=(n != 1);",
269
+ nl: "nplurals=2; plural=(n != 1);",
270
+ sv: "nplurals=2; plural=(n != 1);",
271
+ ja: "nplurals=1; plural=0;",
272
+ zh: "nplurals=1; plural=0;",
273
+ ko: "nplurals=1; plural=0;",
274
+ vi: "nplurals=1; plural=0;"
275
+ };
276
+ function asCanonicalPlural(message) {
277
+ const nodes = parseIcu(message);
278
+ const n = nodes[0];
279
+ if (nodes.length !== 1 || !n || n.t !== "complex" || n.type !== "plural") return null;
280
+ const forms = n.options.map((o) => [o.selector, unparseIcu(o.body)]);
281
+ if (forms.length === 0 || new Set(forms.map((f) => f[0])).size !== forms.length) return null;
282
+ return buildCanonicalPlural(n.name, forms) === message ? { name: n.name, forms } : null;
283
+ }
284
+ var buildCanonicalPlural = (name, forms) => `{${name}, plural,${forms.map(([sel, body]) => ` ${sel} {${body}}`).join("")}}`;
285
+ function catalogToPo(options) {
286
+ const { source, target } = options;
287
+ if (target && target.namespace !== source.namespace) throw new I18nToolsError("invalid-input", "origen y destino son de espacios de nombres distintos");
288
+ const trgLocale = target?.locale ?? options.targetLocale ?? null;
289
+ if (trgLocale !== null && !CATALOG_LOCALE.test(trgLocale)) throw new I18nToolsError("invalid-locale", `idioma de destino no v\xE1lido \xAB${trgLocale}\xBB`);
290
+ const gettext = options.pluralMode === "gettext";
291
+ const trgCats = trgLocale ? pluralCategories(trgLocale) : null;
292
+ const headers = [
293
+ { name: "Content-Type", value: "text/plain; charset=UTF-8" },
294
+ { name: "Content-Transfer-Encoding", value: "8bit" }
295
+ ];
296
+ if (trgLocale) headers.push({ name: "Language", value: trgLocale });
297
+ headers.push(
298
+ { name: "X-Source-Language", value: source.locale },
299
+ { name: "X-Customy-Catalog", value: CATALOG_DOC_VERSION },
300
+ { name: "X-Customy-Namespace", value: source.namespace },
301
+ { name: "X-Customy-Syntax", value: source.syntax }
302
+ );
303
+ if (gettext && trgLocale && trgCats) {
304
+ const forms = GETTEXT_FORMS[trgLocale.split("-")[0] ?? ""];
305
+ if (forms && forms.startsWith(`nplurals=${trgCats.length};`)) headers.push({ name: "Plural-Forms", value: forms });
306
+ headers.push({ name: "X-Customy-Plural-Categories", value: trgCats.join(",") });
307
+ }
308
+ const entries = [];
309
+ for (const key of Object.keys(source.messages).sort(compareCodeUnits)) {
310
+ if (!CATALOG_KEY.test(key)) throw new I18nToolsError("invalid-key", `clave no v\xE1lida \xAB${key}\xBB`);
311
+ const src = source.messages[key] ?? "";
312
+ const trg = target?.messages[key];
313
+ const ctx = options.contexts?.[key];
314
+ const extracted = ctx ? ctx.split("\n") : [];
315
+ let entry = {
316
+ msgctxt: key,
317
+ msgid: src,
318
+ msgidPlural: null,
319
+ msgstr: [trg ?? ""],
320
+ translatorComments: [],
321
+ extractedComments: extracted,
322
+ references: [],
323
+ flags: [],
324
+ previous: [],
325
+ obsolete: false
326
+ };
327
+ if (gettext && trgCats) {
328
+ const sp = asCanonicalPlural(src);
329
+ const sel = sp?.forms.map((f) => f[0]).join(",");
330
+ if (sp && sel === "one,other") {
331
+ const tp = trg === void 0 || trg === "" ? null : asCanonicalPlural(trg);
332
+ const tOk = trg === void 0 || trg === "" || tp !== null && tp.name === sp.name && tp.forms.map((f) => f[0]).join(",") === trgCats.join(",");
333
+ if (tOk) {
334
+ entry = {
335
+ ...entry,
336
+ msgid: sp.forms[0][1],
337
+ msgidPlural: sp.forms[1][1],
338
+ msgstr: tp ? tp.forms.map((f) => f[1]) : trgCats.map(() => ""),
339
+ extractedComments: [`${PLURAL_VAR}${sp.name}`, ...extracted]
340
+ };
341
+ }
342
+ }
343
+ }
344
+ entries.push(entry);
345
+ }
346
+ return { headerComments: [], headers, entries };
347
+ }
348
+ function poToCatalogs(po, options = {}) {
349
+ const namespace = options.namespace ?? poHeader(po, "X-Customy-Namespace");
350
+ if (!namespace || !CATALOG_NAMESPACE.test(namespace)) throw new I18nToolsError("invalid-input", "falta un espacio de nombres v\xE1lido (X-Customy-Namespace u options.namespace)");
351
+ const sourceLocale = options.sourceLocale ?? poHeader(po, "X-Source-Language");
352
+ if (!sourceLocale || !CATALOG_LOCALE.test(sourceLocale)) throw new I18nToolsError("invalid-locale", "falta el idioma de origen (X-Source-Language u options.sourceLocale)");
353
+ const targetLocale = options.targetLocale ?? poHeader(po, "Language");
354
+ if (targetLocale && !CATALOG_LOCALE.test(targetLocale)) throw new I18nToolsError("invalid-locale", `idioma de destino no v\xE1lido \xAB${targetLocale}\xBB`);
355
+ const syntaxHeader = options.syntax ?? poHeader(po, "X-Customy-Syntax") ?? "icu1";
356
+ if (syntaxHeader !== "icu1" && syntaxHeader !== "mf2") throw new I18nToolsError("invalid-input", `sintaxis desconocida \xAB${syntaxHeader}\xBB`);
357
+ const catsHeader = poHeader(po, "X-Customy-Plural-Categories");
358
+ const cats = catsHeader ? catsHeader.split(",").map((c) => c.trim()).filter(Boolean) : targetLocale ? pluralCategories(targetLocale) : [];
359
+ const sourceMessages = {};
360
+ const targetMessages = {};
361
+ const contexts = {};
362
+ const put = (into, key, value) => {
363
+ Object.defineProperty(into, key, { value, enumerable: true, writable: true, configurable: true });
364
+ };
365
+ for (const e of po.entries) {
366
+ if (e.obsolete) continue;
367
+ if (e.msgctxt === null || !CATALOG_KEY.test(e.msgctxt)) throw new I18nToolsError("invalid-key", `la entrada \xAB${e.msgid.slice(0, 40)}\xBB no trae una clave v\xE1lida en msgctxt`);
368
+ const key = e.msgctxt;
369
+ const varLine = e.extractedComments.find((c) => c.startsWith(PLURAL_VAR));
370
+ const ctxLines = e.extractedComments.filter((c) => !c.startsWith(PLURAL_VAR));
371
+ if (ctxLines.length > 0) put(contexts, key, ctxLines.join("\n"));
372
+ if (e.msgidPlural !== null) {
373
+ const name = varLine ? varLine.slice(PLURAL_VAR.length) : "count";
374
+ put(sourceMessages, key, buildCanonicalPlural(name, [["one", e.msgid], ["other", e.msgidPlural]]));
375
+ if (e.msgstr.length === cats.length && e.msgstr.every((s) => s !== "")) put(targetMessages, key, buildCanonicalPlural(name, cats.map((c, i) => [c, e.msgstr[i] ?? ""])));
376
+ } else {
377
+ put(sourceMessages, key, e.msgid);
378
+ const s = e.msgstr[0] ?? "";
379
+ if (s !== "") put(targetMessages, key, s);
380
+ }
381
+ }
382
+ const source = { version: CATALOG_DOC_VERSION, namespace, locale: sourceLocale, syntax: syntaxHeader, messages: sourceMessages };
383
+ const target = targetLocale ? { version: CATALOG_DOC_VERSION, namespace, locale: targetLocale, syntax: syntaxHeader, messages: targetMessages } : null;
384
+ return { source, target, contexts };
385
+ }
386
+
387
+ export { DEFAULT_PO_MAX_BYTES, catalogToPo, parsePo, poHeader, poToCatalogs, stringifyPo };