@customyai/cli 0.10.1 → 0.14.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/CHANGELOG.md +24 -0
- package/README.md +7 -5
- package/dist/bin.cjs +3 -3
- package/dist/bin.mjs +2 -2
- package/dist/{chunk-QKIF4C5R.mjs → chunk-CCF7M44T.mjs} +16 -2
- package/dist/{chunk-6X3AX6PB.cjs → chunk-F7DBJYTA.cjs} +675 -123
- package/dist/{chunk-57NNDUEX.mjs → chunk-GD2FZPDE.mjs} +664 -112
- package/dist/{chunk-2A6WFLXS.cjs → chunk-VUQSQ5YY.cjs} +16 -1
- package/dist/index.cjs +17 -17
- package/dist/index.d.cts +10 -2
- package/dist/index.d.ts +10 -2
- package/dist/index.mjs +2 -2
- package/dist/{json-NETFQXLJ.mjs → json-37BBZACO.mjs} +2 -2
- package/dist/{json-NSJMTBPP.cjs → json-FSAA27RC.cjs} +2 -2
- package/dist/{po-AKWHAYBL.mjs → po-AD6IPL4F.mjs} +2 -2
- package/dist/{po-IJGMXNVY.cjs → po-ZQLZ4U5Q.cjs} +10 -10
- package/dist/{quality-6SEZNA6Q.cjs → quality-2GNGP67B.cjs} +3 -3
- package/dist/{quality-ILK6IA5O.mjs → quality-UALNP7GO.mjs} +1 -1
- package/dist/{xliff-DXICWMWC.cjs → xliff-EBJNXSR6.cjs} +20 -13
- package/dist/{xliff-DEJHB2SY.mjs → xliff-IAIUQGY4.mjs} +12 -5
- package/package.json +1 -1
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkVUQSQ5YY_cjs = require('./chunk-VUQSQ5YY.cjs');
|
|
4
4
|
var zod = require('zod');
|
|
5
5
|
var promises = require('fs/promises');
|
|
6
|
-
var
|
|
6
|
+
var path4 = require('path');
|
|
7
7
|
var provisioning = require('@customyai/provisioning');
|
|
8
8
|
var core = require('@customyai/core');
|
|
9
9
|
var whatsapp = require('@customyai/whatsapp');
|
|
10
10
|
|
|
11
11
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
12
12
|
|
|
13
|
-
var
|
|
13
|
+
var path4__default = /*#__PURE__*/_interopDefault(path4);
|
|
14
14
|
|
|
15
15
|
// src/codegen.ts
|
|
16
16
|
var literal = (value) => JSON.stringify(value);
|
|
@@ -159,6 +159,8 @@ var CONNECTABLE_PRODUCT_MANIFESTS = [
|
|
|
159
159
|
product("customy-data", [{ kind: "external_source", keys: ["analytics-source"], operations: { allowed: ["submit"], mode: "exact" } }]),
|
|
160
160
|
// Experiments: las apps conectadas lo referencian para evaluar flags con su clave publicable; sin enlaces propios todavía (F5).
|
|
161
161
|
product("customy-experiments"),
|
|
162
|
+
// Paywalls: las apps conectadas lo consumen por `decide` con su clave publicable; sin enlaces propios todavía (F2 trae el SDK).
|
|
163
|
+
product("customy-paywalls"),
|
|
162
164
|
product("customy-analytics"),
|
|
163
165
|
product("customy-campaigns", [{ kind: "external_communication", keys: ["weekly-brief"], operations: { allowed: ["read"], mode: "exact" } }]),
|
|
164
166
|
product("customy-engagement", [{ kind: "external_communication", keys: ["notification-delivery", "operator-approval"], operations: { allowed: ["deliver_notification", "request_operator_approval"], mode: "subset" } }]),
|
|
@@ -289,11 +291,11 @@ function appManifestProblems(input, manifests = CONNECTABLE_PRODUCT_MANIFESTS) {
|
|
|
289
291
|
if (!parsed.success) return parsed.error.issues.map((issue) => ({ path: issue.path.join("."), code: "SCHEMA_INVALID" }));
|
|
290
292
|
const app = parsed.data;
|
|
291
293
|
const problems = [];
|
|
292
|
-
const unique = (items, key2,
|
|
294
|
+
const unique = (items, key2, path7) => {
|
|
293
295
|
const seen = /* @__PURE__ */ new Set();
|
|
294
296
|
items.forEach((item, index) => {
|
|
295
297
|
const k = key2(item);
|
|
296
|
-
if (seen.has(k)) problems.push({ path: `${
|
|
298
|
+
if (seen.has(k)) problems.push({ path: `${path7}.${index}`, code: "DUPLICATE" });
|
|
297
299
|
seen.add(k);
|
|
298
300
|
});
|
|
299
301
|
};
|
|
@@ -370,33 +372,43 @@ function validateManifest(input) {
|
|
|
370
372
|
return problems.length ? { ok: false, problems } : { ok: true, manifest: AppManifestSchema.parse(input) };
|
|
371
373
|
}
|
|
372
374
|
var SyncError = class extends Error {
|
|
373
|
-
constructor(code, status2) {
|
|
374
|
-
super(`${code} (${status2})`);
|
|
375
|
+
constructor(code, status2, hint) {
|
|
376
|
+
super(`${code} (${status2})${hint ? ` \u2014 ${hint}` : ""}`);
|
|
375
377
|
this.code = code;
|
|
376
378
|
this.status = status2;
|
|
379
|
+
this.hint = hint;
|
|
377
380
|
}
|
|
378
381
|
code;
|
|
379
382
|
status;
|
|
383
|
+
hint;
|
|
380
384
|
};
|
|
385
|
+
function rejectedCredentialHint(sent) {
|
|
386
|
+
return sent === "bearer" ? "Access rechaz\xF3 el Bearer (CUSTOMY_ACCESS_TOKEN). Access de producci\xF3n espera el secreto de administrador en la cabecera x-admin-secret: define CUSTOMY_ADMIN_SECRET" : "Access rechaz\xF3 x-admin-secret (CUSTOMY_ADMIN_SECRET). Comprueba el secreto de ese entorno o usa un token de administrador del Workspace en CUSTOMY_ACCESS_TOKEN (Bearer)";
|
|
387
|
+
}
|
|
381
388
|
async function syncApp(options) {
|
|
382
389
|
const base = options.accessUrl.replace(/\/$/, "");
|
|
383
390
|
if (!/^https:\/\//.test(base) && !/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(base)) throw new SyncError("ACCESS_URL_INSECURE", 0);
|
|
384
|
-
const
|
|
385
|
-
|
|
391
|
+
const sent = options.adminSecret ? "x-admin-secret" : "bearer";
|
|
392
|
+
if (!options.adminSecret && !options.token) throw new SyncError("ACCESS_CREDENTIAL_MISSING", 0, "define CUSTOMY_ADMIN_SECRET (x-admin-secret) o CUSTOMY_ACCESS_TOKEN (Bearer)");
|
|
393
|
+
const credential = options.adminSecret ? { "x-admin-secret": options.adminSecret, "x-reason": options.reason.slice(0, 256), ...options.actor ? { "x-actor": options.actor } : {} } : { authorization: `Bearer ${options.token}` };
|
|
394
|
+
const call = async (method, path7, body) => {
|
|
395
|
+
const response = await (options.fetch ?? fetch)(`${base}${path7}`, {
|
|
386
396
|
method,
|
|
387
|
-
headers: {
|
|
397
|
+
headers: { ...credential, "content-type": "application/json", "idempotency-key": crypto.randomUUID() },
|
|
388
398
|
body: JSON.stringify(body)
|
|
389
399
|
});
|
|
390
400
|
const json = await response.json().catch(() => ({}));
|
|
391
|
-
if (!response.ok) throw new SyncError(String(json.code ?? json.error ?? "ACCESS_REQUEST_FAILED"), response.status);
|
|
401
|
+
if (!response.ok) throw new SyncError(String(json.code ?? json.error ?? "ACCESS_REQUEST_FAILED"), response.status, response.status === 401 ? rejectedCredentialHint(sent) : void 0);
|
|
392
402
|
return json;
|
|
393
403
|
};
|
|
394
404
|
const env = encodeURIComponent(options.workspaceEnvironmentId);
|
|
395
405
|
const installed = await call("POST", `/api/admin/env/${env}/connected-applications/install`, { manifest: options.manifest, reason: options.reason });
|
|
396
406
|
const connection = installed.connection;
|
|
407
|
+
const key2 = installed.publishableKey ?? connection.publishableKey;
|
|
408
|
+
const publishableKey = typeof key2 === "string" && key2 ? key2 : null;
|
|
397
409
|
const reconciliation = (value) => value && typeof value === "object" ? value : {};
|
|
398
410
|
if (!installed.replayed) {
|
|
399
|
-
return { action: "installed", applicationId: connection.applicationId, environmentId: connection.environmentId, revision: connection.revision, reconciliation: reconciliation(installed.reconciliation) };
|
|
411
|
+
return { action: "installed", applicationId: connection.applicationId, environmentId: connection.environmentId, revision: connection.revision, publishableKey, reconciliation: reconciliation(installed.reconciliation) };
|
|
400
412
|
}
|
|
401
413
|
const updated = await call("PUT", `/api/admin/env/${encodeURIComponent(connection.environmentId)}/connected-application/manifest`, {
|
|
402
414
|
expectedRevision: connection.revision,
|
|
@@ -404,7 +416,7 @@ async function syncApp(options) {
|
|
|
404
416
|
reason: options.reason
|
|
405
417
|
});
|
|
406
418
|
const revision = Number(updated.revision ?? connection.revision);
|
|
407
|
-
return { action: updated.unchanged ? "unchanged" : "updated", applicationId: connection.applicationId, environmentId: connection.environmentId, revision, reconciliation: reconciliation(updated.reconciliation) };
|
|
419
|
+
return { action: updated.unchanged ? "unchanged" : "updated", applicationId: connection.applicationId, environmentId: connection.environmentId, revision, publishableKey, reconciliation: reconciliation(updated.reconciliation) };
|
|
408
420
|
}
|
|
409
421
|
var EXIT = { ok: 0, failure: 1, unsupported: 2, auth: 3, confirmation: 4 };
|
|
410
422
|
var PROVISIONING_GROUPS = ["users", "audit", "policy", "whoami", "login"];
|
|
@@ -740,7 +752,7 @@ async function audit(args, io) {
|
|
|
740
752
|
const text = await liveClient(ctx).audit.export({ format, ...pick(flags) });
|
|
741
753
|
const out = str(flags, "out");
|
|
742
754
|
if (out) {
|
|
743
|
-
const target =
|
|
755
|
+
const target = path4__default.default.resolve(io.cwd, out);
|
|
744
756
|
await promises.writeFile(target, text, { mode: 384 });
|
|
745
757
|
await promises.chmod(target, 384).catch(() => void 0);
|
|
746
758
|
emit(ctx, { out, bytes: text.length, format }, [`wrote ${text.length} characters of ${format} to ${out}`]);
|
|
@@ -873,7 +885,7 @@ async function readBody(flags, io) {
|
|
|
873
885
|
if (typeof file !== "string") throw new UsageError2("falta --file con el JSON de la petici\xF3n");
|
|
874
886
|
let parsed;
|
|
875
887
|
try {
|
|
876
|
-
parsed = JSON.parse(await promises.readFile(
|
|
888
|
+
parsed = JSON.parse(await promises.readFile(path4__default.default.resolve(io.cwd, file), "utf8"));
|
|
877
889
|
} catch (error) {
|
|
878
890
|
throw new UsageError2(`no se pudo leer ${file}: ${error instanceof Error ? error.message : String(error)}`);
|
|
879
891
|
}
|
|
@@ -1023,10 +1035,379 @@ async function runExperimentsCli(group, args, io) {
|
|
|
1023
1035
|
return EXPERIMENTS_EXIT.failure;
|
|
1024
1036
|
}
|
|
1025
1037
|
}
|
|
1038
|
+
var INTEGRATOR_HELP = [
|
|
1039
|
+
" customy experience add [component:|tokens:|catalog:]<name> [--kind component|tokens|catalog] [--dir customy] [--revision n] [--force] [--dry-run]",
|
|
1040
|
+
" bring one artifact from the backend into your project (JSON + a typed .ts module + a lock); --list shows what exists",
|
|
1041
|
+
" customy experience diff <releaseA> [<releaseB>] [--html changes.html] [--fail-on removed,contrast] what changes between two releases, per type",
|
|
1042
|
+
' customy experience pin <app> <release> --reason "..." [--dry-run] | pin <app> --clear --reason "..." declare which release an app should use (write key)',
|
|
1043
|
+
" customy experience status --app <app> [--channel production] which release and source that app sees",
|
|
1044
|
+
" Read commands use CUSTOMY_EXPERIENCE_READ_KEY (falls back to CUSTOMY_EXPERIENCE_TOKEN); `pin` needs CUSTOMY_EXPERIENCE_TOKEN (write)."
|
|
1045
|
+
];
|
|
1046
|
+
var readClient = (flags, io) => makeClient(flags, io, {
|
|
1047
|
+
token: io.env.CUSTOMY_EXPERIENCE_READ_KEY || io.env.CUSTOMY_EXPERIENCE_TOKEN,
|
|
1048
|
+
missing: "falta una credencial de lectura: CUSTOMY_EXPERIENCE_READ_KEY (o CUSTOMY_EXPERIENCE_TOKEN) en el entorno, nunca por la l\xEDnea de comandos"
|
|
1049
|
+
});
|
|
1050
|
+
var writeClient = (flags, io) => makeClient(flags, io, {
|
|
1051
|
+
token: io.env.CUSTOMY_EXPERIENCE_TOKEN,
|
|
1052
|
+
missing: io.env.CUSTOMY_EXPERIENCE_READ_KEY ? "`pin` escribe y una clave de solo lectura no puede: define CUSTOMY_EXPERIENCE_TOKEN (credencial de escritura con experience.release.publish)" : "falta CUSTOMY_EXPERIENCE_TOKEN en el entorno (credencial de escritura con experience.release.publish; nunca por la l\xEDnea de comandos)"
|
|
1053
|
+
});
|
|
1054
|
+
var APP_NAME = /^[a-z][a-z0-9-]{0,39}$/;
|
|
1055
|
+
var num = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
1056
|
+
var KIND_ALIASES = { component: "component", componente: "component", tokens: "tokens", token: "tokens", catalog: "catalog", text: "catalog", texto: "catalog", textos: "catalog" };
|
|
1057
|
+
var KIND_DIR = { component: "components", tokens: "tokens", catalog: "text" };
|
|
1058
|
+
function kindOf(raw) {
|
|
1059
|
+
if (raw === void 0) return null;
|
|
1060
|
+
const kind = typeof raw === "string" ? KIND_ALIASES[raw.toLowerCase()] : void 0;
|
|
1061
|
+
if (!kind) throw new UsageError3("--kind debe ser component|componente, tokens|token o catalog|texto");
|
|
1062
|
+
return kind;
|
|
1063
|
+
}
|
|
1064
|
+
var fileSafe = (name) => name.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^[-.]+|[-.]+$/g, "") || "artifact";
|
|
1065
|
+
var pascal = (name) => name.split(/[^A-Za-z0-9]+/).filter(Boolean).map((p) => p[0].toUpperCase() + p.slice(1)).join("") || "Artifact";
|
|
1066
|
+
var camel = (name) => {
|
|
1067
|
+
const p = pascal(name);
|
|
1068
|
+
return p[0].toLowerCase() + p.slice(1);
|
|
1069
|
+
};
|
|
1070
|
+
var sortedJson = (value) => {
|
|
1071
|
+
if (Array.isArray(value)) return value.map(sortedJson);
|
|
1072
|
+
if (isRec(value)) return Object.fromEntries(Object.keys(value).sort().map((k) => [k, sortedJson(value[k])]));
|
|
1073
|
+
return value;
|
|
1074
|
+
};
|
|
1075
|
+
var pretty = (value) => `${JSON.stringify(sortedJson(value), null, 2)}
|
|
1076
|
+
`;
|
|
1077
|
+
async function listArtifacts(client, kind) {
|
|
1078
|
+
const all = [];
|
|
1079
|
+
let after;
|
|
1080
|
+
for (let page = 0; page < 50; page += 1) {
|
|
1081
|
+
const result = await client.request("GET", "/artifacts", { query: { kind, limit: "200", ...after ? { after } : {} } });
|
|
1082
|
+
const data = isRec(result) && Array.isArray(result.data) ? result.data.filter(isRec) : [];
|
|
1083
|
+
all.push(...data);
|
|
1084
|
+
const next = isRec(result) ? result.next : null;
|
|
1085
|
+
if (typeof next !== "string" || !data.length) break;
|
|
1086
|
+
after = next;
|
|
1087
|
+
}
|
|
1088
|
+
return all.filter((a) => !a.archivedAt);
|
|
1089
|
+
}
|
|
1090
|
+
var LOCK = "customy.add.lock.json";
|
|
1091
|
+
async function readAddLock(dir) {
|
|
1092
|
+
try {
|
|
1093
|
+
const parsed = JSON.parse(await promises.readFile(path4__default.default.join(dir, LOCK), "utf8"));
|
|
1094
|
+
if (isRec(parsed) && isRec(parsed.items)) return parsed;
|
|
1095
|
+
} catch {
|
|
1096
|
+
}
|
|
1097
|
+
return { version: 1, origin: "", items: {} };
|
|
1098
|
+
}
|
|
1099
|
+
function planFiles(kind, name, locale, document, root) {
|
|
1100
|
+
const base = `${root}/${KIND_DIR[kind]}`;
|
|
1101
|
+
const stem = fileSafe(locale ? `${name}.${locale}` : name);
|
|
1102
|
+
if (kind === "catalog") {
|
|
1103
|
+
const checked = chunkVUQSQ5YY_cjs.validateCatalog(document, { limits: chunkVUQSQ5YY_cjs.TRANSLATION_PLAN_LIMITS.enterprise });
|
|
1104
|
+
if (!checked.ok || !checked.doc) throw new ExitError(EXPERIENCE_EXIT.invalid, `el servidor devolvi\xF3 \xAB${name}\xBB sin ser un catalog@1 v\xE1lido: ${checked.issues[0]?.message ?? "?"}`);
|
|
1105
|
+
const keys = Object.keys(checked.doc.messages).sort();
|
|
1106
|
+
const type = `${pascal(name)}Key`;
|
|
1107
|
+
return [
|
|
1108
|
+
{ file: `${base}/${stem}.json`, content: serializeCatalog(checked.doc) },
|
|
1109
|
+
{ file: `${base}/${stem}.ts`, content: `// Generado por \xABcustomy experience add\xBB. No lo edites: vuelve a ejecutar el comando.
|
|
1110
|
+
export type ${type} = ${keys.length ? keys.map((k) => JSON.stringify(k)).join(" | ") : "never"};
|
|
1111
|
+
export const ${camel(name)}Keys: readonly ${type}[] = ${JSON.stringify(keys)};
|
|
1112
|
+
` }
|
|
1113
|
+
];
|
|
1114
|
+
}
|
|
1115
|
+
const doc = isRec(document) ? document : {};
|
|
1116
|
+
const body = `${JSON.stringify(sortedJson(document), null, 2)}`;
|
|
1117
|
+
if (kind === "tokens") {
|
|
1118
|
+
const tokens = isRec(doc.tokens) ? doc.tokens : doc;
|
|
1119
|
+
const names = Object.keys(tokens).sort();
|
|
1120
|
+
return [
|
|
1121
|
+
{ file: `${base}/${stem}.json`, content: pretty(document) },
|
|
1122
|
+
{ file: `${base}/${stem}.ts`, content: `// Generado por \xABcustomy experience add\xBB. No lo edites: vuelve a ejecutar el comando.
|
|
1123
|
+
export const ${camel(name)} = ${body} as const;
|
|
1124
|
+
export type ${pascal(name)} = typeof ${camel(name)};
|
|
1125
|
+
export type ${pascal(name)}Token = ${names.length ? names.map((k) => JSON.stringify(k)).join(" | ") : "never"};
|
|
1126
|
+
` }
|
|
1127
|
+
];
|
|
1128
|
+
}
|
|
1129
|
+
return [
|
|
1130
|
+
{ file: `${base}/${stem}.json`, content: pretty(document) },
|
|
1131
|
+
{ file: `${base}/${stem}.ts`, content: `// Generado por \xABcustomy experience add\xBB. No lo edites: vuelve a ejecutar el comando.
|
|
1132
|
+
export const ${camel(name)} = ${body} as const;
|
|
1133
|
+
export type ${pascal(name)} = typeof ${camel(name)};
|
|
1134
|
+
` }
|
|
1135
|
+
];
|
|
1136
|
+
}
|
|
1137
|
+
async function addCmd(positional, flags, io) {
|
|
1138
|
+
const client = readClient(flags, io);
|
|
1139
|
+
let kind = kindOf(flags.kind);
|
|
1140
|
+
if (flags.list) {
|
|
1141
|
+
const kinds2 = kind ? [kind] : ["component", "tokens", "catalog"];
|
|
1142
|
+
const items = [];
|
|
1143
|
+
for (const k of kinds2) for (const a of await listArtifacts(client, k)) items.push({ kind: k, name: str2(a.name), locale: str2(a.locale) || null, artifactId: str2(a.id) });
|
|
1144
|
+
items.sort((a, b) => a.kind.localeCompare(b.kind) || a.name.localeCompare(b.name) || (a.locale ?? "").localeCompare(b.locale ?? ""));
|
|
1145
|
+
return { lines: items.length ? items.map((i) => ` ${i.kind}:${i.name}${i.locale ? ` (${i.locale})` : ""}`) : [" (nada publicado para esos tipos)"], result: { items } };
|
|
1146
|
+
}
|
|
1147
|
+
if (positional.length !== 1) throw new UsageError3("uso: customy experience add [component:|tokens:|catalog:]<nombre> [--kind \u2026] [--dir customy] [--revision n] [--force] [--dry-run] (o --list)");
|
|
1148
|
+
let name = positional[0];
|
|
1149
|
+
const prefixed = name.match(/^([A-Za-z]+):(.+)$/);
|
|
1150
|
+
if (prefixed) {
|
|
1151
|
+
const fromPrefix = KIND_ALIASES[prefixed[1].toLowerCase()];
|
|
1152
|
+
if (!fromPrefix) throw new UsageError3(`tipo desconocido \xAB${prefixed[1]}\xBB: usa component, tokens o catalog (tambi\xE9n componente, token, texto)`);
|
|
1153
|
+
if (kind && kind !== fromPrefix) throw new UsageError3("el prefijo del nombre y --kind no coinciden");
|
|
1154
|
+
kind = fromPrefix;
|
|
1155
|
+
name = prefixed[2];
|
|
1156
|
+
}
|
|
1157
|
+
const wantedRevision = typeof flags.revision === "string" ? Number(flags.revision) : null;
|
|
1158
|
+
if (wantedRevision !== null && (!Number.isInteger(wantedRevision) || wantedRevision < 1)) throw new UsageError3("--revision debe ser un entero positivo");
|
|
1159
|
+
const kinds = kind ? [kind] : ["component", "tokens", "catalog"];
|
|
1160
|
+
const matches = [];
|
|
1161
|
+
for (const k of kinds) for (const art of await listArtifacts(client, k)) if (str2(art.name) === name) matches.push({ kind: k, art });
|
|
1162
|
+
if (!matches.length) throw new ExitError(EXPERIENCE_EXIT.auth, `no hay ning\xFAn artefacto \xAB${name}\xBB${kind ? ` de tipo ${kind}` : ""} (o no tienes permiso para verlo). Mira lo disponible con \xABcustomy experience add --list\xBB.`);
|
|
1163
|
+
const kindsFound = [...new Set(matches.map((m) => m.kind))];
|
|
1164
|
+
if (kindsFound.length > 1) throw new UsageError3(`\xAB${name}\xBB existe como ${kindsFound.join(" y ")}: indica cu\xE1l con el prefijo (p. ej. ${kindsFound[0]}:${name}) o --kind`);
|
|
1165
|
+
const found = matches[0].kind;
|
|
1166
|
+
const root = typeof flags.dir === "string" ? flags.dir : "customy";
|
|
1167
|
+
const abs = path4__default.default.resolve(io.cwd, root);
|
|
1168
|
+
const planned = [];
|
|
1169
|
+
const lockItems = [];
|
|
1170
|
+
for (const { art } of matches) {
|
|
1171
|
+
const id = str2(art.id);
|
|
1172
|
+
const detail = await client.request("GET", `/artifacts/${encodeURIComponent(id)}`);
|
|
1173
|
+
const latest = isRec(detail) ? num(detail.latestRevision) ?? 0 : 0;
|
|
1174
|
+
const revision = wantedRevision ?? latest;
|
|
1175
|
+
if (revision < 1) throw new ExitError(EXPERIENCE_EXIT.conflict, `\xAB${name}\xBB no tiene ninguna revisi\xF3n publicada: un borrador no se trae. Pide a quien lo edita que lo publique.`);
|
|
1176
|
+
const rev = await client.request("GET", `/artifacts/${encodeURIComponent(id)}/revisions/${revision}`);
|
|
1177
|
+
if (!isRec(rev) || rev.document === void 0) throw new ExitError(EXPERIENCE_EXIT.failure, `el servicio no devolvi\xF3 el documento de \xAB${name}\xBB r${revision}`);
|
|
1178
|
+
const locale = str2(art.locale) || void 0;
|
|
1179
|
+
const files = planFiles(found, name, locale, rev.document, root);
|
|
1180
|
+
planned.push(...files);
|
|
1181
|
+
lockItems.push([`${found}:${name}${locale ? `/${locale}` : ""}`, { kind: found, name, ...locale ? { locale } : {}, artifactId: id, revision, contentHash: typeof rev.contentHash === "string" ? rev.contentHash : null, files: files.map((f) => f.file) }]);
|
|
1182
|
+
}
|
|
1183
|
+
const states = [];
|
|
1184
|
+
for (const f of planned) {
|
|
1185
|
+
let current = null;
|
|
1186
|
+
try {
|
|
1187
|
+
current = await promises.readFile(path4__default.default.resolve(io.cwd, f.file), "utf8");
|
|
1188
|
+
} catch {
|
|
1189
|
+
current = null;
|
|
1190
|
+
}
|
|
1191
|
+
states.push({ file: f.file, action: current === null ? "create" : current === f.content ? "unchanged" : "update" });
|
|
1192
|
+
}
|
|
1193
|
+
const blocked = states.filter((s) => s.action === "update" && !flags.force).map((s) => s.file);
|
|
1194
|
+
if (blocked.length && !flags["dry-run"]) throw new ExitError(EXPERIENCE_EXIT.conflict, `ya existen y difieren (\xBFeditados a mano o de otra revisi\xF3n?): ${blocked.join(", ")}. Revisa con git diff y repite con --force para sobrescribir.`);
|
|
1195
|
+
const summary = lockItems.map(([, e]) => `${e.kind}:${e.name}${e.locale ? `/${e.locale}` : ""} r${e.revision}`).join(", ");
|
|
1196
|
+
const fileLines = states.map((s) => ` ${s.action === "create" ? "+" : s.action === "update" ? "~" : "="} ${s.file}${s.action === "update" && !flags.force ? " (difiere: --force)" : ""}`);
|
|
1197
|
+
if (flags["dry-run"]) return { lines: [`dry-run: se traer\xEDa ${summary}; no se escribi\xF3 nada`, ...fileLines], result: { dryRun: true, kind: found, name, files: states, blocked } };
|
|
1198
|
+
for (const f of planned) {
|
|
1199
|
+
const target = path4__default.default.resolve(io.cwd, f.file);
|
|
1200
|
+
await promises.mkdir(path4__default.default.dirname(target), { recursive: true });
|
|
1201
|
+
await promises.writeFile(target, f.content);
|
|
1202
|
+
}
|
|
1203
|
+
const lock = await readAddLock(abs);
|
|
1204
|
+
lock.origin = client.origin;
|
|
1205
|
+
for (const [key2, entry] of lockItems) lock.items[key2] = entry;
|
|
1206
|
+
const sortedItems = Object.fromEntries(Object.keys(lock.items).sort().map((k) => [k, lock.items[k]]));
|
|
1207
|
+
await promises.mkdir(abs, { recursive: true });
|
|
1208
|
+
await promises.writeFile(path4__default.default.join(abs, LOCK), pretty({ version: 1, origin: lock.origin, items: sortedItems }));
|
|
1209
|
+
return { lines: [`\u2713 ${summary}`, ...fileLines, ` lock: ${root}/${LOCK}`], result: { kind: found, name, files: states, lock: `${root}/${LOCK}` } };
|
|
1210
|
+
}
|
|
1211
|
+
var strList = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
|
|
1212
|
+
function normalizeDiff(data) {
|
|
1213
|
+
const d = isRec(data) ? data : {};
|
|
1214
|
+
const side = (v) => isRec(v) && typeof v.releaseId === "string" && typeof v.number === "number" ? { releaseId: v.releaseId, number: v.number } : null;
|
|
1215
|
+
const to = side(d.to);
|
|
1216
|
+
if (!to) throw new ExitError(EXPERIENCE_EXIT.failure, "el servicio no devolvi\xF3 un diff de release reconocible (\xBFel BFF o el servicio son anteriores a F1?)");
|
|
1217
|
+
const entries = (Array.isArray(d.entries) ? d.entries.filter(isRec) : []).map((e) => {
|
|
1218
|
+
const diff = isRec(e.diff) ? e.diff : null;
|
|
1219
|
+
const colors = diff && isRec(diff.tokens) && Array.isArray(diff.tokens.colors) ? diff.tokens.colors.filter(isRec) : [];
|
|
1220
|
+
const messages2 = diff && isRec(diff.messages) ? { added: strList(diff.messages.added), changed: strList(diff.messages.changed), removed: strList(diff.messages.removed) } : null;
|
|
1221
|
+
const comp = isRec(e.component) ? e.component : diff && isRec(diff.component) ? diff.component : null;
|
|
1222
|
+
return {
|
|
1223
|
+
artifactId: str2(e.artifactId),
|
|
1224
|
+
kind: str2(e.kind),
|
|
1225
|
+
name: str2(e.name),
|
|
1226
|
+
locale: str2(e.locale) || null,
|
|
1227
|
+
change: e.change === "added" || e.change === "removed" ? e.change : "changed",
|
|
1228
|
+
from: isRec(e.from) ? num(e.from.revision) : null,
|
|
1229
|
+
to: isRec(e.to) ? num(e.to.revision) : null,
|
|
1230
|
+
fields: diff && isRec(diff.summary) ? { added: num(diff.summary.added) ?? 0, changed: num(diff.summary.changed) ?? 0, removed: num(diff.summary.removed) ?? 0 } : null,
|
|
1231
|
+
messages: messages2,
|
|
1232
|
+
colors: colors.map((c) => {
|
|
1233
|
+
const cb = isRec(c.contrastBefore) ? c.contrastBefore : null, ca = isRec(c.contrastAfter) ? c.contrastAfter : null;
|
|
1234
|
+
const passesTextAfter = ca && typeof ca.passesText === "boolean" ? ca.passesText : null;
|
|
1235
|
+
return { key: str2(c.key), change: str2(c.change), before: typeof c.before === "string" ? c.before : null, after: typeof c.after === "string" ? c.after : null, contrastBefore: cb ? num(cb.ratio) : null, contrastAfter: ca ? num(ca.ratio) : null, passesTextAfter, regressed: !!(cb && ca && cb.passesText === true && ca.passesText === false) };
|
|
1236
|
+
}),
|
|
1237
|
+
component: comp ? { bump: str2(comp.bump), changes: Array.isArray(comp.changes) ? comp.changes.map((c) => isRec(c) ? `${str2(c.bump)}: ${str2(c.what)}` : String(c)) : [] } : null,
|
|
1238
|
+
changes: diff && Array.isArray(diff.changes) ? diff.changes.filter(isRec).map((c) => ({ path: str2(c.path), change: str2(c.change), before: typeof c.before === "string" ? c.before : null, after: typeof c.after === "string" ? c.after : null })) : []
|
|
1239
|
+
};
|
|
1240
|
+
});
|
|
1241
|
+
const s = isRec(d.summary) ? d.summary : {};
|
|
1242
|
+
return {
|
|
1243
|
+
from: side(d.from),
|
|
1244
|
+
to,
|
|
1245
|
+
summary: { added: num(s.added) ?? 0, changed: num(s.changed) ?? 0, removed: num(s.removed) ?? 0, unchanged: num(s.unchanged) ?? 0 },
|
|
1246
|
+
entries,
|
|
1247
|
+
truncated: d.truncated === true,
|
|
1248
|
+
contrastRegressions: entries.reduce((n, e) => n + e.colors.filter((c) => c.regressed).length, 0)
|
|
1249
|
+
};
|
|
1250
|
+
}
|
|
1251
|
+
var label = (e) => `${e.kind}:${e.name}${e.locale ? `/${e.locale}` : ""}`;
|
|
1252
|
+
var rel = (r) => r ? `#${r.number}` : "(nada: primer release)";
|
|
1253
|
+
function diffLines(d) {
|
|
1254
|
+
const lines = [`Release ${rel(d.from)} \u2192 ${rel(d.to)}: ${d.summary.added} a\xF1adidos, ${d.summary.changed} cambiados, ${d.summary.removed} eliminados, ${d.summary.unchanged} sin cambios`];
|
|
1255
|
+
for (const e of d.entries) {
|
|
1256
|
+
const mark = e.change === "added" ? "+" : e.change === "removed" ? "-" : "~";
|
|
1257
|
+
const revs = e.change === "changed" ? ` r${e.from}\u2192r${e.to}` : e.change === "added" ? ` r${e.to}` : ` r${e.from}`;
|
|
1258
|
+
const detail = [];
|
|
1259
|
+
if (e.messages) detail.push(`textos +${e.messages.added.length} ~${e.messages.changed.length} -${e.messages.removed.length}`);
|
|
1260
|
+
else if (e.fields && e.kind !== "component") detail.push(`campos +${e.fields.added} ~${e.fields.changed} -${e.fields.removed}`);
|
|
1261
|
+
if (e.component) detail.push(`bump ${e.component.bump || "?"}`);
|
|
1262
|
+
lines.push(` ${mark} ${label(e)}${revs}${detail.length ? ` (${detail.join("; ")})` : ""}`);
|
|
1263
|
+
for (const c of e.colors.filter((x) => x.regressed)) lines.push(` ! contraste de ${c.key}: ${c.contrastBefore} \u2192 ${c.contrastAfter} (pierde AA de texto)`);
|
|
1264
|
+
for (const key2 of e.messages?.removed ?? []) lines.push(` ! texto eliminado: ${key2}`);
|
|
1265
|
+
}
|
|
1266
|
+
if (d.truncated) lines.push(" (hay m\xE1s cambios de los que el servicio detalla: el resumen los cuenta todos)");
|
|
1267
|
+
if (d.contrastRegressions) lines.push(`! ${d.contrastRegressions} color(es) pierden el contraste AA de texto`);
|
|
1268
|
+
return lines;
|
|
1269
|
+
}
|
|
1270
|
+
var esc = (value) => String(value ?? "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
1271
|
+
var CHANGE_LABEL = { added: "A\xF1adido", changed: "Cambiado", removed: "Eliminado" };
|
|
1272
|
+
function renderDiffHtml(d) {
|
|
1273
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1274
|
+
for (const e of d.entries) groups.set(e.kind, [...groups.get(e.kind) ?? [], e]);
|
|
1275
|
+
const entryHtml = (e) => {
|
|
1276
|
+
const parts = [];
|
|
1277
|
+
if (e.colors.length) {
|
|
1278
|
+
parts.push(`<table><thead><tr><th>Color</th><th>Antes</th><th>Despu\xE9s</th><th>Contraste</th></tr></thead><tbody>${e.colors.map((c) => `<tr class="${c.regressed ? "bad" : ""}"><td>${esc(c.key)}</td><td>${c.before ? `<i class="sw" style="background:${/^#[0-9a-fA-F]{3,6}$/.test(c.before) ? esc(c.before) : "transparent"}"></i>${esc(c.before)}` : "\u2014"}</td><td>${c.after ? `<i class="sw" style="background:${/^#[0-9a-fA-F]{3,6}$/.test(c.after) ? esc(c.after) : "transparent"}"></i>${esc(c.after)}` : "\u2014"}</td><td>${c.contrastAfter === null ? "\u2014" : `${c.contrastBefore ?? "\u2014"} \u2192 ${c.contrastAfter}${c.regressed ? " \xB7 pierde AA" : c.passesTextAfter === false ? " \xB7 bajo AA" : ""}`}</td></tr>`).join("")}</tbody></table>`);
|
|
1279
|
+
}
|
|
1280
|
+
if (e.messages) {
|
|
1281
|
+
const list3 = (title, keys) => keys.length ? `<p><b>${title} (${keys.length}):</b> ${keys.slice(0, 40).map((k) => `<code>${esc(k)}</code>`).join(" ")}${keys.length > 40 ? " \u2026" : ""}</p>` : "";
|
|
1282
|
+
parts.push(list3("A\xF1adidos", e.messages.added) + list3("Cambiados", e.messages.changed) + list3("Eliminados", e.messages.removed));
|
|
1283
|
+
}
|
|
1284
|
+
if (e.component) parts.push(`<p><b>Bump exigido:</b> ${esc(e.component.bump)}</p><ul>${e.component.changes.map((c) => `<li>${esc(c)}</li>`).join("")}</ul>`);
|
|
1285
|
+
if (!e.colors.length && !e.messages && !e.component && e.changes.length) {
|
|
1286
|
+
parts.push(`<table><thead><tr><th>Campo</th><th>Antes</th><th>Despu\xE9s</th></tr></thead><tbody>${e.changes.slice(0, 60).map((c) => `<tr><td>${esc(c.path)}</td><td>${esc(c.before ?? "\u2014")}</td><td>${esc(c.after ?? "\u2014")}</td></tr>`).join("")}</tbody></table>`);
|
|
1287
|
+
}
|
|
1288
|
+
const revs = e.change === "changed" ? `r${e.from} \u2192 r${e.to}` : e.change === "added" ? `r${e.to}` : `r${e.from}`;
|
|
1289
|
+
return `<article class="${e.change}"><h3><span class="tag">${CHANGE_LABEL[e.change]}</span> ${esc(e.name)}${e.locale ? ` <small>${esc(e.locale)}</small>` : ""} <small>${esc(revs)}</small></h3>${parts.join("")}</article>`;
|
|
1290
|
+
};
|
|
1291
|
+
return `<!doctype html>
|
|
1292
|
+
<html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
1293
|
+
<title>Qu\xE9 cambia: release ${esc(rel(d.from))} a ${esc(rel(d.to))}</title>
|
|
1294
|
+
<style>
|
|
1295
|
+
:root{--bg:#fff;--fg:#14171c;--mut:#5b6472;--line:#d9dee6;--add:#0b7a3b;--chg:#8a5a00;--rem:#b3261e;--card:#f6f8fb}
|
|
1296
|
+
@media (prefers-color-scheme:dark){:root{--bg:#10131a;--fg:#e8ebf0;--mut:#9aa4b2;--line:#2a313c;--add:#4cc582;--chg:#e0b050;--rem:#ff8a80;--card:#171c25}}
|
|
1297
|
+
body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 system-ui,sans-serif}main{max-width:62rem;margin:0 auto;padding:1.5rem 1rem 4rem}
|
|
1298
|
+
h1{font-size:1.5rem;margin:0 0 .25rem}h2{margin:2rem 0 .5rem;font-size:1.1rem;border-bottom:1px solid var(--line);padding-bottom:.25rem}h3{font-size:1rem;margin:0 0 .5rem}small{color:var(--mut);font-weight:400}
|
|
1299
|
+
.sum{display:flex;gap:.75rem;flex-wrap:wrap;margin:1rem 0}.sum div{background:var(--card);border:1px solid var(--line);border-radius:8px;padding:.5rem .9rem}.sum b{font-size:1.25rem;display:block}
|
|
1300
|
+
article{background:var(--card);border:1px solid var(--line);border-left:4px solid var(--chg);border-radius:8px;padding:.75rem 1rem;margin:.6rem 0}article.added{border-left-color:var(--add)}article.removed{border-left-color:var(--rem)}
|
|
1301
|
+
.tag{font-size:.75rem;text-transform:uppercase;letter-spacing:.04em;color:var(--mut)}table{border-collapse:collapse;width:100%;margin:.4rem 0;font-size:.9rem}th,td{text-align:left;padding:.25rem .5rem;border-bottom:1px solid var(--line);vertical-align:top;word-break:break-word}
|
|
1302
|
+
tr.bad td{color:var(--rem);font-weight:600}.sw{display:inline-block;width:.9em;height:.9em;border:1px solid var(--line);border-radius:3px;margin-right:.35em;vertical-align:-.1em}code{background:var(--bg);border:1px solid var(--line);border-radius:4px;padding:0 .3em}
|
|
1303
|
+
.warn{border:1px solid var(--rem);color:var(--rem);border-radius:8px;padding:.5rem .9rem;margin:.75rem 0}
|
|
1304
|
+
</style></head><body><main>
|
|
1305
|
+
<h1>Qu\xE9 cambia en este release</h1>
|
|
1306
|
+
<p>Release <b>${esc(rel(d.from))}</b> \u2192 <b>${esc(rel(d.to))}</b> \xB7 generado por <code>customy experience diff</code>. Vista de revisi\xF3n previa: no publica ni fija nada.</p>
|
|
1307
|
+
<div class="sum"><div><b>${d.summary.added}</b>a\xF1adidos</div><div><b>${d.summary.changed}</b>cambiados</div><div><b>${d.summary.removed}</b>eliminados</div><div><b>${d.summary.unchanged}</b>sin cambios</div></div>
|
|
1308
|
+
${d.contrastRegressions ? `<div class="warn">${d.contrastRegressions} color(es) pierden el contraste AA de texto con este cambio.</div>` : ""}
|
|
1309
|
+
${d.truncated ? `<p><small>El servicio detalla solo una parte de los cambios; el resumen los cuenta todos.</small></p>` : ""}
|
|
1310
|
+
${[...groups].map(([kind, list3]) => `<h2>${esc(kind)} (${list3.length})</h2>${list3.map(entryHtml).join("")}`).join("") || "<p>Sin cambios entre estos releases.</p>"}
|
|
1311
|
+
</main></body></html>
|
|
1312
|
+
`;
|
|
1313
|
+
}
|
|
1314
|
+
async function diffCmd(positional, flags, io) {
|
|
1315
|
+
if (positional.length < 1 || positional.length > 2) throw new UsageError3("uso: customy experience diff <releaseA> [<releaseB>] [--html cambios.html] [--fail-on removed,contrast] (un solo release = contra su padre)");
|
|
1316
|
+
const failOn = typeof flags["fail-on"] === "string" ? flags["fail-on"].split(",").map((x) => x.trim()).filter(Boolean) : [];
|
|
1317
|
+
const badFail = failOn.filter((x) => x !== "removed" && x !== "contrast");
|
|
1318
|
+
if (badFail.length) throw new UsageError3(`--fail-on admite removed y contrast (recib\xED: ${badFail.join(", ")})`);
|
|
1319
|
+
if (flags.html !== void 0 && typeof flags.html !== "string") throw new UsageError3("--html necesita un fichero de salida");
|
|
1320
|
+
const client = readClient(flags, io);
|
|
1321
|
+
const [a, b] = positional.length === 2 ? [positional[0], positional[1]] : [null, positional[0]];
|
|
1322
|
+
const target = await resolveRelease(client, b);
|
|
1323
|
+
const base = a ? await resolveRelease(client, a) : null;
|
|
1324
|
+
const data = await client.request("GET", `/releases/${encodeURIComponent(target.id)}/diff`, { query: base ? { against: base.id } : {} });
|
|
1325
|
+
const diff = normalizeDiff(data);
|
|
1326
|
+
const lines = diffLines(diff);
|
|
1327
|
+
let html = null;
|
|
1328
|
+
if (typeof flags.html === "string") {
|
|
1329
|
+
html = path4__default.default.relative(io.cwd, path4__default.default.resolve(io.cwd, flags.html)) || flags.html;
|
|
1330
|
+
if (flags["dry-run"]) lines.push(`dry-run: no se escribi\xF3 ${html}`);
|
|
1331
|
+
else {
|
|
1332
|
+
const target2 = path4__default.default.resolve(io.cwd, flags.html);
|
|
1333
|
+
await promises.mkdir(path4__default.default.dirname(target2), { recursive: true });
|
|
1334
|
+
await promises.writeFile(target2, renderDiffHtml(diff));
|
|
1335
|
+
lines.push(`\u2713 vista de revisi\xF3n: ${html}`);
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
const tripped = [...failOn.includes("removed") && diff.summary.removed > 0 ? ["removed"] : [], ...failOn.includes("contrast") && diff.contrastRegressions > 0 ? ["contrast"] : []];
|
|
1339
|
+
if (tripped.length) lines.push(`\u2717 --fail-on: ${tripped.join(", ")}`);
|
|
1340
|
+
return { lines, result: { ...diff, html, dryRun: flags["dry-run"] === true, failedOn: tripped }, code: tripped.length ? EXPERIENCE_EXIT.invalid : EXPERIENCE_EXIT.ok };
|
|
1341
|
+
}
|
|
1342
|
+
async function pinCmd(positional, flags, io) {
|
|
1343
|
+
const clear = flags.clear === true;
|
|
1344
|
+
if (positional.length !== (clear ? 1 : 2)) throw new UsageError3('uso: customy experience pin <app> <release|#n\xFAmero> --reason "\u2026" [--dry-run] | pin <app> --clear --reason "\u2026"');
|
|
1345
|
+
const app = positional[0];
|
|
1346
|
+
if (!APP_NAME.test(app)) throw new UsageError3("el nombre de la app debe ser min\xFAsculas, d\xEDgitos y guiones (hasta 40, empezando por letra)");
|
|
1347
|
+
const reason = typeof flags.reason === "string" ? flags.reason.trim() : "";
|
|
1348
|
+
if (reason.length < 3 || reason.length > 500) throw new UsageError3('--reason "\u2026" es obligatorio (3 a 500 caracteres): queda en la auditor\xEDa');
|
|
1349
|
+
const client = writeClient(flags, io);
|
|
1350
|
+
if (clear) {
|
|
1351
|
+
if (flags["dry-run"]) return { lines: [`dry-run: se quitar\xEDa el pin de ${app}; no se envi\xF3 nada`], result: { dryRun: true, app, clear: true } };
|
|
1352
|
+
await client.request("POST", `/pins/${encodeURIComponent(app)}/clear`, { body: { reason } });
|
|
1353
|
+
return { lines: [`\u2713 pin de ${app} retirado: vuelve a seguir su canal`], result: { app, cleared: true } };
|
|
1354
|
+
}
|
|
1355
|
+
const target = await resolveRelease(client, positional[1]);
|
|
1356
|
+
const label2 = `release ${target.number !== null ? `#${target.number} ` : ""}${target.id}`;
|
|
1357
|
+
if (flags["dry-run"]) return { lines: [`dry-run: se fijar\xEDa ${app} al ${label2}; no se envi\xF3 nada`], result: { dryRun: true, app, releaseId: target.id, releaseNumber: target.number } };
|
|
1358
|
+
const result = await client.request("PUT", `/pins/${encodeURIComponent(app)}`, { body: { releaseId: target.id, reason } });
|
|
1359
|
+
const rec = isRec(result) ? result : {};
|
|
1360
|
+
const pin = isRec(rec.pin) ? rec.pin : {};
|
|
1361
|
+
const served = strList(pin.servedByChannels);
|
|
1362
|
+
const already = rec.alreadyPinned === true;
|
|
1363
|
+
const lines = [
|
|
1364
|
+
already ? `= ${app} ya estaba fijada al ${label2}` : `\u2713 ${app} fijada al ${label2}`,
|
|
1365
|
+
` declarado (no medido): ${num(pin.behindLatest) ? `${pin.behindLatest} release(s) por detr\xE1s del \xFAltimo` : "es el \xFAltimo release"}`,
|
|
1366
|
+
served.length ? ` servido hoy por: ${served.join(", ")}` : " ! ning\xFAn canal sirve hoy ese release: para que la app lo obedezca hay que publicarlo de nuevo con una sequence nueva (el trinquete no admite una menor)"
|
|
1367
|
+
];
|
|
1368
|
+
return { lines, result: { app, releaseId: str2(pin.releaseId) || target.id, releaseNumber: num(pin.releaseNumber) ?? target.number, alreadyPinned: already, servedByChannels: served, behindLatest: num(pin.behindLatest), delivery: "declared" } };
|
|
1369
|
+
}
|
|
1370
|
+
async function statusApp(flags, io) {
|
|
1371
|
+
const app = flags.app;
|
|
1372
|
+
if (!APP_NAME.test(app)) throw new UsageError3("--app debe ser min\xFAsculas, d\xEDgitos y guiones (hasta 40, empezando por letra)");
|
|
1373
|
+
const channel = typeof flags.channel === "string" ? flags.channel : "production";
|
|
1374
|
+
const client = readClient(flags, io);
|
|
1375
|
+
const usage = await client.request("GET", "/usage");
|
|
1376
|
+
const u = isRec(usage) ? usage : {};
|
|
1377
|
+
const pin = (Array.isArray(u.pins) ? u.pins.filter(isRec) : []).find((p) => p.app === app) ?? null;
|
|
1378
|
+
const row = (Array.isArray(u.channels) ? u.channels.filter(isRec) : []).find((c) => c.channel === channel) ?? null;
|
|
1379
|
+
let timestampUrl = null;
|
|
1380
|
+
let scopeKey = null;
|
|
1381
|
+
try {
|
|
1382
|
+
const scope = await client.request("GET", "/scope");
|
|
1383
|
+
const delivery = isRec(scope) && isRec(scope.delivery) ? scope.delivery : {};
|
|
1384
|
+
scopeKey = isRec(scope) ? str2(scope.key) || null : null;
|
|
1385
|
+
timestampUrl = (Array.isArray(delivery.channels) ? delivery.channels.filter(isRec) : []).find((c) => c.channel === channel)?.timestampUrl ?? null;
|
|
1386
|
+
} catch (error) {
|
|
1387
|
+
if (!(error instanceof ApiError && error.status === 404)) throw error;
|
|
1388
|
+
}
|
|
1389
|
+
const pinned = pin ? { releaseNumber: num(pin.releaseNumber), releaseId: str2(pin.releaseId), reason: str2(pin.reason), since: str2(pin.since) || null, behindLatest: num(pin.behindLatest), servedByChannels: strList(pin.servedByChannels), releaseState: str2(pin.releaseState) } : null;
|
|
1390
|
+
const served = row ? { releaseNumber: num(row.releaseNumber), releaseId: typeof row.releaseId === "string" ? row.releaseId : null, sequence: num(row.sequence), minSequence: num(row.minSequence) } : null;
|
|
1391
|
+
const source = pinned ? "pin" : served?.releaseId ? `canal ${channel}` : "ninguna";
|
|
1392
|
+
const effective = pinned ? pinned.releaseNumber : served?.releaseNumber ?? null;
|
|
1393
|
+
const obeyed = pinned ? pinned.servedByChannels.length > 0 : null;
|
|
1394
|
+
const lines = [
|
|
1395
|
+
`App ${app}: ${effective !== null ? `release #${effective}` : "sin release"} (fuente: ${source})`,
|
|
1396
|
+
pinned ? ` pin \u2192 release #${pinned.releaseNumber}${pinned.behindLatest ? `, ${pinned.behindLatest} por detr\xE1s del \xFAltimo` : ""} \xB7 \xAB${pinned.reason}\xBB \xB7 desde ${pinned.since ?? "?"}` : " sin pin: la app sigue el canal",
|
|
1397
|
+
served ? ` canal ${channel} \u2192 ${served.releaseNumber !== null ? `release #${served.releaseNumber}` : "sin release"} \xB7 seq ${served.sequence ?? "-"} \xB7 minSeq ${served.minSequence ?? "-"}` : ` canal ${channel}: no existe en este entorno`,
|
|
1398
|
+
...obeyed === false ? [` ! el pin no lo sirve ning\xFAn canal: hay que publicar ese release con una sequence nueva para que la app lo obedezca`] : [],
|
|
1399
|
+
` puntero que sondea el cliente: ${timestampUrl ?? "(sin base p\xFAblica configurada)"}`,
|
|
1400
|
+
" el pin es una declaraci\xF3n; el consumo real por app no se mide todav\xEDa"
|
|
1401
|
+
];
|
|
1402
|
+
return { lines, result: { app, source, effectiveReleaseNumber: effective, pin: pinned, channel: { name: channel, ...served ?? {} }, scope: scopeKey, timestampUrl, delivery: { pins: "declared", consumers: "not_measured" } } };
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
// src/experience.ts
|
|
1026
1406
|
var EXPERIENCE_GROUPS = ["experience"];
|
|
1027
1407
|
var EXPERIENCE_EXIT = { ok: 0, invalid: 1, usage: 2, auth: 3, conflict: 4, failure: 5 };
|
|
1028
1408
|
var EXPERIENCE_HELP = [
|
|
1029
|
-
"Customy Experience (token: CUSTOMY_EXPERIENCE_TOKEN, origin: --base-url or CUSTOMY_EXPERIENCE_URL;
|
|
1409
|
+
"Customy Experience (token: CUSTOMY_EXPERIENCE_TOKEN, origin: --base-url or CUSTOMY_EXPERIENCE_URL;",
|
|
1410
|
+
" API: <origin>/public/author/v1/* with a machine token cxw_\u2026 (external clients) or <origin>/api/experience/* behind the Workspace BFF; force with --api public|bff):",
|
|
1030
1411
|
" customy experience pull [--dir catalogs] [--namespace a,b] [--locale es,en] [--draft] download catalog@1 files (sorted by key) + a lock file",
|
|
1031
1412
|
' customy experience push [file.json ...] [--dir catalogs] [--create] [--rebase] [--publish] [--note "..."]',
|
|
1032
1413
|
" [--ack-remove k1,k2] [--ack-placeholders k3] [--plan free|pro|enterprise] [--dry-run]",
|
|
@@ -1042,11 +1423,15 @@ var EXPERIENCE_HELP = [
|
|
|
1042
1423
|
' customy experience scope show | rotate --reason "..." | retire [--force] delivery scope (rotate/retire: experience.scope.rotate)',
|
|
1043
1424
|
" customy experience signing plan [--retire id,id] [--threshold n] [--compromised id,id] READ-ONLY key rotation plan",
|
|
1044
1425
|
' customy experience signing rotate --reason "..." [--retire id,id] [--compromised id,id] [--window-elapsed] publishes ONE rotation step',
|
|
1426
|
+
' customy experience publish [--channel staging] [--note "..."] [--dry-run] create a release from the latest revision of every artifact and move the channel',
|
|
1427
|
+
" customy experience env [--channel staging] [--format env|json] print the NON-secret EXPERIENCE_* values of the environment your token belongs to",
|
|
1428
|
+
" customy experience locale put <bcp47> [<bcp47> ...] [--status translating] [--direction ltr|rtl] [--fallback es,en] open or update languages",
|
|
1045
1429
|
" customy experience reconcile <channel> after a database restore (storage ahead of database)",
|
|
1430
|
+
...INTEGRATOR_HELP,
|
|
1046
1431
|
"Common flags: --json (one JSON document on stdout), --timeout MS (default 30000). Exit codes: 0 ok, 1 invalid/check failed, 2 usage, 3 auth, 4 conflict, 5 network/server."
|
|
1047
1432
|
];
|
|
1048
1433
|
var LOCK_FILE = ".customy-experience.lock.json";
|
|
1049
|
-
var VALUE_FLAGS2 = /* @__PURE__ */ new Set(["base-url", "dir", "namespace", "locale", "locales", "base-locale", "src", "note", "ack-remove", "ack-placeholders", "plan", "warn-hours", "timeout", "format", "source-locale", "out", "glossary", "reason", "fallback", "channel", "retire", "threshold", "compromised"]);
|
|
1434
|
+
var VALUE_FLAGS2 = /* @__PURE__ */ new Set(["base-url", "dir", "namespace", "locale", "locales", "base-locale", "src", "note", "ack-remove", "ack-placeholders", "plan", "warn-hours", "timeout", "format", "source-locale", "out", "glossary", "reason", "fallback", "channel", "retire", "threshold", "compromised", "kind", "release", "app", "html", "revision", "fail-on", "api", "status", "direction"]);
|
|
1050
1435
|
var UsageError3 = class extends Error {
|
|
1051
1436
|
};
|
|
1052
1437
|
var ExitError = class extends Error {
|
|
@@ -1092,9 +1477,9 @@ var list = (value) => typeof value === "string" ? value.split(",").map((item) =>
|
|
|
1092
1477
|
var sortedKeys = (record) => Object.keys(record).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
|
|
1093
1478
|
function limitsOf(flags) {
|
|
1094
1479
|
const plan2 = flags.plan;
|
|
1095
|
-
if (plan2 === void 0) return
|
|
1480
|
+
if (plan2 === void 0) return chunkVUQSQ5YY_cjs.TRANSLATION_PLAN_LIMITS.pro;
|
|
1096
1481
|
if (plan2 !== "free" && plan2 !== "pro" && plan2 !== "enterprise") throw new UsageError3("--plan debe ser free, pro o enterprise");
|
|
1097
|
-
return
|
|
1482
|
+
return chunkVUQSQ5YY_cjs.TRANSLATION_PLAN_LIMITS[plan2];
|
|
1098
1483
|
}
|
|
1099
1484
|
function serializeCatalog(doc) {
|
|
1100
1485
|
const messages2 = {};
|
|
@@ -1102,32 +1487,58 @@ function serializeCatalog(doc) {
|
|
|
1102
1487
|
return `${JSON.stringify({ version: doc.version, namespace: doc.namespace, locale: doc.locale, syntax: doc.syntax, messages: messages2 }, null, 2)}
|
|
1103
1488
|
`;
|
|
1104
1489
|
}
|
|
1105
|
-
|
|
1490
|
+
var PUBLIC_AUTHOR_PREFIX = "/public/author/v1";
|
|
1491
|
+
function apiOf(flags, token) {
|
|
1492
|
+
const forced = flags.api;
|
|
1493
|
+
if (forced !== void 0) {
|
|
1494
|
+
if (forced !== "public" && forced !== "bff") throw new UsageError3("--api debe ser public o bff");
|
|
1495
|
+
return forced;
|
|
1496
|
+
}
|
|
1497
|
+
return token.startsWith("cxw_") ? "public" : "bff";
|
|
1498
|
+
}
|
|
1499
|
+
var sleepMs = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
1500
|
+
var MAX_RATE_RETRIES = 3;
|
|
1501
|
+
var MAX_RATE_WAIT_SECONDS = 30;
|
|
1502
|
+
function makeClient(flags, io, auth) {
|
|
1106
1503
|
const base = (typeof flags["base-url"] === "string" ? flags["base-url"] : io.env.CUSTOMY_EXPERIENCE_URL)?.replace(/\/+$/, "");
|
|
1107
1504
|
if (!base) throw new UsageError3("falta el origen: --base-url o CUSTOMY_EXPERIENCE_URL");
|
|
1108
1505
|
if (!/^https:\/\//i.test(base) && !/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?(\/|$)/i.test(base)) {
|
|
1109
1506
|
throw new UsageError3("el origen de Experience debe ser https:// (http:// solo hacia localhost): el token viajar\xEDa en claro");
|
|
1110
1507
|
}
|
|
1111
|
-
const token = io.env.CUSTOMY_EXPERIENCE_TOKEN;
|
|
1112
|
-
if (!token) throw new UsageError3("falta CUSTOMY_EXPERIENCE_TOKEN en el entorno (nunca por la l\xEDnea de comandos)");
|
|
1508
|
+
const token = auth ? auth.token : io.env.CUSTOMY_EXPERIENCE_TOKEN;
|
|
1509
|
+
if (!token) throw new UsageError3(auth?.missing ?? "falta CUSTOMY_EXPERIENCE_TOKEN en el entorno (nunca por la l\xEDnea de comandos)");
|
|
1113
1510
|
const timeout = typeof flags.timeout === "string" ? Number(flags.timeout) : 3e4;
|
|
1114
1511
|
if (!Number.isFinite(timeout) || timeout < 1) throw new UsageError3("--timeout debe ser un n\xFAmero de milisegundos");
|
|
1115
1512
|
const doFetch = io.fetch ?? fetch;
|
|
1513
|
+
const api = apiOf(flags, token);
|
|
1514
|
+
const prefix = api === "public" ? PUBLIC_AUTHOR_PREFIX : "/api/experience";
|
|
1515
|
+
const sleep = io.sleep ?? sleepMs;
|
|
1116
1516
|
return {
|
|
1117
1517
|
origin: base,
|
|
1518
|
+
api,
|
|
1118
1519
|
async request(method, route, options = {}) {
|
|
1119
|
-
const
|
|
1520
|
+
const queryOptions = api === "public" && method !== "GET" && options.query ? Object.fromEntries(Object.entries(options.query).filter(([k]) => k !== "kind" && k !== "locale" && k !== "action")) : options.query;
|
|
1521
|
+
const query = queryOptions && Object.keys(queryOptions).length ? `?${new URLSearchParams(queryOptions)}` : "";
|
|
1120
1522
|
let response;
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1523
|
+
for (let attempt = 0; attempt <= MAX_RATE_RETRIES; attempt += 1) {
|
|
1524
|
+
try {
|
|
1525
|
+
response = await doFetch(`${base}${prefix}${route}${query}`, {
|
|
1526
|
+
method,
|
|
1527
|
+
headers: { authorization: `Bearer ${token}`, accept: "application/json", "user-agent": "customy-cli", ...options.body !== void 0 ? { "content-type": "application/json" } : {} },
|
|
1528
|
+
...options.body !== void 0 ? { body: JSON.stringify(options.body) } : {},
|
|
1529
|
+
signal: AbortSignal.timeout(timeout)
|
|
1530
|
+
});
|
|
1531
|
+
} catch (error) {
|
|
1532
|
+
throw new ExitError(EXPERIENCE_EXIT.failure, `no se pudo conectar con ${base}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1533
|
+
}
|
|
1534
|
+
const wait = Number(response.headers.get("retry-after"));
|
|
1535
|
+
if (response.status === 429 && attempt < MAX_RATE_RETRIES && Number.isFinite(wait) && wait > 0 && wait <= MAX_RATE_WAIT_SECONDS) {
|
|
1536
|
+
await sleep(Math.ceil(wait) * 1e3);
|
|
1537
|
+
continue;
|
|
1538
|
+
}
|
|
1539
|
+
break;
|
|
1130
1540
|
}
|
|
1541
|
+
if (!response) throw new ExitError(EXPERIENCE_EXIT.failure, `no se pudo conectar con ${base}`);
|
|
1131
1542
|
const text = await response.text();
|
|
1132
1543
|
let data;
|
|
1133
1544
|
try {
|
|
@@ -1153,7 +1564,8 @@ function exitFor(error) {
|
|
|
1153
1564
|
}
|
|
1154
1565
|
function explain(error, what) {
|
|
1155
1566
|
const details = isRec(error.details) ? error.details : {};
|
|
1156
|
-
if (error.status === 401) return `${what}: credencial rechazada (401). Revisa CUSTOMY_EXPERIENCE_TOKEN.`;
|
|
1567
|
+
if (error.status === 401) return `${what}: credencial rechazada (401). Revisa CUSTOMY_EXPERIENCE_TOKEN${error.name === "invalid_token" ? ": un token de m\xE1quina vencido, revocado o con el secreto cambiado se ve igual; pide uno nuevo o rota el actual en el panel de Experience (Tokens de m\xE1quina)" : ""}.`;
|
|
1568
|
+
if (error.status === 429) return `${what}: demasiadas peticiones por minuto con este token (429)${details.retryAfterSeconds ? `; reintenta en ${String(details.retryAfterSeconds)} s` : ""}. El CLI ya esper\xF3 y repiti\xF3; baja el ritmo o pide un token con m\xE1s tasa.`;
|
|
1157
1569
|
if (error.status === 403) return `${what}: sin permiso (403). ${error.message}`;
|
|
1158
1570
|
if (error.status === 404) return `${what}: sin permiso o inexistente (404). El servicio responde igual en ambos casos; revisa el identificador y que tu token tenga la capacidad exacta.`;
|
|
1159
1571
|
if (error.status === 402) return `${what}: tope del plan agotado (402). ${error.message}`;
|
|
@@ -1165,6 +1577,8 @@ function explain(error, what) {
|
|
|
1165
1577
|
if (error.name === "scope_still_draining") return `${what}: el \xE1mbito a\xFAn drena hasta ${String(details.drainsUntil ?? "?")}. Retirarlo antes deja sin migrar a los clientes que no lo hicieron; si lo quieres, repite con --force.`;
|
|
1166
1578
|
if (error.name === "scope_force_too_early") return `${what}: --force no se admite hasta ${String(details.forceAllowedAt ?? "?")} (${String(details.forceMinDays ?? "?")} d\xEDas tras rotar): los clientes que no sondearon antes no aprender\xEDan el \xE1mbito nuevo. Espera a esa fecha o a ${String(details.drainsUntil ?? "drainsUntil")} y repite${details.drainsUntil ? " sin --force" : ""}.`;
|
|
1167
1579
|
if (error.name === "scope_rotation_limit") return `${what}: este entorno ya rot\xF3 ${String(details.rotatedThisMonth ?? "?")} veces en ${String(details.month ?? "este mes")} (tope ${String(details.maxRotationsPerMonth ?? "?")}). Cada rotaci\xF3n copia todos los archivos vigentes: espera al mes siguiente o pide a plataforma subir EXPERIENCE_SCOPE_MAX_ROTATIONS_PER_MONTH.`;
|
|
1580
|
+
if (error.name === "machine_token_limit") return `${what}: este entorno ya tiene el m\xE1ximo de tokens de m\xE1quina activos (402). Revoca o deja vencer alguno.`;
|
|
1581
|
+
if (error.name === "production_requires_approval") return `${what}: ${error.message}`;
|
|
1168
1582
|
if (error.name === "internal_key_route_forbidden") return `${what}: la llave interna del servicio no abre esta ruta (403). Es un fallo de configuraci\xF3n del BFF/despliegue, no de tu token: avisa a plataforma (runbook, \xABLlaves internas por consumidor\xBB).`;
|
|
1169
1583
|
if (error.name === "fallback_required") return `${what}: hay canales que sirven este release (${channelNames(details.channels)}). Indica --fallback <release no revocado> para volver a publicarlos.`;
|
|
1170
1584
|
if (error.name === "fallback_invalid" || error.name === "fallback_revoked") return `${what}: ${error.message} (canales: ${channelNames(details.channels)})`;
|
|
@@ -1182,7 +1596,7 @@ var lockKey = (namespace, locale) => `${namespace}/${locale}`;
|
|
|
1182
1596
|
var fileName = (namespace, locale) => `${namespace}.${locale}.json`;
|
|
1183
1597
|
async function readLock(dir) {
|
|
1184
1598
|
try {
|
|
1185
|
-
const parsed = JSON.parse(await promises.readFile(
|
|
1599
|
+
const parsed = JSON.parse(await promises.readFile(path4__default.default.join(dir, LOCK_FILE), "utf8"));
|
|
1186
1600
|
return isRec(parsed) && isRec(parsed.artifacts) ? parsed : null;
|
|
1187
1601
|
} catch {
|
|
1188
1602
|
return null;
|
|
@@ -1195,12 +1609,12 @@ async function catalogFilesIn(dir) {
|
|
|
1195
1609
|
} catch {
|
|
1196
1610
|
throw new UsageError3(`no se pudo leer el directorio ${dir}`);
|
|
1197
1611
|
}
|
|
1198
|
-
return names.filter((name) => name.endsWith(".json") && !name.startsWith(".")).sort().map((name) =>
|
|
1612
|
+
return names.filter((name) => name.endsWith(".json") && !name.startsWith(".")).sort().map((name) => path4__default.default.join(dir, name));
|
|
1199
1613
|
}
|
|
1200
1614
|
async function loadFiles(files, io) {
|
|
1201
1615
|
const out = [];
|
|
1202
1616
|
for (const file of files) {
|
|
1203
|
-
const display =
|
|
1617
|
+
const display = path4__default.default.relative(io.cwd, file) || file;
|
|
1204
1618
|
try {
|
|
1205
1619
|
out.push({ file, display, raw: JSON.parse(await promises.readFile(file, "utf8")), parseError: null });
|
|
1206
1620
|
} catch (error) {
|
|
@@ -1241,13 +1655,13 @@ async function readArtifactDoc(client, id, draft) {
|
|
|
1241
1655
|
contentHash = isRec(rev) && typeof rev.contentHash === "string" ? rev.contentHash : null;
|
|
1242
1656
|
revision = isRec(rev) && typeof rev.n === "number" ? rev.n : latest;
|
|
1243
1657
|
}
|
|
1244
|
-
const checked =
|
|
1658
|
+
const checked = chunkVUQSQ5YY_cjs.validateCatalog(document, { limits: chunkVUQSQ5YY_cjs.TRANSLATION_PLAN_LIMITS.enterprise });
|
|
1245
1659
|
if (!checked.ok || !checked.doc) return { skip: `el servidor devolvi\xF3 un documento que no es catalog@1 v\xE1lido: ${checked.issues[0]?.message ?? "?"}` };
|
|
1246
1660
|
return { doc: checked.doc, revision, contentHash, draftVersion };
|
|
1247
1661
|
}
|
|
1248
1662
|
async function pull(flags, io) {
|
|
1249
1663
|
const client = makeClient(flags, io);
|
|
1250
|
-
const dir =
|
|
1664
|
+
const dir = path4__default.default.resolve(io.cwd, typeof flags.dir === "string" ? flags.dir : "catalogs");
|
|
1251
1665
|
const namespaces = list(flags.namespace);
|
|
1252
1666
|
const locales = list(flags.locale);
|
|
1253
1667
|
const artifacts = (await listCatalogArtifacts(client)).filter((a) => (!namespaces.length || namespaces.includes(str2(a.name))) && (!locales.length || locales.includes(str2(a.locale))));
|
|
@@ -1268,29 +1682,29 @@ async function pull(flags, io) {
|
|
|
1268
1682
|
continue;
|
|
1269
1683
|
}
|
|
1270
1684
|
const { doc: checkedDoc, revision, contentHash, draftVersion } = read2;
|
|
1271
|
-
const file =
|
|
1685
|
+
const file = path4__default.default.join(dir, fileName(name, locale));
|
|
1272
1686
|
const content = serializeCatalog(checkedDoc);
|
|
1273
1687
|
let existing = null;
|
|
1274
1688
|
try {
|
|
1275
1689
|
existing = await promises.readFile(file, "utf8");
|
|
1276
1690
|
} catch {
|
|
1277
1691
|
}
|
|
1278
|
-
if (existing === content) unchanged.push(
|
|
1692
|
+
if (existing === content) unchanged.push(path4__default.default.relative(io.cwd, file));
|
|
1279
1693
|
else {
|
|
1280
1694
|
await promises.writeFile(file, content);
|
|
1281
|
-
written.push(
|
|
1695
|
+
written.push(path4__default.default.relative(io.cwd, file));
|
|
1282
1696
|
}
|
|
1283
1697
|
lock.artifacts[lockKey(name, locale)] = { artifactId: id, revision, contentHash, draftVersion };
|
|
1284
1698
|
}
|
|
1285
|
-
await promises.writeFile(
|
|
1699
|
+
await promises.writeFile(path4__default.default.join(dir, LOCK_FILE), `${JSON.stringify({ ...lock, artifacts: Object.fromEntries(sortedKeys(lock.artifacts).map((k) => [k, lock.artifacts[k]])) }, null, 2)}
|
|
1286
1700
|
`);
|
|
1287
1701
|
const lines = [
|
|
1288
1702
|
...written.map((f) => `\u2713 ${f}`),
|
|
1289
1703
|
...unchanged.map((f) => `= ${f} (sin cambios)`),
|
|
1290
1704
|
...skipped.map((s) => `- ${s.name}/${s.locale}: ${s.reason}`),
|
|
1291
|
-
`${written.length} escritos, ${unchanged.length} sin cambios, ${skipped.length} omitidos (lock: ${
|
|
1705
|
+
`${written.length} escritos, ${unchanged.length} sin cambios, ${skipped.length} omitidos (lock: ${path4__default.default.relative(io.cwd, path4__default.default.join(dir, LOCK_FILE))})`
|
|
1292
1706
|
];
|
|
1293
|
-
return { lines, result: { written, unchanged, skipped, lock:
|
|
1707
|
+
return { lines, result: { written, unchanged, skipped, lock: path4__default.default.relative(io.cwd, path4__default.default.join(dir, LOCK_FILE)) } };
|
|
1294
1708
|
}
|
|
1295
1709
|
function checkAckFlags(flags) {
|
|
1296
1710
|
const ackRemove = list(flags["ack-remove"]);
|
|
@@ -1300,8 +1714,8 @@ function checkAckFlags(flags) {
|
|
|
1300
1714
|
}
|
|
1301
1715
|
async function push(positional, flags, io) {
|
|
1302
1716
|
const limits = limitsOf(flags);
|
|
1303
|
-
const dir =
|
|
1304
|
-
const files = positional.length ? positional.map((p) =>
|
|
1717
|
+
const dir = path4__default.default.resolve(io.cwd, typeof flags.dir === "string" ? flags.dir : "catalogs");
|
|
1718
|
+
const files = positional.length ? positional.map((p) => path4__default.default.resolve(io.cwd, p)) : await catalogFilesIn(dir);
|
|
1305
1719
|
if (!files.length) throw new UsageError3("no hay ficheros que subir: pasa archivos o --dir con catalog@1");
|
|
1306
1720
|
checkAckFlags(flags);
|
|
1307
1721
|
const loaded = await loadFiles(files, io);
|
|
@@ -1312,7 +1726,7 @@ async function push(positional, flags, io) {
|
|
|
1312
1726
|
problems.push({ file: item.display, issues: [{ path: "", message: `no es JSON: ${item.parseError}` }] });
|
|
1313
1727
|
continue;
|
|
1314
1728
|
}
|
|
1315
|
-
const checked =
|
|
1729
|
+
const checked = chunkVUQSQ5YY_cjs.validateCatalog(item.raw, { limits });
|
|
1316
1730
|
if (!checked.ok || !checked.doc) problems.push({ file: item.display, issues: checked.issues.map((i) => ({ path: i.path, message: i.message })) });
|
|
1317
1731
|
else docs.push({ display: item.display, doc: checked.doc });
|
|
1318
1732
|
}
|
|
@@ -1322,38 +1736,38 @@ async function push(positional, flags, io) {
|
|
|
1322
1736
|
if (flags["dry-run"]) {
|
|
1323
1737
|
return { lines: [...docs.map((d) => `\u2713 ${d.display}: ${d.doc.namespace}/${d.doc.locale}, ${Object.keys(d.doc.messages).length} claves (v\xE1lido)`), "dry-run: no se envi\xF3 nada"], result: { dryRun: true, files: docs.map((d) => ({ file: d.display, namespace: d.doc.namespace, locale: d.doc.locale, keys: Object.keys(d.doc.messages).length })) } };
|
|
1324
1738
|
}
|
|
1325
|
-
return uploadDocs(docs, flags, io, positional.length ?
|
|
1739
|
+
return uploadDocs(docs, flags, io, positional.length ? path4__default.default.dirname(files[0]) : dir);
|
|
1326
1740
|
}
|
|
1327
1741
|
async function uploadDocs(docs, flags, io, lockDir) {
|
|
1328
1742
|
const ackRemove = list(flags["ack-remove"]);
|
|
1329
1743
|
const ackPlaceholders = list(flags["ack-placeholders"]);
|
|
1330
1744
|
const client = makeClient(flags, io);
|
|
1331
1745
|
const lock = await readLock(lockDir);
|
|
1332
|
-
if (lock && lock.origin !== client.origin) throw new UsageError3(`el lock de ${
|
|
1746
|
+
if (lock && lock.origin !== client.origin) throw new UsageError3(`el lock de ${path4__default.default.relative(io.cwd, lockDir) || "."} es de otro origen (${lock.origin}); haz pull contra este origen`);
|
|
1333
1747
|
const lockFile = { version: 1, origin: client.origin, artifacts: { ...lock?.artifacts ?? {} } };
|
|
1334
1748
|
const known = await listCatalogArtifacts(client);
|
|
1335
1749
|
const results = [];
|
|
1336
1750
|
const lines = [];
|
|
1337
1751
|
const saveLock = async () => {
|
|
1338
1752
|
await promises.mkdir(lockDir, { recursive: true }).catch(() => void 0);
|
|
1339
|
-
await promises.writeFile(
|
|
1753
|
+
await promises.writeFile(path4__default.default.join(lockDir, LOCK_FILE), `${JSON.stringify({ ...lockFile, artifacts: Object.fromEntries(sortedKeys(lockFile.artifacts).map((k) => [k, lockFile.artifacts[k]])) }, null, 2)}
|
|
1340
1754
|
`).catch(() => void 0);
|
|
1341
1755
|
};
|
|
1342
1756
|
for (const { display, doc } of docs) {
|
|
1343
1757
|
const key2 = lockKey(doc.namespace, doc.locale);
|
|
1344
|
-
const
|
|
1758
|
+
const label2 = `${display} (${key2})`;
|
|
1345
1759
|
try {
|
|
1346
1760
|
let artifact = known.find((a) => a.name === doc.namespace && a.locale === doc.locale);
|
|
1347
1761
|
let created = false;
|
|
1348
1762
|
if (!artifact) {
|
|
1349
|
-
if (!flags.create) throw new ExitError(EXPERIENCE_EXIT.invalid, `${
|
|
1763
|
+
if (!flags.create) throw new ExitError(EXPERIENCE_EXIT.invalid, `${label2}: no existe ese cat\xE1logo en el servidor; usa --create para crearlo`);
|
|
1350
1764
|
artifact = await client.request("POST", "/artifacts", { body: { kind: "catalog", name: doc.namespace, locale: doc.locale } });
|
|
1351
1765
|
created = true;
|
|
1352
1766
|
}
|
|
1353
1767
|
const id = str2(artifact.id);
|
|
1354
1768
|
let entry = lockFile.artifacts[key2];
|
|
1355
1769
|
if (!created && (!entry || entry.artifactId !== id)) {
|
|
1356
|
-
if (!flags.rebase) throw new ExitError(EXPERIENCE_EXIT.conflict, `${
|
|
1770
|
+
if (!flags.rebase) throw new ExitError(EXPERIENCE_EXIT.conflict, `${label2}: no hay base conocida (sin lock de un pull previo). Ejecuta \xABcustomy experience pull\xBB o usa --rebase para partir de lo \xFAltimo del servidor.`);
|
|
1357
1771
|
const detail = await client.request("GET", `/artifacts/${encodeURIComponent(id)}`);
|
|
1358
1772
|
entry = { artifactId: id, revision: isRec(detail) && typeof detail.latestRevision === "number" ? detail.latestRevision : 0, contentHash: null, draftVersion: isRec(detail) && isRec(detail.draft) && typeof detail.draft.version === "number" ? detail.draft.version : 0 };
|
|
1359
1773
|
}
|
|
@@ -1364,7 +1778,7 @@ async function uploadDocs(docs, flags, io, lockDir) {
|
|
|
1364
1778
|
const draftVersion = isRec(saved) && typeof saved.version === "number" ? saved.version : base.draftVersion + 1;
|
|
1365
1779
|
lockFile.artifacts[key2] = { ...base, draftVersion };
|
|
1366
1780
|
const outcome = { file: display, namespace: doc.namespace, locale: doc.locale, artifactId: id, artifactCreated: created, revisionBase: base.revision, draftVersion, published: null };
|
|
1367
|
-
lines.push(`\u2713 ${
|
|
1781
|
+
lines.push(`\u2713 ${label2}: borrador guardado (versi\xF3n ${draftVersion}, base r${base.revision})${created ? " \xB7 cat\xE1logo creado" : ""}`);
|
|
1368
1782
|
if (flags.publish) {
|
|
1369
1783
|
const body = { ...typeof flags.note === "string" ? { note: flags.note } : {}, ...ackRemove.length || ackPlaceholders.length ? { acknowledge: { ...ackRemove.length ? { removeKeys: ackRemove } : {}, ...ackPlaceholders.length ? { placeholderKeys: ackPlaceholders } : {} } } : {} };
|
|
1370
1784
|
const published = await client.request("POST", `/artifacts/${encodeURIComponent(id)}/revisions`, { body, query: catalogHint });
|
|
@@ -1373,12 +1787,12 @@ async function uploadDocs(docs, flags, io, lockDir) {
|
|
|
1373
1787
|
const n = typeof rev.n === "number" ? rev.n : base.revision;
|
|
1374
1788
|
outcome.published = { created: wasCreated, revision: n, contentHash: typeof rev.contentHash === "string" ? rev.contentHash : null, warnings: isRec(published) && Array.isArray(published.warnings) ? published.warnings : [] };
|
|
1375
1789
|
lockFile.artifacts[key2] = { artifactId: id, revision: n, contentHash: typeof rev.contentHash === "string" ? rev.contentHash : null, draftVersion };
|
|
1376
|
-
lines.push(wasCreated ? `\u2713 ${
|
|
1790
|
+
lines.push(wasCreated ? `\u2713 ${label2}: revisi\xF3n r${n} publicada` : `= ${label2}: sin cambios respecto a r${n}, no se cre\xF3 revisi\xF3n`);
|
|
1377
1791
|
}
|
|
1378
1792
|
results.push(outcome);
|
|
1379
1793
|
} catch (error) {
|
|
1380
1794
|
await saveLock();
|
|
1381
|
-
if (error instanceof ApiError) throw new ExitError(exitFor(error), [...lines, `\u2717 ${explain(error,
|
|
1795
|
+
if (error instanceof ApiError) throw new ExitError(exitFor(error), [...lines, `\u2717 ${explain(error, label2)}`].join("\n"));
|
|
1382
1796
|
if (error instanceof ExitError) throw new ExitError(error.code, [...lines, `\u2717 ${error.message}`].join("\n"));
|
|
1383
1797
|
throw error;
|
|
1384
1798
|
}
|
|
@@ -1386,7 +1800,118 @@ async function uploadDocs(docs, flags, io, lockDir) {
|
|
|
1386
1800
|
await saveLock();
|
|
1387
1801
|
return { lines, result: { files: results } };
|
|
1388
1802
|
}
|
|
1389
|
-
var
|
|
1803
|
+
var CHANNEL_RE = /^[a-z][a-z0-9-]{0,23}$/;
|
|
1804
|
+
async function publishCmd(positional, flags, io) {
|
|
1805
|
+
if (positional.length) throw new UsageError3('uso: customy experience publish [--channel staging] [--note "\u2026"] [--dry-run]');
|
|
1806
|
+
const channel = typeof flags.channel === "string" ? flags.channel : "staging";
|
|
1807
|
+
if (!CHANNEL_RE.test(channel)) throw new UsageError3("--channel no es un nombre de canal v\xE1lido (min\xFAsculas, d\xEDgitos y guiones)");
|
|
1808
|
+
if (flags.note !== void 0 && typeof flags.note !== "string") throw new UsageError3("--note necesita un texto");
|
|
1809
|
+
if (flags["dry-run"]) return { lines: [`dry-run: se crear\xEDa un release con la \xFAltima revisi\xF3n de cada artefacto y se mover\xEDa el canal \xAB${channel}\xBB; no se envi\xF3 nada`], result: { dryRun: true, channel } };
|
|
1810
|
+
const client = makeClient(flags, io);
|
|
1811
|
+
let release;
|
|
1812
|
+
try {
|
|
1813
|
+
release = await client.request("POST", "/releases", { body: typeof flags.note === "string" ? { note: flags.note } : {} });
|
|
1814
|
+
} catch (error) {
|
|
1815
|
+
if (error instanceof ApiError) throw new ExitError(exitFor(error), `\u2717 ${explain(error, "crear el release")}`);
|
|
1816
|
+
throw error;
|
|
1817
|
+
}
|
|
1818
|
+
const rel2 = isRec(release) ? release : {};
|
|
1819
|
+
const releaseId = str2(rel2.id);
|
|
1820
|
+
const warnings = Array.isArray(rel2.warnings) ? rel2.warnings : [];
|
|
1821
|
+
if (!releaseId) throw new ExitError(EXPERIENCE_EXIT.failure, "el servicio no devolvi\xF3 el id del release");
|
|
1822
|
+
let moved;
|
|
1823
|
+
try {
|
|
1824
|
+
moved = await client.request("PUT", `/channels/${encodeURIComponent(channel)}`, { body: { releaseId } });
|
|
1825
|
+
} catch (error) {
|
|
1826
|
+
if (error instanceof ApiError) throw new ExitError(exitFor(error), [`\u2713 release #${typeof rel2.number === "number" ? rel2.number : "?"} ${releaseId} creado (el canal NO se movi\xF3)`, `\u2717 ${explain(error, `mover el canal \xAB${channel}\xBB`)}`].join("\n"));
|
|
1827
|
+
throw error;
|
|
1828
|
+
}
|
|
1829
|
+
const move = isRec(moved) ? moved : {};
|
|
1830
|
+
const sequence = typeof move.sequence === "number" ? move.sequence : isRec(move.channel) && typeof move.channel.sequence === "number" ? move.channel.sequence : null;
|
|
1831
|
+
const lines = [
|
|
1832
|
+
`\u2713 release #${typeof rel2.number === "number" ? rel2.number : "?"} ${releaseId}: ${typeof rel2.artifacts === "number" ? `${rel2.artifacts} artefactos` : Array.isArray(rel2.entries) ? `${rel2.entries.length} artefactos` : "creado"}`,
|
|
1833
|
+
`\u2713 canal \xAB${channel}\xBB \u2192 ${releaseId}${sequence !== null ? ` (sequence ${sequence})` : ""}`,
|
|
1834
|
+
...warnings.filter(isRec).slice(0, 10).map((w) => ` aviso ${str2(w.code)}: ${str2(w.message)}`),
|
|
1835
|
+
" Los clientes ven el cambio cuando su sondeo lea el timestamp firmado del canal (del orden de 1\u20132 min en el borde)."
|
|
1836
|
+
];
|
|
1837
|
+
return { lines, result: { releaseId, releaseNumber: typeof rel2.number === "number" ? rel2.number : null, channel, sequence, warnings } };
|
|
1838
|
+
}
|
|
1839
|
+
async function artifactNames(client, kind) {
|
|
1840
|
+
const result = await client.request("GET", "/artifacts", { query: { kind, limit: "200" } });
|
|
1841
|
+
const names = (isRec(result) && Array.isArray(result.data) ? result.data.filter(isRec) : []).filter((a) => a.archivedAt === null || a.archivedAt === void 0).map((a) => str2(a.name)).filter(Boolean);
|
|
1842
|
+
return [...new Set(names)].sort();
|
|
1843
|
+
}
|
|
1844
|
+
async function envCmd(positional, flags, io) {
|
|
1845
|
+
if (positional.length) throw new UsageError3("uso: customy experience env [--channel staging] [--format env|json]");
|
|
1846
|
+
const format = typeof flags.format === "string" ? flags.format : "env";
|
|
1847
|
+
if (format !== "env" && format !== "json") throw new UsageError3("--format debe ser env o json");
|
|
1848
|
+
const channel = channelFlag(flags, "production");
|
|
1849
|
+
const client = makeClient(flags, io);
|
|
1850
|
+
const context3 = await client.request("GET", "/context");
|
|
1851
|
+
const info = scopeFrom(context3);
|
|
1852
|
+
if (!info) throw new ExitError(EXPERIENCE_EXIT.failure, "GET /context no devolvi\xF3 el \xE1mbito de entrega (\xBFel servicio es anterior a manifest@2?)");
|
|
1853
|
+
const tenant = isRec(context3) && isRec(context3.tenant) ? context3.tenant : {};
|
|
1854
|
+
const environmentId = str2(tenant.environmentId) || null;
|
|
1855
|
+
const keys = isRec(context3) && Array.isArray(context3.keys) ? context3.keys.filter(isRec) : [];
|
|
1856
|
+
const anchors = keys.map((k) => ({ keyId: k.keyId, alg: k.alg, publicKey: k.publicKey, roles: rolesOf(k) }));
|
|
1857
|
+
const [tokens, catalogs, components] = await Promise.all([artifactNames(client, "tokens"), artifactNames(client, "catalog"), artifactNames(client, "component")]);
|
|
1858
|
+
const brandBases = [...new Set(tokens.map((n) => n.replace(/-(light|dark)$/, "")))].sort();
|
|
1859
|
+
const values = {
|
|
1860
|
+
EXPERIENCE_BASE_URL: info.delivery.base,
|
|
1861
|
+
EXPERIENCE_BRAND_SCOPE: info.key,
|
|
1862
|
+
EXPERIENCE_BRAND_ENVIRONMENT_ID: environmentId,
|
|
1863
|
+
EXPERIENCE_BRAND_CHANNEL: channel,
|
|
1864
|
+
EXPERIENCE_ANCHORED_KEYS: anchors.length ? JSON.stringify(anchors) : null,
|
|
1865
|
+
EXPERIENCE_BRAND_NAME: brandBases.length === 1 ? brandBases[0] : null,
|
|
1866
|
+
EXPERIENCE_NAMESPACE: [...new Set(catalogs)].length === 1 ? catalogs[0] : null
|
|
1867
|
+
};
|
|
1868
|
+
const notes = [];
|
|
1869
|
+
if (!info.delivery.base) notes.push("EXPERIENCE_BASE_URL: el servicio no tiene origen p\xFAblico de entrega configurado (lo configura Customy).");
|
|
1870
|
+
if (!environmentId) notes.push("EXPERIENCE_BRAND_ENVIRONMENT_ID: el contexto no trajo el id del entorno.");
|
|
1871
|
+
if (!anchors.length) notes.push("EXPERIENCE_ANCHORED_KEYS: este token no las ve (solo `experience.release.publish`). P\xEDdelas a quien tenga ese alcance, o ejecuta `customy experience init` con un token que lo lleve.");
|
|
1872
|
+
if (brandBases.length === 0) notes.push("EXPERIENCE_BRAND_NAME: el entorno a\xFAn no tiene marca (artefactos `tokens`): publ\xEDcala o d\xE9jala sin definir.");
|
|
1873
|
+
if (brandBases.length > 1) notes.push(`EXPERIENCE_BRAND_NAME: hay varias marcas (${brandBases.join(", ")}): elige la de TU app.`);
|
|
1874
|
+
if (catalogs.length === 0) notes.push("EXPERIENCE_NAMESPACE: el entorno a\xFAn no tiene cat\xE1logos.");
|
|
1875
|
+
if (new Set(catalogs).size > 1) notes.push(`EXPERIENCE_NAMESPACE: hay varios espacios de textos (${[...new Set(catalogs)].join(", ")}): elige el de TU app.`);
|
|
1876
|
+
notes.push("EXPERIENCE_BRAND_APPEARANCE: opcional; `appearance@2` solo si tu entorno declara esa capacidad (gu\xEDa \xA74.1); no sale de aqu\xED.");
|
|
1877
|
+
notes.push(`Componentes servidos (nombre del documento para ExperienceComponent y EXPERIENCE_SERVED_COMPONENTS): ${components.length ? components.join(", ") : "(ninguno publicado)"}.`);
|
|
1878
|
+
const result = { channel, values, brands: brandBases, namespaces: [...new Set(catalogs)], components, notes };
|
|
1879
|
+
if (format === "json") return { lines: [JSON.stringify(result, null, 2)], result };
|
|
1880
|
+
const lines = [
|
|
1881
|
+
"# Valores NO secretos de tu entorno (gu\xEDa \xA74.1 y \xA711.6). Ning\xFAn secreto: el origen, el \xE1mbito y las anclas son p\xFAblicos.",
|
|
1882
|
+
...Object.entries(values).map(([name, value]) => value === null ? `# ${name}= (sin valor: ver nota)` : `${name}=${value}`),
|
|
1883
|
+
...notes.map((n) => `# ${n}`)
|
|
1884
|
+
];
|
|
1885
|
+
return { lines, result };
|
|
1886
|
+
}
|
|
1887
|
+
var LOCALE_STATUSES = ["planned", "translating", "beta", "live", "disabled"];
|
|
1888
|
+
var LOCALE_RE = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8}){0,2}$/;
|
|
1889
|
+
async function localeCmd(positional, flags, io) {
|
|
1890
|
+
const [sub, ...locales] = positional;
|
|
1891
|
+
if (sub !== "put" || locales.length === 0) throw new UsageError3("uso: customy experience locale put <bcp47> [<bcp47> ...] [--status planned|translating|beta|live|disabled] [--direction ltr|rtl] [--fallback es,en]");
|
|
1892
|
+
const status2 = typeof flags.status === "string" ? flags.status : "translating";
|
|
1893
|
+
if (!LOCALE_STATUSES.includes(status2)) throw new UsageError3(`--status debe ser uno de: ${LOCALE_STATUSES.join(", ")}`);
|
|
1894
|
+
const direction = typeof flags.direction === "string" ? flags.direction : "ltr";
|
|
1895
|
+
if (direction !== "ltr" && direction !== "rtl") throw new UsageError3("--direction debe ser ltr o rtl");
|
|
1896
|
+
const fallback = list(flags.fallback);
|
|
1897
|
+
for (const l of [...locales, ...fallback]) if (!LOCALE_RE.test(l)) throw new UsageError3(`\xAB${l}\xBB no es un idioma BCP 47 v\xE1lido`);
|
|
1898
|
+
const client = makeClient(flags, io);
|
|
1899
|
+
const done = [];
|
|
1900
|
+
const lines = [];
|
|
1901
|
+
for (const locale of locales) {
|
|
1902
|
+
try {
|
|
1903
|
+
const result = await client.request("PUT", `/locales/${encodeURIComponent(locale)}`, { body: { status: status2, direction, fallback } });
|
|
1904
|
+
const rec = isRec(result) ? result : {};
|
|
1905
|
+
done.push({ locale, status: str2(rec.status) || status2 });
|
|
1906
|
+
lines.push(`\u2713 ${locale}: ${str2(rec.status) || status2}`);
|
|
1907
|
+
} catch (error) {
|
|
1908
|
+
if (error instanceof ApiError) throw new ExitError(exitFor(error), [...lines, `\u2717 ${explain(error, `idioma ${locale}`)}`].join("\n"));
|
|
1909
|
+
throw error;
|
|
1910
|
+
}
|
|
1911
|
+
}
|
|
1912
|
+
return { lines, result: { locales: done } };
|
|
1913
|
+
}
|
|
1914
|
+
var num2 = (v) => typeof v === "number" ? v : void 0;
|
|
1390
1915
|
var opt = (v) => typeof v === "string" ? v : void 0;
|
|
1391
1916
|
function scopeFrom(data) {
|
|
1392
1917
|
if (!isRec(data)) return null;
|
|
@@ -1401,7 +1926,7 @@ function scopeFrom(data) {
|
|
|
1401
1926
|
successor: typeof scope.successor === "string" ? scope.successor : null,
|
|
1402
1927
|
drainsUntil: typeof scope.drainsUntil === "string" ? scope.drainsUntil : null,
|
|
1403
1928
|
draining: view(data.draining),
|
|
1404
|
-
rot: { n:
|
|
1929
|
+
rot: { n: num2(data.rotationsThisMonth), max: num2(data.maxRotationsPerMonth), last: opt(data.lastRotatedAt), force: opt(data.forceAllowedAt), stuck: num2(data.channelsNotMigrated) },
|
|
1405
1930
|
delivery: {
|
|
1406
1931
|
base: typeof delivery.base === "string" ? delivery.base : null,
|
|
1407
1932
|
channels: (Array.isArray(delivery.channels) ? delivery.channels.filter(isRec) : []).map((c) => ({ channel: str2(c.channel), timestampUrl: typeof c.timestampUrl === "string" ? c.timestampUrl : null })),
|
|
@@ -1426,6 +1951,7 @@ function scopeLines(info) {
|
|
|
1426
1951
|
];
|
|
1427
1952
|
}
|
|
1428
1953
|
async function status(flags, io) {
|
|
1954
|
+
if (typeof flags.app === "string") return { ...await statusApp(flags, io), code: 0 };
|
|
1429
1955
|
const client = makeClient(flags, io);
|
|
1430
1956
|
const explicitWarn = typeof flags["warn-hours"] === "string" ? Number(flags["warn-hours"]) : null;
|
|
1431
1957
|
if (explicitWarn !== null && (!Number.isFinite(explicitWarn) || explicitWarn < 0)) throw new UsageError3("--warn-hours debe ser un n\xFAmero de horas");
|
|
@@ -1476,12 +2002,12 @@ async function usedKeys(root) {
|
|
|
1476
2002
|
if (depth > 12) return;
|
|
1477
2003
|
for (const entry of (await promises.readdir(dir, { withFileTypes: true })).sort((a, b) => a.name < b.name ? -1 : 1)) {
|
|
1478
2004
|
if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "dist" || entry.name === "build") continue;
|
|
1479
|
-
const full =
|
|
2005
|
+
const full = path4__default.default.join(dir, entry.name);
|
|
1480
2006
|
if (entry.isDirectory()) {
|
|
1481
2007
|
await walk(full, depth + 1);
|
|
1482
2008
|
continue;
|
|
1483
2009
|
}
|
|
1484
|
-
if (!entry.isFile() || !SRC_EXT.has(
|
|
2010
|
+
if (!entry.isFile() || !SRC_EXT.has(path4__default.default.extname(entry.name))) continue;
|
|
1485
2011
|
if ((await promises.stat(full)).size > 1e6) continue;
|
|
1486
2012
|
const text = await promises.readFile(full, "utf8");
|
|
1487
2013
|
for (const pattern of USAGE_PATTERNS) for (const match of text.matchAll(pattern)) if (!found.has(match[1])) found.set(match[1], full);
|
|
@@ -1492,9 +2018,9 @@ async function usedKeys(root) {
|
|
|
1492
2018
|
}
|
|
1493
2019
|
async function check(flags, io) {
|
|
1494
2020
|
const limits = limitsOf(flags);
|
|
1495
|
-
const dir =
|
|
2021
|
+
const dir = path4__default.default.resolve(io.cwd, typeof flags.dir === "string" ? flags.dir : "catalogs");
|
|
1496
2022
|
const loaded = (await loadFiles(await catalogFilesIn(dir), io)).filter((item) => item.parseError || isCatalogLike(item.raw));
|
|
1497
|
-
if (!loaded.length) throw new UsageError3(`no hay cat\xE1logos catalog@1 en ${
|
|
2023
|
+
if (!loaded.length) throw new UsageError3(`no hay cat\xE1logos catalog@1 en ${path4__default.default.relative(io.cwd, dir) || "."}`);
|
|
1498
2024
|
const failures = [];
|
|
1499
2025
|
const invalid = [];
|
|
1500
2026
|
const byNamespace = /* @__PURE__ */ new Map();
|
|
@@ -1504,7 +2030,7 @@ async function check(flags, io) {
|
|
|
1504
2030
|
invalid.push({ file: item.display, path: "", message: `no es JSON: ${item.parseError}` });
|
|
1505
2031
|
continue;
|
|
1506
2032
|
}
|
|
1507
|
-
const checked =
|
|
2033
|
+
const checked = chunkVUQSQ5YY_cjs.validateCatalog(item.raw, { limits });
|
|
1508
2034
|
if (!checked.ok || !checked.doc) {
|
|
1509
2035
|
for (const issue of checked.issues) invalid.push({ file: item.display, path: issue.path, message: issue.message });
|
|
1510
2036
|
continue;
|
|
@@ -1522,7 +2048,7 @@ async function check(flags, io) {
|
|
|
1522
2048
|
const present = Object.keys(byLocale).sort();
|
|
1523
2049
|
const need = required2.length ? required2 : present;
|
|
1524
2050
|
const base = typeof flags["base-locale"] === "string" ? flags["base-locale"] : need.includes("en") ? "en" : need[0];
|
|
1525
|
-
const report3 =
|
|
2051
|
+
const report3 = chunkVUQSQ5YY_cjs.parityReport(byLocale, need, base);
|
|
1526
2052
|
parity.push({ namespace, locales: need, base, ok: report3.ok, missing: report3.missing, placeholderMismatch: report3.placeholderMismatch });
|
|
1527
2053
|
for (const [locale, keys] of Object.entries(report3.missing)) failures.push(`\u2717 ${namespace}/${locale}: faltan ${keys.length} claves (${keys.slice(0, 5).join(", ")}${keys.length > 5 ? ", \u2026" : ""})`);
|
|
1528
2054
|
for (const m of report3.placeholderMismatch) failures.push(`\u2717 ${namespace}/${m.locale} ${m.key}: variables {${m.got.join(", ")}} \u2260 las de ${base} {${m.expected.join(", ")}}`);
|
|
@@ -1530,7 +2056,7 @@ async function check(flags, io) {
|
|
|
1530
2056
|
const glossary = await loadGlossary(flags, io);
|
|
1531
2057
|
const strict = flags.strict === true;
|
|
1532
2058
|
const mismatched = new Set(parity.flatMap((p) => p.placeholderMismatch.map((m) => `${String(p.namespace)}\0${m.locale}\0${m.key}`)));
|
|
1533
|
-
const { checkCatalog } = await import('./quality-
|
|
2059
|
+
const { checkCatalog } = await import('./quality-2GNGP67B.cjs');
|
|
1534
2060
|
const findings2 = [];
|
|
1535
2061
|
const warnings = [];
|
|
1536
2062
|
for (const p of parity) {
|
|
@@ -1552,7 +2078,7 @@ async function check(flags, io) {
|
|
|
1552
2078
|
}
|
|
1553
2079
|
let usage = null;
|
|
1554
2080
|
if (typeof flags.src === "string") {
|
|
1555
|
-
const src =
|
|
2081
|
+
const src = path4__default.default.resolve(io.cwd, flags.src);
|
|
1556
2082
|
let used;
|
|
1557
2083
|
try {
|
|
1558
2084
|
used = await usedKeys(src);
|
|
@@ -1563,8 +2089,8 @@ async function check(flags, io) {
|
|
|
1563
2089
|
for (const p of parity) for (const key2 of Object.keys((byNamespace.get(String(p.namespace)) ?? {})[String(p.base)] ?? {})) defined.add(key2);
|
|
1564
2090
|
const missing = [...used.keys()].filter((key2) => !defined.has(key2)).sort();
|
|
1565
2091
|
const unused = [...defined].filter((key2) => !used.has(key2)).sort();
|
|
1566
|
-
usage = { src:
|
|
1567
|
-
for (const key2 of missing) failures.push(`\u2717 el c\xF3digo usa \xAB${key2}\xBB (${
|
|
2092
|
+
usage = { src: path4__default.default.relative(io.cwd, src) || ".", usedKeys: used.size, missing: missing.map((key2) => ({ key: key2, file: path4__default.default.relative(io.cwd, used.get(key2)) })), unused };
|
|
2093
|
+
for (const key2 of missing) failures.push(`\u2717 el c\xF3digo usa \xAB${key2}\xBB (${path4__default.default.relative(io.cwd, used.get(key2))}) y el cat\xE1logo no la define`);
|
|
1568
2094
|
if (flags["fail-on-unused"]) for (const key2 of unused) failures.push(`\u2717 \xAB${key2}\xBB est\xE1 en el cat\xE1logo y el c\xF3digo no la usa`);
|
|
1569
2095
|
}
|
|
1570
2096
|
const ok = failures.length === 0;
|
|
@@ -1581,7 +2107,7 @@ async function loadGlossary(flags, io) {
|
|
|
1581
2107
|
if (typeof flags.glossary !== "string") throw new UsageError3("--glossary necesita un fichero");
|
|
1582
2108
|
let raw;
|
|
1583
2109
|
try {
|
|
1584
|
-
raw = JSON.parse(await promises.readFile(
|
|
2110
|
+
raw = JSON.parse(await promises.readFile(path4__default.default.resolve(io.cwd, flags.glossary), "utf8"));
|
|
1585
2111
|
} catch (error) {
|
|
1586
2112
|
throw new UsageError3(`--glossary: no se pudo leer ${flags.glossary} como JSON (${error instanceof Error ? error.message : String(error)})`);
|
|
1587
2113
|
}
|
|
@@ -1631,9 +2157,9 @@ function formatFlag(flags, allowAuto) {
|
|
|
1631
2157
|
}
|
|
1632
2158
|
function outputPath(out, io, fallbackDir, name, single) {
|
|
1633
2159
|
if (out !== void 0 && typeof out !== "string") throw new UsageError3("--out necesita una ruta");
|
|
1634
|
-
if (out === void 0) return
|
|
1635
|
-
const resolved =
|
|
1636
|
-
return single && /\.(xlf|xliff|po|pot|json)$/i.test(out) ? resolved :
|
|
2160
|
+
if (out === void 0) return path4__default.default.resolve(io.cwd, fallbackDir, name);
|
|
2161
|
+
const resolved = path4__default.default.resolve(io.cwd, out);
|
|
2162
|
+
return single && /\.(xlf|xliff|po|pot|json)$/i.test(out) ? resolved : path4__default.default.join(resolved, name);
|
|
1637
2163
|
}
|
|
1638
2164
|
async function exportCmd(flags, io) {
|
|
1639
2165
|
const format = formatFlag(flags, false);
|
|
@@ -1648,9 +2174,9 @@ async function exportCmd(flags, io) {
|
|
|
1648
2174
|
for (const wantedNamespace of namespaces) if (!byNamespace.has(wantedNamespace)) throw new UsageError3(`no existe el espacio de nombres \xAB${wantedNamespace}\xBB en el servidor`);
|
|
1649
2175
|
if (!byNamespace.size) throw new ExitError(EXPERIENCE_EXIT.invalid, "no hay cat\xE1logos en el servidor que exportar");
|
|
1650
2176
|
const tools = {
|
|
1651
|
-
xliff: format === "xliff" ? await import('./xliff-
|
|
1652
|
-
po: format === "po" ? await import('./po-
|
|
1653
|
-
json: format === "json" ? await import('./json-
|
|
2177
|
+
xliff: format === "xliff" ? await import('./xliff-EBJNXSR6.cjs') : null,
|
|
2178
|
+
po: format === "po" ? await import('./po-ZQLZ4U5Q.cjs') : null,
|
|
2179
|
+
json: format === "json" ? await import('./json-FSAA27RC.cjs') : null
|
|
1654
2180
|
};
|
|
1655
2181
|
const exported = [];
|
|
1656
2182
|
const skipped = [];
|
|
@@ -1700,9 +2226,9 @@ async function exportCmd(flags, io) {
|
|
|
1700
2226
|
const lines = [];
|
|
1701
2227
|
for (const job of jobs) {
|
|
1702
2228
|
const file = outputPath(flags.out, io, "translations", job.name, jobs.length === 1);
|
|
1703
|
-
await promises.mkdir(
|
|
2229
|
+
await promises.mkdir(path4__default.default.dirname(file), { recursive: true });
|
|
1704
2230
|
await promises.writeFile(file, job.content);
|
|
1705
|
-
const shown =
|
|
2231
|
+
const shown = path4__default.default.relative(io.cwd, file) || file;
|
|
1706
2232
|
exported.push({ namespace: job.namespace, locale: job.locale, format, file: shown, keys: job.keys, source: draft ? "draft" : "published", from: job.from });
|
|
1707
2233
|
lines.push(`\u2713 ${shown} (${job.namespace}/${job.locale}, ${job.keys} claves, ${job.from})`);
|
|
1708
2234
|
}
|
|
@@ -1712,7 +2238,7 @@ async function exportCmd(flags, io) {
|
|
|
1712
2238
|
}
|
|
1713
2239
|
function detectFormat(flag, file, text) {
|
|
1714
2240
|
if (flag !== "auto") return flag;
|
|
1715
|
-
const ext =
|
|
2241
|
+
const ext = path4__default.default.extname(file).toLowerCase();
|
|
1716
2242
|
if (ext === ".xlf" || ext === ".xliff") return "xliff";
|
|
1717
2243
|
if (ext === ".po" || ext === ".pot") return "po";
|
|
1718
2244
|
if (ext === ".json") return "json";
|
|
@@ -1737,9 +2263,9 @@ async function importCmd(positional, flags, io) {
|
|
|
1737
2263
|
const localeFlag = singleLocale(flags, "locale");
|
|
1738
2264
|
const sourceLocaleFlag = singleLocale(flags, "source-locale");
|
|
1739
2265
|
const glossary = await loadGlossary(flags, io);
|
|
1740
|
-
const dir =
|
|
1741
|
-
const file =
|
|
1742
|
-
const display =
|
|
2266
|
+
const dir = path4__default.default.resolve(io.cwd, typeof flags.dir === "string" ? flags.dir : "catalogs");
|
|
2267
|
+
const file = path4__default.default.resolve(io.cwd, positional[0]);
|
|
2268
|
+
const display = path4__default.default.relative(io.cwd, file) || file;
|
|
1743
2269
|
let size;
|
|
1744
2270
|
try {
|
|
1745
2271
|
const info = await promises.stat(file);
|
|
@@ -1761,10 +2287,10 @@ async function importCmd(positional, flags, io) {
|
|
|
1761
2287
|
let target;
|
|
1762
2288
|
try {
|
|
1763
2289
|
if (format === "xliff") {
|
|
1764
|
-
const t = await import('./xliff-
|
|
2290
|
+
const t = await import('./xliff-EBJNXSR6.cjs');
|
|
1765
2291
|
({ source, target } = t.xliffToCatalogs(t.importXliff(bytes, namespaceFlag ? { namespace: namespaceFlag } : {})));
|
|
1766
2292
|
} else if (format === "po") {
|
|
1767
|
-
const t = await import('./po-
|
|
2293
|
+
const t = await import('./po-ZQLZ4U5Q.cjs');
|
|
1768
2294
|
({ source, target } = t.poToCatalogs(t.parsePo(text), { ...namespaceFlag ? { namespace: namespaceFlag } : {}, ...sourceLocaleFlag ? { sourceLocale: sourceLocaleFlag } : {}, ...localeFlag ? { targetLocale: localeFlag } : {} }));
|
|
1769
2295
|
} else {
|
|
1770
2296
|
let parsed;
|
|
@@ -1774,14 +2300,14 @@ async function importCmd(positional, flags, io) {
|
|
|
1774
2300
|
parsed = void 0;
|
|
1775
2301
|
}
|
|
1776
2302
|
if (isCatalogLike(parsed)) {
|
|
1777
|
-
const checked2 =
|
|
2303
|
+
const checked2 = chunkVUQSQ5YY_cjs.validateCatalog(parsed, { limits });
|
|
1778
2304
|
if (!checked2.ok || !checked2.doc) throw new ExitError(EXPERIENCE_EXIT.invalid, [`validaci\xF3n local fallida; no se envi\xF3 nada:`, ...checked2.issues.map((i) => ` ${display}${i.path ? ` ${i.path}` : ""}: ${i.message}`)].join("\n"));
|
|
1779
2305
|
source = null;
|
|
1780
2306
|
target = checked2.doc;
|
|
1781
2307
|
} else {
|
|
1782
|
-
const t = await import('./json-
|
|
2308
|
+
const t = await import('./json-FSAA27RC.cjs');
|
|
1783
2309
|
const flat = t.parseFlatJson(text);
|
|
1784
|
-
const named =
|
|
2310
|
+
const named = path4__default.default.basename(file).match(/^([a-z][a-z0-9-]{1,31})\.([a-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,2})(?:\.flat)?\.json$/);
|
|
1785
2311
|
const namespace = namespaceFlag ?? named?.[1];
|
|
1786
2312
|
const locale = localeFlag ?? named?.[2];
|
|
1787
2313
|
if (!namespace || !locale) throw new UsageError3("un JSON plano necesita --namespace y --locale (o un nombre \xAB<espacio>.<idioma>.json\xBB)");
|
|
@@ -1798,15 +2324,15 @@ async function importCmd(positional, flags, io) {
|
|
|
1798
2324
|
if (localeFlag && target.locale !== localeFlag) target = { ...target, locale: localeFlag };
|
|
1799
2325
|
if (source && namespaceFlag && source.namespace !== namespaceFlag) source = { ...source, namespace: namespaceFlag };
|
|
1800
2326
|
if (!Object.keys(target.messages).length) throw new ExitError(EXPERIENCE_EXIT.invalid, `${display}: no trae ninguna traducci\xF3n`);
|
|
1801
|
-
const checked =
|
|
2327
|
+
const checked = chunkVUQSQ5YY_cjs.validateCatalog(target, { limits });
|
|
1802
2328
|
if (!checked.ok || !checked.doc) {
|
|
1803
2329
|
throw new ExitError(EXPERIENCE_EXIT.invalid, ["validaci\xF3n local fallida; no se envi\xF3 nada:", ...checked.issues.map((i) => ` ${display}${i.path ? ` ${i.path}` : ""}: ${i.message}`)].join("\n"));
|
|
1804
2330
|
}
|
|
1805
2331
|
const doc = checked.doc;
|
|
1806
2332
|
if (!source && format === "json") {
|
|
1807
|
-
const localSource =
|
|
2333
|
+
const localSource = path4__default.default.join(dir, fileName(doc.namespace, sourceLocaleFlag ?? "en"));
|
|
1808
2334
|
try {
|
|
1809
|
-
const candidate =
|
|
2335
|
+
const candidate = chunkVUQSQ5YY_cjs.validateCatalog(JSON.parse(await promises.readFile(localSource, "utf8")), { limits: chunkVUQSQ5YY_cjs.TRANSLATION_PLAN_LIMITS.enterprise });
|
|
1810
2336
|
if (candidate.ok && candidate.doc && candidate.doc.locale !== doc.locale) source = candidate.doc;
|
|
1811
2337
|
} catch {
|
|
1812
2338
|
}
|
|
@@ -1814,7 +2340,7 @@ async function importCmd(positional, flags, io) {
|
|
|
1814
2340
|
const findings2 = [];
|
|
1815
2341
|
const noteLines = [];
|
|
1816
2342
|
if (source) {
|
|
1817
|
-
const { checkCatalog } = await import('./quality-
|
|
2343
|
+
const { checkCatalog } = await import('./quality-2GNGP67B.cjs');
|
|
1818
2344
|
for (const f of checkCatalog(source, doc, { glossary, severities: QUALITY_SEVERITIES })) findings2.push(qualityRow(doc.namespace, f));
|
|
1819
2345
|
const strictFail = flags.strict === true;
|
|
1820
2346
|
const failing = (row) => row.severity === "error" || strictFail && row.severity === "warning";
|
|
@@ -1843,8 +2369,8 @@ async function pseudoCmd(positional, flags, io) {
|
|
|
1843
2369
|
if (locale === sourceLocale) throw new UsageError3("--locale no puede ser el idioma de origen");
|
|
1844
2370
|
const limits = limitsOf(flags);
|
|
1845
2371
|
const namespaces = list(flags.namespace);
|
|
1846
|
-
const dir =
|
|
1847
|
-
const files = positional.length ? positional.map((p) =>
|
|
2372
|
+
const dir = path4__default.default.resolve(io.cwd, typeof flags.dir === "string" ? flags.dir : "catalogs");
|
|
2373
|
+
const files = positional.length ? positional.map((p) => path4__default.default.resolve(io.cwd, p)) : await catalogFilesIn(dir);
|
|
1848
2374
|
const loaded = (await loadFiles(files, io)).filter((item) => positional.length || item.parseError || isCatalogLike(item.raw));
|
|
1849
2375
|
const sources = [];
|
|
1850
2376
|
const problems = [];
|
|
@@ -1857,7 +2383,7 @@ async function pseudoCmd(positional, flags, io) {
|
|
|
1857
2383
|
if (positional.length) problems.push(` ${item.display}: no es un cat\xE1logo del idioma de origen ${sourceLocale}`);
|
|
1858
2384
|
continue;
|
|
1859
2385
|
}
|
|
1860
|
-
const checked =
|
|
2386
|
+
const checked = chunkVUQSQ5YY_cjs.validateCatalog(item.raw, { limits });
|
|
1861
2387
|
if (!checked.ok || !checked.doc) {
|
|
1862
2388
|
problems.push(...checked.issues.map((i) => ` ${item.display}${i.path ? ` ${i.path}` : ""}: ${i.message}`));
|
|
1863
2389
|
continue;
|
|
@@ -1865,7 +2391,7 @@ async function pseudoCmd(positional, flags, io) {
|
|
|
1865
2391
|
if (!namespaces.length || namespaces.includes(checked.doc.namespace)) sources.push({ display: item.display, doc: checked.doc });
|
|
1866
2392
|
}
|
|
1867
2393
|
if (problems.length) throw new ExitError(EXPERIENCE_EXIT.invalid, ["cat\xE1logo de origen no v\xE1lido; no se escribi\xF3 nada:", ...problems].join("\n"));
|
|
1868
|
-
if (!sources.length) throw new UsageError3(`no hay cat\xE1logos de origen \xAB${sourceLocale}\xBB en ${
|
|
2394
|
+
if (!sources.length) throw new UsageError3(`no hay cat\xE1logos de origen \xAB${sourceLocale}\xBB en ${path4__default.default.relative(io.cwd, dir) || "."}`);
|
|
1869
2395
|
const { pseudoLocalizeMessages } = await import('./pseudo-LBLMBD2T.cjs');
|
|
1870
2396
|
const outputs = [];
|
|
1871
2397
|
for (const { display, doc } of sources) {
|
|
@@ -1874,7 +2400,7 @@ async function pseudoCmd(positional, flags, io) {
|
|
|
1874
2400
|
continue;
|
|
1875
2401
|
}
|
|
1876
2402
|
const out = { version: doc.version, namespace: doc.namespace, locale, syntax: doc.syntax, messages: pseudoLocalizeMessages(doc.messages, { strategy: flags.rtl ? "rtl" : "accented" }) };
|
|
1877
|
-
const checked =
|
|
2403
|
+
const checked = chunkVUQSQ5YY_cjs.validateCatalog(out, { limits });
|
|
1878
2404
|
if (!checked.ok || !checked.doc) {
|
|
1879
2405
|
problems.push(...checked.issues.map((i) => ` ${doc.namespace}/${locale}${i.path ? ` ${i.path}` : ""}: ${i.message}`));
|
|
1880
2406
|
continue;
|
|
@@ -1882,14 +2408,14 @@ async function pseudoCmd(positional, flags, io) {
|
|
|
1882
2408
|
outputs.push({ doc: checked.doc, from: display });
|
|
1883
2409
|
}
|
|
1884
2410
|
if (problems.length) throw new ExitError(EXPERIENCE_EXIT.invalid, ["la pseudo-localizaci\xF3n no es un cat\xE1logo v\xE1lido; no se escribi\xF3 nada:", ...problems].join("\n"));
|
|
1885
|
-
const fallbackDir = positional.length ?
|
|
2411
|
+
const fallbackDir = positional.length ? path4__default.default.dirname(files[0]) : dir;
|
|
1886
2412
|
const written = [];
|
|
1887
2413
|
const lines = [];
|
|
1888
2414
|
for (const { doc, from } of outputs) {
|
|
1889
|
-
const target = outputPath(flags.out, io,
|
|
1890
|
-
await promises.mkdir(
|
|
2415
|
+
const target = outputPath(flags.out, io, path4__default.default.relative(io.cwd, fallbackDir) || ".", fileName(doc.namespace, locale), outputs.length === 1);
|
|
2416
|
+
await promises.mkdir(path4__default.default.dirname(target), { recursive: true });
|
|
1891
2417
|
await promises.writeFile(target, serializeCatalog(doc));
|
|
1892
|
-
const shown =
|
|
2418
|
+
const shown = path4__default.default.relative(io.cwd, target) || target;
|
|
1893
2419
|
written.push({ namespace: doc.namespace, locale, strategy: flags.rtl ? "rtl" : "accented", file: shown, from, keys: Object.keys(doc.messages).length });
|
|
1894
2420
|
lines.push(`\u2713 ${shown} (${doc.namespace}/${locale}, ${Object.keys(doc.messages).length} claves, desde ${from})`);
|
|
1895
2421
|
}
|
|
@@ -1932,8 +2458,8 @@ var rolesOf = (key2) => Array.isArray(key2.roles) ? key2.roles.filter((r) => typ
|
|
|
1932
2458
|
async function initCmd(flags, io) {
|
|
1933
2459
|
const client = makeClient(flags, io);
|
|
1934
2460
|
const channel = channelFlag(flags, "production");
|
|
1935
|
-
const out =
|
|
1936
|
-
const shown =
|
|
2461
|
+
const out = path4__default.default.resolve(io.cwd, typeof flags.out === "string" ? flags.out : CONFIG_FILE);
|
|
2462
|
+
const shown = path4__default.default.relative(io.cwd, out) || out;
|
|
1937
2463
|
if (!flags.force) {
|
|
1938
2464
|
let exists = true;
|
|
1939
2465
|
try {
|
|
@@ -1957,7 +2483,7 @@ async function initCmd(flags, io) {
|
|
|
1957
2483
|
const tenant = isRec(context3) && isRec(context3.tenant) ? context3.tenant : {};
|
|
1958
2484
|
const environmentId = typeof tenant.environmentId === "string" ? tenant.environmentId : null;
|
|
1959
2485
|
const config = { scope: info.key, base: info.delivery.base, ...environmentId ? { environmentId } : {}, channel, anchors: keys.map((k) => ({ keyId: k.keyId, alg: k.alg, publicKey: k.publicKey, roles: rolesOf(k) })), ...floor ? { floor } : {}, strict: false };
|
|
1960
|
-
await promises.mkdir(
|
|
2486
|
+
await promises.mkdir(path4__default.default.dirname(out), { recursive: true });
|
|
1961
2487
|
await promises.writeFile(out, `${JSON.stringify(config, null, 2)}
|
|
1962
2488
|
`);
|
|
1963
2489
|
const lines = [
|
|
@@ -1976,14 +2502,14 @@ async function revokeCmd(positional, flags, io) {
|
|
|
1976
2502
|
const target = await resolveRelease(client, positional[0]);
|
|
1977
2503
|
const fallback = typeof flags.fallback === "string" ? await resolveRelease(client, flags.fallback) : null;
|
|
1978
2504
|
if (fallback && fallback.id === target.id) throw new UsageError3("--fallback no puede ser el release que se revoca");
|
|
1979
|
-
const
|
|
1980
|
-
if (flags["dry-run"]) return { lines: [`dry-run: se revocar\xEDa el ${
|
|
2505
|
+
const label2 = `release ${target.number !== null ? `#${target.number} ` : ""}${target.id}`;
|
|
2506
|
+
if (flags["dry-run"]) return { lines: [`dry-run: se revocar\xEDa el ${label2}${fallback ? ` con respaldo ${fallback.id}` : " (sin respaldo: el servicio pedir\xE1 --fallback si alg\xFAn canal lo sirve)"}; no se envi\xF3 nada`], result: { dryRun: true, releaseId: target.id, fallbackReleaseId: fallback?.id ?? null } };
|
|
1981
2507
|
const result = await client.request("POST", `/releases/${encodeURIComponent(target.id)}/revoke`, { body: { reason, ...fallback ? { fallbackReleaseId: fallback.id } : {} } });
|
|
1982
2508
|
const rec = isRec(result) ? result : {};
|
|
1983
2509
|
const repointed = (Array.isArray(rec.repointed) ? rec.repointed.filter(isRec) : []).map((r) => ({ channel: str2(r.channel), sequence: typeof r.sequence === "number" ? r.sequence : null, releaseNumber: typeof r.releaseNumber === "number" ? r.releaseNumber : null, minSequence: typeof r.minSequence === "number" ? r.minSequence : null }));
|
|
1984
2510
|
const already = rec.alreadyRevoked === true;
|
|
1985
2511
|
const lines = [
|
|
1986
|
-
already ? `= ${
|
|
2512
|
+
already ? `= ${label2}: ya estaba revocado` : `\u2713 ${label2}: revocado`,
|
|
1987
2513
|
...repointed.map((r) => ` ${r.channel}: vuelve a publicar el release #${r.releaseNumber ?? "?"} con sequence ${r.sequence ?? "?"} y minSequence ${r.minSequence ?? "?"} (los clientes descartan lo instalado con sequence menor)`),
|
|
1988
2514
|
...repointed.length ? [" Verifica en la CDN: GET <base>/t/<scope>/<canal>/timestamp.json debe traer esa sequence y ese minSequence (mira CF-Cache-Status; el 200 de una purga no prueba nada)."] : []
|
|
1989
2515
|
];
|
|
@@ -2062,12 +2588,12 @@ async function reconcileCmd(positional, flags, io) {
|
|
|
2062
2588
|
const rec = await client.request("POST", `/channels/${encodeURIComponent(channel)}/reconcile`, { body: {} });
|
|
2063
2589
|
const data = isRec(rec) ? rec : {};
|
|
2064
2590
|
const republished = isRec(data.republished) ? data.republished : null;
|
|
2065
|
-
const
|
|
2591
|
+
const num3 = (value) => typeof value === "number" ? value : null;
|
|
2066
2592
|
const lines = [
|
|
2067
|
-
`\u2713 canal ${channel} reconciliado: contador ${
|
|
2068
|
-
republished ? ` release vigente publicado de nuevo con sequence ${
|
|
2593
|
+
`\u2713 canal ${channel} reconciliado: contador ${num3(data.previousSequence) ?? "?"} \u2192 ${num3(data.sequence) ?? "?"} (el almac\xE9n anunci\xF3 hasta ${num3(data.storedSequence) ?? "?"})`,
|
|
2594
|
+
republished ? ` release vigente publicado de nuevo con sequence ${num3(republished.sequence) ?? "?"}` : " el canal no ten\xEDa release vigente: no se republic\xF3 nada"
|
|
2069
2595
|
];
|
|
2070
|
-
return { lines, result: { channel, previousSequence:
|
|
2596
|
+
return { lines, result: { channel, previousSequence: num3(data.previousSequence), storedSequence: num3(data.storedSequence), sequence: num3(data.sequence), republished: republished ? { sequence: num3(republished.sequence) } : null } };
|
|
2071
2597
|
}
|
|
2072
2598
|
async function runExperienceCli(args, io) {
|
|
2073
2599
|
const asJson = args.includes("--json");
|
|
@@ -2116,8 +2642,26 @@ async function runExperienceCli(args, io) {
|
|
|
2116
2642
|
case "reconcile":
|
|
2117
2643
|
outcome = await reconcileCmd(positional, flags, io);
|
|
2118
2644
|
break;
|
|
2645
|
+
case "publish":
|
|
2646
|
+
outcome = await publishCmd(positional, flags, io);
|
|
2647
|
+
break;
|
|
2648
|
+
case "locale":
|
|
2649
|
+
outcome = await localeCmd(positional, flags, io);
|
|
2650
|
+
break;
|
|
2651
|
+
case "env":
|
|
2652
|
+
outcome = await envCmd(positional, flags, io);
|
|
2653
|
+
break;
|
|
2654
|
+
case "add":
|
|
2655
|
+
outcome = await addCmd(positional, flags, io);
|
|
2656
|
+
break;
|
|
2657
|
+
case "diff":
|
|
2658
|
+
outcome = await diffCmd(positional, flags, io);
|
|
2659
|
+
break;
|
|
2660
|
+
case "pin":
|
|
2661
|
+
outcome = await pinCmd(positional, flags, io);
|
|
2662
|
+
break;
|
|
2119
2663
|
default:
|
|
2120
|
-
throw new UsageError3(`comando desconocido: customy experience ${command2} (pull|push|status|check|export|import|pseudo|init|revoke|scope|signing|reconcile)`);
|
|
2664
|
+
throw new UsageError3(`comando desconocido: customy experience ${command2} (pull|push|status|check|export|import|pseudo|init|revoke|scope|signing|reconcile|publish|locale|env|add|diff|pin)`);
|
|
2121
2665
|
}
|
|
2122
2666
|
const code = outcome.code ?? EXPERIENCE_EXIT.ok;
|
|
2123
2667
|
if (asJson) io.out(JSON.stringify({ ok: code === 0, command: command2, exitCode: code, ...isRec(outcome.result) ? outcome.result : { result: outcome.result } }, null, 2));
|
|
@@ -2242,7 +2786,7 @@ function table2(rows) {
|
|
|
2242
2786
|
}
|
|
2243
2787
|
async function readJsonFile(io, file) {
|
|
2244
2788
|
try {
|
|
2245
|
-
return JSON.parse(await promises.readFile(
|
|
2789
|
+
return JSON.parse(await promises.readFile(path4__default.default.resolve(io.cwd, file), "utf8"));
|
|
2246
2790
|
} catch (error) {
|
|
2247
2791
|
throw new UsageError4(`no se pudo leer ${file}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2248
2792
|
}
|
|
@@ -2548,10 +3092,10 @@ async function tail(args, io) {
|
|
|
2548
3092
|
}
|
|
2549
3093
|
return WHATSAPP_EXIT.ok;
|
|
2550
3094
|
}
|
|
2551
|
-
function dryRun(ctx, method,
|
|
2552
|
-
emit2(ctx, { dryRun: true, method, path:
|
|
3095
|
+
function dryRun(ctx, method, path7, body) {
|
|
3096
|
+
emit2(ctx, { dryRun: true, method, path: path7, ...body === void 0 ? {} : { body } }, [
|
|
2553
3097
|
"DRY RUN (no se cambia nada)",
|
|
2554
|
-
`${method} ${
|
|
3098
|
+
`${method} ${path7}`,
|
|
2555
3099
|
...body === void 0 ? [] : [JSON.stringify(body, null, 2)]
|
|
2556
3100
|
]);
|
|
2557
3101
|
return WHATSAPP_EXIT.ok;
|
|
@@ -2671,7 +3215,7 @@ async function recipientsFromFile(io, file) {
|
|
|
2671
3215
|
return parsed;
|
|
2672
3216
|
}
|
|
2673
3217
|
try {
|
|
2674
|
-
return (await promises.readFile(
|
|
3218
|
+
return (await promises.readFile(path4__default.default.resolve(io.cwd, file), "utf8")).split(/\r?\n/).map((line) => line.split("#")[0].trim()).filter(Boolean);
|
|
2675
3219
|
} catch (error) {
|
|
2676
3220
|
throw new UsageError4(`no se pudo leer ${file}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2677
3221
|
}
|
|
@@ -2874,7 +3418,7 @@ async function webhookBody(flags, io) {
|
|
|
2874
3418
|
if (file === void 0 === (inline === void 0)) throw new UsageError4("indica exactamente uno: --body-file o --body (el cuerpo CRUDO, sin re-serializar)");
|
|
2875
3419
|
if (inline !== void 0) return inline;
|
|
2876
3420
|
try {
|
|
2877
|
-
return await promises.readFile(
|
|
3421
|
+
return await promises.readFile(path4__default.default.resolve(io.cwd, file), "utf8");
|
|
2878
3422
|
} catch (error) {
|
|
2879
3423
|
throw new UsageError4(`no se pudo leer ${file}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2880
3424
|
}
|
|
@@ -3171,12 +3715,12 @@ function option(args, name) {
|
|
|
3171
3715
|
return index >= 0 ? args[index + 1] : void 0;
|
|
3172
3716
|
}
|
|
3173
3717
|
async function loadManifest(args, io) {
|
|
3174
|
-
const file =
|
|
3718
|
+
const file = path4__default.default.resolve(io.cwd, option(args, "file") ?? "customy.app.json");
|
|
3175
3719
|
let raw;
|
|
3176
3720
|
try {
|
|
3177
3721
|
raw = JSON.parse(await promises.readFile(file, "utf8"));
|
|
3178
3722
|
} catch (error) {
|
|
3179
|
-
io.err(`no se pudo leer ${
|
|
3723
|
+
io.err(`no se pudo leer ${path4__default.default.relative(io.cwd, file) || file}: ${error instanceof Error ? error.message : error}`);
|
|
3180
3724
|
return null;
|
|
3181
3725
|
}
|
|
3182
3726
|
const result = validateManifest(raw);
|
|
@@ -3208,17 +3752,18 @@ async function runCli(argv, io) {
|
|
|
3208
3752
|
return 0;
|
|
3209
3753
|
}
|
|
3210
3754
|
if (command2 === "codegen") {
|
|
3211
|
-
const out =
|
|
3212
|
-
await promises.mkdir(
|
|
3755
|
+
const out = path4__default.default.resolve(io.cwd, option(args, "out") ?? "customy.generated.ts");
|
|
3756
|
+
await promises.mkdir(path4__default.default.dirname(out), { recursive: true });
|
|
3213
3757
|
await promises.writeFile(out, generateAppTypes(manifest));
|
|
3214
|
-
io.out(`\u2713 tipos de ${manifest.key} en ${
|
|
3758
|
+
io.out(`\u2713 tipos de ${manifest.key} en ${path4__default.default.relative(io.cwd, out)}`);
|
|
3215
3759
|
return 0;
|
|
3216
3760
|
}
|
|
3217
3761
|
const workspaceEnvironmentId = option(args, "workspace-env");
|
|
3218
3762
|
const accessUrl = io.env.CUSTOMY_ACCESS_URL;
|
|
3219
3763
|
const token = io.env.CUSTOMY_ACCESS_TOKEN;
|
|
3220
|
-
|
|
3221
|
-
|
|
3764
|
+
const adminSecret = io.env.CUSTOMY_ADMIN_SECRET;
|
|
3765
|
+
if (!workspaceEnvironmentId || !accessUrl || !token && !adminSecret) {
|
|
3766
|
+
io.err("sync necesita --workspace-env, CUSTOMY_ACCESS_URL y una credencial: CUSTOMY_ADMIN_SECRET (x-admin-secret, producci\xF3n) o CUSTOMY_ACCESS_TOKEN (Bearer)");
|
|
3222
3767
|
return 2;
|
|
3223
3768
|
}
|
|
3224
3769
|
try {
|
|
@@ -3226,12 +3771,19 @@ async function runCli(argv, io) {
|
|
|
3226
3771
|
manifest,
|
|
3227
3772
|
accessUrl,
|
|
3228
3773
|
token,
|
|
3774
|
+
adminSecret,
|
|
3775
|
+
actor: io.env.CUSTOMY_ADMIN_ACTOR,
|
|
3229
3776
|
workspaceEnvironmentId,
|
|
3230
3777
|
reason: option(args, "reason") ?? `customy apps sync ${manifest.key}`,
|
|
3231
3778
|
fetch: io.fetch
|
|
3232
3779
|
});
|
|
3233
3780
|
const verb = { installed: "instalada", updated: "actualizada", unchanged: "sin cambios" }[result.action];
|
|
3234
3781
|
io.out(`\u2713 ${manifest.key} ${verb}: aplicaci\xF3n ${result.applicationId}, entorno ${result.environmentId}, revisi\xF3n ${result.revision} (${authorizationSummary(manifest)})`);
|
|
3782
|
+
if (result.publishableKey) {
|
|
3783
|
+
io.out("Para el .env de la app (la clave p\xFAblica no es secreta):");
|
|
3784
|
+
io.out(`CUSTOMY_PUBLISHABLE_KEY=${result.publishableKey}`);
|
|
3785
|
+
}
|
|
3786
|
+
io.out(`CUSTOMY_ENVIRONMENT_ID=${result.environmentId}`);
|
|
3235
3787
|
let failed = false;
|
|
3236
3788
|
for (const [product2, outcome] of Object.entries(result.reconciliation)) {
|
|
3237
3789
|
if (outcome.status === "failed") {
|