@customyai/cli 0.7.2 → 0.10.1

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/dist/index.d.ts CHANGED
@@ -10,6 +10,10 @@ type CliIo = {
10
10
  isTTY?: boolean;
11
11
  /** Asks a question on the terminal (the prompt goes to stderr) and returns the typed line. */
12
12
  prompt?: (question: string) => Promise<string>;
13
+ /** Cancela los comandos que no terminan solos (`customy whatsapp tail`); la terminal lo dispara con Ctrl+C. */
14
+ signal?: AbortSignal;
15
+ /** Espera entre sondeos de `tail` (inyectable en pruebas). */
16
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
13
17
  };
14
18
  declare function runCli(argv: string[], io: CliIo): Promise<number>;
15
19
 
@@ -370,4 +374,62 @@ declare const EXPERIMENTS_EXIT: {
370
374
  };
371
375
  declare function runExperimentsCli(group: string, args: string[], io: CliIo): Promise<number>;
372
376
 
373
- export { type CliIo, EXPERIMENTS_EXIT as EXPERIMENTS_EXIT_CODES, EXIT as PROVISIONING_EXIT_CODES, SyncError, type SyncOptions, type SyncResult, generateAppTypes, runCli, runExperimentsCli, runProvisioningCli, schemaToType, syncApp, validateManifest };
377
+ /**
378
+ * `catalog@1`: traducciones como DATOS versionados, en lugar de textos escritos en el código.
379
+ *
380
+ * Plan: docs/CUSTOMY_EXPERIENCE_CONTROL_PLANE_PLAN.md (§5.7). Es el contrato que usan, sin duplicarse, el motor `@customy/i18n`, el design system
381
+ * (`DesignSystemMessagesProvider` sustituye textos por clave) y los componentes propios (`{ $t: "clave" }` en `component-registry.ts`).
382
+ *
383
+ * Un catálogo es PLANO (`clave.con.puntos → mensaje ICU`) y de UN idioma de UN espacio de nombres. Cada publicación es una **revisión inmutable**
384
+ * identificada por su número y por la huella de su contenido; restaurar crea una revisión nueva. Puro: sin DOM ni I/O; nunca lanza al validar.
385
+ *
386
+ * Qué garantiza:
387
+ * 1. `validateCatalog`: forma, claves, mensajes ICU bien formados (llaves, plurales con `other`), sin HTML, límites por plan.
388
+ * 2. `checkCatalogPublish`: una revisión nueva no puede quitar una clave ni cambiar sus variables sin reconocerlo, porque eso rompe a quien ya la usa.
389
+ * 3. `parityReport`: qué idioma no tiene una clave y dónde un mensaje cambió de variables entre idiomas.
390
+ * 4. `resolveCatalog`: capas (plataforma → organización → entorno) y cadena de respaldo de idiomas; nunca devuelve una clave cruda.
391
+ */
392
+
393
+ declare const CatalogDocSchema: z.ZodObject<{
394
+ version: z.ZodLiteral<"catalog@1">;
395
+ namespace: z.ZodString;
396
+ locale: z.ZodString;
397
+ syntax: z.ZodDefault<z.ZodEnum<["icu1", "mf2"]>>;
398
+ messages: z.ZodRecord<z.ZodString, z.ZodString>;
399
+ }, "strict", z.ZodTypeAny, {
400
+ locale: string;
401
+ version: "catalog@1";
402
+ namespace: string;
403
+ syntax: "icu1" | "mf2";
404
+ messages: Record<string, string>;
405
+ }, {
406
+ locale: string;
407
+ version: "catalog@1";
408
+ namespace: string;
409
+ messages: Record<string, string>;
410
+ syntax?: "icu1" | "mf2" | undefined;
411
+ }>;
412
+ type CatalogDoc = z.infer<typeof CatalogDocSchema>;
413
+
414
+ declare const EXPERIENCE_EXIT: {
415
+ readonly ok: 0;
416
+ readonly invalid: 1;
417
+ readonly usage: 2;
418
+ readonly auth: 3;
419
+ readonly conflict: 4;
420
+ readonly failure: 5;
421
+ };
422
+ /** El documento tal como se escribe a disco: orden fijo de campos y mensajes ordenados por clave (diffs estables en Git). */
423
+ declare function serializeCatalog(doc: CatalogDoc): string;
424
+ declare function runExperienceCli(args: string[], io: CliIo): Promise<number>;
425
+
426
+ declare const WHATSAPP_EXIT: {
427
+ readonly ok: 0;
428
+ readonly failure: 1;
429
+ readonly unsupported: 2;
430
+ readonly auth: 3;
431
+ readonly findings: 4;
432
+ };
433
+ declare function runWhatsAppCli(args: string[], io: CliIo): Promise<number>;
434
+
435
+ export { type CliIo, EXPERIENCE_EXIT as EXPERIENCE_EXIT_CODES, EXPERIMENTS_EXIT as EXPERIMENTS_EXIT_CODES, EXIT as PROVISIONING_EXIT_CODES, SyncError, type SyncOptions, type SyncResult, WHATSAPP_EXIT as WHATSAPP_EXIT_CODES, generateAppTypes, runCli, runExperienceCli, runExperimentsCli, runProvisioningCli, runWhatsAppCli, schemaToType, serializeCatalog, syncApp, validateManifest };
package/dist/index.mjs CHANGED
@@ -1 +1,2 @@
1
- export { EXPERIMENTS_EXIT as EXPERIMENTS_EXIT_CODES, EXIT as PROVISIONING_EXIT_CODES, SyncError, generateAppTypes, runCli, runExperimentsCli, runProvisioningCli, schemaToType, syncApp, validateManifest } from './chunk-762M6SBX.mjs';
1
+ export { EXPERIENCE_EXIT as EXPERIENCE_EXIT_CODES, EXPERIMENTS_EXIT as EXPERIMENTS_EXIT_CODES, EXIT as PROVISIONING_EXIT_CODES, SyncError, WHATSAPP_EXIT as WHATSAPP_EXIT_CODES, generateAppTypes, runCli, runExperienceCli, runExperimentsCli, runProvisioningCli, runWhatsAppCli, schemaToType, serializeCatalog, syncApp, validateManifest } from './chunk-57NNDUEX.mjs';
2
+ import './chunk-QKIF4C5R.mjs';
@@ -0,0 +1,67 @@
1
+ import { utf8ByteLength, I18nToolsError, compareCodeUnits } from './chunk-BYMLRMNS.mjs';
2
+ import { CATALOG_KEY } from './chunk-QKIF4C5R.mjs';
3
+
4
+ // src/vendor/i18n-tools/json.ts
5
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
6
+ function parseFlatJson(input, options = {}) {
7
+ const maxBytes = options.maxBytes ?? 4 * 1024 * 1024;
8
+ if (input.length > maxBytes || utf8ByteLength(input) > maxBytes) throw new I18nToolsError("too-large", `el JSON pasa de ${maxBytes} bytes`);
9
+ let data;
10
+ try {
11
+ data = JSON.parse(input.charCodeAt(0) === 65279 ? input.slice(1) : input);
12
+ } catch (e) {
13
+ throw new I18nToolsError("malformed-json", `JSON no v\xE1lido: ${e.message}`);
14
+ }
15
+ if (!isObject(data)) throw new I18nToolsError("malformed-json", "se esperaba un objeto en la ra\xEDz");
16
+ const strict = options.strictKeys !== false;
17
+ const maxDepth = options.maxDepth ?? 8;
18
+ const messages = [];
19
+ const descriptions = [];
20
+ const seen = /* @__PURE__ */ new Set();
21
+ const add = (key, value) => {
22
+ if (strict && !CATALOG_KEY.test(key)) throw new I18nToolsError("invalid-key", `clave no v\xE1lida \xAB${key}\xBB`);
23
+ if (seen.has(key)) throw new I18nToolsError("duplicate-key", `clave repetida \xAB${key}\xBB (tras aplanar)`);
24
+ seen.add(key);
25
+ if (typeof value === "string") {
26
+ messages.push([key, value]);
27
+ return;
28
+ }
29
+ if (isObject(value)) {
30
+ const message = value["message"] ?? value["defaultMessage"];
31
+ if (typeof message === "string") {
32
+ messages.push([key, message]);
33
+ const d = value["description"];
34
+ if (typeof d === "string" && d !== "") descriptions.push([key, d]);
35
+ return;
36
+ }
37
+ }
38
+ throw new I18nToolsError("malformed-json", `el valor de \xAB${key}\xBB debe ser un texto o un objeto con \xABmessage\xBB`);
39
+ };
40
+ const stack = [{ prefix: "", obj: data, depth: 1 }];
41
+ while (stack.length > 0) {
42
+ const { prefix, obj, depth } = stack.pop();
43
+ for (const [k, v] of Object.entries(obj)) {
44
+ const key = prefix ? `${prefix}.${k}` : k;
45
+ const isLeafObject = isObject(v) && (typeof v["message"] === "string" || typeof v["defaultMessage"] === "string");
46
+ if (options.nested && isObject(v) && !isLeafObject) {
47
+ if (depth >= maxDepth) throw new I18nToolsError("too-deep", `anidamiento de m\xE1s de ${maxDepth} niveles`);
48
+ stack.push({ prefix: key, obj: v, depth: depth + 1 });
49
+ } else add(key, v);
50
+ }
51
+ }
52
+ messages.sort((a, b) => compareCodeUnits(a[0], b[0]));
53
+ descriptions.sort((a, b) => compareCodeUnits(a[0], b[0]));
54
+ return { messages: Object.fromEntries(messages), descriptions: Object.fromEntries(descriptions) };
55
+ }
56
+ function stringifyFlatJson(messages, options = {}) {
57
+ const entries = Object.keys(messages).sort(compareCodeUnits).map((k) => {
58
+ const message = messages[k] ?? "";
59
+ const description = options.descriptions?.[k];
60
+ const value = options.style === "described" ? description ? { message, description } : { message } : message;
61
+ return [k, value];
62
+ });
63
+ return `${JSON.stringify(Object.fromEntries(entries), null, options.indent ?? 2)}
64
+ `;
65
+ }
66
+
67
+ export { parseFlatJson, stringifyFlatJson };
@@ -0,0 +1,70 @@
1
+ 'use strict';
2
+
3
+ var chunkMFJL3NO5_cjs = require('./chunk-MFJL3NO5.cjs');
4
+ var chunk2A6WFLXS_cjs = require('./chunk-2A6WFLXS.cjs');
5
+
6
+ // src/vendor/i18n-tools/json.ts
7
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
8
+ function parseFlatJson(input, options = {}) {
9
+ const maxBytes = options.maxBytes ?? 4 * 1024 * 1024;
10
+ if (input.length > maxBytes || chunkMFJL3NO5_cjs.utf8ByteLength(input) > maxBytes) throw new chunkMFJL3NO5_cjs.I18nToolsError("too-large", `el JSON pasa de ${maxBytes} bytes`);
11
+ let data;
12
+ try {
13
+ data = JSON.parse(input.charCodeAt(0) === 65279 ? input.slice(1) : input);
14
+ } catch (e) {
15
+ throw new chunkMFJL3NO5_cjs.I18nToolsError("malformed-json", `JSON no v\xE1lido: ${e.message}`);
16
+ }
17
+ if (!isObject(data)) throw new chunkMFJL3NO5_cjs.I18nToolsError("malformed-json", "se esperaba un objeto en la ra\xEDz");
18
+ const strict = options.strictKeys !== false;
19
+ const maxDepth = options.maxDepth ?? 8;
20
+ const messages = [];
21
+ const descriptions = [];
22
+ const seen = /* @__PURE__ */ new Set();
23
+ const add = (key, value) => {
24
+ if (strict && !chunk2A6WFLXS_cjs.CATALOG_KEY.test(key)) throw new chunkMFJL3NO5_cjs.I18nToolsError("invalid-key", `clave no v\xE1lida \xAB${key}\xBB`);
25
+ if (seen.has(key)) throw new chunkMFJL3NO5_cjs.I18nToolsError("duplicate-key", `clave repetida \xAB${key}\xBB (tras aplanar)`);
26
+ seen.add(key);
27
+ if (typeof value === "string") {
28
+ messages.push([key, value]);
29
+ return;
30
+ }
31
+ if (isObject(value)) {
32
+ const message = value["message"] ?? value["defaultMessage"];
33
+ if (typeof message === "string") {
34
+ messages.push([key, message]);
35
+ const d = value["description"];
36
+ if (typeof d === "string" && d !== "") descriptions.push([key, d]);
37
+ return;
38
+ }
39
+ }
40
+ throw new chunkMFJL3NO5_cjs.I18nToolsError("malformed-json", `el valor de \xAB${key}\xBB debe ser un texto o un objeto con \xABmessage\xBB`);
41
+ };
42
+ const stack = [{ prefix: "", obj: data, depth: 1 }];
43
+ while (stack.length > 0) {
44
+ const { prefix, obj, depth } = stack.pop();
45
+ for (const [k, v] of Object.entries(obj)) {
46
+ const key = prefix ? `${prefix}.${k}` : k;
47
+ const isLeafObject = isObject(v) && (typeof v["message"] === "string" || typeof v["defaultMessage"] === "string");
48
+ if (options.nested && isObject(v) && !isLeafObject) {
49
+ if (depth >= maxDepth) throw new chunkMFJL3NO5_cjs.I18nToolsError("too-deep", `anidamiento de m\xE1s de ${maxDepth} niveles`);
50
+ stack.push({ prefix: key, obj: v, depth: depth + 1 });
51
+ } else add(key, v);
52
+ }
53
+ }
54
+ messages.sort((a, b) => chunkMFJL3NO5_cjs.compareCodeUnits(a[0], b[0]));
55
+ descriptions.sort((a, b) => chunkMFJL3NO5_cjs.compareCodeUnits(a[0], b[0]));
56
+ return { messages: Object.fromEntries(messages), descriptions: Object.fromEntries(descriptions) };
57
+ }
58
+ function stringifyFlatJson(messages, options = {}) {
59
+ const entries = Object.keys(messages).sort(chunkMFJL3NO5_cjs.compareCodeUnits).map((k) => {
60
+ const message = messages[k] ?? "";
61
+ const description = options.descriptions?.[k];
62
+ const value = options.style === "described" ? description ? { message, description } : { message } : message;
63
+ return [k, value];
64
+ });
65
+ return `${JSON.stringify(Object.fromEntries(entries), null, options.indent ?? 2)}
66
+ `;
67
+ }
68
+
69
+ exports.parseFlatJson = parseFlatJson;
70
+ exports.stringifyFlatJson = stringifyFlatJson;
@@ -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 };