@customyai/cli 0.7.1 → 0.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +83 -0
- package/LICENSE +2 -1
- package/README.md +77 -0
- package/dist/bin.cjs +6 -2
- package/dist/bin.mjs +5 -1
- package/dist/chunk-2A6WFLXS.cjs +235 -0
- package/dist/chunk-3M6ZLCSN.mjs +237 -0
- package/dist/chunk-57NNDUEX.mjs +3246 -0
- package/dist/chunk-6X3AX6PB.cjs +3266 -0
- package/dist/chunk-ABK4QQWW.cjs +244 -0
- package/dist/chunk-BYMLRMNS.mjs +27 -0
- package/dist/chunk-MFJL3NO5.cjs +31 -0
- package/dist/chunk-QKIF4C5R.mjs +226 -0
- package/dist/index.cjs +32 -11
- package/dist/index.d.cts +63 -1
- package/dist/index.d.ts +63 -1
- package/dist/index.mjs +2 -1
- package/dist/json-NETFQXLJ.mjs +67 -0
- package/dist/json-NSJMTBPP.cjs +70 -0
- package/dist/po-AKWHAYBL.mjs +387 -0
- package/dist/po-IJGMXNVY.cjs +394 -0
- package/dist/pseudo-CKYMJJBX.mjs +101 -0
- package/dist/pseudo-LBLMBD2T.cjs +106 -0
- package/dist/quality-6SEZNA6Q.cjs +207 -0
- package/dist/quality-ILK6IA5O.mjs +199 -0
- package/dist/xliff-DEJHB2SY.mjs +512 -0
- package/dist/xliff-DXICWMWC.cjs +518 -0
- package/package.json +9 -3
- package/dist/chunk-6KGKN5HN.cjs +0 -1108
- package/dist/chunk-KDUW3KTG.mjs +0 -1093
|
@@ -0,0 +1,3246 @@
|
|
|
1
|
+
import { validateCatalog, TRANSLATION_PLAN_LIMITS, parityReport } from './chunk-QKIF4C5R.mjs';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { mkdir, writeFile, chmod, stat, readFile, readdir } from 'fs/promises';
|
|
4
|
+
import path3 from 'path';
|
|
5
|
+
import { CustomyProvisioningError, CustomyScopeError, CustomyEnvironmentMismatchError, CustomyConflictError, CustomyRateLimitError, CustomyAuthError, createProvisioning } from '@customyai/provisioning';
|
|
6
|
+
import { createMachineTokens, discoverPlatform } from '@customyai/core';
|
|
7
|
+
import { verifyMetaSignature, verifyWebhook, WebhookVerificationError, signMetaPayload, signPayload, CustomyWhatsAppError, WHATSAPP_AUDIENCE, createWhatsApp, WHATSAPP_WEBHOOK_EVENTS } from '@customyai/whatsapp';
|
|
8
|
+
|
|
9
|
+
// src/codegen.ts
|
|
10
|
+
var literal = (value) => JSON.stringify(value);
|
|
11
|
+
var union = (values) => values.length ? values.map(literal).join(" | ") : "never";
|
|
12
|
+
var key = (name) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : literal(name);
|
|
13
|
+
function schemaToType(schema, indent = "") {
|
|
14
|
+
if (!schema || typeof schema !== "object") return "unknown";
|
|
15
|
+
if (Array.isArray(schema.enum)) return schema.enum.length ? schema.enum.map(literal).join(" | ") : "never";
|
|
16
|
+
const types = Array.isArray(schema.type) ? schema.type : schema.type ? [schema.type] : [];
|
|
17
|
+
if (types.length > 1) return types.map((type) => schemaToType({ ...schema, type }, indent)).join(" | ");
|
|
18
|
+
switch (types[0]) {
|
|
19
|
+
case "string":
|
|
20
|
+
return "string";
|
|
21
|
+
case "number":
|
|
22
|
+
case "integer":
|
|
23
|
+
return "number";
|
|
24
|
+
case "boolean":
|
|
25
|
+
return "boolean";
|
|
26
|
+
case "null":
|
|
27
|
+
return "null";
|
|
28
|
+
case "array":
|
|
29
|
+
return `Array<${schemaToType(schema.items, indent)}>`;
|
|
30
|
+
case "object": {
|
|
31
|
+
const required2 = new Set(schema.required ?? []);
|
|
32
|
+
const inner = `${indent} `;
|
|
33
|
+
const fields = Object.entries(schema.properties ?? {}).map(([name, value]) => `${inner}${key(name)}${required2.has(name) ? "" : "?"}: ${schemaToType(value, inner)};`);
|
|
34
|
+
if (schema.additionalProperties !== false && !schema.properties) return "Record<string, unknown>";
|
|
35
|
+
return fields.length ? `{
|
|
36
|
+
${fields.join("\n")}
|
|
37
|
+
${indent}}` : "Record<string, never>";
|
|
38
|
+
}
|
|
39
|
+
default:
|
|
40
|
+
return "unknown";
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function generateAppTypes(manifest) {
|
|
44
|
+
const roles = manifest.roles ?? [];
|
|
45
|
+
const permissions = (manifest.permissions ?? []).map((permission) => permission.key);
|
|
46
|
+
const events = manifest.events.map((event) => ` ${literal(event.name)}: ${schemaToType(event.properties, " ")};`);
|
|
47
|
+
return [
|
|
48
|
+
`// Generado por \`customy apps codegen\` desde customy.app.json (${manifest.key}). No editar a mano.`,
|
|
49
|
+
"",
|
|
50
|
+
`export type CustomyEventName = ${union(manifest.events.map((event) => event.name))};`,
|
|
51
|
+
"",
|
|
52
|
+
"export type CustomyEventProperties = {",
|
|
53
|
+
...events,
|
|
54
|
+
"};",
|
|
55
|
+
"",
|
|
56
|
+
`export type CustomyCapability = ${union(manifest.capabilities.map((capability) => capability.lookupKey))};`,
|
|
57
|
+
"",
|
|
58
|
+
"/** Valor que devuelve cada capability: `boolean`, `number` (medida) o `unknown` (configuraci\xF3n). */",
|
|
59
|
+
`export type CustomyCapabilityValues = {
|
|
60
|
+
${manifest.capabilities.map((capability) => ` ${literal(capability.lookupKey)}: ${capability.type === "boolean" ? "boolean" : capability.type === "metered" ? "number" : "unknown"};`).join("\n")}
|
|
61
|
+
};`,
|
|
62
|
+
`export type CustomyPlan = ${union(manifest.plans.map((plan2) => plan2.code))};`,
|
|
63
|
+
`export type CustomyMeter = ${union(manifest.meters.map((meter) => meter.code))};`,
|
|
64
|
+
"",
|
|
65
|
+
"/** Permisos y roles del manifiesto (`permissions[]`, `roles[]`): la app pregunta por permisos y nunca escribe un nombre de rol. */",
|
|
66
|
+
`export type CustomyPermission = ${union(permissions)};`,
|
|
67
|
+
`export type CustomyRole = ${union(roles.map((role) => role.key))};`,
|
|
68
|
+
"",
|
|
69
|
+
"/** Lo que da cada rol, tal como lo declara el manifiesto. */",
|
|
70
|
+
`export const CUSTOMY_ROLE_PERMISSIONS = {
|
|
71
|
+
${roles.map((role) => ` ${literal(role.key)}: ${literal(role.permissions)},`).join("\n")}
|
|
72
|
+
} as const satisfies Record<CustomyRole, readonly CustomyPermission[]>;`,
|
|
73
|
+
"",
|
|
74
|
+
"/** Los tipos de la app juntos: `createCustomy<CustomyAppTypes>()`, `createAccess<CustomyCapability, CustomyRole, CustomyPermission>()`. */",
|
|
75
|
+
"export type CustomyAppTypes = {",
|
|
76
|
+
" events: CustomyEventProperties;",
|
|
77
|
+
" meters: CustomyMeter;",
|
|
78
|
+
" capabilities: CustomyCapability;",
|
|
79
|
+
" capabilityValues: CustomyCapabilityValues;",
|
|
80
|
+
" roles: CustomyRole;",
|
|
81
|
+
" permissions: CustomyPermission;",
|
|
82
|
+
"};",
|
|
83
|
+
"",
|
|
84
|
+
"/** Prop\xF3sitos de consentimiento que exige cada evento. */",
|
|
85
|
+
`export const CUSTOMY_EVENT_PURPOSES = {
|
|
86
|
+
${manifest.events.map((event) => ` ${literal(event.name)}: ${literal(event.purposes)},`).join("\n")}
|
|
87
|
+
} as const;`,
|
|
88
|
+
""
|
|
89
|
+
].join("\n");
|
|
90
|
+
}
|
|
91
|
+
var EntitlementMeterAggregationSchema = z.enum(["sum", "count", "last"]);
|
|
92
|
+
var identifier = z.string().regex(/^[a-z][a-z0-9-]{1,62}$/);
|
|
93
|
+
var ConnectedOperationSchema = z.enum([
|
|
94
|
+
"read",
|
|
95
|
+
"propose",
|
|
96
|
+
"submit",
|
|
97
|
+
"read_owned",
|
|
98
|
+
"write_owned",
|
|
99
|
+
"research",
|
|
100
|
+
"deliver_budget_alert",
|
|
101
|
+
"deliver_notification",
|
|
102
|
+
"request_operator_approval"
|
|
103
|
+
]);
|
|
104
|
+
var ConnectedBindingKindSchema = z.enum([
|
|
105
|
+
"product",
|
|
106
|
+
"internal_service",
|
|
107
|
+
"external_destination",
|
|
108
|
+
"public_form",
|
|
109
|
+
"private_collection",
|
|
110
|
+
"external_source",
|
|
111
|
+
"external_automation",
|
|
112
|
+
"external_communication"
|
|
113
|
+
]);
|
|
114
|
+
var ProductBindingSchema = z.object({
|
|
115
|
+
kind: ConnectedBindingKindSchema,
|
|
116
|
+
/** Claves de recurso admitidas; sin lista, cualquiera. Son nombres del producto, nunca de apps. */
|
|
117
|
+
keys: z.array(identifier).min(1).optional(),
|
|
118
|
+
/** Patrón que debe cumplir el identificador del recurso en el producto. */
|
|
119
|
+
resourceIdPattern: z.string().min(1).optional(),
|
|
120
|
+
operations: z.object({
|
|
121
|
+
allowed: z.array(ConnectedOperationSchema).max(4),
|
|
122
|
+
/** exact: exactamente `allowed`; subset: un subconjunto no vacío. */
|
|
123
|
+
mode: z.enum(["exact", "subset"]),
|
|
124
|
+
/** false: las operaciones pueden omitirse (si se dan, cumplen el modo). */
|
|
125
|
+
required: z.boolean().default(true)
|
|
126
|
+
}).strict().optional(),
|
|
127
|
+
maxPerConnection: z.number().int().positive().optional()
|
|
128
|
+
}).strict();
|
|
129
|
+
var ProductManifestSchema = z.object({
|
|
130
|
+
schema: z.literal("product/v1"),
|
|
131
|
+
key: z.string().regex(/^customy-[a-z][a-z0-9-]*$/),
|
|
132
|
+
/** Audiencia de sus tokens de máquina (discovery). */
|
|
133
|
+
audience: z.string().regex(/^customy-[a-z][a-z0-9-]*$/),
|
|
134
|
+
/** Si true, todo enlace debe declarar `bindingKind` (no admite el enlace implícito). */
|
|
135
|
+
bindingRequired: z.boolean().default(false),
|
|
136
|
+
bindings: z.array(ProductBindingSchema).default([]),
|
|
137
|
+
/** Productos a los que llama en nombre de una app (token exchange). Solo esos lo aceptan como actor. */
|
|
138
|
+
requires: z.array(z.string().regex(/^customy-[a-z][a-z0-9-]*$/)).default([])
|
|
139
|
+
}).strict().superRefine((manifest, context3) => {
|
|
140
|
+
const kinds = manifest.bindings.map((binding) => binding.kind);
|
|
141
|
+
if (new Set(kinds).size !== kinds.length) context3.addIssue({ code: z.ZodIssueCode.custom, message: "Binding kinds must be unique per product" });
|
|
142
|
+
if (manifest.requires.includes(manifest.key)) context3.addIssue({ code: z.ZodIssueCode.custom, message: "A product cannot require itself" });
|
|
143
|
+
});
|
|
144
|
+
var product = (key2, bindings = [], bindingRequired = false, requires = []) => ProductManifestSchema.parse({ schema: "product/v1", key: key2, audience: key2, bindingRequired, bindings, requires });
|
|
145
|
+
var CONNECTABLE_PRODUCT_MANIFESTS = [
|
|
146
|
+
product("customy-atlas", [{ kind: "internal_service", operations: { allowed: ["read", "propose"], mode: "subset" } }]),
|
|
147
|
+
product("customy-tables", [{ kind: "private_collection", keys: ["favorites", "comparisons", "preferences"], operations: { allowed: ["read_owned", "write_owned"], mode: "subset" } }]),
|
|
148
|
+
product("customy-agent", [{ kind: "external_automation", keys: ["catalog-updater"], operations: { allowed: ["research", "deliver_budget_alert"], mode: "subset" } }]),
|
|
149
|
+
product("customy-forms", [{ kind: "public_form", keys: ["subscription", "contact", "commercial"], resourceIdPattern: "^frm_[a-zA-Z0-9_-]+$", operations: { allowed: ["read", "submit"], mode: "exact" } }], false, ["customy-links"]),
|
|
150
|
+
product("customy-crm"),
|
|
151
|
+
product("customy-content", [{ kind: "external_destination", operations: { allowed: ["read"], mode: "exact" } }]),
|
|
152
|
+
product("customy-storage"),
|
|
153
|
+
product("customy-data", [{ kind: "external_source", keys: ["analytics-source"], operations: { allowed: ["submit"], mode: "exact" } }]),
|
|
154
|
+
// Experiments: las apps conectadas lo referencian para evaluar flags con su clave publicable; sin enlaces propios todavía (F5).
|
|
155
|
+
product("customy-experiments"),
|
|
156
|
+
product("customy-analytics"),
|
|
157
|
+
product("customy-campaigns", [{ kind: "external_communication", keys: ["weekly-brief"], operations: { allowed: ["read"], mode: "exact" } }]),
|
|
158
|
+
product("customy-engagement", [{ kind: "external_communication", keys: ["notification-delivery", "operator-approval"], operations: { allowed: ["deliver_notification", "request_operator_approval"], mode: "subset" } }]),
|
|
159
|
+
// Una referencia de solo lectura a un sitio de Pages del Workspace; no concede edición ni publicación.
|
|
160
|
+
product("customy-pages", [{ kind: "product", resourceIdPattern: "^[0-9]{6,20}$", operations: { allowed: ["read"], mode: "exact", required: false }, maxPerConnection: 1 }], true),
|
|
161
|
+
// La clave pública identifica el sitio SiteSight enlazado por un administrador del Workspace.
|
|
162
|
+
// Es una referencia publicable; Access comprueba el producto y el entorno propietario.
|
|
163
|
+
product("customy-sitesight", [{ kind: "product", keys: ["sitesight-site"], resourceIdPattern: "^ss_pub_[a-z0-9]{2,16}_[a-f0-9]{32}$", operations: { allowed: ["read"], mode: "exact" }, maxPerConnection: 1 }], true)
|
|
164
|
+
];
|
|
165
|
+
function connectedResourceViolation(resource, manifests = CONNECTABLE_PRODUCT_MANIFESTS) {
|
|
166
|
+
const manifest = manifests.find((entry) => entry.key === resource.productKey);
|
|
167
|
+
if (!manifest) return "PRODUCT_NOT_CONNECTABLE";
|
|
168
|
+
if (manifest.bindingRequired && !resource.bindingKind) return "BINDING_KIND_REQUIRED";
|
|
169
|
+
const binding = resource.bindingKind ? manifest.bindings.find((entry) => entry.kind === resource.bindingKind) : void 0;
|
|
170
|
+
if (!binding) {
|
|
171
|
+
const plainReference = resource.bindingKind === void 0 || resource.bindingKind === "product";
|
|
172
|
+
if (plainReference && !resource.operations) return null;
|
|
173
|
+
return plainReference ? "OPERATIONS_REQUIRE_BINDING" : "BINDING_NOT_OFFERED";
|
|
174
|
+
}
|
|
175
|
+
if (binding.keys && !binding.keys.includes(resource.key)) return "BINDING_KEY_NOT_ALLOWED";
|
|
176
|
+
if (binding.resourceIdPattern && !new RegExp(binding.resourceIdPattern).test(resource.resourceId)) return "BINDING_RESOURCE_ID_INVALID";
|
|
177
|
+
const rule = binding.operations;
|
|
178
|
+
const operations = resource.operations;
|
|
179
|
+
if (!rule) return operations ? "OPERATIONS_REQUIRE_BINDING" : null;
|
|
180
|
+
if (!operations || operations.length === 0) return rule.required ? "BINDING_OPERATIONS_REQUIRED" : null;
|
|
181
|
+
if (operations.some((operation) => !rule.allowed.includes(operation))) return "BINDING_OPERATION_NOT_ALLOWED";
|
|
182
|
+
if (rule.mode === "exact" && (operations.length !== rule.allowed.length || rule.allowed.some((operation) => !operations.includes(operation)))) return "BINDING_OPERATIONS_MISMATCH";
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
function connectedResourceLimit(productKey2, manifests = CONNECTABLE_PRODUCT_MANIFESTS) {
|
|
186
|
+
const limits = manifests.find((entry) => entry.key === productKey2)?.bindings.map((binding) => binding.maxPerConnection).filter((value) => value !== void 0) ?? [];
|
|
187
|
+
return limits.length ? Math.min(...limits) : null;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// src/vendor/app-manifest.ts
|
|
191
|
+
var slug = z.string().regex(/^[a-z][a-z0-9-]{1,38}[a-z0-9]$/);
|
|
192
|
+
var productKey = z.string().regex(/^customy-[a-z][a-z0-9-]*$/);
|
|
193
|
+
var httpsOrigin = z.string().url().max(512).refine((value) => {
|
|
194
|
+
const url = new URL(value);
|
|
195
|
+
return url.origin === value && (url.protocol === "https:" || ["localhost", "127.0.0.1"].includes(url.hostname));
|
|
196
|
+
}, "Origins must be bare https origins");
|
|
197
|
+
var eventName = z.string().regex(/^[a-z][a-z0-9_.:-]{0,199}$/);
|
|
198
|
+
var lookupKey = z.string().regex(/^[a-z][a-z0-9_.:-]{0,79}$/);
|
|
199
|
+
var AppProductUseSchema = z.object({
|
|
200
|
+
product: productKey,
|
|
201
|
+
/** Scopes de producto que pedirán sus credenciales de máquina (`<producto>:<scope>`). */
|
|
202
|
+
scopes: z.array(z.string().regex(/^[a-z][a-z0-9_-]*:[a-z0-9_:.-]+$/)).max(64).default([])
|
|
203
|
+
}).strict();
|
|
204
|
+
var AppResourceSchema = z.object({
|
|
205
|
+
key: z.string().regex(/^[a-z][a-z0-9-]{1,62}$/),
|
|
206
|
+
product: productKey,
|
|
207
|
+
bindingKind: ConnectedBindingKindSchema.optional(),
|
|
208
|
+
operations: z.array(ConnectedOperationSchema).min(1).max(2).optional()
|
|
209
|
+
}).strict();
|
|
210
|
+
var AppEventSchema = z.object({
|
|
211
|
+
name: eventName,
|
|
212
|
+
type: z.enum(["track", "identify", "group", "page", "screen", "alias"]),
|
|
213
|
+
schemaVersion: z.number().int().positive(),
|
|
214
|
+
/** JSON Schema de `properties`; se publica como schema fijado del evento. */
|
|
215
|
+
properties: z.record(z.unknown()).default({ type: "object" }),
|
|
216
|
+
purposes: z.array(z.string().regex(/^[a-z][a-z0-9_.:-]{0,79}$/)).min(1).max(8)
|
|
217
|
+
}).strict();
|
|
218
|
+
var AppCapabilitySchema = z.object({
|
|
219
|
+
lookupKey,
|
|
220
|
+
name: z.string().min(1).max(120),
|
|
221
|
+
type: z.enum(["boolean", "metered", "config"]),
|
|
222
|
+
meter: lookupKey.optional()
|
|
223
|
+
}).strict();
|
|
224
|
+
var AppPlanSchema = z.object({
|
|
225
|
+
code: lookupKey,
|
|
226
|
+
name: z.string().min(1).max(120),
|
|
227
|
+
rank: z.number().int().nonnegative().default(100),
|
|
228
|
+
capabilities: z.record(lookupKey, z.unknown()).default({})
|
|
229
|
+
}).strict();
|
|
230
|
+
var AppMeterSchema = z.object({
|
|
231
|
+
code: lookupKey,
|
|
232
|
+
aggregation: EntitlementMeterAggregationSchema,
|
|
233
|
+
unit: z.string().min(1).max(40)
|
|
234
|
+
}).strict();
|
|
235
|
+
var APP_AUTHORIZATION_LIMITS = { permissions: 128, roles: 32, permissionsPerRole: 128 };
|
|
236
|
+
var authorizationKey = z.string().min(3).max(120).regex(/^[a-z][a-z0-9-]*(\.[a-z][a-z0-9_-]*)+$/, "Keys are dotted lowercase identifiers without wildcards");
|
|
237
|
+
var AppPermissionDeclarationSchema = z.object({
|
|
238
|
+
key: authorizationKey,
|
|
239
|
+
description: z.string().trim().min(1).max(300)
|
|
240
|
+
}).strict();
|
|
241
|
+
var AppRoleDeclarationSchema = z.object({
|
|
242
|
+
key: authorizationKey,
|
|
243
|
+
name: z.string().trim().min(1).max(80),
|
|
244
|
+
description: z.string().trim().max(300).default(""),
|
|
245
|
+
permissions: z.array(authorizationKey).max(APP_AUTHORIZATION_LIMITS.permissionsPerRole)
|
|
246
|
+
}).strict();
|
|
247
|
+
var AppManifestSchema = z.object({
|
|
248
|
+
/** Referencia opcional al JSON Schema publicado, para autocompletado en editores. */
|
|
249
|
+
$schema: z.string().url().max(200).optional(),
|
|
250
|
+
schema: z.literal("app/v1"),
|
|
251
|
+
key: slug,
|
|
252
|
+
name: z.string().trim().min(1).max(80),
|
|
253
|
+
origins: z.object({ staging: httpsOrigin.optional(), production: httpsOrigin.optional() }).strict().refine((origins) => Boolean(origins.staging || origins.production), "Declare at least one origin"),
|
|
254
|
+
products: z.array(AppProductUseSchema).max(32).default([]),
|
|
255
|
+
resources: z.array(AppResourceSchema).max(64).default([]),
|
|
256
|
+
events: z.array(AppEventSchema).max(256).default([]),
|
|
257
|
+
capabilities: z.array(AppCapabilitySchema).max(256).default([]),
|
|
258
|
+
plans: z.array(AppPlanSchema).max(32).default([]),
|
|
259
|
+
meters: z.array(AppMeterSchema).max(64).default([]),
|
|
260
|
+
/** Opcional: permisos y roles de la app (clave `<clave-de-la-app>.…`, sin comodines). */
|
|
261
|
+
permissions: z.array(AppPermissionDeclarationSchema).max(APP_AUTHORIZATION_LIMITS.permissions).optional(),
|
|
262
|
+
roles: z.array(AppRoleDeclarationSchema).max(APP_AUTHORIZATION_LIMITS.roles).optional()
|
|
263
|
+
}).strict();
|
|
264
|
+
var APP_ACCESS_SCOPES = [
|
|
265
|
+
"capabilities:read",
|
|
266
|
+
"users:contact:read",
|
|
267
|
+
"users:read",
|
|
268
|
+
"flags:read",
|
|
269
|
+
"catalog:read",
|
|
270
|
+
"app-relationships:read",
|
|
271
|
+
"app-relationships:write",
|
|
272
|
+
"app-plans:write",
|
|
273
|
+
"app-roles:read",
|
|
274
|
+
"app-roles:write"
|
|
275
|
+
];
|
|
276
|
+
var APP_ACCESS_SCOPE_SET = new Set(APP_ACCESS_SCOPES);
|
|
277
|
+
function appScopeAllowed(product2, scope) {
|
|
278
|
+
if (product2 === "customy-access") return APP_ACCESS_SCOPE_SET.has(scope);
|
|
279
|
+
return scope.startsWith(`${product2.replace(/^customy-/, "")}:`);
|
|
280
|
+
}
|
|
281
|
+
function appManifestProblems(input, manifests = CONNECTABLE_PRODUCT_MANIFESTS) {
|
|
282
|
+
const parsed = AppManifestSchema.safeParse(input);
|
|
283
|
+
if (!parsed.success) return parsed.error.issues.map((issue) => ({ path: issue.path.join("."), code: "SCHEMA_INVALID" }));
|
|
284
|
+
const app = parsed.data;
|
|
285
|
+
const problems = [];
|
|
286
|
+
const unique = (items, key2, path6) => {
|
|
287
|
+
const seen = /* @__PURE__ */ new Set();
|
|
288
|
+
items.forEach((item, index) => {
|
|
289
|
+
const k = key2(item);
|
|
290
|
+
if (seen.has(k)) problems.push({ path: `${path6}.${index}`, code: "DUPLICATE" });
|
|
291
|
+
seen.add(k);
|
|
292
|
+
});
|
|
293
|
+
};
|
|
294
|
+
unique(app.products, (p) => p.product, "products");
|
|
295
|
+
unique(app.resources, (r) => r.key, "resources");
|
|
296
|
+
unique(app.events, (e) => e.name, "events");
|
|
297
|
+
unique(app.capabilities, (c) => c.lookupKey, "capabilities");
|
|
298
|
+
unique(app.plans, (p) => p.code, "plans");
|
|
299
|
+
unique(app.meters, (m) => m.code, "meters");
|
|
300
|
+
app.products.forEach((use, index) => {
|
|
301
|
+
use.scopes.forEach((scope, scopeIndex) => {
|
|
302
|
+
if (!appScopeAllowed(use.product, scope)) problems.push({ path: `products.${index}.scopes.${scopeIndex}`, code: "SCOPE_OUTSIDE_PRODUCT" });
|
|
303
|
+
});
|
|
304
|
+
});
|
|
305
|
+
const counts = /* @__PURE__ */ new Map();
|
|
306
|
+
app.resources.forEach((resource, index) => {
|
|
307
|
+
const violation = connectedResourceViolation({ ...resource, productKey: resource.product, resourceId: "manifest" }, manifests);
|
|
308
|
+
if (violation && violation !== "BINDING_RESOURCE_ID_INVALID") problems.push({ path: `resources.${index}`, code: violation });
|
|
309
|
+
counts.set(resource.product, (counts.get(resource.product) ?? 0) + 1);
|
|
310
|
+
});
|
|
311
|
+
for (const [product2, count] of counts) {
|
|
312
|
+
const limit = connectedResourceLimit(product2, manifests);
|
|
313
|
+
if (limit !== null && count > limit) problems.push({ path: "resources", code: "BINDING_LIMIT_EXCEEDED" });
|
|
314
|
+
}
|
|
315
|
+
const meters = new Set(app.meters.map((meter) => meter.code));
|
|
316
|
+
const capabilities = new Set(app.capabilities.map((capability) => capability.lookupKey));
|
|
317
|
+
app.capabilities.forEach((capability, index) => {
|
|
318
|
+
if (capability.type === "metered" && (!capability.meter || !meters.has(capability.meter))) problems.push({ path: `capabilities.${index}.meter`, code: "METER_UNDECLARED" });
|
|
319
|
+
if (capability.type !== "metered" && capability.meter) problems.push({ path: `capabilities.${index}.meter`, code: "METER_ON_UNMETERED" });
|
|
320
|
+
});
|
|
321
|
+
app.plans.forEach((plan2, index) => {
|
|
322
|
+
for (const key2 of Object.keys(plan2.capabilities)) if (!capabilities.has(key2)) problems.push({ path: `plans.${index}.capabilities.${key2}`, code: "CAPABILITY_UNDECLARED" });
|
|
323
|
+
});
|
|
324
|
+
const prefix = `${app.key}.`;
|
|
325
|
+
const permissionKeys = /* @__PURE__ */ new Set();
|
|
326
|
+
(app.permissions ?? []).forEach((permission, index) => {
|
|
327
|
+
if (!permission.key.startsWith(prefix)) problems.push({ path: `permissions.${index}.key`, code: "PERMISSION_NAMESPACE_VIOLATION" });
|
|
328
|
+
if (permissionKeys.has(permission.key)) problems.push({ path: `permissions.${index}`, code: "DUPLICATE" });
|
|
329
|
+
permissionKeys.add(permission.key);
|
|
330
|
+
});
|
|
331
|
+
const roleKeys = /* @__PURE__ */ new Set();
|
|
332
|
+
const roleNames = /* @__PURE__ */ new Set();
|
|
333
|
+
(app.roles ?? []).forEach((role, index) => {
|
|
334
|
+
if (!role.key.startsWith(prefix)) problems.push({ path: `roles.${index}.key`, code: "ROLE_NAMESPACE_VIOLATION" });
|
|
335
|
+
if (roleKeys.has(role.key)) problems.push({ path: `roles.${index}`, code: "DUPLICATE" });
|
|
336
|
+
if (roleNames.has(role.name.toLowerCase())) problems.push({ path: `roles.${index}.name`, code: "DUPLICATE" });
|
|
337
|
+
roleKeys.add(role.key);
|
|
338
|
+
roleNames.add(role.name.toLowerCase());
|
|
339
|
+
const inRole = /* @__PURE__ */ new Set();
|
|
340
|
+
role.permissions.forEach((code, permissionIndex) => {
|
|
341
|
+
if (!permissionKeys.has(code)) problems.push({ path: `roles.${index}.permissions.${permissionIndex}`, code: "PERMISSION_UNDECLARED" });
|
|
342
|
+
if (inRole.has(code)) problems.push({ path: `roles.${index}.permissions.${permissionIndex}`, code: "DUPLICATE" });
|
|
343
|
+
inRole.add(code);
|
|
344
|
+
});
|
|
345
|
+
});
|
|
346
|
+
return problems;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// src/apps.ts
|
|
350
|
+
var PROBLEM_HINTS = {
|
|
351
|
+
PERMISSION_NAMESPACE_VIOLATION: "la clave del permiso debe empezar por \xAB<clave-de-la-app>.\xBB",
|
|
352
|
+
ROLE_NAMESPACE_VIOLATION: "la clave del rol debe empezar por \xAB<clave-de-la-app>.\xBB",
|
|
353
|
+
PERMISSION_UNDECLARED: "el rol usa un permiso que no est\xE1 declarado en permissions[]"
|
|
354
|
+
};
|
|
355
|
+
function describeProblem(problem) {
|
|
356
|
+
const hint = PROBLEM_HINTS[problem.code];
|
|
357
|
+
return `\u2717 ${problem.path || "(ra\xEDz)"}: ${problem.code}${hint ? ` \u2014 ${hint}` : ""}`;
|
|
358
|
+
}
|
|
359
|
+
function authorizationSummary(manifest) {
|
|
360
|
+
return `${manifest.permissions?.length ?? 0} permisos, ${manifest.roles?.length ?? 0} roles`;
|
|
361
|
+
}
|
|
362
|
+
function validateManifest(input) {
|
|
363
|
+
const problems = appManifestProblems(input);
|
|
364
|
+
return problems.length ? { ok: false, problems } : { ok: true, manifest: AppManifestSchema.parse(input) };
|
|
365
|
+
}
|
|
366
|
+
var SyncError = class extends Error {
|
|
367
|
+
constructor(code, status2) {
|
|
368
|
+
super(`${code} (${status2})`);
|
|
369
|
+
this.code = code;
|
|
370
|
+
this.status = status2;
|
|
371
|
+
}
|
|
372
|
+
code;
|
|
373
|
+
status;
|
|
374
|
+
};
|
|
375
|
+
async function syncApp(options) {
|
|
376
|
+
const base = options.accessUrl.replace(/\/$/, "");
|
|
377
|
+
if (!/^https:\/\//.test(base) && !/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(base)) throw new SyncError("ACCESS_URL_INSECURE", 0);
|
|
378
|
+
const call = async (method, path6, body) => {
|
|
379
|
+
const response = await (options.fetch ?? fetch)(`${base}${path6}`, {
|
|
380
|
+
method,
|
|
381
|
+
headers: { authorization: `Bearer ${options.token}`, "content-type": "application/json", "idempotency-key": crypto.randomUUID() },
|
|
382
|
+
body: JSON.stringify(body)
|
|
383
|
+
});
|
|
384
|
+
const json = await response.json().catch(() => ({}));
|
|
385
|
+
if (!response.ok) throw new SyncError(String(json.code ?? json.error ?? "ACCESS_REQUEST_FAILED"), response.status);
|
|
386
|
+
return json;
|
|
387
|
+
};
|
|
388
|
+
const env = encodeURIComponent(options.workspaceEnvironmentId);
|
|
389
|
+
const installed = await call("POST", `/api/admin/env/${env}/connected-applications/install`, { manifest: options.manifest, reason: options.reason });
|
|
390
|
+
const connection = installed.connection;
|
|
391
|
+
const reconciliation = (value) => value && typeof value === "object" ? value : {};
|
|
392
|
+
if (!installed.replayed) {
|
|
393
|
+
return { action: "installed", applicationId: connection.applicationId, environmentId: connection.environmentId, revision: connection.revision, reconciliation: reconciliation(installed.reconciliation) };
|
|
394
|
+
}
|
|
395
|
+
const updated = await call("PUT", `/api/admin/env/${encodeURIComponent(connection.environmentId)}/connected-application/manifest`, {
|
|
396
|
+
expectedRevision: connection.revision,
|
|
397
|
+
manifest: options.manifest,
|
|
398
|
+
reason: options.reason
|
|
399
|
+
});
|
|
400
|
+
const revision = Number(updated.revision ?? connection.revision);
|
|
401
|
+
return { action: updated.unchanged ? "unchanged" : "updated", applicationId: connection.applicationId, environmentId: connection.environmentId, revision, reconciliation: reconciliation(updated.reconciliation) };
|
|
402
|
+
}
|
|
403
|
+
var EXIT = { ok: 0, failure: 1, unsupported: 2, auth: 3, confirmation: 4 };
|
|
404
|
+
var PROVISIONING_GROUPS = ["users", "audit", "policy", "whoami", "login"];
|
|
405
|
+
var PROVISIONING_HELP = [
|
|
406
|
+
"Provisioning of TEST users (every command needs --env staging|production; there is no default):",
|
|
407
|
+
" customy users test create --env E --count N (--email-base me@x.com | --email-domain qa.example.com)",
|
|
408
|
+
' [--currency USD --country US --locale es-CO --tag T --expires-in-days N --reason "..." --ticket X --batch-id Y]',
|
|
409
|
+
' customy users test cleanup --env E (--batch ID | --mine) --reason "..."',
|
|
410
|
+
" customy users get <externalKey> --env E",
|
|
411
|
+
" customy users list --env E [--kind test|regular --batch ID --q PREFIX --limit N --all]",
|
|
412
|
+
' customy users upsert <externalKey> --env E --email ... --reason "..." [--name N --kind test|regular --attr k=v ... --password generate|none]',
|
|
413
|
+
' customy users delete <externalKey> --env E --reason "..."',
|
|
414
|
+
' customy users signin-link <externalKey> --env E --reason "..."',
|
|
415
|
+
" customy audit list --env E [--actor --action --subject --batch --from --to --limit --all]",
|
|
416
|
+
" customy audit export --env E --format csv|ndjson [--out file] [filters]",
|
|
417
|
+
" customy audit verify --env E",
|
|
418
|
+
" customy policy get --env E | customy whoami --env E",
|
|
419
|
+
" customy login (device flow: not available yet)",
|
|
420
|
+
"Common flags: --json (one JSON document on stdout), --base-url URL (or CUSTOMY_ACCESS_URL),",
|
|
421
|
+
" --dry-run (writes: print the request, send nothing), --yes-i-am-sure production (non-interactive production writes).",
|
|
422
|
+
"Credentials: CUSTOMY_CLIENT_ID + CUSTOMY_CLIENT_SECRET (or CUSTOMY_TOKEN), never argv."
|
|
423
|
+
];
|
|
424
|
+
var UsageError = class extends Error {
|
|
425
|
+
};
|
|
426
|
+
var Refused = class extends Error {
|
|
427
|
+
};
|
|
428
|
+
var COMMON = { env: "string", "base-url": "string", json: "boolean", "dry-run": "boolean", "yes-i-am-sure": "string", help: "boolean" };
|
|
429
|
+
function parse(args, spec, positionals) {
|
|
430
|
+
const known = { ...COMMON, ...spec };
|
|
431
|
+
const flags = {};
|
|
432
|
+
const rest = [];
|
|
433
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
434
|
+
const arg = args[i];
|
|
435
|
+
if (!arg.startsWith("--")) {
|
|
436
|
+
rest.push(arg);
|
|
437
|
+
continue;
|
|
438
|
+
}
|
|
439
|
+
const eq = arg.indexOf("=");
|
|
440
|
+
const name = eq >= 0 ? arg.slice(2, eq) : arg.slice(2);
|
|
441
|
+
const kind = known[name];
|
|
442
|
+
if (!kind) throw new UsageError(`unknown flag --${name}`);
|
|
443
|
+
if (kind === "boolean") {
|
|
444
|
+
flags[name] = eq >= 0 ? arg.slice(eq + 1) !== "false" : true;
|
|
445
|
+
continue;
|
|
446
|
+
}
|
|
447
|
+
let value = eq >= 0 ? arg.slice(eq + 1) : args[i + 1];
|
|
448
|
+
if (eq < 0) i += 1;
|
|
449
|
+
if (value === void 0 || eq < 0 && value.startsWith("--")) throw new UsageError(`--${name} needs a value`);
|
|
450
|
+
if (kind === "list") flags[name] = [...flags[name] ?? [], value];
|
|
451
|
+
else flags[name] = value;
|
|
452
|
+
}
|
|
453
|
+
if (rest.length !== positionals) throw new UsageError(positionals === 0 ? `unexpected argument "${rest[0]}"` : `expected ${positionals} argument(s), got ${rest.length}`);
|
|
454
|
+
return { flags, rest };
|
|
455
|
+
}
|
|
456
|
+
var str = (flags, name) => typeof flags[name] === "string" ? flags[name] : void 0;
|
|
457
|
+
var bool = (flags, name) => flags[name] === true;
|
|
458
|
+
function int(flags, name, min, max) {
|
|
459
|
+
const raw = str(flags, name);
|
|
460
|
+
if (raw === void 0) return void 0;
|
|
461
|
+
const value = Number(raw);
|
|
462
|
+
if (!/^\d+$/.test(raw) || value < min || value > max) throw new UsageError(`--${name} must be an integer between ${min} and ${max}`);
|
|
463
|
+
return value;
|
|
464
|
+
}
|
|
465
|
+
function required(flags, name) {
|
|
466
|
+
const value = str(flags, name);
|
|
467
|
+
if (!value) throw new UsageError(`--${name} is required`);
|
|
468
|
+
return value;
|
|
469
|
+
}
|
|
470
|
+
function environmentOf(flags) {
|
|
471
|
+
const env = str(flags, "env");
|
|
472
|
+
if (env === void 0) throw new UsageError("--env is required (staging|production); there is no default environment");
|
|
473
|
+
if (env !== "staging" && env !== "production") throw new UsageError(`--env must be "staging" or "production", got "${env}"`);
|
|
474
|
+
return env;
|
|
475
|
+
}
|
|
476
|
+
function attributes(flags) {
|
|
477
|
+
const out = {};
|
|
478
|
+
for (const key2 of ["currency", "country", "locale"]) {
|
|
479
|
+
const value = str(flags, key2);
|
|
480
|
+
if (value) out[key2] = value;
|
|
481
|
+
}
|
|
482
|
+
for (const pair of flags.attr ?? []) {
|
|
483
|
+
const at = pair.indexOf("=");
|
|
484
|
+
if (at <= 0) throw new UsageError(`--attr expects key=value, got "${pair}"`);
|
|
485
|
+
out[pair.slice(0, at)] = pair.slice(at + 1);
|
|
486
|
+
}
|
|
487
|
+
return Object.keys(out).length ? out : void 0;
|
|
488
|
+
}
|
|
489
|
+
function expiry(flags) {
|
|
490
|
+
const days = int(flags, "expires-in-days", 1, 3650);
|
|
491
|
+
return days === void 0 ? void 0 : new Date(Date.now() + days * 864e5);
|
|
492
|
+
}
|
|
493
|
+
function dryRunClient(env) {
|
|
494
|
+
let captured;
|
|
495
|
+
const fakeFetch = (async (input, init) => {
|
|
496
|
+
const url = new URL(String(input));
|
|
497
|
+
if (url.pathname === "/oauth/token") return new Response(JSON.stringify({ access_token: "dry-run-token", expires_in: 900 }), { status: 200, headers: { "content-type": "application/json" } });
|
|
498
|
+
const headers = new Headers(init?.headers);
|
|
499
|
+
const query = {};
|
|
500
|
+
url.searchParams.forEach((value, name) => {
|
|
501
|
+
query[name] = value;
|
|
502
|
+
});
|
|
503
|
+
captured = {
|
|
504
|
+
method: init?.method ?? "GET",
|
|
505
|
+
path: url.pathname,
|
|
506
|
+
...Object.keys(query).length ? { query } : {},
|
|
507
|
+
headers: { "Customy-Environment": headers.get("customy-environment") ?? env, ...headers.get("idempotency-key") ? { "Idempotency-Key": headers.get("idempotency-key") } : {}, ...headers.get("if-match") ? { "If-Match": headers.get("if-match") } : {} },
|
|
508
|
+
...typeof init?.body === "string" ? { body: JSON.parse(init.body) } : {}
|
|
509
|
+
};
|
|
510
|
+
throw new Error("dry-run: request captured, nothing sent");
|
|
511
|
+
});
|
|
512
|
+
const api = createProvisioning({ environment: env, baseUrl: "https://dry-run.invalid", clientId: "dry-run", clientSecret: "dry-run-secret", fetch: fakeFetch, retry: false });
|
|
513
|
+
return { api, captured: () => captured };
|
|
514
|
+
}
|
|
515
|
+
function liveClient(ctx) {
|
|
516
|
+
const baseUrl = str(ctx.flags, "base-url") ?? ctx.io.env.CUSTOMY_ACCESS_URL;
|
|
517
|
+
if (!baseUrl) throw new UsageError("the Access origin is required: pass --base-url or set CUSTOMY_ACCESS_URL (there is no default host)");
|
|
518
|
+
const { CUSTOMY_CLIENT_ID: clientId, CUSTOMY_CLIENT_SECRET: clientSecret, CUSTOMY_TOKEN: accessToken } = ctx.io.env;
|
|
519
|
+
const common = { environment: ctx.env, baseUrl, ...ctx.io.fetch ? { fetch: ctx.io.fetch } : {} };
|
|
520
|
+
if (clientId && clientSecret) return createProvisioning({ ...common, clientId, clientSecret });
|
|
521
|
+
if (accessToken) return createProvisioning({ ...common, accessToken });
|
|
522
|
+
throw new CustomyAuthError({ code: "SDK_CREDENTIALS_REQUIRED", status: 0, message: "set CUSTOMY_CLIENT_ID and CUSTOMY_CLIENT_SECRET (or CUSTOMY_TOKEN) in the environment" });
|
|
523
|
+
}
|
|
524
|
+
async function confirmProduction(ctx, summary) {
|
|
525
|
+
if (ctx.env !== "production") return;
|
|
526
|
+
const given = str(ctx.flags, "yes-i-am-sure");
|
|
527
|
+
if (given !== void 0) {
|
|
528
|
+
if (given !== "production") throw new Refused(`--yes-i-am-sure must equal "production", got "${given}"`);
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
if (!ctx.io.isTTY || !ctx.io.prompt) throw new Refused("production writes without a terminal need --yes-i-am-sure production");
|
|
532
|
+
ctx.io.err(`About to ${summary} in PRODUCTION.`);
|
|
533
|
+
const answer = await ctx.io.prompt('Type "production" to confirm: ');
|
|
534
|
+
if (answer.trim() !== "production") throw new Refused("confirmation refused: nothing was changed");
|
|
535
|
+
}
|
|
536
|
+
function emit(ctx, json, human) {
|
|
537
|
+
if (ctx.json) ctx.io.out(JSON.stringify(json, null, 2));
|
|
538
|
+
else for (const line of human) ctx.io.out(line);
|
|
539
|
+
}
|
|
540
|
+
function table(rows) {
|
|
541
|
+
const widths = rows[0].map((_, col) => Math.max(...rows.map((row) => (row[col] ?? "").length)));
|
|
542
|
+
return rows.map((row) => row.map((cell, col) => col === row.length - 1 ? cell : cell.padEnd(widths[col])).join(" ").trimEnd());
|
|
543
|
+
}
|
|
544
|
+
var SECRET_WARNING = "Store these now: passwords and links are shown ONCE and cannot be retrieved again.";
|
|
545
|
+
async function write(ctx, summary, run, render) {
|
|
546
|
+
if (bool(ctx.flags, "dry-run")) {
|
|
547
|
+
const dry = dryRunClient(ctx.env);
|
|
548
|
+
try {
|
|
549
|
+
await run(dry.api);
|
|
550
|
+
} catch (error) {
|
|
551
|
+
const request = dry.captured();
|
|
552
|
+
if (!request) throw error;
|
|
553
|
+
const { method, path: urlPath, query, headers, body } = request;
|
|
554
|
+
const doc = { dryRun: true, environment: ctx.env, request: { method, path: urlPath, ...query ? { query } : {}, headers, ...body !== void 0 ? { body } : {} } };
|
|
555
|
+
emit(ctx, doc, [
|
|
556
|
+
`DRY RUN (nothing sent): ${summary}`,
|
|
557
|
+
`environment: ${ctx.env}`,
|
|
558
|
+
`${method} ${urlPath}${query ? `?${new URLSearchParams(query)}` : ""}`,
|
|
559
|
+
...Object.entries(headers).map(([name, value]) => `${name}: ${value}`),
|
|
560
|
+
...body !== void 0 ? [JSON.stringify(body, null, 2)] : []
|
|
561
|
+
]);
|
|
562
|
+
return EXIT.ok;
|
|
563
|
+
}
|
|
564
|
+
throw new Error("dry run did not capture a request");
|
|
565
|
+
}
|
|
566
|
+
await confirmProduction(ctx, summary);
|
|
567
|
+
const result = await run(liveClient(ctx));
|
|
568
|
+
const out = render(result);
|
|
569
|
+
if (out.secret && !ctx.json) ctx.io.err(SECRET_WARNING);
|
|
570
|
+
emit(ctx, out.json ?? result, out.human);
|
|
571
|
+
return EXIT.ok;
|
|
572
|
+
}
|
|
573
|
+
async function read(ctx, run, render) {
|
|
574
|
+
const result = await run(liveClient(ctx));
|
|
575
|
+
const out = render(result);
|
|
576
|
+
emit(ctx, out.json ?? result, out.human);
|
|
577
|
+
return EXIT.ok;
|
|
578
|
+
}
|
|
579
|
+
var userLines = (user) => [
|
|
580
|
+
`externalKey: ${user.externalKey}`,
|
|
581
|
+
`id: ${user.id}`,
|
|
582
|
+
`kind: ${user.kind}`,
|
|
583
|
+
`email: ${user.email}`,
|
|
584
|
+
`version: ${user.version}`,
|
|
585
|
+
`expiresAt: ${user.expiresAt ?? "-"}`,
|
|
586
|
+
`createdAt: ${user.createdAt}`,
|
|
587
|
+
...user.batchId ? [`batch: ${user.batchId}`] : []
|
|
588
|
+
];
|
|
589
|
+
var usersTable = (users2) => users2.length === 0 ? ["(no users)"] : table([["EXTERNAL KEY", "KIND", "EMAIL", "EXPIRES"], ...users2.map((u) => [u.externalKey, u.kind, u.email, u.expiresAt ?? "-"])]);
|
|
590
|
+
var auditTable = (entries) => entries.length === 0 ? ["(no entries)"] : table([["SEQ", "AT", "ACTION", "SUBJECT", "ACTOR"], ...entries.map((e) => [String(e.seq), e.at, e.action, e.subject.key, e.actor.id])]);
|
|
591
|
+
function batchLines(result) {
|
|
592
|
+
return [
|
|
593
|
+
`batch ${result.batch.id}: ${result.batch.count} users, expires ${result.batch.expiresAt ?? "-"}`,
|
|
594
|
+
...table([["EXTERNAL KEY", "EMAIL", "PASSWORD"], ...result.users.map((u) => [u.externalKey, u.email, u.credentials.password ?? "(not returned)"])])
|
|
595
|
+
];
|
|
596
|
+
}
|
|
597
|
+
async function users(args, io) {
|
|
598
|
+
const [first, ...tail2] = args;
|
|
599
|
+
if (first === "test") {
|
|
600
|
+
const [action, ...rest] = tail2;
|
|
601
|
+
if (action === "create") {
|
|
602
|
+
const { flags } = parse(rest, { count: "string", "email-base": "string", "email-domain": "string", currency: "string", country: "string", locale: "string", tag: "string", "expires-in-days": "string", reason: "string", ticket: "string", "batch-id": "string", attr: "list" }, 0);
|
|
603
|
+
const ctx = context(io, flags);
|
|
604
|
+
const count = int(flags, "count", 1, 1e3);
|
|
605
|
+
if (count === void 0) throw new UsageError("--count is required (1-1000)");
|
|
606
|
+
const emailBase = str(flags, "email-base");
|
|
607
|
+
const emailDomain = str(flags, "email-domain");
|
|
608
|
+
if (emailBase === void 0 === (emailDomain === void 0)) throw new UsageError("pass exactly one of --email-base or --email-domain");
|
|
609
|
+
const input = {
|
|
610
|
+
count,
|
|
611
|
+
...emailBase !== void 0 ? { emailBase } : { emailDomain },
|
|
612
|
+
...str(flags, "tag") ? { tag: str(flags, "tag") } : {},
|
|
613
|
+
...attributes(flags) ? { attributes: attributes(flags) } : {},
|
|
614
|
+
...expiry(flags) ? { expiresAt: expiry(flags) } : {},
|
|
615
|
+
...str(flags, "ticket") ? { ticket: str(flags, "ticket") } : {},
|
|
616
|
+
...str(flags, "batch-id") ? { batchId: str(flags, "batch-id") } : {},
|
|
617
|
+
reason: str(flags, "reason") ?? `customy cli: create ${count} test users`
|
|
618
|
+
};
|
|
619
|
+
return write(ctx, `create ${count} test users`, (api) => api.testUsers.batch(input), (result) => ({ human: batchLines(result), secret: true }));
|
|
620
|
+
}
|
|
621
|
+
if (action === "cleanup") {
|
|
622
|
+
const { flags } = parse(rest, { batch: "string", mine: "boolean", reason: "string", ticket: "string" }, 0);
|
|
623
|
+
const ctx = context(io, flags);
|
|
624
|
+
const batch = str(flags, "batch");
|
|
625
|
+
if (batch === void 0 === !bool(flags, "mine")) throw new UsageError("pass exactly one of --batch ID or --mine");
|
|
626
|
+
const reason = required(flags, "reason");
|
|
627
|
+
return write(
|
|
628
|
+
ctx,
|
|
629
|
+
batch ? `delete test users of batch ${batch}` : "delete all your test users",
|
|
630
|
+
(api) => api.testUsers.cleanup(batch ? { batch } : { mine: true }, { reason, ...str(flags, "ticket") ? { ticket: str(flags, "ticket") } : {} }),
|
|
631
|
+
(r) => ({ human: [`deleted ${r.deleted} test users${r.batch ? ` (batch ${r.batch})` : ""}`] })
|
|
632
|
+
);
|
|
633
|
+
}
|
|
634
|
+
throw new UsageError("usage: customy users test <create|cleanup> --env staging|production ...");
|
|
635
|
+
}
|
|
636
|
+
if (first === "get") {
|
|
637
|
+
const { flags, rest } = parse(tail2, {}, 1);
|
|
638
|
+
const ctx = context(io, flags);
|
|
639
|
+
return read(ctx, (api) => api.users.get(rest[0]), (user) => ({ human: userLines(user) }));
|
|
640
|
+
}
|
|
641
|
+
if (first === "list") {
|
|
642
|
+
const { flags } = parse(tail2, { kind: "string", batch: "string", q: "string", limit: "string", all: "boolean", cursor: "string", "created-by": "string" }, 0);
|
|
643
|
+
const ctx = context(io, flags);
|
|
644
|
+
const kind = str(flags, "kind");
|
|
645
|
+
if (kind !== void 0 && kind !== "test" && kind !== "regular") throw new UsageError("--kind must be test or regular");
|
|
646
|
+
const params = { ...kind ? { kind } : {}, ...str(flags, "batch") ? { batch: str(flags, "batch") } : {}, ...str(flags, "q") ? { q: str(flags, "q") } : {}, ...str(flags, "created-by") ? { createdBy: str(flags, "created-by") } : {}, ...int(flags, "limit", 1, 200) ? { limit: int(flags, "limit", 1, 200) } : {} };
|
|
647
|
+
if (bool(flags, "all")) {
|
|
648
|
+
return read(ctx, async (api) => {
|
|
649
|
+
const all = [];
|
|
650
|
+
for await (const user of api.users.listAll(params)) all.push(user);
|
|
651
|
+
return all;
|
|
652
|
+
}, (all) => ({ json: { data: all }, human: usersTable(all) }));
|
|
653
|
+
}
|
|
654
|
+
return read(ctx, (api) => api.users.list({ ...params, ...str(flags, "cursor") ? { cursor: str(flags, "cursor") } : {} }), (page) => ({
|
|
655
|
+
human: [...usersTable(page.data), ...page.page.nextCursor ? [`more results: --cursor ${page.page.nextCursor} (or --all)`] : []]
|
|
656
|
+
}));
|
|
657
|
+
}
|
|
658
|
+
if (first === "upsert") {
|
|
659
|
+
const { flags, rest } = parse(tail2, { email: "string", name: "string", kind: "string", attr: "list", currency: "string", country: "string", locale: "string", password: "string", "expires-in-days": "string", reason: "string", ticket: "string", "expected-version": "string" }, 1);
|
|
660
|
+
const ctx = context(io, flags);
|
|
661
|
+
const kind = str(flags, "kind") ?? "test";
|
|
662
|
+
if (kind !== "test" && kind !== "regular") throw new UsageError("--kind must be test or regular");
|
|
663
|
+
const password = str(flags, "password") ?? (kind === "test" ? "generate" : "none");
|
|
664
|
+
if (password !== "generate" && password !== "none") throw new UsageError('--password accepts only "generate" or "none" (passwords never travel on the command line)');
|
|
665
|
+
const input = {
|
|
666
|
+
email: required(flags, "email"),
|
|
667
|
+
kind,
|
|
668
|
+
reason: required(flags, "reason"),
|
|
669
|
+
...str(flags, "name") ? { name: str(flags, "name") } : {},
|
|
670
|
+
...attributes(flags) ? { attributes: attributes(flags) } : {},
|
|
671
|
+
...password === "generate" ? { password: "generate" } : {},
|
|
672
|
+
...expiry(flags) ? { expiresAt: expiry(flags) } : {},
|
|
673
|
+
...str(flags, "ticket") ? { ticket: str(flags, "ticket") } : {},
|
|
674
|
+
...int(flags, "expected-version", 0, Number.MAX_SAFE_INTEGER) !== void 0 ? { expectedVersion: int(flags, "expected-version", 0, Number.MAX_SAFE_INTEGER) } : {}
|
|
675
|
+
};
|
|
676
|
+
return write(ctx, `upsert user ${rest[0]}`, (api) => api.users.upsert(rest[0], input), (result) => ({
|
|
677
|
+
human: [
|
|
678
|
+
`${result.created ? "created" : result.changed ? "updated" : "unchanged"} ${result.externalKey} (version ${result.version})`,
|
|
679
|
+
...userLines(result),
|
|
680
|
+
...result.credentials?.password ? [`password: ${result.credentials.password}`] : []
|
|
681
|
+
],
|
|
682
|
+
secret: Boolean(result.credentials?.password)
|
|
683
|
+
}));
|
|
684
|
+
}
|
|
685
|
+
if (first === "delete") {
|
|
686
|
+
const { flags, rest } = parse(tail2, { reason: "string", ticket: "string", "if-match": "string" }, 1);
|
|
687
|
+
const ctx = context(io, flags);
|
|
688
|
+
const reason = required(flags, "reason");
|
|
689
|
+
return write(
|
|
690
|
+
ctx,
|
|
691
|
+
`delete user ${rest[0]}`,
|
|
692
|
+
(api) => api.users.delete(rest[0], { reason, ...str(flags, "ticket") ? { ticket: str(flags, "ticket") } : {}, ...str(flags, "if-match") ? { ifMatch: str(flags, "if-match") } : {} }),
|
|
693
|
+
(r) => ({ human: [`deleted ${r.externalKey} (version ${r.version})`] })
|
|
694
|
+
);
|
|
695
|
+
}
|
|
696
|
+
if (first === "signin-link") {
|
|
697
|
+
const { flags, rest } = parse(tail2, { reason: "string", ticket: "string" }, 1);
|
|
698
|
+
const ctx = context(io, flags);
|
|
699
|
+
const reason = required(flags, "reason");
|
|
700
|
+
return write(
|
|
701
|
+
ctx,
|
|
702
|
+
`issue a signin link for ${rest[0]}`,
|
|
703
|
+
(api) => api.users.signinLink(rest[0], { reason, ...str(flags, "ticket") ? { ticket: str(flags, "ticket") } : {} }),
|
|
704
|
+
(r) => ({ human: [`link: ${r.link ?? "(not returned)"}`, `expiresAt: ${r.expiresAt}`], secret: Boolean(r.link) })
|
|
705
|
+
);
|
|
706
|
+
}
|
|
707
|
+
throw new UsageError("usage: customy users <test create|test cleanup|get|list|upsert|delete|signin-link> --env staging|production ...");
|
|
708
|
+
}
|
|
709
|
+
async function audit(args, io) {
|
|
710
|
+
const [action, ...rest] = args;
|
|
711
|
+
const filters = { actor: "string", action: "string", subject: "string", batch: "string", from: "string", to: "string" };
|
|
712
|
+
const pick = (flags) => Object.fromEntries(Object.keys(filters).filter((name) => str(flags, name)).map((name) => [name, str(flags, name)]));
|
|
713
|
+
if (action === "list") {
|
|
714
|
+
const { flags } = parse(rest, { ...filters, limit: "string", all: "boolean", cursor: "string" }, 0);
|
|
715
|
+
const ctx = context(io, flags);
|
|
716
|
+
const limit = int(flags, "limit", 1, 200);
|
|
717
|
+
const params = { ...pick(flags), ...limit ? { limit } : {} };
|
|
718
|
+
if (bool(flags, "all")) {
|
|
719
|
+
return read(ctx, async (api) => {
|
|
720
|
+
const all = [];
|
|
721
|
+
for await (const entry of api.audit.listAll(params)) all.push(entry);
|
|
722
|
+
return all;
|
|
723
|
+
}, (all) => ({ json: { data: all }, human: auditTable(all) }));
|
|
724
|
+
}
|
|
725
|
+
return read(ctx, (api) => api.audit.list({ ...params, ...str(flags, "cursor") ? { cursor: str(flags, "cursor") } : {} }), (page) => ({
|
|
726
|
+
human: [...auditTable(page.data), ...page.page.nextCursor ? [`more results: --cursor ${page.page.nextCursor} (or --all)`] : []]
|
|
727
|
+
}));
|
|
728
|
+
}
|
|
729
|
+
if (action === "export") {
|
|
730
|
+
const { flags } = parse(rest, { ...filters, format: "string", out: "string" }, 0);
|
|
731
|
+
const ctx = context(io, flags);
|
|
732
|
+
const format = required(flags, "format");
|
|
733
|
+
if (format !== "csv" && format !== "ndjson") throw new UsageError("--format must be csv or ndjson");
|
|
734
|
+
const text = await liveClient(ctx).audit.export({ format, ...pick(flags) });
|
|
735
|
+
const out = str(flags, "out");
|
|
736
|
+
if (out) {
|
|
737
|
+
const target = path3.resolve(io.cwd, out);
|
|
738
|
+
await writeFile(target, text, { mode: 384 });
|
|
739
|
+
await chmod(target, 384).catch(() => void 0);
|
|
740
|
+
emit(ctx, { out, bytes: text.length, format }, [`wrote ${text.length} characters of ${format} to ${out}`]);
|
|
741
|
+
} else io.out(text.replace(/\n$/, ""));
|
|
742
|
+
return EXIT.ok;
|
|
743
|
+
}
|
|
744
|
+
if (action === "verify") {
|
|
745
|
+
const { flags } = parse(rest, {}, 0);
|
|
746
|
+
const ctx = context(io, flags);
|
|
747
|
+
const result = await liveClient(ctx).audit.verify();
|
|
748
|
+
emit(ctx, result, [result.ok ? `audit chain OK: ${result.verified} entries verified (head seq ${result.headSeq})` : `audit chain BROKEN at seq ${result.brokenAtSeq}: ${result.reason}`]);
|
|
749
|
+
return result.ok ? EXIT.ok : EXIT.failure;
|
|
750
|
+
}
|
|
751
|
+
throw new UsageError("usage: customy audit <list|export|verify> --env staging|production ...");
|
|
752
|
+
}
|
|
753
|
+
async function policy(args, io) {
|
|
754
|
+
const [action, ...rest] = args;
|
|
755
|
+
if (action !== "get") throw new UsageError("usage: customy policy get --env staging|production");
|
|
756
|
+
const ctx = context(io, parse(rest, {}, 0).flags);
|
|
757
|
+
return read(ctx, (api) => api.policy.get(), (view) => ({
|
|
758
|
+
human: [
|
|
759
|
+
`policy version ${view.version}`,
|
|
760
|
+
`writes enabled (effective): ${view.effective.writesEnabled} (deployment ${view.effective.deployment.enabled ? "on" : "off"}, stage ${view.effective.stage})`,
|
|
761
|
+
`approval mode: ${view.policy.approvalMode}`,
|
|
762
|
+
...Object.entries(view.policy.caps).map(([name, value]) => `${name}: ${value}`),
|
|
763
|
+
`allowRegularUsers: ${view.policy.allowRegularUsers}`,
|
|
764
|
+
`allowSigninLinks: ${view.policy.allowSigninLinks}`
|
|
765
|
+
]
|
|
766
|
+
}));
|
|
767
|
+
}
|
|
768
|
+
async function whoami(args, io) {
|
|
769
|
+
const ctx = context(io, parse(args, {}, 0).flags);
|
|
770
|
+
return read(ctx, (api) => api.whoami(), (me) => ({
|
|
771
|
+
human: [`client: ${me.client.id} (owner ${me.client.owner})`, `environment: ${me.environmentId} (${me.stage})`, `audience: ${me.audience}`, `scopes: ${me.scopes.join(" ") || "-"}`, `writes: ${me.effective.writesEnabled ? "enabled" : "disabled"} (policy v${me.policy.version}, ${me.policy.approvalMode})`]
|
|
772
|
+
}));
|
|
773
|
+
}
|
|
774
|
+
function context(io, flags) {
|
|
775
|
+
return { io, flags, env: environmentOf(flags), json: bool(flags, "json") };
|
|
776
|
+
}
|
|
777
|
+
function login(io) {
|
|
778
|
+
io.err("customy login: the interactive device flow is not available yet.");
|
|
779
|
+
io.err("Use client credentials instead: export CUSTOMY_CLIENT_ID, CUSTOMY_CLIENT_SECRET and CUSTOMY_ACCESS_URL (an Access API key of the target environment),");
|
|
780
|
+
io.err("then pass --env staging|production. A pre-obtained bearer can be given as CUSTOMY_TOKEN.");
|
|
781
|
+
return EXIT.unsupported;
|
|
782
|
+
}
|
|
783
|
+
function report(error, io) {
|
|
784
|
+
if (error instanceof UsageError) {
|
|
785
|
+
io.err(`error: ${error.message}`);
|
|
786
|
+
io.err("run `customy --help` for usage");
|
|
787
|
+
return EXIT.failure;
|
|
788
|
+
}
|
|
789
|
+
if (error instanceof Refused) {
|
|
790
|
+
io.err(`refused: ${error.message}`);
|
|
791
|
+
return EXIT.confirmation;
|
|
792
|
+
}
|
|
793
|
+
if (error instanceof CustomyProvisioningError) {
|
|
794
|
+
const request = error.requestId ? ` (request ${error.requestId})` : "";
|
|
795
|
+
io.err(`error ${error.code}${error.status ? ` [${error.status}]` : ""}: ${error.message}${request}`);
|
|
796
|
+
if (error instanceof CustomyScopeError && error.scope) io.err(`missing scope: ${error.scope}`);
|
|
797
|
+
if (error instanceof CustomyEnvironmentMismatchError) io.err("the API key belongs to another environment than --env");
|
|
798
|
+
if (error instanceof CustomyConflictError && error.currentVersion !== void 0) io.err(`current version: ${error.currentVersion}`);
|
|
799
|
+
if (error instanceof CustomyRateLimitError && error.retryAfter !== void 0) io.err(`retry after ${error.retryAfter}s`);
|
|
800
|
+
if (error instanceof CustomyEnvironmentMismatchError) return EXIT.confirmation;
|
|
801
|
+
if (error instanceof CustomyAuthError) return EXIT.auth;
|
|
802
|
+
return EXIT.failure;
|
|
803
|
+
}
|
|
804
|
+
io.err(`error: ${error instanceof Error ? error.message : "unexpected failure"}`);
|
|
805
|
+
return EXIT.failure;
|
|
806
|
+
}
|
|
807
|
+
async function runProvisioningCli(group, args, io) {
|
|
808
|
+
try {
|
|
809
|
+
if (args.includes("--help") && group !== "login") {
|
|
810
|
+
io.out(PROVISIONING_HELP.join("\n"));
|
|
811
|
+
return EXIT.ok;
|
|
812
|
+
}
|
|
813
|
+
switch (group) {
|
|
814
|
+
case "users":
|
|
815
|
+
return await users(args, io);
|
|
816
|
+
case "audit":
|
|
817
|
+
return await audit(args, io);
|
|
818
|
+
case "policy":
|
|
819
|
+
return await policy(args, io);
|
|
820
|
+
case "whoami":
|
|
821
|
+
return await whoami(args, io);
|
|
822
|
+
default:
|
|
823
|
+
return login(io);
|
|
824
|
+
}
|
|
825
|
+
} catch (error) {
|
|
826
|
+
return report(error, io);
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
var EXPERIMENTS_GROUPS = ["flags", "segments", "experiments"];
|
|
830
|
+
var EXPERIMENTS_EXIT = { ok: 0, failure: 1, auth: 3, conflict: 4 };
|
|
831
|
+
var EXPERIMENTS_HELP = [
|
|
832
|
+
"Customy Experiments (credential: CUSTOMY_EXPERIMENTS_TOKEN, origin: --base-url or CUSTOMY_EXPERIMENTS_URL):",
|
|
833
|
+
" customy flags list [--q TEXT --tag T --archived true|false --limit N --cursor C]",
|
|
834
|
+
' customy flags get <key> | customy flags create --file flag.json --reason "..."',
|
|
835
|
+
' customy flags update <key> --file patch.json --reason "..."',
|
|
836
|
+
' customy flags archive|restore|delete <key> --reason "..." | customy flags kill <key> [--environment E] --reason "..."',
|
|
837
|
+
" customy segments list|get <key> | create --file segment.json --reason | update <key> --file patch.json --reason | delete <key> --reason",
|
|
838
|
+
' customy segments members add|remove <key> --unit-keys a,b,c --reason "..."',
|
|
839
|
+
" customy experiments list|get <key> | create --file experiment.json --reason | update <key> --file patch.json --reason",
|
|
840
|
+
' customy experiments start|pause <key> --reason "..." | customy experiments conclude <key> --decision ship|rollback|iterate --reason "..."',
|
|
841
|
+
"Common flags: --json (the response as one JSON document), --dry-run (writes: print the request, send nothing)."
|
|
842
|
+
];
|
|
843
|
+
var UsageError2 = class extends Error {
|
|
844
|
+
};
|
|
845
|
+
var VALUE_FLAGS = /* @__PURE__ */ new Set(["file", "reason", "base-url", "q", "tag", "archived", "limit", "cursor", "environment", "unit-keys", "decision"]);
|
|
846
|
+
function parse2(args) {
|
|
847
|
+
const positional = [];
|
|
848
|
+
const flags = {};
|
|
849
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
850
|
+
const arg = args[index];
|
|
851
|
+
if (!arg.startsWith("--")) {
|
|
852
|
+
positional.push(arg);
|
|
853
|
+
continue;
|
|
854
|
+
}
|
|
855
|
+
const name = arg.slice(2);
|
|
856
|
+
if (VALUE_FLAGS.has(name)) {
|
|
857
|
+
const value = args[index + 1];
|
|
858
|
+
if (value === void 0 || value.startsWith("--")) throw new UsageError2(`--${name} necesita un valor`);
|
|
859
|
+
flags[name] = value;
|
|
860
|
+
index += 1;
|
|
861
|
+
} else flags[name] = true;
|
|
862
|
+
}
|
|
863
|
+
return { positional, flags };
|
|
864
|
+
}
|
|
865
|
+
async function readBody(flags, io) {
|
|
866
|
+
const file = flags.file;
|
|
867
|
+
if (typeof file !== "string") throw new UsageError2("falta --file con el JSON de la petici\xF3n");
|
|
868
|
+
let parsed;
|
|
869
|
+
try {
|
|
870
|
+
parsed = JSON.parse(await readFile(path3.resolve(io.cwd, file), "utf8"));
|
|
871
|
+
} catch (error) {
|
|
872
|
+
throw new UsageError2(`no se pudo leer ${file}: ${error instanceof Error ? error.message : String(error)}`);
|
|
873
|
+
}
|
|
874
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new UsageError2(`${file} debe contener un objeto JSON`);
|
|
875
|
+
return parsed;
|
|
876
|
+
}
|
|
877
|
+
function reasonOf(flags) {
|
|
878
|
+
const reason = typeof flags.reason === "string" ? flags.reason.trim() : "";
|
|
879
|
+
if (reason.length < 3) throw new UsageError2('toda escritura exige --reason "\u2026" (m\xEDnimo 3 caracteres)');
|
|
880
|
+
return reason;
|
|
881
|
+
}
|
|
882
|
+
function keyOf(positional, what) {
|
|
883
|
+
const key2 = positional[0];
|
|
884
|
+
if (!key2) throw new UsageError2(`falta la clave de ${what}`);
|
|
885
|
+
return encodeURIComponent(key2);
|
|
886
|
+
}
|
|
887
|
+
function listQuery(flags, names) {
|
|
888
|
+
const query = {};
|
|
889
|
+
for (const name of names) if (typeof flags[name] === "string") query[name] = flags[name];
|
|
890
|
+
return query;
|
|
891
|
+
}
|
|
892
|
+
async function plan(group, args, io) {
|
|
893
|
+
const [command2, ...rest] = args;
|
|
894
|
+
const { positional, flags } = parse2(rest);
|
|
895
|
+
const withReason = async (call, extra = {}) => ({ ...call, write: true, body: { ...extra, reason: reasonOf(flags) } });
|
|
896
|
+
const fromFile = async (call) => ({ ...call, write: true, body: { ...await readBody(flags, io), reason: reasonOf(flags) } });
|
|
897
|
+
if (group === "flags") {
|
|
898
|
+
switch (command2) {
|
|
899
|
+
case "list":
|
|
900
|
+
return { method: "GET", path: "/flags", query: listQuery(flags, ["q", "tag", "archived", "limit", "cursor"]), write: false };
|
|
901
|
+
case "get":
|
|
902
|
+
return { method: "GET", path: `/flags/${keyOf(positional, "flag")}`, write: false };
|
|
903
|
+
case "create":
|
|
904
|
+
return fromFile({ method: "POST", path: "/flags" });
|
|
905
|
+
case "update":
|
|
906
|
+
return fromFile({ method: "PATCH", path: `/flags/${keyOf(positional, "flag")}` });
|
|
907
|
+
case "archive":
|
|
908
|
+
case "restore":
|
|
909
|
+
return withReason({ method: "POST", path: `/flags/${keyOf(positional, "flag")}/${command2}` });
|
|
910
|
+
case "delete":
|
|
911
|
+
return withReason({ method: "DELETE", path: `/flags/${keyOf(positional, "flag")}` });
|
|
912
|
+
case "kill":
|
|
913
|
+
return withReason({ method: "POST", path: `/flags/${keyOf(positional, "flag")}/kill` }, typeof flags.environment === "string" ? { environment: flags.environment } : {});
|
|
914
|
+
}
|
|
915
|
+
} else if (group === "segments") {
|
|
916
|
+
if (command2 === "members") {
|
|
917
|
+
const [action, ...more] = positional;
|
|
918
|
+
const unitKeys = typeof flags["unit-keys"] === "string" ? flags["unit-keys"].split(",").map((item) => item.trim()).filter(Boolean) : [];
|
|
919
|
+
if (action !== "add" && action !== "remove") throw new UsageError2('customy segments members add|remove <key> --unit-keys a,b --reason "\u2026"');
|
|
920
|
+
if (!unitKeys.length) throw new UsageError2("falta --unit-keys a,b,c");
|
|
921
|
+
return withReason({ method: action === "add" ? "POST" : "DELETE", path: `/segments/${keyOf(more, "segmento")}/members` }, { unitKeys });
|
|
922
|
+
}
|
|
923
|
+
switch (command2) {
|
|
924
|
+
case "list":
|
|
925
|
+
return { method: "GET", path: "/segments", query: listQuery(flags, ["limit", "cursor"]), write: false };
|
|
926
|
+
case "get":
|
|
927
|
+
return { method: "GET", path: `/segments/${keyOf(positional, "segmento")}`, write: false };
|
|
928
|
+
case "create":
|
|
929
|
+
return fromFile({ method: "POST", path: "/segments" });
|
|
930
|
+
case "update":
|
|
931
|
+
return fromFile({ method: "PATCH", path: `/segments/${keyOf(positional, "segmento")}` });
|
|
932
|
+
case "delete":
|
|
933
|
+
return withReason({ method: "DELETE", path: `/segments/${keyOf(positional, "segmento")}` });
|
|
934
|
+
}
|
|
935
|
+
} else {
|
|
936
|
+
switch (command2) {
|
|
937
|
+
case "list":
|
|
938
|
+
return { method: "GET", path: "/experiments", query: listQuery(flags, ["limit", "cursor"]), write: false };
|
|
939
|
+
case "get":
|
|
940
|
+
return { method: "GET", path: `/experiments/${keyOf(positional, "experimento")}`, write: false };
|
|
941
|
+
case "create":
|
|
942
|
+
return fromFile({ method: "POST", path: "/experiments" });
|
|
943
|
+
case "update":
|
|
944
|
+
return fromFile({ method: "PATCH", path: `/experiments/${keyOf(positional, "experimento")}` });
|
|
945
|
+
case "start":
|
|
946
|
+
case "pause":
|
|
947
|
+
return withReason({ method: "POST", path: `/experiments/${keyOf(positional, "experimento")}/${command2}` });
|
|
948
|
+
case "conclude": {
|
|
949
|
+
const decision = flags.decision;
|
|
950
|
+
if (decision !== "ship" && decision !== "rollback" && decision !== "iterate") throw new UsageError2("conclude exige --decision ship|rollback|iterate");
|
|
951
|
+
return withReason({ method: "POST", path: `/experiments/${keyOf(positional, "experimento")}/conclude` }, { decision });
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
throw new UsageError2(`comando desconocido: customy ${group} ${command2 ?? ""}`.trim() + " (customy --help)");
|
|
956
|
+
}
|
|
957
|
+
function summarize(group, call, data) {
|
|
958
|
+
if (!data || typeof data !== "object") return ["\u2713 hecho"];
|
|
959
|
+
const record = data;
|
|
960
|
+
const rowOf = (item) => {
|
|
961
|
+
const row = item;
|
|
962
|
+
return `${String(row.key ?? row.id ?? "?")} ${String(row.name ?? "")} ${String(row.status ?? row.kind ?? "")}`;
|
|
963
|
+
};
|
|
964
|
+
if (Array.isArray(record.items)) return [...record.items.map(rowOf), ...record.nextCursor ? [`# m\xE1s: --cursor ${String(record.nextCursor)}`] : []];
|
|
965
|
+
if (call.write) return [`\u2713 ${group} ${call.method} ${call.path}${record.key ? ` (${String(record.key)})` : ""}`];
|
|
966
|
+
return [rowOf(data), ...typeof record.description === "string" ? [String(record.description)] : []];
|
|
967
|
+
}
|
|
968
|
+
async function runExperimentsCli(group, args, io) {
|
|
969
|
+
try {
|
|
970
|
+
if (args.includes("--help")) {
|
|
971
|
+
io.out(EXPERIMENTS_HELP.join("\n"));
|
|
972
|
+
return EXPERIMENTS_EXIT.ok;
|
|
973
|
+
}
|
|
974
|
+
const { flags } = parse2(args.slice(1));
|
|
975
|
+
const call = await plan(group, args, io);
|
|
976
|
+
const base = (typeof flags["base-url"] === "string" ? flags["base-url"] : io.env.CUSTOMY_EXPERIMENTS_URL)?.replace(/\/$/, "");
|
|
977
|
+
if (!base) throw new UsageError2("falta el origen: --base-url o CUSTOMY_EXPERIMENTS_URL");
|
|
978
|
+
if (!/^https:\/\//i.test(base) && !/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?(\/|$)/i.test(base)) {
|
|
979
|
+
throw new UsageError2("el origen de Experiments debe ser https:// (http:// solo hacia localhost): el token viajar\xEDa en claro");
|
|
980
|
+
}
|
|
981
|
+
const query = call.query && Object.keys(call.query).length ? `?${new URLSearchParams(call.query)}` : "";
|
|
982
|
+
const url = `${base}/v1/experiments${call.path}${query}`;
|
|
983
|
+
if (call.write && flags["dry-run"]) {
|
|
984
|
+
io.out(JSON.stringify({ dryRun: true, method: call.method, url, body: call.body }, null, 2));
|
|
985
|
+
return EXPERIMENTS_EXIT.ok;
|
|
986
|
+
}
|
|
987
|
+
const token = io.env.CUSTOMY_EXPERIMENTS_TOKEN;
|
|
988
|
+
if (!token) throw new UsageError2("falta CUSTOMY_EXPERIMENTS_TOKEN en el entorno (nunca por la l\xEDnea de comandos)");
|
|
989
|
+
const doFetch = io.fetch ?? fetch;
|
|
990
|
+
const response = await doFetch(url, {
|
|
991
|
+
method: call.method,
|
|
992
|
+
headers: { authorization: `Bearer ${token}`, accept: "application/json", "user-agent": "customy-cli", ...call.body !== void 0 ? { "content-type": "application/json" } : {} },
|
|
993
|
+
...call.body !== void 0 ? { body: JSON.stringify(call.body) } : {}
|
|
994
|
+
});
|
|
995
|
+
const text = await response.text();
|
|
996
|
+
let data;
|
|
997
|
+
try {
|
|
998
|
+
data = text ? JSON.parse(text) : void 0;
|
|
999
|
+
} catch {
|
|
1000
|
+
data = text;
|
|
1001
|
+
}
|
|
1002
|
+
if (!response.ok) {
|
|
1003
|
+
const body = data && typeof data === "object" ? data : {};
|
|
1004
|
+
io.err(`\u2717 HTTP ${response.status}${body.name ? ` ${body.name}` : ""}: ${body.message ?? (typeof data === "string" && data ? data : response.statusText)}`);
|
|
1005
|
+
if (body.details !== void 0) io.err(JSON.stringify(body.details));
|
|
1006
|
+
return response.status === 401 || response.status === 403 ? EXPERIMENTS_EXIT.auth : response.status === 409 || response.status === 412 ? EXPERIMENTS_EXIT.conflict : EXPERIMENTS_EXIT.failure;
|
|
1007
|
+
}
|
|
1008
|
+
if (flags.json) io.out(JSON.stringify(data ?? null, null, 2));
|
|
1009
|
+
else for (const line of summarize(group, call, data)) io.out(line);
|
|
1010
|
+
return EXPERIMENTS_EXIT.ok;
|
|
1011
|
+
} catch (error) {
|
|
1012
|
+
if (error instanceof UsageError2) {
|
|
1013
|
+
io.err(`\u2717 ${error.message}`);
|
|
1014
|
+
return EXPERIMENTS_EXIT.failure;
|
|
1015
|
+
}
|
|
1016
|
+
io.err(`\u2717 ${error instanceof Error ? error.message : String(error)}`);
|
|
1017
|
+
return EXPERIMENTS_EXIT.failure;
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
var EXPERIENCE_GROUPS = ["experience"];
|
|
1021
|
+
var EXPERIENCE_EXIT = { ok: 0, invalid: 1, usage: 2, auth: 3, conflict: 4, failure: 5 };
|
|
1022
|
+
var EXPERIENCE_HELP = [
|
|
1023
|
+
"Customy Experience (token: CUSTOMY_EXPERIENCE_TOKEN, origin: --base-url or CUSTOMY_EXPERIENCE_URL; API: <origin>/api/experience/*):",
|
|
1024
|
+
" customy experience pull [--dir catalogs] [--namespace a,b] [--locale es,en] [--draft] download catalog@1 files (sorted by key) + a lock file",
|
|
1025
|
+
' customy experience push [file.json ...] [--dir catalogs] [--create] [--rebase] [--publish] [--note "..."]',
|
|
1026
|
+
" [--ack-remove k1,k2] [--ack-placeholders k3] [--plan free|pro|enterprise] [--dry-run]",
|
|
1027
|
+
" customy experience status [--locale es] [--warn-hours 24] [--fail-on-expiry] revisions, releases, channels and manifest expiry",
|
|
1028
|
+
" customy experience check [--dir catalogs] [--locales es,en] [--base-locale en] [--src src] [--fail-on-unused] LOCAL, for CI",
|
|
1029
|
+
" [--glossary glossary.json] [--strict] quality checks (variables, plurals, length, glossary)",
|
|
1030
|
+
" customy experience export --format xliff|po|json [--namespace a,b] [--locale es,fr] [--source-locale en] [--out dir|file] [--draft]",
|
|
1031
|
+
" customy experience import <file> [--format auto|xliff|po|json] [--dir catalogs] [--create] [--rebase] [--strict] [--glossary g.json]",
|
|
1032
|
+
' [--publish] [--note "..."] [--ack-remove k1,k2] [--ack-placeholders k3] [--plan ...] [--dry-run] saves a DRAFT; publishes only with --publish',
|
|
1033
|
+
" customy experience pseudo --locale xx [--rtl] [--source-locale en] [--namespace a] [--dir catalogs] [--out dir|file] LOCAL pseudo-localized catalog",
|
|
1034
|
+
" customy experience init [--channel production] [--out customy.experience.json] [--force] app config: scope, base, anchors with roles, floor",
|
|
1035
|
+
' customy experience revoke <release|#number> --reason "..." [--fallback <release|#number>] [--dry-run] raises minSequence (experience.release.kill)',
|
|
1036
|
+
' customy experience scope show | rotate --reason "..." | retire [--force] delivery scope (rotate/retire: experience.scope.rotate)',
|
|
1037
|
+
" customy experience signing plan [--retire id,id] [--threshold n] [--compromised id,id] READ-ONLY key rotation plan",
|
|
1038
|
+
' customy experience signing rotate --reason "..." [--retire id,id] [--compromised id,id] [--window-elapsed] publishes ONE rotation step',
|
|
1039
|
+
" customy experience reconcile <channel> after a database restore (storage ahead of database)",
|
|
1040
|
+
"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."
|
|
1041
|
+
];
|
|
1042
|
+
var LOCK_FILE = ".customy-experience.lock.json";
|
|
1043
|
+
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"]);
|
|
1044
|
+
var UsageError3 = class extends Error {
|
|
1045
|
+
};
|
|
1046
|
+
var ExitError = class extends Error {
|
|
1047
|
+
constructor(code, message) {
|
|
1048
|
+
super(message);
|
|
1049
|
+
this.code = code;
|
|
1050
|
+
}
|
|
1051
|
+
code;
|
|
1052
|
+
};
|
|
1053
|
+
var ApiError = class extends Error {
|
|
1054
|
+
constructor(status2, name, message, details) {
|
|
1055
|
+
super(message);
|
|
1056
|
+
this.status = status2;
|
|
1057
|
+
this.name = name;
|
|
1058
|
+
this.details = details;
|
|
1059
|
+
}
|
|
1060
|
+
status;
|
|
1061
|
+
name;
|
|
1062
|
+
details;
|
|
1063
|
+
};
|
|
1064
|
+
var isRec = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
1065
|
+
var str2 = (value, fallback = "") => typeof value === "string" ? value : fallback;
|
|
1066
|
+
function parse3(args) {
|
|
1067
|
+
const positional = [];
|
|
1068
|
+
const flags = {};
|
|
1069
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
1070
|
+
const arg = args[index];
|
|
1071
|
+
if (!arg.startsWith("--")) {
|
|
1072
|
+
positional.push(arg);
|
|
1073
|
+
continue;
|
|
1074
|
+
}
|
|
1075
|
+
const name = arg.slice(2);
|
|
1076
|
+
if (VALUE_FLAGS2.has(name)) {
|
|
1077
|
+
const value = args[index + 1];
|
|
1078
|
+
if (value === void 0 || value.startsWith("--")) throw new UsageError3(`--${name} necesita un valor`);
|
|
1079
|
+
flags[name] = value;
|
|
1080
|
+
index += 1;
|
|
1081
|
+
} else flags[name] = true;
|
|
1082
|
+
}
|
|
1083
|
+
return { positional, flags };
|
|
1084
|
+
}
|
|
1085
|
+
var list = (value) => typeof value === "string" ? value.split(",").map((item) => item.trim()).filter(Boolean) : [];
|
|
1086
|
+
var sortedKeys = (record) => Object.keys(record).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
|
|
1087
|
+
function limitsOf(flags) {
|
|
1088
|
+
const plan2 = flags.plan;
|
|
1089
|
+
if (plan2 === void 0) return TRANSLATION_PLAN_LIMITS.pro;
|
|
1090
|
+
if (plan2 !== "free" && plan2 !== "pro" && plan2 !== "enterprise") throw new UsageError3("--plan debe ser free, pro o enterprise");
|
|
1091
|
+
return TRANSLATION_PLAN_LIMITS[plan2];
|
|
1092
|
+
}
|
|
1093
|
+
function serializeCatalog(doc) {
|
|
1094
|
+
const messages2 = {};
|
|
1095
|
+
for (const key2 of sortedKeys(doc.messages)) messages2[key2] = doc.messages[key2];
|
|
1096
|
+
return `${JSON.stringify({ version: doc.version, namespace: doc.namespace, locale: doc.locale, syntax: doc.syntax, messages: messages2 }, null, 2)}
|
|
1097
|
+
`;
|
|
1098
|
+
}
|
|
1099
|
+
function makeClient(flags, io) {
|
|
1100
|
+
const base = (typeof flags["base-url"] === "string" ? flags["base-url"] : io.env.CUSTOMY_EXPERIENCE_URL)?.replace(/\/+$/, "");
|
|
1101
|
+
if (!base) throw new UsageError3("falta el origen: --base-url o CUSTOMY_EXPERIENCE_URL");
|
|
1102
|
+
if (!/^https:\/\//i.test(base) && !/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?(\/|$)/i.test(base)) {
|
|
1103
|
+
throw new UsageError3("el origen de Experience debe ser https:// (http:// solo hacia localhost): el token viajar\xEDa en claro");
|
|
1104
|
+
}
|
|
1105
|
+
const token = io.env.CUSTOMY_EXPERIENCE_TOKEN;
|
|
1106
|
+
if (!token) throw new UsageError3("falta CUSTOMY_EXPERIENCE_TOKEN en el entorno (nunca por la l\xEDnea de comandos)");
|
|
1107
|
+
const timeout = typeof flags.timeout === "string" ? Number(flags.timeout) : 3e4;
|
|
1108
|
+
if (!Number.isFinite(timeout) || timeout < 1) throw new UsageError3("--timeout debe ser un n\xFAmero de milisegundos");
|
|
1109
|
+
const doFetch = io.fetch ?? fetch;
|
|
1110
|
+
return {
|
|
1111
|
+
origin: base,
|
|
1112
|
+
async request(method, route, options = {}) {
|
|
1113
|
+
const query = options.query && Object.keys(options.query).length ? `?${new URLSearchParams(options.query)}` : "";
|
|
1114
|
+
let response;
|
|
1115
|
+
try {
|
|
1116
|
+
response = await doFetch(`${base}/api/experience${route}${query}`, {
|
|
1117
|
+
method,
|
|
1118
|
+
headers: { authorization: `Bearer ${token}`, accept: "application/json", "user-agent": "customy-cli", ...options.body !== void 0 ? { "content-type": "application/json" } : {} },
|
|
1119
|
+
...options.body !== void 0 ? { body: JSON.stringify(options.body) } : {},
|
|
1120
|
+
signal: AbortSignal.timeout(timeout)
|
|
1121
|
+
});
|
|
1122
|
+
} catch (error) {
|
|
1123
|
+
throw new ExitError(EXPERIENCE_EXIT.failure, `no se pudo conectar con ${base}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1124
|
+
}
|
|
1125
|
+
const text = await response.text();
|
|
1126
|
+
let data;
|
|
1127
|
+
try {
|
|
1128
|
+
data = text ? JSON.parse(text) : void 0;
|
|
1129
|
+
} catch {
|
|
1130
|
+
data = void 0;
|
|
1131
|
+
}
|
|
1132
|
+
if (!response.ok) {
|
|
1133
|
+
const body = isRec(data) ? data : {};
|
|
1134
|
+
const name = str2(body.name) || str2(body.error) || `http_${response.status}`;
|
|
1135
|
+
const message = str2(body.message) || str2(body.reason) || response.statusText || `HTTP ${response.status}`;
|
|
1136
|
+
throw new ApiError(response.status, name, body.capability ? `${message} (capacidad: ${String(body.capability)})` : message, body.details ?? (body.issues !== void 0 ? { issues: body.issues } : void 0));
|
|
1137
|
+
}
|
|
1138
|
+
return data;
|
|
1139
|
+
}
|
|
1140
|
+
};
|
|
1141
|
+
}
|
|
1142
|
+
function exitFor(error) {
|
|
1143
|
+
if (error.status === 401 || error.status === 403 || error.status === 404) return EXPERIENCE_EXIT.auth;
|
|
1144
|
+
if (error.status === 409) return EXPERIENCE_EXIT.conflict;
|
|
1145
|
+
if (error.status === 422) return EXPERIENCE_EXIT.invalid;
|
|
1146
|
+
return EXPERIENCE_EXIT.failure;
|
|
1147
|
+
}
|
|
1148
|
+
function explain(error, what) {
|
|
1149
|
+
const details = isRec(error.details) ? error.details : {};
|
|
1150
|
+
if (error.status === 401) return `${what}: credencial rechazada (401). Revisa CUSTOMY_EXPERIENCE_TOKEN.`;
|
|
1151
|
+
if (error.status === 403) return `${what}: sin permiso (403). ${error.message}`;
|
|
1152
|
+
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.`;
|
|
1153
|
+
if (error.status === 402) return `${what}: tope del plan agotado (402). ${error.message}`;
|
|
1154
|
+
if (error.name === "stale_revision_base") return `${what}: alguien public\xF3 la revisi\xF3n ${String(details.latestRevision ?? "?")} desde tu \xFAltimo pull. Ejecuta \xABcustomy experience pull\xBB, rebasa tus cambios y vuelve a hacer push.`;
|
|
1155
|
+
if (error.name === "draft_conflict") return `${what}: otra persona guard\xF3 este borrador (versi\xF3n ${String(details.draftVersion ?? "?")}) mientras lo editabas. Ejecuta \xABcustomy experience pull --draft\xBB, integra sus cambios y vuelve a hacer push.`;
|
|
1156
|
+
if (error.name === "storage_ahead_of_database") return `${what}: el almac\xE9n va por delante de la base (restauraci\xF3n reciente). Ejecuta \xABcustomy experience reconcile <canal>\xBB (en producci\xF3n, con dos personas).`;
|
|
1157
|
+
if (error.name === "scope_rotation_in_progress") return `${what}: ya hay una rotaci\xF3n en curso (un \xE1mbito drena). Ret\xEDrala con \xABcustomy experience scope retire\xBB antes de rotar de nuevo.`;
|
|
1158
|
+
if (error.name === "scope_not_draining") return `${what}: no hay ning\xFAn \xE1mbito que drene; no hay nada que retirar.`;
|
|
1159
|
+
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.`;
|
|
1160
|
+
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" : ""}.`;
|
|
1161
|
+
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.`;
|
|
1162
|
+
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).`;
|
|
1163
|
+
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.`;
|
|
1164
|
+
if (error.name === "fallback_invalid" || error.name === "fallback_revoked") return `${what}: ${error.message} (canales: ${channelNames(details.channels)})`;
|
|
1165
|
+
if (error.name === "approval_required") return `${what}: este entorno se opera como producci\xF3n y exige una solicitud (POST /v1/change-requests, action ${str2(details.action) || "move"}) que aprueben ${String(details.requiredApprovals ?? 2)} personas distintas de quien la pide: la primera respalda y la segunda aprueba.`;
|
|
1166
|
+
if (error.name === "catalog_gate_blocked") {
|
|
1167
|
+
const blocked = Array.isArray(details.blocked) ? details.blocked.filter(isRec) : [];
|
|
1168
|
+
const removed = blocked.filter((item) => item.reason === "removed").map((item) => str2(item.key));
|
|
1169
|
+
const changed = blocked.filter((item) => item.reason === "placeholders-changed").map((item) => str2(item.key));
|
|
1170
|
+
return `${what}: la revisi\xF3n romper\xEDa a quien ya usa estas claves. El borrador qued\xF3 guardado; para publicar reconoce cada clave${removed.length ? ` con --ack-remove ${removed.join(",")}` : ""}${changed.length ? ` con --ack-placeholders ${changed.join(",")}` : ""}.`;
|
|
1171
|
+
}
|
|
1172
|
+
return `${what}: HTTP ${error.status} ${error.name}: ${error.message}`;
|
|
1173
|
+
}
|
|
1174
|
+
var channelNames = (value) => Array.isArray(value) ? value.map((item) => isRec(item) ? str2(item.channel) : String(item)).filter(Boolean).join(", ") || "?" : "?";
|
|
1175
|
+
var lockKey = (namespace, locale) => `${namespace}/${locale}`;
|
|
1176
|
+
var fileName = (namespace, locale) => `${namespace}.${locale}.json`;
|
|
1177
|
+
async function readLock(dir) {
|
|
1178
|
+
try {
|
|
1179
|
+
const parsed = JSON.parse(await readFile(path3.join(dir, LOCK_FILE), "utf8"));
|
|
1180
|
+
return isRec(parsed) && isRec(parsed.artifacts) ? parsed : null;
|
|
1181
|
+
} catch {
|
|
1182
|
+
return null;
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
async function catalogFilesIn(dir) {
|
|
1186
|
+
let names;
|
|
1187
|
+
try {
|
|
1188
|
+
names = await readdir(dir);
|
|
1189
|
+
} catch {
|
|
1190
|
+
throw new UsageError3(`no se pudo leer el directorio ${dir}`);
|
|
1191
|
+
}
|
|
1192
|
+
return names.filter((name) => name.endsWith(".json") && !name.startsWith(".")).sort().map((name) => path3.join(dir, name));
|
|
1193
|
+
}
|
|
1194
|
+
async function loadFiles(files, io) {
|
|
1195
|
+
const out = [];
|
|
1196
|
+
for (const file of files) {
|
|
1197
|
+
const display = path3.relative(io.cwd, file) || file;
|
|
1198
|
+
try {
|
|
1199
|
+
out.push({ file, display, raw: JSON.parse(await readFile(file, "utf8")), parseError: null });
|
|
1200
|
+
} catch (error) {
|
|
1201
|
+
out.push({ file, display, raw: null, parseError: error instanceof Error ? error.message : String(error) });
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
return out;
|
|
1205
|
+
}
|
|
1206
|
+
var isCatalogLike = (raw) => isRec(raw) && raw.version === "catalog@1";
|
|
1207
|
+
async function listCatalogArtifacts(client) {
|
|
1208
|
+
const all = [];
|
|
1209
|
+
let after;
|
|
1210
|
+
for (let page = 0; page < 200; page += 1) {
|
|
1211
|
+
const result = await client.request("GET", "/artifacts", { query: { kind: "catalog", limit: "200", ...after ? { after } : {} } });
|
|
1212
|
+
const data = isRec(result) && Array.isArray(result.data) ? result.data.filter(isRec) : [];
|
|
1213
|
+
all.push(...data);
|
|
1214
|
+
const next = isRec(result) ? result.next : null;
|
|
1215
|
+
if (typeof next !== "string" || !data.length) break;
|
|
1216
|
+
after = next;
|
|
1217
|
+
}
|
|
1218
|
+
return all.filter((artifact) => !artifact.archivedAt);
|
|
1219
|
+
}
|
|
1220
|
+
async function readArtifactDoc(client, id, draft) {
|
|
1221
|
+
const detail = await client.request("GET", `/artifacts/${encodeURIComponent(id)}`);
|
|
1222
|
+
const latest = isRec(detail) && typeof detail.latestRevision === "number" ? detail.latestRevision : 0;
|
|
1223
|
+
const draftVersion = isRec(detail) && isRec(detail.draft) && typeof detail.draft.version === "number" ? detail.draft.version : 0;
|
|
1224
|
+
let document;
|
|
1225
|
+
let contentHash = null;
|
|
1226
|
+
let revision = latest;
|
|
1227
|
+
if (draft) {
|
|
1228
|
+
const saved = await client.request("GET", `/artifacts/${encodeURIComponent(id)}/draft`);
|
|
1229
|
+
document = isRec(saved) && isRec(saved.draft) ? saved.draft.document : void 0;
|
|
1230
|
+
if (document === void 0) return { skip: "sin borrador" };
|
|
1231
|
+
} else {
|
|
1232
|
+
if (latest < 1) return { skip: "sin revisi\xF3n publicada (usa --draft)" };
|
|
1233
|
+
const rev = await client.request("GET", `/artifacts/${encodeURIComponent(id)}/revisions/${latest}`);
|
|
1234
|
+
document = isRec(rev) ? rev.document : void 0;
|
|
1235
|
+
contentHash = isRec(rev) && typeof rev.contentHash === "string" ? rev.contentHash : null;
|
|
1236
|
+
revision = isRec(rev) && typeof rev.n === "number" ? rev.n : latest;
|
|
1237
|
+
}
|
|
1238
|
+
const checked = validateCatalog(document, { limits: TRANSLATION_PLAN_LIMITS.enterprise });
|
|
1239
|
+
if (!checked.ok || !checked.doc) return { skip: `el servidor devolvi\xF3 un documento que no es catalog@1 v\xE1lido: ${checked.issues[0]?.message ?? "?"}` };
|
|
1240
|
+
return { doc: checked.doc, revision, contentHash, draftVersion };
|
|
1241
|
+
}
|
|
1242
|
+
async function pull(flags, io) {
|
|
1243
|
+
const client = makeClient(flags, io);
|
|
1244
|
+
const dir = path3.resolve(io.cwd, typeof flags.dir === "string" ? flags.dir : "catalogs");
|
|
1245
|
+
const namespaces = list(flags.namespace);
|
|
1246
|
+
const locales = list(flags.locale);
|
|
1247
|
+
const artifacts = (await listCatalogArtifacts(client)).filter((a) => (!namespaces.length || namespaces.includes(str2(a.name))) && (!locales.length || locales.includes(str2(a.locale))));
|
|
1248
|
+
const lock = { version: 1, origin: client.origin, artifacts: {} };
|
|
1249
|
+
const previous = await readLock(dir);
|
|
1250
|
+
if (previous && previous.origin === client.origin) lock.artifacts = { ...previous.artifacts };
|
|
1251
|
+
const written = [];
|
|
1252
|
+
const unchanged = [];
|
|
1253
|
+
const skipped = [];
|
|
1254
|
+
await mkdir(dir, { recursive: true });
|
|
1255
|
+
for (const artifact of artifacts) {
|
|
1256
|
+
const id = str2(artifact.id);
|
|
1257
|
+
const name = str2(artifact.name);
|
|
1258
|
+
const locale = str2(artifact.locale);
|
|
1259
|
+
const read2 = await readArtifactDoc(client, id, flags.draft === true);
|
|
1260
|
+
if ("skip" in read2) {
|
|
1261
|
+
skipped.push({ name, locale, reason: read2.skip });
|
|
1262
|
+
continue;
|
|
1263
|
+
}
|
|
1264
|
+
const { doc: checkedDoc, revision, contentHash, draftVersion } = read2;
|
|
1265
|
+
const file = path3.join(dir, fileName(name, locale));
|
|
1266
|
+
const content = serializeCatalog(checkedDoc);
|
|
1267
|
+
let existing = null;
|
|
1268
|
+
try {
|
|
1269
|
+
existing = await readFile(file, "utf8");
|
|
1270
|
+
} catch {
|
|
1271
|
+
}
|
|
1272
|
+
if (existing === content) unchanged.push(path3.relative(io.cwd, file));
|
|
1273
|
+
else {
|
|
1274
|
+
await writeFile(file, content);
|
|
1275
|
+
written.push(path3.relative(io.cwd, file));
|
|
1276
|
+
}
|
|
1277
|
+
lock.artifacts[lockKey(name, locale)] = { artifactId: id, revision, contentHash, draftVersion };
|
|
1278
|
+
}
|
|
1279
|
+
await writeFile(path3.join(dir, LOCK_FILE), `${JSON.stringify({ ...lock, artifacts: Object.fromEntries(sortedKeys(lock.artifacts).map((k) => [k, lock.artifacts[k]])) }, null, 2)}
|
|
1280
|
+
`);
|
|
1281
|
+
const lines = [
|
|
1282
|
+
...written.map((f) => `\u2713 ${f}`),
|
|
1283
|
+
...unchanged.map((f) => `= ${f} (sin cambios)`),
|
|
1284
|
+
...skipped.map((s) => `- ${s.name}/${s.locale}: ${s.reason}`),
|
|
1285
|
+
`${written.length} escritos, ${unchanged.length} sin cambios, ${skipped.length} omitidos (lock: ${path3.relative(io.cwd, path3.join(dir, LOCK_FILE))})`
|
|
1286
|
+
];
|
|
1287
|
+
return { lines, result: { written, unchanged, skipped, lock: path3.relative(io.cwd, path3.join(dir, LOCK_FILE)) } };
|
|
1288
|
+
}
|
|
1289
|
+
function checkAckFlags(flags) {
|
|
1290
|
+
const ackRemove = list(flags["ack-remove"]);
|
|
1291
|
+
const ackPlaceholders = list(flags["ack-placeholders"]);
|
|
1292
|
+
if ((ackRemove.length || ackPlaceholders.length) && !flags.publish) throw new UsageError3("--ack-remove y --ack-placeholders solo tienen sentido con --publish");
|
|
1293
|
+
if (ackRemove.length > 500 || ackPlaceholders.length > 500) throw new UsageError3("m\xE1ximo 500 claves reconocidas por lista");
|
|
1294
|
+
}
|
|
1295
|
+
async function push(positional, flags, io) {
|
|
1296
|
+
const limits = limitsOf(flags);
|
|
1297
|
+
const dir = path3.resolve(io.cwd, typeof flags.dir === "string" ? flags.dir : "catalogs");
|
|
1298
|
+
const files = positional.length ? positional.map((p) => path3.resolve(io.cwd, p)) : await catalogFilesIn(dir);
|
|
1299
|
+
if (!files.length) throw new UsageError3("no hay ficheros que subir: pasa archivos o --dir con catalog@1");
|
|
1300
|
+
checkAckFlags(flags);
|
|
1301
|
+
const loaded = await loadFiles(files, io);
|
|
1302
|
+
const problems = [];
|
|
1303
|
+
const docs = [];
|
|
1304
|
+
for (const item of loaded) {
|
|
1305
|
+
if (item.parseError) {
|
|
1306
|
+
problems.push({ file: item.display, issues: [{ path: "", message: `no es JSON: ${item.parseError}` }] });
|
|
1307
|
+
continue;
|
|
1308
|
+
}
|
|
1309
|
+
const checked = validateCatalog(item.raw, { limits });
|
|
1310
|
+
if (!checked.ok || !checked.doc) problems.push({ file: item.display, issues: checked.issues.map((i) => ({ path: i.path, message: i.message })) });
|
|
1311
|
+
else docs.push({ display: item.display, doc: checked.doc });
|
|
1312
|
+
}
|
|
1313
|
+
if (problems.length) {
|
|
1314
|
+
throw new ExitError(EXPERIENCE_EXIT.invalid, ["validaci\xF3n local fallida; no se envi\xF3 nada:", ...problems.flatMap((p) => p.issues.map((i) => ` ${p.file}${i.path ? ` ${i.path}` : ""}: ${i.message}`))].join("\n"));
|
|
1315
|
+
}
|
|
1316
|
+
if (flags["dry-run"]) {
|
|
1317
|
+
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 })) } };
|
|
1318
|
+
}
|
|
1319
|
+
return uploadDocs(docs, flags, io, positional.length ? path3.dirname(files[0]) : dir);
|
|
1320
|
+
}
|
|
1321
|
+
async function uploadDocs(docs, flags, io, lockDir) {
|
|
1322
|
+
const ackRemove = list(flags["ack-remove"]);
|
|
1323
|
+
const ackPlaceholders = list(flags["ack-placeholders"]);
|
|
1324
|
+
const client = makeClient(flags, io);
|
|
1325
|
+
const lock = await readLock(lockDir);
|
|
1326
|
+
if (lock && lock.origin !== client.origin) throw new UsageError3(`el lock de ${path3.relative(io.cwd, lockDir) || "."} es de otro origen (${lock.origin}); haz pull contra este origen`);
|
|
1327
|
+
const lockFile = { version: 1, origin: client.origin, artifacts: { ...lock?.artifacts ?? {} } };
|
|
1328
|
+
const known = await listCatalogArtifacts(client);
|
|
1329
|
+
const results = [];
|
|
1330
|
+
const lines = [];
|
|
1331
|
+
const saveLock = async () => {
|
|
1332
|
+
await mkdir(lockDir, { recursive: true }).catch(() => void 0);
|
|
1333
|
+
await writeFile(path3.join(lockDir, LOCK_FILE), `${JSON.stringify({ ...lockFile, artifacts: Object.fromEntries(sortedKeys(lockFile.artifacts).map((k) => [k, lockFile.artifacts[k]])) }, null, 2)}
|
|
1334
|
+
`).catch(() => void 0);
|
|
1335
|
+
};
|
|
1336
|
+
for (const { display, doc } of docs) {
|
|
1337
|
+
const key2 = lockKey(doc.namespace, doc.locale);
|
|
1338
|
+
const label = `${display} (${key2})`;
|
|
1339
|
+
try {
|
|
1340
|
+
let artifact = known.find((a) => a.name === doc.namespace && a.locale === doc.locale);
|
|
1341
|
+
let created = false;
|
|
1342
|
+
if (!artifact) {
|
|
1343
|
+
if (!flags.create) throw new ExitError(EXPERIENCE_EXIT.invalid, `${label}: no existe ese cat\xE1logo en el servidor; usa --create para crearlo`);
|
|
1344
|
+
artifact = await client.request("POST", "/artifacts", { body: { kind: "catalog", name: doc.namespace, locale: doc.locale } });
|
|
1345
|
+
created = true;
|
|
1346
|
+
}
|
|
1347
|
+
const id = str2(artifact.id);
|
|
1348
|
+
let entry = lockFile.artifacts[key2];
|
|
1349
|
+
if (!created && (!entry || entry.artifactId !== id)) {
|
|
1350
|
+
if (!flags.rebase) throw new ExitError(EXPERIENCE_EXIT.conflict, `${label}: 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.`);
|
|
1351
|
+
const detail = await client.request("GET", `/artifacts/${encodeURIComponent(id)}`);
|
|
1352
|
+
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 };
|
|
1353
|
+
}
|
|
1354
|
+
if (created) entry = { artifactId: id, revision: 0, contentHash: null, draftVersion: 0 };
|
|
1355
|
+
const base = entry;
|
|
1356
|
+
const catalogHint = { kind: "catalog", locale: doc.locale };
|
|
1357
|
+
const saved = await client.request("PUT", `/artifacts/${encodeURIComponent(id)}/draft`, { body: { document: doc, revisionBase: base.revision, draftVersion: base.draftVersion }, query: catalogHint });
|
|
1358
|
+
const draftVersion = isRec(saved) && typeof saved.version === "number" ? saved.version : base.draftVersion + 1;
|
|
1359
|
+
lockFile.artifacts[key2] = { ...base, draftVersion };
|
|
1360
|
+
const outcome = { file: display, namespace: doc.namespace, locale: doc.locale, artifactId: id, artifactCreated: created, revisionBase: base.revision, draftVersion, published: null };
|
|
1361
|
+
lines.push(`\u2713 ${label}: borrador guardado (versi\xF3n ${draftVersion}, base r${base.revision})${created ? " \xB7 cat\xE1logo creado" : ""}`);
|
|
1362
|
+
if (flags.publish) {
|
|
1363
|
+
const body = { ...typeof flags.note === "string" ? { note: flags.note } : {}, ...ackRemove.length || ackPlaceholders.length ? { acknowledge: { ...ackRemove.length ? { removeKeys: ackRemove } : {}, ...ackPlaceholders.length ? { placeholderKeys: ackPlaceholders } : {} } } : {} };
|
|
1364
|
+
const published = await client.request("POST", `/artifacts/${encodeURIComponent(id)}/revisions`, { body, query: catalogHint });
|
|
1365
|
+
const rev = isRec(published) && isRec(published.revision) ? published.revision : {};
|
|
1366
|
+
const wasCreated = isRec(published) && published.created === true;
|
|
1367
|
+
const n = typeof rev.n === "number" ? rev.n : base.revision;
|
|
1368
|
+
outcome.published = { created: wasCreated, revision: n, contentHash: typeof rev.contentHash === "string" ? rev.contentHash : null, warnings: isRec(published) && Array.isArray(published.warnings) ? published.warnings : [] };
|
|
1369
|
+
lockFile.artifacts[key2] = { artifactId: id, revision: n, contentHash: typeof rev.contentHash === "string" ? rev.contentHash : null, draftVersion };
|
|
1370
|
+
lines.push(wasCreated ? `\u2713 ${label}: revisi\xF3n r${n} publicada` : `= ${label}: sin cambios respecto a r${n}, no se cre\xF3 revisi\xF3n`);
|
|
1371
|
+
}
|
|
1372
|
+
results.push(outcome);
|
|
1373
|
+
} catch (error) {
|
|
1374
|
+
await saveLock();
|
|
1375
|
+
if (error instanceof ApiError) throw new ExitError(exitFor(error), [...lines, `\u2717 ${explain(error, label)}`].join("\n"));
|
|
1376
|
+
if (error instanceof ExitError) throw new ExitError(error.code, [...lines, `\u2717 ${error.message}`].join("\n"));
|
|
1377
|
+
throw error;
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
await saveLock();
|
|
1381
|
+
return { lines, result: { files: results } };
|
|
1382
|
+
}
|
|
1383
|
+
var num = (v) => typeof v === "number" ? v : void 0;
|
|
1384
|
+
var opt = (v) => typeof v === "string" ? v : void 0;
|
|
1385
|
+
function scopeFrom(data) {
|
|
1386
|
+
if (!isRec(data)) return null;
|
|
1387
|
+
const scope = isRec(data.scope) ? data.scope : data;
|
|
1388
|
+
if (typeof scope.key !== "string") return null;
|
|
1389
|
+
const view = (value) => isRec(value) && typeof value.key === "string" ? { key: value.key, generation: typeof value.generation === "number" ? value.generation : 0, successor: typeof value.successor === "string" ? value.successor : null, drainsUntil: typeof value.drainsUntil === "string" ? value.drainsUntil : null } : null;
|
|
1390
|
+
const delivery = isRec(data.delivery) ? data.delivery : {};
|
|
1391
|
+
return {
|
|
1392
|
+
key: scope.key,
|
|
1393
|
+
status: str2(scope.status, "active"),
|
|
1394
|
+
generation: typeof scope.generation === "number" ? scope.generation : 0,
|
|
1395
|
+
successor: typeof scope.successor === "string" ? scope.successor : null,
|
|
1396
|
+
drainsUntil: typeof scope.drainsUntil === "string" ? scope.drainsUntil : null,
|
|
1397
|
+
draining: view(data.draining),
|
|
1398
|
+
rot: { n: num(data.rotationsThisMonth), max: num(data.maxRotationsPerMonth), last: opt(data.lastRotatedAt), force: opt(data.forceAllowedAt), stuck: num(data.channelsNotMigrated) },
|
|
1399
|
+
delivery: {
|
|
1400
|
+
base: typeof delivery.base === "string" ? delivery.base : null,
|
|
1401
|
+
channels: (Array.isArray(delivery.channels) ? delivery.channels.filter(isRec) : []).map((c) => ({ channel: str2(c.channel), timestampUrl: typeof c.timestampUrl === "string" ? c.timestampUrl : null })),
|
|
1402
|
+
timestampValiditySeconds: typeof delivery.timestampValiditySeconds === "number" ? delivery.timestampValiditySeconds : null
|
|
1403
|
+
}
|
|
1404
|
+
};
|
|
1405
|
+
}
|
|
1406
|
+
async function readScope(client) {
|
|
1407
|
+
try {
|
|
1408
|
+
return scopeFrom(await client.request("GET", "/scope"));
|
|
1409
|
+
} catch (error) {
|
|
1410
|
+
if (error instanceof ApiError && error.status === 404) return null;
|
|
1411
|
+
throw error;
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
1414
|
+
function scopeLines(info) {
|
|
1415
|
+
if (!info) return [" (no disponible: sin permiso o inexistente; el BFF puede ser anterior a manifest@2)"];
|
|
1416
|
+
return [
|
|
1417
|
+
` ${info.key} ${info.status} generaci\xF3n ${info.generation}${info.delivery.base ? ` base ${info.delivery.base}` : ""}`,
|
|
1418
|
+
...info.draining ? [` DRENANDO ${info.draining.key} generaci\xF3n ${info.draining.generation} hasta ${info.draining.drainsUntil ?? "?"}${info.draining.successor ? ` sucesor ${info.draining.successor}` : ""} (retira con \xABcustomy experience scope retire\xBB)${info.rot.force ? ` --force desde ${info.rot.force}` : ""}${info.rot.stuck ? ` sin migrar ${info.rot.stuck}` : ""}`] : [],
|
|
1419
|
+
...info.rot.n === void 0 ? [] : [` rotaciones este mes ${info.rot.n}/${info.rot.max ?? "?"}${info.rot.last ? ` \xFAltima ${info.rot.last}` : ""}`]
|
|
1420
|
+
];
|
|
1421
|
+
}
|
|
1422
|
+
async function status(flags, io) {
|
|
1423
|
+
const client = makeClient(flags, io);
|
|
1424
|
+
const explicitWarn = typeof flags["warn-hours"] === "string" ? Number(flags["warn-hours"]) : null;
|
|
1425
|
+
if (explicitWarn !== null && (!Number.isFinite(explicitWarn) || explicitWarn < 0)) throw new UsageError3("--warn-hours debe ser un n\xFAmero de horas");
|
|
1426
|
+
const locales = list(flags.locale);
|
|
1427
|
+
const now = Date.now();
|
|
1428
|
+
const arts = (await listCatalogArtifacts(client)).filter((a) => !locales.length || locales.includes(str2(a.locale))).slice(0, 60);
|
|
1429
|
+
const revisions = [];
|
|
1430
|
+
for (const a of arts) {
|
|
1431
|
+
const result = await client.request("GET", `/artifacts/${encodeURIComponent(str2(a.id))}/revisions`, { query: { limit: "1" } });
|
|
1432
|
+
const latest = isRec(result) && Array.isArray(result.data) ? result.data.find(isRec) : void 0;
|
|
1433
|
+
revisions.push({ name: str2(a.name), locale: str2(a.locale), revision: latest && typeof latest.n === "number" ? latest.n : 0, createdAt: latest ? str2(latest.createdAt) || null : null, contentHash: latest ? str2(latest.contentHash) || null : null });
|
|
1434
|
+
}
|
|
1435
|
+
const relResult = await client.request("GET", "/releases", { query: { limit: "5" } });
|
|
1436
|
+
const releases = (isRec(relResult) && Array.isArray(relResult.data) ? relResult.data.filter(isRec) : []).map((r) => ({ id: str2(r.id), number: typeof r.number === "number" ? r.number : 0, state: str2(r.state), artifacts: typeof r.artifacts === "number" ? r.artifacts : null, createdAt: str2(r.createdAt) || null }));
|
|
1437
|
+
const chResult = await client.request("GET", "/channels");
|
|
1438
|
+
const scopeInfo = await readScope(client);
|
|
1439
|
+
const warnHours = explicitWarn ?? (scopeInfo?.delivery.timestampValiditySeconds ? scopeInfo.delivery.timestampValiditySeconds / 6 / 3600 : 24);
|
|
1440
|
+
const urlByChannel = new Map(scopeInfo?.delivery.channels.map((c) => [c.channel, c.timestampUrl]) ?? []);
|
|
1441
|
+
const numberById = new Map(releases.map((r) => [r.id, r.number]));
|
|
1442
|
+
let worst = 0;
|
|
1443
|
+
const channels = (isRec(chResult) && Array.isArray(chResult.data) ? chResult.data.filter(isRec) : []).map((c) => {
|
|
1444
|
+
const expiresAt = typeof c.expiresAt === "string" ? c.expiresAt : isRec(c.manifest) && typeof c.manifest.expiresAt === "string" ? c.manifest.expiresAt : null;
|
|
1445
|
+
const hours = expiresAt && !Number.isNaN(Date.parse(expiresAt)) ? (Date.parse(expiresAt) - now) / 36e5 : null;
|
|
1446
|
+
const state = hours === null ? "unknown" : hours <= 0 ? "expired" : hours <= warnHours ? "expiring" : "ok";
|
|
1447
|
+
if (state === "expired" || state === "expiring") worst = 1;
|
|
1448
|
+
const releaseId = typeof c.releaseId === "string" ? c.releaseId : null;
|
|
1449
|
+
const candidate = isRec(c.candidate) && typeof c.candidate.sequence === "number" ? { sequence: c.candidate.sequence, decisionPoint: typeof c.decisionPoint === "string" ? c.decisionPoint : null } : null;
|
|
1450
|
+
return { channel: str2(c.channel), releaseId, releaseNumber: releaseId ? numberById.get(releaseId) ?? null : null, sequence: typeof c.sequence === "number" ? c.sequence : null, minSequence: typeof c.minSequence === "number" ? c.minSequence : null, candidate, timestampUrl: urlByChannel.get(str2(c.channel)) ?? null, movedAt: str2(c.movedAt) || null, expiresAt, hoursLeft: hours === null ? null : Math.round(hours * 10) / 10, expiry: state };
|
|
1451
|
+
});
|
|
1452
|
+
const lines = [
|
|
1453
|
+
"Revisiones (\xFAltima por cat\xE1logo):",
|
|
1454
|
+
...revisions.length ? revisions.map((r) => ` ${r.name}/${r.locale} r${r.revision} ${r.createdAt ?? "-"}`) : [" (sin cat\xE1logos)"],
|
|
1455
|
+
"Releases (\xFAltimos 5):",
|
|
1456
|
+
...releases.length ? releases.map((r) => ` #${r.number} ${r.state} ${r.artifacts ?? "?"} artefactos ${r.createdAt ?? "-"}`) : [" (ninguno)"],
|
|
1457
|
+
"\xC1mbito de entrega:",
|
|
1458
|
+
...scopeLines(scopeInfo),
|
|
1459
|
+
"Canales (el timestamp es el puntero que sondean los clientes; el manifiesto no caduca):",
|
|
1460
|
+
...channels.length ? channels.map((c) => ` ${c.channel} ${c.releaseNumber !== null ? `release #${c.releaseNumber}` : c.releaseId ?? "sin release"} seq ${c.sequence ?? "-"} minSeq ${c.minSequence ?? "-"}${c.candidate ? ` candidato seq ${c.candidate.sequence}` : ""} timestamp caduca ${c.expiresAt ?? "desconocido"}${c.expiry === "expired" ? " (CADUCADO)" : c.expiry === "expiring" ? ` (caduca en ${c.hoursLeft} h)` : ""}`) : [" (ninguno)"]
|
|
1461
|
+
];
|
|
1462
|
+
return { lines, result: { revisions, releases, scope: scopeInfo, channels }, code: flags["fail-on-expiry"] ? worst : 0 };
|
|
1463
|
+
}
|
|
1464
|
+
var SRC_EXT = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".vue", ".svelte"]);
|
|
1465
|
+
var KEY_BODY = "[a-z][A-Za-z0-9]*(?:\\.[a-z][A-Za-z0-9-]*)+";
|
|
1466
|
+
var USAGE_PATTERNS = [new RegExp(`\\bt\\(\\s*["'\`](${KEY_BODY})["'\`]`, "g"), new RegExp(`\\$t\\s*:\\s*["'\`](${KEY_BODY})["'\`]`, "g"), new RegExp(`\\bi18nKey\\s*=\\s*\\{?\\s*["'\`](${KEY_BODY})["'\`]`, "g")];
|
|
1467
|
+
async function usedKeys(root) {
|
|
1468
|
+
const found = /* @__PURE__ */ new Map();
|
|
1469
|
+
const walk = async (dir, depth) => {
|
|
1470
|
+
if (depth > 12) return;
|
|
1471
|
+
for (const entry of (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name < b.name ? -1 : 1)) {
|
|
1472
|
+
if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "dist" || entry.name === "build") continue;
|
|
1473
|
+
const full = path3.join(dir, entry.name);
|
|
1474
|
+
if (entry.isDirectory()) {
|
|
1475
|
+
await walk(full, depth + 1);
|
|
1476
|
+
continue;
|
|
1477
|
+
}
|
|
1478
|
+
if (!entry.isFile() || !SRC_EXT.has(path3.extname(entry.name))) continue;
|
|
1479
|
+
if ((await stat(full)).size > 1e6) continue;
|
|
1480
|
+
const text = await readFile(full, "utf8");
|
|
1481
|
+
for (const pattern of USAGE_PATTERNS) for (const match of text.matchAll(pattern)) if (!found.has(match[1])) found.set(match[1], full);
|
|
1482
|
+
}
|
|
1483
|
+
};
|
|
1484
|
+
await walk(root, 0);
|
|
1485
|
+
return found;
|
|
1486
|
+
}
|
|
1487
|
+
async function check(flags, io) {
|
|
1488
|
+
const limits = limitsOf(flags);
|
|
1489
|
+
const dir = path3.resolve(io.cwd, typeof flags.dir === "string" ? flags.dir : "catalogs");
|
|
1490
|
+
const loaded = (await loadFiles(await catalogFilesIn(dir), io)).filter((item) => item.parseError || isCatalogLike(item.raw));
|
|
1491
|
+
if (!loaded.length) throw new UsageError3(`no hay cat\xE1logos catalog@1 en ${path3.relative(io.cwd, dir) || "."}`);
|
|
1492
|
+
const failures = [];
|
|
1493
|
+
const invalid = [];
|
|
1494
|
+
const byNamespace = /* @__PURE__ */ new Map();
|
|
1495
|
+
const docsByNamespace = /* @__PURE__ */ new Map();
|
|
1496
|
+
for (const item of loaded) {
|
|
1497
|
+
if (item.parseError) {
|
|
1498
|
+
invalid.push({ file: item.display, path: "", message: `no es JSON: ${item.parseError}` });
|
|
1499
|
+
continue;
|
|
1500
|
+
}
|
|
1501
|
+
const checked = validateCatalog(item.raw, { limits });
|
|
1502
|
+
if (!checked.ok || !checked.doc) {
|
|
1503
|
+
for (const issue of checked.issues) invalid.push({ file: item.display, path: issue.path, message: issue.message });
|
|
1504
|
+
continue;
|
|
1505
|
+
}
|
|
1506
|
+
const doc = checked.doc;
|
|
1507
|
+
const locales = byNamespace.get(doc.namespace) ?? {};
|
|
1508
|
+
locales[doc.locale] = doc.messages;
|
|
1509
|
+
byNamespace.set(doc.namespace, locales);
|
|
1510
|
+
docsByNamespace.set(doc.namespace, { ...docsByNamespace.get(doc.namespace) ?? {}, [doc.locale]: doc });
|
|
1511
|
+
}
|
|
1512
|
+
for (const i of invalid) failures.push(`\u2717 ${i.file}${i.path ? ` ${i.path}` : ""}: ${i.message}`);
|
|
1513
|
+
const required2 = list(flags.locales);
|
|
1514
|
+
const parity = [];
|
|
1515
|
+
for (const [namespace, byLocale] of [...byNamespace.entries()].sort((a, b) => a[0] < b[0] ? -1 : 1)) {
|
|
1516
|
+
const present = Object.keys(byLocale).sort();
|
|
1517
|
+
const need = required2.length ? required2 : present;
|
|
1518
|
+
const base = typeof flags["base-locale"] === "string" ? flags["base-locale"] : need.includes("en") ? "en" : need[0];
|
|
1519
|
+
const report3 = parityReport(byLocale, need, base);
|
|
1520
|
+
parity.push({ namespace, locales: need, base, ok: report3.ok, missing: report3.missing, placeholderMismatch: report3.placeholderMismatch });
|
|
1521
|
+
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" : ""})`);
|
|
1522
|
+
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(", ")}}`);
|
|
1523
|
+
}
|
|
1524
|
+
const glossary = await loadGlossary(flags, io);
|
|
1525
|
+
const strict = flags.strict === true;
|
|
1526
|
+
const mismatched = new Set(parity.flatMap((p) => p.placeholderMismatch.map((m) => `${String(p.namespace)}\0${m.locale}\0${m.key}`)));
|
|
1527
|
+
const { checkCatalog } = await import('./quality-ILK6IA5O.mjs');
|
|
1528
|
+
const findings2 = [];
|
|
1529
|
+
const warnings = [];
|
|
1530
|
+
for (const p of parity) {
|
|
1531
|
+
const docs = docsByNamespace.get(String(p.namespace)) ?? {};
|
|
1532
|
+
const baseDoc = docs[String(p.base)];
|
|
1533
|
+
if (!baseDoc) continue;
|
|
1534
|
+
for (const locale of p.locales) {
|
|
1535
|
+
const target = docs[locale];
|
|
1536
|
+
if (!target || locale === p.base) continue;
|
|
1537
|
+
for (const f of checkCatalog(baseDoc, target, { glossary, severities: QUALITY_SEVERITIES })) {
|
|
1538
|
+
if (f.code === "missing-translation") continue;
|
|
1539
|
+
if ((f.code === "variables-missing" || f.code === "variables-extra") && mismatched.has(`${String(p.namespace)}\0${locale}\0${f.key}`)) continue;
|
|
1540
|
+
findings2.push(qualityRow(String(p.namespace), f));
|
|
1541
|
+
const failing = f.severity === "error" || strict && f.severity === "warning";
|
|
1542
|
+
if (failing) failures.push(findingLine(String(p.namespace), f, true));
|
|
1543
|
+
else if (f.severity === "warning") warnings.push(findingLine(String(p.namespace), f, false));
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
let usage = null;
|
|
1548
|
+
if (typeof flags.src === "string") {
|
|
1549
|
+
const src = path3.resolve(io.cwd, flags.src);
|
|
1550
|
+
let used;
|
|
1551
|
+
try {
|
|
1552
|
+
used = await usedKeys(src);
|
|
1553
|
+
} catch {
|
|
1554
|
+
throw new UsageError3(`no se pudo leer --src ${flags.src}`);
|
|
1555
|
+
}
|
|
1556
|
+
const defined = /* @__PURE__ */ new Set();
|
|
1557
|
+
for (const p of parity) for (const key2 of Object.keys((byNamespace.get(String(p.namespace)) ?? {})[String(p.base)] ?? {})) defined.add(key2);
|
|
1558
|
+
const missing = [...used.keys()].filter((key2) => !defined.has(key2)).sort();
|
|
1559
|
+
const unused = [...defined].filter((key2) => !used.has(key2)).sort();
|
|
1560
|
+
usage = { src: path3.relative(io.cwd, src) || ".", usedKeys: used.size, missing: missing.map((key2) => ({ key: key2, file: path3.relative(io.cwd, used.get(key2)) })), unused };
|
|
1561
|
+
for (const key2 of missing) failures.push(`\u2717 el c\xF3digo usa \xAB${key2}\xBB (${path3.relative(io.cwd, used.get(key2))}) y el cat\xE1logo no la define`);
|
|
1562
|
+
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`);
|
|
1563
|
+
}
|
|
1564
|
+
const ok = failures.length === 0;
|
|
1565
|
+
const lines = [...failures, ...warnings, ok ? `\u2713 ${loaded.length} ficheros, ${byNamespace.size} espacios de nombres: ICU v\xE1lido, paridad completa${usage ? `, ${String(usage.usedKeys)} claves del c\xF3digo cubiertas` : ""}` : `\u2717 check fall\xF3: ${failures.length} problemas`];
|
|
1566
|
+
if (usage && ok && Array.isArray(usage.unused) && usage.unused.length) lines.push(`# ${usage.unused.length} claves sin uso en ${String(usage.src)} (informativo; --fail-on-unused las trata como error)`);
|
|
1567
|
+
return { lines, result: { ok, files: loaded.length, invalid, parity, quality: { ...countRows(findings2), glossary: glossary.length, findings: findings2 }, usage }, code: ok ? 0 : EXPERIENCE_EXIT.invalid };
|
|
1568
|
+
}
|
|
1569
|
+
var QUALITY_SEVERITIES = { "plural-missing-category": "warning" };
|
|
1570
|
+
var qualityRow = (namespace, f) => ({ namespace, locale: f.locale ?? null, key: f.key ?? null, severity: f.severity, code: f.code, message: f.message, ...f.detail ? { detail: f.detail } : {} });
|
|
1571
|
+
var findingLine = (namespace, f, failing) => `${failing ? "\u2717" : "!"} ${namespace}/${f.locale ?? "?"}${f.key ? ` ${f.key}` : ""} [${f.code}]: ${f.message}`;
|
|
1572
|
+
var countRows = (rows) => ({ errors: rows.filter((r) => r.severity === "error").length, warnings: rows.filter((r) => r.severity === "warning").length, info: rows.filter((r) => r.severity === "info").length });
|
|
1573
|
+
async function loadGlossary(flags, io) {
|
|
1574
|
+
if (flags.glossary === void 0) return [];
|
|
1575
|
+
if (typeof flags.glossary !== "string") throw new UsageError3("--glossary necesita un fichero");
|
|
1576
|
+
let raw;
|
|
1577
|
+
try {
|
|
1578
|
+
raw = JSON.parse(await readFile(path3.resolve(io.cwd, flags.glossary), "utf8"));
|
|
1579
|
+
} catch (error) {
|
|
1580
|
+
throw new UsageError3(`--glossary: no se pudo leer ${flags.glossary} como JSON (${error instanceof Error ? error.message : String(error)})`);
|
|
1581
|
+
}
|
|
1582
|
+
const items = Array.isArray(raw) ? raw : isRec(raw) && Array.isArray(raw.glossary) ? raw.glossary : null;
|
|
1583
|
+
if (!items || items.length > 5e3) throw new UsageError3("--glossary: se espera un arreglo de entradas (m\xE1ximo 5000)");
|
|
1584
|
+
const strings = (value) => Array.isArray(value) && value.every((v) => typeof v === "string");
|
|
1585
|
+
return items.map((item, index) => {
|
|
1586
|
+
const bad = (why) => new UsageError3(`--glossary: la entrada ${index} ${why}`);
|
|
1587
|
+
if (!isRec(item) || typeof item.term !== "string" || !item.term) throw bad("necesita un \xABterm\xBB de texto");
|
|
1588
|
+
const entry = { term: item.term };
|
|
1589
|
+
if (item.translation !== void 0) {
|
|
1590
|
+
if (typeof item.translation !== "string" && !strings(item.translation)) throw bad("tiene un \xABtranslation\xBB que no es texto ni lista de textos");
|
|
1591
|
+
entry.translation = item.translation;
|
|
1592
|
+
}
|
|
1593
|
+
if (item.forbidden !== void 0) {
|
|
1594
|
+
if (!strings(item.forbidden)) throw bad("tiene un \xABforbidden\xBB que no es lista de textos");
|
|
1595
|
+
entry.forbidden = item.forbidden;
|
|
1596
|
+
}
|
|
1597
|
+
for (const flag of ["doNotTranslate", "caseSensitive", "wholeWord"]) {
|
|
1598
|
+
if (item[flag] !== void 0) {
|
|
1599
|
+
if (typeof item[flag] !== "boolean") throw bad(`tiene \xAB${flag}\xBB que no es booleano`);
|
|
1600
|
+
entry[flag] = item[flag];
|
|
1601
|
+
}
|
|
1602
|
+
}
|
|
1603
|
+
if (item.locale !== void 0) {
|
|
1604
|
+
if (typeof item.locale !== "string") throw bad("tiene un \xABlocale\xBB que no es texto");
|
|
1605
|
+
entry.locale = item.locale;
|
|
1606
|
+
}
|
|
1607
|
+
return entry;
|
|
1608
|
+
});
|
|
1609
|
+
}
|
|
1610
|
+
var EXTENSION = { xliff: ".xlf", po: ".po", json: ".flat.json" };
|
|
1611
|
+
var MAX_IMPORT_BYTES = 8 * 1024 * 1024;
|
|
1612
|
+
function toolsFailure(error, what) {
|
|
1613
|
+
if (error instanceof Error && error.name === "I18nToolsError") throw new ExitError(EXPERIENCE_EXIT.invalid, `${what}: ${error.code ?? "invalid"}: ${error.message}`);
|
|
1614
|
+
throw error;
|
|
1615
|
+
}
|
|
1616
|
+
function formatFlag(flags, allowAuto) {
|
|
1617
|
+
const value = flags.format;
|
|
1618
|
+
if (value === void 0) {
|
|
1619
|
+
if (allowAuto) return "auto";
|
|
1620
|
+
throw new UsageError3("--format xliff|po|json es obligatorio");
|
|
1621
|
+
}
|
|
1622
|
+
if (value === "xliff" || value === "po" || value === "json") return value;
|
|
1623
|
+
if (allowAuto && value === "auto") return "auto";
|
|
1624
|
+
throw new UsageError3(`--format debe ser ${allowAuto ? "auto, " : ""}xliff, po o json`);
|
|
1625
|
+
}
|
|
1626
|
+
function outputPath(out, io, fallbackDir, name, single) {
|
|
1627
|
+
if (out !== void 0 && typeof out !== "string") throw new UsageError3("--out necesita una ruta");
|
|
1628
|
+
if (out === void 0) return path3.resolve(io.cwd, fallbackDir, name);
|
|
1629
|
+
const resolved = path3.resolve(io.cwd, out);
|
|
1630
|
+
return single && /\.(xlf|xliff|po|pot|json)$/i.test(out) ? resolved : path3.join(resolved, name);
|
|
1631
|
+
}
|
|
1632
|
+
async function exportCmd(flags, io) {
|
|
1633
|
+
const format = formatFlag(flags, false);
|
|
1634
|
+
const client = makeClient(flags, io);
|
|
1635
|
+
const draft = flags.draft === true;
|
|
1636
|
+
const namespaces = list(flags.namespace);
|
|
1637
|
+
const wanted = list(flags.locale);
|
|
1638
|
+
const sourceLocale = typeof flags["source-locale"] === "string" ? flags["source-locale"] : "en";
|
|
1639
|
+
const artifacts = (await listCatalogArtifacts(client)).filter((a) => !namespaces.length || namespaces.includes(str2(a.name)));
|
|
1640
|
+
const byNamespace = /* @__PURE__ */ new Map();
|
|
1641
|
+
for (const a of artifacts) byNamespace.set(str2(a.name), (byNamespace.get(str2(a.name)) ?? /* @__PURE__ */ new Map()).set(str2(a.locale), a));
|
|
1642
|
+
for (const wantedNamespace of namespaces) if (!byNamespace.has(wantedNamespace)) throw new UsageError3(`no existe el espacio de nombres \xAB${wantedNamespace}\xBB en el servidor`);
|
|
1643
|
+
if (!byNamespace.size) throw new ExitError(EXPERIENCE_EXIT.invalid, "no hay cat\xE1logos en el servidor que exportar");
|
|
1644
|
+
const tools = {
|
|
1645
|
+
xliff: format === "xliff" ? await import('./xliff-DEJHB2SY.mjs') : null,
|
|
1646
|
+
po: format === "po" ? await import('./po-AKWHAYBL.mjs') : null,
|
|
1647
|
+
json: format === "json" ? await import('./json-NETFQXLJ.mjs') : null
|
|
1648
|
+
};
|
|
1649
|
+
const exported = [];
|
|
1650
|
+
const skipped = [];
|
|
1651
|
+
const jobs = [];
|
|
1652
|
+
for (const [namespace, locales] of [...byNamespace.entries()].sort((a, b) => a[0] < b[0] ? -1 : 1)) {
|
|
1653
|
+
const read2 = async (locale) => {
|
|
1654
|
+
const artifact = locales.get(locale);
|
|
1655
|
+
return artifact ? readArtifactDoc(client, str2(artifact.id), draft) : { skip: "no existe ese cat\xE1logo" };
|
|
1656
|
+
};
|
|
1657
|
+
const describe = (r) => draft ? `borrador v${r.draftVersion}` : `r${r.revision}`;
|
|
1658
|
+
if (format === "json") {
|
|
1659
|
+
for (const locale of wanted.length ? wanted : [...locales.keys()].sort()) {
|
|
1660
|
+
const r = await read2(locale);
|
|
1661
|
+
if ("skip" in r) {
|
|
1662
|
+
skipped.push({ namespace, locale, reason: r.skip });
|
|
1663
|
+
continue;
|
|
1664
|
+
}
|
|
1665
|
+
jobs.push({ namespace, locale, name: `${namespace}.${locale}${EXTENSION.json}`, content: tools.json.stringifyFlatJson(r.doc.messages), keys: Object.keys(r.doc.messages).length, from: describe(r) });
|
|
1666
|
+
}
|
|
1667
|
+
continue;
|
|
1668
|
+
}
|
|
1669
|
+
const source = await read2(sourceLocale);
|
|
1670
|
+
if ("skip" in source) {
|
|
1671
|
+
skipped.push({ namespace, locale: sourceLocale, reason: `idioma de origen: ${source.skip}${source.skip === "no existe ese cat\xE1logo" ? " (usa --source-locale)" : ""}` });
|
|
1672
|
+
continue;
|
|
1673
|
+
}
|
|
1674
|
+
const targets = (wanted.length ? wanted : [...locales.keys()].sort()).filter((locale) => locale !== sourceLocale);
|
|
1675
|
+
if (!targets.length) {
|
|
1676
|
+
skipped.push({ namespace, locale: null, reason: "sin idioma de destino (usa --locale)" });
|
|
1677
|
+
continue;
|
|
1678
|
+
}
|
|
1679
|
+
for (const locale of targets) {
|
|
1680
|
+
const t = locales.has(locale) ? await read2(locale) : null;
|
|
1681
|
+
if (t && "skip" in t) {
|
|
1682
|
+
skipped.push({ namespace, locale, reason: t.skip });
|
|
1683
|
+
continue;
|
|
1684
|
+
}
|
|
1685
|
+
try {
|
|
1686
|
+
const base = format === "xliff" ? { name: `${namespace}.${sourceLocale}-${locale}${EXTENSION.xliff}`, content: tools.xliff.exportXliff({ source: source.doc, ...t ? { target: t.doc } : { targetLocale: locale } }) } : { name: `${namespace}.${locale}${EXTENSION.po}`, content: tools.po.stringifyPo(tools.po.catalogToPo({ source: source.doc, ...t ? { target: t.doc } : { targetLocale: locale } })) };
|
|
1687
|
+
jobs.push({ namespace, locale, ...base, keys: Object.keys(source.doc.messages).length, from: `${describe(source)}${t ? `, destino ${describe(t)}` : ", sin destino (plantilla)"}` });
|
|
1688
|
+
} catch (error) {
|
|
1689
|
+
toolsFailure(error, `${namespace}/${locale}`);
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
}
|
|
1693
|
+
if (!jobs.length) throw new ExitError(EXPERIENCE_EXIT.invalid, `no se export\xF3 nada: ${skipped.map((s) => `${s.namespace}/${s.locale ?? "-"}: ${s.reason}`).join("; ") || "sin cat\xE1logos"}`);
|
|
1694
|
+
const lines = [];
|
|
1695
|
+
for (const job of jobs) {
|
|
1696
|
+
const file = outputPath(flags.out, io, "translations", job.name, jobs.length === 1);
|
|
1697
|
+
await mkdir(path3.dirname(file), { recursive: true });
|
|
1698
|
+
await writeFile(file, job.content);
|
|
1699
|
+
const shown = path3.relative(io.cwd, file) || file;
|
|
1700
|
+
exported.push({ namespace: job.namespace, locale: job.locale, format, file: shown, keys: job.keys, source: draft ? "draft" : "published", from: job.from });
|
|
1701
|
+
lines.push(`\u2713 ${shown} (${job.namespace}/${job.locale}, ${job.keys} claves, ${job.from})`);
|
|
1702
|
+
}
|
|
1703
|
+
for (const s of skipped) lines.push(`- ${s.namespace}/${s.locale ?? "-"}: ${s.reason}`);
|
|
1704
|
+
lines.push(`${exported.length} exportados, ${skipped.length} omitidos`);
|
|
1705
|
+
return { lines, result: { format, exported, skipped } };
|
|
1706
|
+
}
|
|
1707
|
+
function detectFormat(flag, file, text) {
|
|
1708
|
+
if (flag !== "auto") return flag;
|
|
1709
|
+
const ext = path3.extname(file).toLowerCase();
|
|
1710
|
+
if (ext === ".xlf" || ext === ".xliff") return "xliff";
|
|
1711
|
+
if (ext === ".po" || ext === ".pot") return "po";
|
|
1712
|
+
if (ext === ".json") return "json";
|
|
1713
|
+
const head = text.replace(/^/, "").trimStart();
|
|
1714
|
+
if (head.startsWith("<")) return "xliff";
|
|
1715
|
+
if (head.startsWith("{")) return "json";
|
|
1716
|
+
if (/^(#|msgid|msgctxt)/m.test(head)) return "po";
|
|
1717
|
+
throw new UsageError3("no se pudo deducir el formato de la extensi\xF3n ni del contenido: usa --format xliff|po|json");
|
|
1718
|
+
}
|
|
1719
|
+
var singleLocale = (flags, name) => {
|
|
1720
|
+
const value = flags[name];
|
|
1721
|
+
if (value === void 0) return void 0;
|
|
1722
|
+
if (typeof value !== "string" || value.includes(",")) throw new UsageError3(`--${name} admite un solo valor aqu\xED`);
|
|
1723
|
+
return value;
|
|
1724
|
+
};
|
|
1725
|
+
async function importCmd(positional, flags, io) {
|
|
1726
|
+
if (positional.length !== 1) throw new UsageError3("uso: customy experience import <fichero> [--format auto|xliff|po|json] \u2026");
|
|
1727
|
+
const formatChoice = formatFlag(flags, true);
|
|
1728
|
+
const limits = limitsOf(flags);
|
|
1729
|
+
checkAckFlags(flags);
|
|
1730
|
+
const namespaceFlag = singleLocale(flags, "namespace");
|
|
1731
|
+
const localeFlag = singleLocale(flags, "locale");
|
|
1732
|
+
const sourceLocaleFlag = singleLocale(flags, "source-locale");
|
|
1733
|
+
const glossary = await loadGlossary(flags, io);
|
|
1734
|
+
const dir = path3.resolve(io.cwd, typeof flags.dir === "string" ? flags.dir : "catalogs");
|
|
1735
|
+
const file = path3.resolve(io.cwd, positional[0]);
|
|
1736
|
+
const display = path3.relative(io.cwd, file) || file;
|
|
1737
|
+
let size;
|
|
1738
|
+
try {
|
|
1739
|
+
const info = await stat(file);
|
|
1740
|
+
if (!info.isFile()) throw new Error("no es un fichero");
|
|
1741
|
+
size = info.size;
|
|
1742
|
+
} catch {
|
|
1743
|
+
throw new UsageError3(`no se pudo leer ${display}`);
|
|
1744
|
+
}
|
|
1745
|
+
if (size > MAX_IMPORT_BYTES) throw new ExitError(EXPERIENCE_EXIT.invalid, `${display}: ${size} bytes; el tope de importaci\xF3n es ${MAX_IMPORT_BYTES}`);
|
|
1746
|
+
const bytes = await readFile(file);
|
|
1747
|
+
let text;
|
|
1748
|
+
try {
|
|
1749
|
+
text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
1750
|
+
} catch {
|
|
1751
|
+
throw new ExitError(EXPERIENCE_EXIT.invalid, `${display}: no es UTF-8 v\xE1lido`);
|
|
1752
|
+
}
|
|
1753
|
+
const format = detectFormat(formatChoice, file, text);
|
|
1754
|
+
let source;
|
|
1755
|
+
let target;
|
|
1756
|
+
try {
|
|
1757
|
+
if (format === "xliff") {
|
|
1758
|
+
const t = await import('./xliff-DEJHB2SY.mjs');
|
|
1759
|
+
({ source, target } = t.xliffToCatalogs(t.importXliff(bytes, namespaceFlag ? { namespace: namespaceFlag } : {})));
|
|
1760
|
+
} else if (format === "po") {
|
|
1761
|
+
const t = await import('./po-AKWHAYBL.mjs');
|
|
1762
|
+
({ source, target } = t.poToCatalogs(t.parsePo(text), { ...namespaceFlag ? { namespace: namespaceFlag } : {}, ...sourceLocaleFlag ? { sourceLocale: sourceLocaleFlag } : {}, ...localeFlag ? { targetLocale: localeFlag } : {} }));
|
|
1763
|
+
} else {
|
|
1764
|
+
let parsed;
|
|
1765
|
+
try {
|
|
1766
|
+
parsed = JSON.parse(text.replace(/^/, ""));
|
|
1767
|
+
} catch {
|
|
1768
|
+
parsed = void 0;
|
|
1769
|
+
}
|
|
1770
|
+
if (isCatalogLike(parsed)) {
|
|
1771
|
+
const checked2 = validateCatalog(parsed, { limits });
|
|
1772
|
+
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"));
|
|
1773
|
+
source = null;
|
|
1774
|
+
target = checked2.doc;
|
|
1775
|
+
} else {
|
|
1776
|
+
const t = await import('./json-NETFQXLJ.mjs');
|
|
1777
|
+
const flat = t.parseFlatJson(text);
|
|
1778
|
+
const named = path3.basename(file).match(/^([a-z][a-z0-9-]{1,31})\.([a-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,2})(?:\.flat)?\.json$/);
|
|
1779
|
+
const namespace = namespaceFlag ?? named?.[1];
|
|
1780
|
+
const locale = localeFlag ?? named?.[2];
|
|
1781
|
+
if (!namespace || !locale) throw new UsageError3("un JSON plano necesita --namespace y --locale (o un nombre \xAB<espacio>.<idioma>.json\xBB)");
|
|
1782
|
+
source = null;
|
|
1783
|
+
target = { version: "catalog@1", namespace, locale, syntax: "icu1", messages: flat.messages };
|
|
1784
|
+
}
|
|
1785
|
+
}
|
|
1786
|
+
} catch (error) {
|
|
1787
|
+
if (error instanceof ExitError || error instanceof UsageError3) throw error;
|
|
1788
|
+
return toolsFailure(error, display);
|
|
1789
|
+
}
|
|
1790
|
+
if (!target) throw new ExitError(EXPERIENCE_EXIT.invalid, `${display}: no declara idioma de destino (usa --locale)`);
|
|
1791
|
+
if (namespaceFlag && target.namespace !== namespaceFlag) target = { ...target, namespace: namespaceFlag };
|
|
1792
|
+
if (localeFlag && target.locale !== localeFlag) target = { ...target, locale: localeFlag };
|
|
1793
|
+
if (source && namespaceFlag && source.namespace !== namespaceFlag) source = { ...source, namespace: namespaceFlag };
|
|
1794
|
+
if (!Object.keys(target.messages).length) throw new ExitError(EXPERIENCE_EXIT.invalid, `${display}: no trae ninguna traducci\xF3n`);
|
|
1795
|
+
const checked = validateCatalog(target, { limits });
|
|
1796
|
+
if (!checked.ok || !checked.doc) {
|
|
1797
|
+
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"));
|
|
1798
|
+
}
|
|
1799
|
+
const doc = checked.doc;
|
|
1800
|
+
if (!source && format === "json") {
|
|
1801
|
+
const localSource = path3.join(dir, fileName(doc.namespace, sourceLocaleFlag ?? "en"));
|
|
1802
|
+
try {
|
|
1803
|
+
const candidate = validateCatalog(JSON.parse(await readFile(localSource, "utf8")), { limits: TRANSLATION_PLAN_LIMITS.enterprise });
|
|
1804
|
+
if (candidate.ok && candidate.doc && candidate.doc.locale !== doc.locale) source = candidate.doc;
|
|
1805
|
+
} catch {
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
const findings2 = [];
|
|
1809
|
+
const noteLines = [];
|
|
1810
|
+
if (source) {
|
|
1811
|
+
const { checkCatalog } = await import('./quality-ILK6IA5O.mjs');
|
|
1812
|
+
for (const f of checkCatalog(source, doc, { glossary, severities: QUALITY_SEVERITIES })) findings2.push(qualityRow(doc.namespace, f));
|
|
1813
|
+
const strictFail = flags.strict === true;
|
|
1814
|
+
const failing = (row) => row.severity === "error" || strictFail && row.severity === "warning";
|
|
1815
|
+
const asFinding = (row) => ({ severity: row.severity, code: row.code, message: row.message, ...row.key ? { key: row.key } : {}, ...row.locale ? { locale: row.locale } : {} });
|
|
1816
|
+
const shown = findings2.filter((row) => row.severity !== "info");
|
|
1817
|
+
if (strictFail && shown.some(failing)) {
|
|
1818
|
+
throw new ExitError(EXPERIENCE_EXIT.invalid, [`--strict: la calidad no pasa; no se envi\xF3 nada:`, ...shown.map((row) => findingLine(row.namespace, asFinding(row), failing(row)))].join("\n"));
|
|
1819
|
+
}
|
|
1820
|
+
for (const row of shown) noteLines.push(findingLine(row.namespace, asFinding(row), false));
|
|
1821
|
+
} else noteLines.push(`! sin cat\xE1logo de origen para ${doc.namespace}: no se hicieron comprobaciones de calidad`);
|
|
1822
|
+
const summary = { format, file: display, namespace: doc.namespace, locale: doc.locale, sourceLocale: source?.locale ?? null, keys: Object.keys(doc.messages).length, quality: { ...countRows(findings2), glossary: glossary.length, strict: flags.strict === true, findings: findings2 } };
|
|
1823
|
+
const header = `\u2713 ${display}: ${format}, ${doc.namespace}/${doc.locale}, ${summary.keys} claves (v\xE1lido; ${summary.quality.errors} errores, ${summary.quality.warnings} avisos de calidad)`;
|
|
1824
|
+
if (flags["dry-run"]) return { lines: [header, ...noteLines, "dry-run: no se envi\xF3 nada"], result: { dryRun: true, ...summary } };
|
|
1825
|
+
try {
|
|
1826
|
+
const uploaded = await uploadDocs([{ display, doc }], flags, io, dir);
|
|
1827
|
+
return { lines: [header, ...noteLines, ...uploaded.lines], result: { ...summary, ...isRec(uploaded.result) ? uploaded.result : {} } };
|
|
1828
|
+
} catch (error) {
|
|
1829
|
+
if (error instanceof ExitError) throw new ExitError(error.code, [header, ...noteLines, error.message].join("\n"));
|
|
1830
|
+
throw error;
|
|
1831
|
+
}
|
|
1832
|
+
}
|
|
1833
|
+
async function pseudoCmd(positional, flags, io) {
|
|
1834
|
+
const locale = singleLocale(flags, "locale");
|
|
1835
|
+
if (!locale) throw new UsageError3("falta --locale xx (el idioma de la pseudo-localizaci\xF3n)");
|
|
1836
|
+
const sourceLocale = singleLocale(flags, "source-locale") ?? "en";
|
|
1837
|
+
if (locale === sourceLocale) throw new UsageError3("--locale no puede ser el idioma de origen");
|
|
1838
|
+
const limits = limitsOf(flags);
|
|
1839
|
+
const namespaces = list(flags.namespace);
|
|
1840
|
+
const dir = path3.resolve(io.cwd, typeof flags.dir === "string" ? flags.dir : "catalogs");
|
|
1841
|
+
const files = positional.length ? positional.map((p) => path3.resolve(io.cwd, p)) : await catalogFilesIn(dir);
|
|
1842
|
+
const loaded = (await loadFiles(files, io)).filter((item) => positional.length || item.parseError || isCatalogLike(item.raw));
|
|
1843
|
+
const sources = [];
|
|
1844
|
+
const problems = [];
|
|
1845
|
+
for (const item of loaded) {
|
|
1846
|
+
if (item.parseError) {
|
|
1847
|
+
problems.push(` ${item.display}: no es JSON: ${item.parseError}`);
|
|
1848
|
+
continue;
|
|
1849
|
+
}
|
|
1850
|
+
if (!isRec(item.raw) || item.raw.locale !== sourceLocale) {
|
|
1851
|
+
if (positional.length) problems.push(` ${item.display}: no es un cat\xE1logo del idioma de origen ${sourceLocale}`);
|
|
1852
|
+
continue;
|
|
1853
|
+
}
|
|
1854
|
+
const checked = validateCatalog(item.raw, { limits });
|
|
1855
|
+
if (!checked.ok || !checked.doc) {
|
|
1856
|
+
problems.push(...checked.issues.map((i) => ` ${item.display}${i.path ? ` ${i.path}` : ""}: ${i.message}`));
|
|
1857
|
+
continue;
|
|
1858
|
+
}
|
|
1859
|
+
if (!namespaces.length || namespaces.includes(checked.doc.namespace)) sources.push({ display: item.display, doc: checked.doc });
|
|
1860
|
+
}
|
|
1861
|
+
if (problems.length) throw new ExitError(EXPERIENCE_EXIT.invalid, ["cat\xE1logo de origen no v\xE1lido; no se escribi\xF3 nada:", ...problems].join("\n"));
|
|
1862
|
+
if (!sources.length) throw new UsageError3(`no hay cat\xE1logos de origen \xAB${sourceLocale}\xBB en ${path3.relative(io.cwd, dir) || "."}`);
|
|
1863
|
+
const { pseudoLocalizeMessages } = await import('./pseudo-CKYMJJBX.mjs');
|
|
1864
|
+
const outputs = [];
|
|
1865
|
+
for (const { display, doc } of sources) {
|
|
1866
|
+
if (doc.syntax !== "icu1") {
|
|
1867
|
+
problems.push(` ${display}: la sintaxis ${doc.syntax} no se pseudo-localiza (solo icu1)`);
|
|
1868
|
+
continue;
|
|
1869
|
+
}
|
|
1870
|
+
const out = { version: doc.version, namespace: doc.namespace, locale, syntax: doc.syntax, messages: pseudoLocalizeMessages(doc.messages, { strategy: flags.rtl ? "rtl" : "accented" }) };
|
|
1871
|
+
const checked = validateCatalog(out, { limits });
|
|
1872
|
+
if (!checked.ok || !checked.doc) {
|
|
1873
|
+
problems.push(...checked.issues.map((i) => ` ${doc.namespace}/${locale}${i.path ? ` ${i.path}` : ""}: ${i.message}`));
|
|
1874
|
+
continue;
|
|
1875
|
+
}
|
|
1876
|
+
outputs.push({ doc: checked.doc, from: display });
|
|
1877
|
+
}
|
|
1878
|
+
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"));
|
|
1879
|
+
const fallbackDir = positional.length ? path3.dirname(files[0]) : dir;
|
|
1880
|
+
const written = [];
|
|
1881
|
+
const lines = [];
|
|
1882
|
+
for (const { doc, from } of outputs) {
|
|
1883
|
+
const target = outputPath(flags.out, io, path3.relative(io.cwd, fallbackDir) || ".", fileName(doc.namespace, locale), outputs.length === 1);
|
|
1884
|
+
await mkdir(path3.dirname(target), { recursive: true });
|
|
1885
|
+
await writeFile(target, serializeCatalog(doc));
|
|
1886
|
+
const shown = path3.relative(io.cwd, target) || target;
|
|
1887
|
+
written.push({ namespace: doc.namespace, locale, strategy: flags.rtl ? "rtl" : "accented", file: shown, from, keys: Object.keys(doc.messages).length });
|
|
1888
|
+
lines.push(`\u2713 ${shown} (${doc.namespace}/${locale}, ${Object.keys(doc.messages).length} claves, desde ${from})`);
|
|
1889
|
+
}
|
|
1890
|
+
lines.push(`${written.length} cat\xE1logos pseudo-localizados (${flags.rtl ? "rtl" : "acentuado"}), sin red`);
|
|
1891
|
+
return { lines, result: { locale, sourceLocale, strategy: flags.rtl ? "rtl" : "accented", written } };
|
|
1892
|
+
}
|
|
1893
|
+
var RELEASE_CHANNEL_NAMES = ["production", "staging", "preview", "beta"];
|
|
1894
|
+
var CONFIG_FILE = "customy.experience.json";
|
|
1895
|
+
function channelFlag(flags, fallback) {
|
|
1896
|
+
const value = flags.channel;
|
|
1897
|
+
if (value === void 0) {
|
|
1898
|
+
return fallback;
|
|
1899
|
+
}
|
|
1900
|
+
if (typeof value !== "string" || !RELEASE_CHANNEL_NAMES.includes(value)) throw new UsageError3(`--channel debe ser ${RELEASE_CHANNEL_NAMES.join(", ")}`);
|
|
1901
|
+
return value;
|
|
1902
|
+
}
|
|
1903
|
+
function reasonFlag(flags) {
|
|
1904
|
+
const reason = typeof flags.reason === "string" ? flags.reason.trim() : "";
|
|
1905
|
+
if (reason.length < 3) throw new UsageError3('--reason "\u2026" es obligatorio (3 caracteres o m\xE1s): queda en la auditor\xEDa');
|
|
1906
|
+
if (reason.length > 500) throw new UsageError3("--reason admite como m\xE1ximo 500 caracteres");
|
|
1907
|
+
return reason;
|
|
1908
|
+
}
|
|
1909
|
+
async function resolveRelease(client, ref) {
|
|
1910
|
+
const numeric = ref.match(/^#?(\d+)$/);
|
|
1911
|
+
if (!numeric) return { id: ref, number: null };
|
|
1912
|
+
const wanted = Number(numeric[1]);
|
|
1913
|
+
let before;
|
|
1914
|
+
for (let page = 0; page < 50; page += 1) {
|
|
1915
|
+
const result = await client.request("GET", "/releases", { query: { limit: "200", ...before ? { before } : {} } });
|
|
1916
|
+
const data = isRec(result) && Array.isArray(result.data) ? result.data.filter(isRec) : [];
|
|
1917
|
+
const hit = data.find((r) => r.number === wanted);
|
|
1918
|
+
if (hit) return { id: str2(hit.id), number: wanted };
|
|
1919
|
+
const next = isRec(result) ? result.next : null;
|
|
1920
|
+
if (next === null || next === void 0 || !data.length) break;
|
|
1921
|
+
before = String(next);
|
|
1922
|
+
}
|
|
1923
|
+
throw new ExitError(EXPERIENCE_EXIT.auth, `no existe el release #${wanted} (o no tienes permiso para verlo; el servicio responde igual en ambos casos)`);
|
|
1924
|
+
}
|
|
1925
|
+
var rolesOf = (key2) => Array.isArray(key2.roles) ? key2.roles.filter((r) => typeof r === "string") : [];
|
|
1926
|
+
async function initCmd(flags, io) {
|
|
1927
|
+
const client = makeClient(flags, io);
|
|
1928
|
+
const channel = channelFlag(flags, "production");
|
|
1929
|
+
const out = path3.resolve(io.cwd, typeof flags.out === "string" ? flags.out : CONFIG_FILE);
|
|
1930
|
+
const shown = path3.relative(io.cwd, out) || out;
|
|
1931
|
+
if (!flags.force) {
|
|
1932
|
+
let exists = true;
|
|
1933
|
+
try {
|
|
1934
|
+
await stat(out);
|
|
1935
|
+
} catch {
|
|
1936
|
+
exists = false;
|
|
1937
|
+
}
|
|
1938
|
+
if (exists) throw new UsageError3(`${shown} ya existe: usa --force para sobrescribirlo`);
|
|
1939
|
+
}
|
|
1940
|
+
const context3 = await client.request("GET", "/context");
|
|
1941
|
+
const info = scopeFrom(context3);
|
|
1942
|
+
if (!info) throw new ExitError(EXPERIENCE_EXIT.failure, "GET /context no devolvi\xF3 el \xE1mbito de entrega (\xBFel BFF o el servicio son anteriores a manifest@2?)");
|
|
1943
|
+
if (!info.delivery.base) throw new ExitError(EXPERIENCE_EXIT.failure, "el servicio no tiene EXPERIENCE_PUBLIC_BASE_URL configurada: no hay `base` que escribir en la configuraci\xF3n");
|
|
1944
|
+
const keys = isRec(context3) && Array.isArray(context3.keys) ? context3.keys.filter(isRec) : [];
|
|
1945
|
+
if (!keys.length) throw new ExitError(EXPERIENCE_EXIT.auth, "GET /context no trajo las claves de firma p\xFAblicas: solo las ve quien tiene experience.release.publish");
|
|
1946
|
+
const anchorProblem = keys.length < 2 ? "se necesitan al menos 2 claves ancladas" : !keys.some((k) => rolesOf(k).includes("manifest")) ? "ninguna clave tiene el rol manifest" : !keys.some((k) => rolesOf(k).includes("timestamp")) ? "ninguna clave tiene el rol timestamp" : null;
|
|
1947
|
+
if (anchorProblem) throw new ExitError(EXPERIENCE_EXIT.failure, `las claves publicadas no sirven de anclas: ${anchorProblem}. Configura la clave siguiente del servicio (runbook \xA74) antes de generar la configuraci\xF3n de una app.`);
|
|
1948
|
+
const channelsResult = await client.request("GET", "/channels");
|
|
1949
|
+
const row = (isRec(channelsResult) && Array.isArray(channelsResult.data) ? channelsResult.data.filter(isRec) : []).find((c) => c.channel === channel);
|
|
1950
|
+
const floor = row && typeof row.releaseId === "string" && typeof row.lastPointerSequence === "number" && row.lastPointerSequence >= 1 && typeof row.minSequence === "number" ? { sequence: row.lastPointerSequence, minSequence: row.minSequence } : null;
|
|
1951
|
+
const tenant = isRec(context3) && isRec(context3.tenant) ? context3.tenant : {};
|
|
1952
|
+
const environmentId = typeof tenant.environmentId === "string" ? tenant.environmentId : null;
|
|
1953
|
+
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 };
|
|
1954
|
+
await mkdir(path3.dirname(out), { recursive: true });
|
|
1955
|
+
await writeFile(out, `${JSON.stringify(config, null, 2)}
|
|
1956
|
+
`);
|
|
1957
|
+
const lines = [
|
|
1958
|
+
`\u2713 ${shown}: \xE1mbito ${info.key} (${info.status}, generaci\xF3n ${info.generation}), canal ${channel}, ${keys.length} anclas con roles`,
|
|
1959
|
+
floor ? ` piso: sequence ${floor.sequence}, minSequence ${floor.minSequence}` : ` sin piso: el canal ${channel} a\xFAn no tiene release publicado (el primer contacto ser\xE1 TOFU; vuelve a ejecutar init tras publicar)`,
|
|
1960
|
+
...environmentId ? [] : ["! el contexto no trajo environmentId: compl\xE9talo a mano en la configuraci\xF3n"],
|
|
1961
|
+
...info.draining ? [`! el \xE1mbito ${info.draining.key} drena hasta ${info.draining.drainsUntil ?? "?"}: las apps que lo usen migran solas por successor; las nuevas deben usar ${info.key}`] : []
|
|
1962
|
+
];
|
|
1963
|
+
return { lines, result: { file: shown, scope: info.key, scopeStatus: info.status, generation: info.generation, channel, anchors: keys.length, floor } };
|
|
1964
|
+
}
|
|
1965
|
+
async function revokeCmd(positional, flags, io) {
|
|
1966
|
+
if (positional.length !== 1) throw new UsageError3('uso: customy experience revoke <release|#n\xFAmero> --reason "\u2026" [--fallback <release|#n\xFAmero>] [--dry-run]');
|
|
1967
|
+
const reason = reasonFlag(flags);
|
|
1968
|
+
if (flags.fallback !== void 0 && typeof flags.fallback !== "string") throw new UsageError3("--fallback necesita un release");
|
|
1969
|
+
const client = makeClient(flags, io);
|
|
1970
|
+
const target = await resolveRelease(client, positional[0]);
|
|
1971
|
+
const fallback = typeof flags.fallback === "string" ? await resolveRelease(client, flags.fallback) : null;
|
|
1972
|
+
if (fallback && fallback.id === target.id) throw new UsageError3("--fallback no puede ser el release que se revoca");
|
|
1973
|
+
const label = `release ${target.number !== null ? `#${target.number} ` : ""}${target.id}`;
|
|
1974
|
+
if (flags["dry-run"]) return { lines: [`dry-run: se revocar\xEDa el ${label}${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 } };
|
|
1975
|
+
const result = await client.request("POST", `/releases/${encodeURIComponent(target.id)}/revoke`, { body: { reason, ...fallback ? { fallbackReleaseId: fallback.id } : {} } });
|
|
1976
|
+
const rec = isRec(result) ? result : {};
|
|
1977
|
+
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 }));
|
|
1978
|
+
const already = rec.alreadyRevoked === true;
|
|
1979
|
+
const lines = [
|
|
1980
|
+
already ? `= ${label}: ya estaba revocado` : `\u2713 ${label}: revocado`,
|
|
1981
|
+
...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)`),
|
|
1982
|
+
...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)."] : []
|
|
1983
|
+
];
|
|
1984
|
+
return { lines, result: { releaseId: target.id, releaseNumber: target.number, alreadyRevoked: already, repointed } };
|
|
1985
|
+
}
|
|
1986
|
+
async function scopeCmd(positional, flags, io) {
|
|
1987
|
+
const [sub, ...extra] = positional;
|
|
1988
|
+
if (!sub || extra.length) throw new UsageError3('uso: customy experience scope show | rotate --reason "\u2026" | retire [--force]');
|
|
1989
|
+
if (sub === "show") {
|
|
1990
|
+
const client = makeClient(flags, io);
|
|
1991
|
+
const info = scopeFrom(await client.request("GET", "/scope"));
|
|
1992
|
+
if (!info) throw new ExitError(EXPERIENCE_EXIT.failure, "GET /scope no devolvi\xF3 un \xE1mbito v\xE1lido");
|
|
1993
|
+
return { lines: [...scopeLines(info), ...info.delivery.channels.map((c) => ` ${c.channel} ${c.timestampUrl ?? "(sin base p\xFAblica)"}`)], result: { scope: info } };
|
|
1994
|
+
}
|
|
1995
|
+
if (sub === "rotate") {
|
|
1996
|
+
const reason = reasonFlag(flags);
|
|
1997
|
+
const client = makeClient(flags, io);
|
|
1998
|
+
const rec = await client.request("POST", "/scope/rotate", { body: { reason } });
|
|
1999
|
+
const data = isRec(rec) ? rec : {};
|
|
2000
|
+
const active = scopeFrom({ scope: data.scope });
|
|
2001
|
+
const draining = scopeFrom({ scope: data.draining });
|
|
2002
|
+
const republished = (Array.isArray(data.republished) ? data.republished.filter(isRec) : []).map((r) => ({ channel: str2(r.channel), sequence: typeof r.sequence === "number" ? r.sequence : null }));
|
|
2003
|
+
const failed = (Array.isArray(data.failed) ? data.failed.filter(isRec) : []).map((r) => ({ channel: str2(r.channel), code: str2(r.code, "error") }));
|
|
2004
|
+
const lines = [
|
|
2005
|
+
`\u2713 \xE1mbito rotado: nuevo ${active?.key ?? "?"} (generaci\xF3n ${active?.generation ?? "?"}); ${draining?.key ?? "?"} drena hasta ${draining?.drainsUntil ?? "?"}`,
|
|
2006
|
+
...republished.map((r) => ` ${r.channel}: publicado en los dos \xE1mbitos (sequence ${r.sequence ?? "?"})`),
|
|
2007
|
+
...failed.map((r) => `\u2717 ${r.channel}: no se republic\xF3 (${r.code}); recup\xE9ralo moviendo el canal al mismo release`),
|
|
2008
|
+
" Las apps ya instaladas migran solas por successor; las nuevas deben usar el \xE1mbito nuevo (customy experience init --force). Retira el viejo con \xABcustomy experience scope retire\xBB cuando drene."
|
|
2009
|
+
];
|
|
2010
|
+
return { lines, result: { scope: active, draining, republished, failed }, code: failed.length ? EXPERIENCE_EXIT.failure : EXPERIENCE_EXIT.ok };
|
|
2011
|
+
}
|
|
2012
|
+
if (sub === "retire") {
|
|
2013
|
+
const client = makeClient(flags, io);
|
|
2014
|
+
const rec = await client.request("POST", "/scope/retire", { body: flags.force ? { force: true } : {} });
|
|
2015
|
+
const retired = scopeFrom({ scope: isRec(rec) ? rec.retired : void 0 });
|
|
2016
|
+
return { lines: [`\u2713 \xE1mbito ${retired?.key ?? "?"} retirado: se dej\xF3 de escribir en \xE9l. Borrar sus objetos (t/<\xE1mbito>/\u2026, a/<\xE1mbito>/\u2026) y purgar la CDN es una operaci\xF3n de almac\xE9n aparte (runbook \xA75.4).`], result: { retired } };
|
|
2017
|
+
}
|
|
2018
|
+
throw new UsageError3(`subcomando desconocido: customy experience scope ${sub} (show|rotate|retire)`);
|
|
2019
|
+
}
|
|
2020
|
+
async function signingCmd(positional, flags, io) {
|
|
2021
|
+
const [sub, ...extra] = positional;
|
|
2022
|
+
if (sub === "rotate" && !extra.length) {
|
|
2023
|
+
const reason = reasonFlag(flags);
|
|
2024
|
+
const client2 = makeClient(flags, io);
|
|
2025
|
+
const retire2 = list(flags.retire), compromised2 = list(flags.compromised);
|
|
2026
|
+
const plan2 = await client2.request("POST", "/signing/rotation/plan", { body: { retire: retire2, compromised: compromised2 } });
|
|
2027
|
+
const done = await client2.request("POST", "/signing/rotation/step", { body: { keys: isRec(plan2) ? plan2.next : [], compromised: compromised2, windowElapsed: flags["window-elapsed"] === true, reason } });
|
|
2028
|
+
const d = isRec(done) ? done : {};
|
|
2029
|
+
if (!d.complete) throw new ExitError(EXPERIENCE_EXIT.failure, "repite el comando");
|
|
2030
|
+
return { lines: ["\u2713 paso"], result: d };
|
|
2031
|
+
}
|
|
2032
|
+
if (sub !== "plan" || extra.length) throw new UsageError3("uso: customy experience signing plan [--retire id,id] [--threshold n] [--compromised id,id]");
|
|
2033
|
+
const threshold = typeof flags.threshold === "string" ? Number(flags.threshold) : void 0;
|
|
2034
|
+
if (threshold !== void 0 && (!Number.isInteger(threshold) || threshold < 1 || threshold > 8)) throw new UsageError3("--threshold debe ser un entero entre 1 y 8");
|
|
2035
|
+
const retire = list(flags.retire);
|
|
2036
|
+
const compromised = list(flags.compromised);
|
|
2037
|
+
const client = makeClient(flags, io);
|
|
2038
|
+
const rec = await client.request("POST", "/signing/rotation/plan", { body: { ...retire.length ? { retire } : {}, ...compromised.length ? { compromised } : {}, ...threshold !== void 0 ? { threshold } : {} } });
|
|
2039
|
+
const data = isRec(rec) ? rec : {};
|
|
2040
|
+
const keyIds = (value) => Array.isArray(value) ? value.filter(isRec).map((k) => str2(k.keyId)) : [];
|
|
2041
|
+
const steps = (Array.isArray(data.steps) ? data.steps.filter(isRec) : []).map((step) => ({ action: str2(step.action), description: str2(step.description), signWith: Array.isArray(step.signWith) ? step.signWith.map(String) : [], available: Array.isArray(step.available) ? step.available.map(String) : [], missing: Array.isArray(step.missing) ? step.missing.map(String) : [] }));
|
|
2042
|
+
const windowDays = typeof data.windowMs === "number" ? Math.round(data.windowMs / 864e5) : null;
|
|
2043
|
+
const lines = [
|
|
2044
|
+
`Claves vigentes: ${keyIds(data.current).join(", ") || "-"} \u2192 siguientes: ${keyIds(data.next).join(", ") || "-"}; este publicador tiene: ${Array.isArray(data.held) ? data.held.map(String).join(", ") : "-"}`,
|
|
2045
|
+
...steps.map((step, index) => ` ${index + 1}. ${step.action}: ${step.description}
|
|
2046
|
+
firma con ${step.signWith.join(", ") || "-"}${step.missing.length ? ` \xB7 FALTAN en este publicador: ${step.missing.join(", ")}` : ""}`),
|
|
2047
|
+
...windowDays !== null ? [`Ventana m\xEDnima entre pasos: ${windowDays} d\xEDas. Es solo un plan: el CLI no firma ni publica nada.`] : []
|
|
2048
|
+
];
|
|
2049
|
+
return { lines, result: { current: keyIds(data.current), next: keyIds(data.next), held: Array.isArray(data.held) ? data.held : [], windowMs: data.windowMs ?? null, steps } };
|
|
2050
|
+
}
|
|
2051
|
+
async function reconcileCmd(positional, flags, io) {
|
|
2052
|
+
if (positional.length !== 1) throw new UsageError3("uso: customy experience reconcile <canal>");
|
|
2053
|
+
const channel = positional[0];
|
|
2054
|
+
if (!RELEASE_CHANNEL_NAMES.includes(channel)) throw new UsageError3(`el canal debe ser ${RELEASE_CHANNEL_NAMES.join(", ")}`);
|
|
2055
|
+
const client = makeClient(flags, io);
|
|
2056
|
+
const rec = await client.request("POST", `/channels/${encodeURIComponent(channel)}/reconcile`, { body: {} });
|
|
2057
|
+
const data = isRec(rec) ? rec : {};
|
|
2058
|
+
const republished = isRec(data.republished) ? data.republished : null;
|
|
2059
|
+
const num2 = (value) => typeof value === "number" ? value : null;
|
|
2060
|
+
const lines = [
|
|
2061
|
+
`\u2713 canal ${channel} reconciliado: contador ${num2(data.previousSequence) ?? "?"} \u2192 ${num2(data.sequence) ?? "?"} (el almac\xE9n anunci\xF3 hasta ${num2(data.storedSequence) ?? "?"})`,
|
|
2062
|
+
republished ? ` release vigente publicado de nuevo con sequence ${num2(republished.sequence) ?? "?"}` : " el canal no ten\xEDa release vigente: no se republic\xF3 nada"
|
|
2063
|
+
];
|
|
2064
|
+
return { lines, result: { channel, previousSequence: num2(data.previousSequence), storedSequence: num2(data.storedSequence), sequence: num2(data.sequence), republished: republished ? { sequence: num2(republished.sequence) } : null } };
|
|
2065
|
+
}
|
|
2066
|
+
async function runExperienceCli(args, io) {
|
|
2067
|
+
const asJson = args.includes("--json");
|
|
2068
|
+
try {
|
|
2069
|
+
const [command2, ...rest] = args;
|
|
2070
|
+
if (!command2 || command2 === "--help" || args.includes("--help")) {
|
|
2071
|
+
io.out(EXPERIENCE_HELP.join("\n"));
|
|
2072
|
+
return command2 ? EXPERIENCE_EXIT.ok : EXPERIENCE_EXIT.usage;
|
|
2073
|
+
}
|
|
2074
|
+
const { positional, flags } = parse3(rest);
|
|
2075
|
+
let outcome;
|
|
2076
|
+
switch (command2) {
|
|
2077
|
+
case "pull":
|
|
2078
|
+
outcome = await pull(flags, io);
|
|
2079
|
+
break;
|
|
2080
|
+
case "push":
|
|
2081
|
+
outcome = await push(positional, flags, io);
|
|
2082
|
+
break;
|
|
2083
|
+
case "status":
|
|
2084
|
+
outcome = await status(flags, io);
|
|
2085
|
+
break;
|
|
2086
|
+
case "check":
|
|
2087
|
+
outcome = await check(flags, io);
|
|
2088
|
+
break;
|
|
2089
|
+
case "export":
|
|
2090
|
+
outcome = await exportCmd(flags, io);
|
|
2091
|
+
break;
|
|
2092
|
+
case "import":
|
|
2093
|
+
outcome = await importCmd(positional, flags, io);
|
|
2094
|
+
break;
|
|
2095
|
+
case "pseudo":
|
|
2096
|
+
outcome = await pseudoCmd(positional, flags, io);
|
|
2097
|
+
break;
|
|
2098
|
+
case "init":
|
|
2099
|
+
outcome = await initCmd(flags, io);
|
|
2100
|
+
break;
|
|
2101
|
+
case "revoke":
|
|
2102
|
+
outcome = await revokeCmd(positional, flags, io);
|
|
2103
|
+
break;
|
|
2104
|
+
case "scope":
|
|
2105
|
+
outcome = await scopeCmd(positional, flags, io);
|
|
2106
|
+
break;
|
|
2107
|
+
case "signing":
|
|
2108
|
+
outcome = await signingCmd(positional, flags, io);
|
|
2109
|
+
break;
|
|
2110
|
+
case "reconcile":
|
|
2111
|
+
outcome = await reconcileCmd(positional, flags, io);
|
|
2112
|
+
break;
|
|
2113
|
+
default:
|
|
2114
|
+
throw new UsageError3(`comando desconocido: customy experience ${command2} (pull|push|status|check|export|import|pseudo|init|revoke|scope|signing|reconcile)`);
|
|
2115
|
+
}
|
|
2116
|
+
const code = outcome.code ?? EXPERIENCE_EXIT.ok;
|
|
2117
|
+
if (asJson) io.out(JSON.stringify({ ok: code === 0, command: command2, exitCode: code, ...isRec(outcome.result) ? outcome.result : { result: outcome.result } }, null, 2));
|
|
2118
|
+
else for (const line of outcome.lines) (code === 0 || !line.startsWith("\u2717") ? io.out : io.err)(line);
|
|
2119
|
+
return code;
|
|
2120
|
+
} catch (error) {
|
|
2121
|
+
let code = EXPERIENCE_EXIT.failure;
|
|
2122
|
+
let message;
|
|
2123
|
+
if (error instanceof UsageError3) {
|
|
2124
|
+
code = EXPERIENCE_EXIT.usage;
|
|
2125
|
+
message = error.message;
|
|
2126
|
+
} else if (error instanceof ExitError) {
|
|
2127
|
+
code = error.code;
|
|
2128
|
+
message = error.message;
|
|
2129
|
+
} else if (error instanceof ApiError) {
|
|
2130
|
+
code = exitFor(error);
|
|
2131
|
+
message = explain(error, command(args));
|
|
2132
|
+
} else message = error instanceof Error ? error.message : String(error);
|
|
2133
|
+
if (asJson) io.out(JSON.stringify({ ok: false, exitCode: code, error: message.replace(/^✗ /gm, "") }, null, 2));
|
|
2134
|
+
else io.err(message.startsWith("\u2717") || message.includes("\n\u2717") ? message : `\u2717 ${message}`);
|
|
2135
|
+
return code;
|
|
2136
|
+
}
|
|
2137
|
+
}
|
|
2138
|
+
function command(args) {
|
|
2139
|
+
return `experience ${args[0] ?? ""}`.trim();
|
|
2140
|
+
}
|
|
2141
|
+
var WHATSAPP_EXIT = { ok: 0, failure: 1, unsupported: 2, auth: 3, findings: 4 };
|
|
2142
|
+
var WHATSAPP_GROUPS = ["whatsapp", "wa"];
|
|
2143
|
+
var WHATSAPP_HELP = [
|
|
2144
|
+
"Customy WhatsApp (credencial en el entorno: CUSTOMY_CLIENT_ID + CUSTOMY_CLIENT_SECRET + CUSTOMY_ACCESS_URL, o CUSTOMY_TOKEN):",
|
|
2145
|
+
" customy whatsapp numbers list [--status S --channel cloud_api|baileys|whatsmeow]",
|
|
2146
|
+
" customy whatsapp numbers status [<id>] (estado de los n\xFAmeros y readiness: qu\xE9 bloquea el env\xEDo)",
|
|
2147
|
+
' customy whatsapp send --to +573001234567 --text "Hola" [--phone ID]',
|
|
2148
|
+
" customy whatsapp send --to \u2026 --template order_update [--language es --param 1=Ana --param 2=#42] [--components-file c.json] (--language es obligatorio en Cloud API: el idioma aprobado exacto)",
|
|
2149
|
+
" customy whatsapp send --to \u2026 (--image|--video|--audio|--document|--sticker URL) [--caption T --voice]",
|
|
2150
|
+
" customy whatsapp send --to \u2026 --interactive-file botones.json (objeto `interactive` de la Cloud API)",
|
|
2151
|
+
" [--purpose marketing|service|transactional --consent opted_in|opted_out|unknown --ref ID --idempotency-key K]",
|
|
2152
|
+
" customy whatsapp messages list [--phone ID --direction inbound|outbound --conversation ID --limit N --from ISO --to ISO]",
|
|
2153
|
+
" customy whatsapp conversations list [--phone ID --limit N]",
|
|
2154
|
+
" customy whatsapp tail [--phone ID --direction inbound|outbound --interval 3 --count N] (sigue los mensajes nuevos; con --json, una l\xEDnea por mensaje)",
|
|
2155
|
+
" customy whatsapp numbers connect [--name N --external-id ID --redirect-url URL --connection-type cloud_api|business_app --expires-in S --branding-file b.json] [--dry-run]",
|
|
2156
|
+
" (devuelve el enlace de Embedded Signup para que el due\xF1o conecte su n\xFAmero; la URL se ve una vez) \xB7 numbers connection <id> (\xBFya conect\xF3?)",
|
|
2157
|
+
" customy whatsapp templates list [--status approved|pending|rejected|paused --phone ID] | get <id> | status <id> | sync [--phone ID] [--dry-run]",
|
|
2158
|
+
" customy whatsapp templates create --file plantilla.json [--dry-run] \xB7 edit <id> --file cambios.json [--dry-run] \xB7 delete <id> --yes [--dry-run]",
|
|
2159
|
+
" customy whatsapp broadcasts create --template N --language es (--to +57\u2026 [--to \u2026] | --recipients-file r.json|r.txt) [--name N --schedule ISO --consent opted_in --purpose marketing|service|transactional --idempotency-key K] [--dry-run]",
|
|
2160
|
+
" (o --file difusion.json con { name, templateName, templateLanguage, recipients, scheduledAt })",
|
|
2161
|
+
" customy whatsapp broadcasts list [--status S --limit N] | status <id> [--failures] [--recipient-status failed|suppressed|\u2026] | cancel <id> --yes [--dry-run]",
|
|
2162
|
+
" customy whatsapp flows list [--status draft|published] | get <id> | create --file flujo.json [--dry-run] | preview <id> | publish <id> --yes [--category C] [--dry-run]",
|
|
2163
|
+
" customy whatsapp readiness",
|
|
2164
|
+
" customy whatsapp findings [--hours 24] [--fail-on critical|high|medium|low] (problemas de entrega por causa, con la acci\xF3n que los resuelve)",
|
|
2165
|
+
" customy whatsapp webhooks verify (--body-file f | --body TEXT) --header webhook-id=\u2026 --header webhook-timestamp=\u2026 --header webhook-signature=\u2026 [--secret-env VAR] [--meta] [--tolerance S]",
|
|
2166
|
+
" customy whatsapp webhooks sign (--body-file f | --body TEXT) [--secret-env VAR] [--meta] (cabeceras firmadas para probar tu endpoint)",
|
|
2167
|
+
" customy whatsapp webhooks list | get <id> | delete <id> | rotate <id> (endpoints de webhook; scope whatsapp:webhooks)",
|
|
2168
|
+
" customy whatsapp webhooks create --url https://app.example.com/wa [--event message.received ...] [--description T] (el secreto whsec_\u2026 se muestra UNA vez)",
|
|
2169
|
+
" customy whatsapp webhooks update <id> [--url U] [--event E ... | --all-events] [--description T] [--enable | --disable]",
|
|
2170
|
+
" customy whatsapp webhooks test <id> [--wait] (encola un evento webhook.test firmado; --wait espera el resultado)",
|
|
2171
|
+
" customy whatsapp webhooks deliveries [--endpoint ID --status pending|delivered|dead --event E --limit N] | delivery <id> | redeliver <id>",
|
|
2172
|
+
" customy whatsapp webhooks tail [--endpoint ID --status S --event E --interval 3 --count N --payload] (sigue las entregas: nuevas y cambios de estado; con --json, una l\xEDnea por entrega)",
|
|
2173
|
+
"Comunes: --json (un documento JSON), --base-url URL (o CUSTOMY_WHATSAPP_URL), --phone ID (o CUSTOMY_WHATSAPP_PHONE_ID), --dry-run (send, templates, broadcasts, flows y numbers connect: imprime la petici\xF3n y no cambia nada), --yes (confirma borrar, cancelar y publicar)."
|
|
2174
|
+
];
|
|
2175
|
+
var UsageError4 = class extends Error {
|
|
2176
|
+
};
|
|
2177
|
+
var COMMON2 = { json: "boolean", "base-url": "string", phone: "string", help: "boolean" };
|
|
2178
|
+
function parse4(args, spec, positionals) {
|
|
2179
|
+
const known = { ...COMMON2, ...spec };
|
|
2180
|
+
const flags = {};
|
|
2181
|
+
const rest = [];
|
|
2182
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
2183
|
+
const arg = args[i];
|
|
2184
|
+
if (!arg.startsWith("--")) {
|
|
2185
|
+
rest.push(arg);
|
|
2186
|
+
continue;
|
|
2187
|
+
}
|
|
2188
|
+
const eq = arg.indexOf("=");
|
|
2189
|
+
const name = eq >= 0 ? arg.slice(2, eq) : arg.slice(2);
|
|
2190
|
+
const kind = known[name];
|
|
2191
|
+
if (!kind) throw new UsageError4(`flag desconocida --${name}`);
|
|
2192
|
+
if (kind === "boolean") {
|
|
2193
|
+
flags[name] = eq >= 0 ? arg.slice(eq + 1) !== "false" : true;
|
|
2194
|
+
continue;
|
|
2195
|
+
}
|
|
2196
|
+
const value = eq >= 0 ? arg.slice(eq + 1) : args[i + 1];
|
|
2197
|
+
if (eq < 0) i += 1;
|
|
2198
|
+
if (value === void 0 || eq < 0 && value.startsWith("--")) throw new UsageError4(`--${name} necesita un valor`);
|
|
2199
|
+
if (kind === "list") flags[name] = [...flags[name] ?? [], value];
|
|
2200
|
+
else flags[name] = value;
|
|
2201
|
+
}
|
|
2202
|
+
if (rest.length < positionals.min || rest.length > positionals.max) {
|
|
2203
|
+
throw new UsageError4(positionals.max === 0 ? `argumento inesperado "${rest[0]}"` : `se esperaban ${positionals.min === positionals.max ? positionals.min : `${positionals.min}-${positionals.max}`} argumento(s), hay ${rest.length}`);
|
|
2204
|
+
}
|
|
2205
|
+
return { flags, rest };
|
|
2206
|
+
}
|
|
2207
|
+
var str3 = (flags, name) => typeof flags[name] === "string" ? flags[name] : void 0;
|
|
2208
|
+
var bool2 = (flags, name) => flags[name] === true;
|
|
2209
|
+
var list2 = (flags, name) => Array.isArray(flags[name]) ? flags[name] : [];
|
|
2210
|
+
function int2(flags, name, min, max) {
|
|
2211
|
+
const raw = str3(flags, name);
|
|
2212
|
+
if (raw === void 0) return void 0;
|
|
2213
|
+
if (!/^\d+$/.test(raw) || Number(raw) < min || Number(raw) > max) throw new UsageError4(`--${name} debe ser un entero entre ${min} y ${max}`);
|
|
2214
|
+
return Number(raw);
|
|
2215
|
+
}
|
|
2216
|
+
function oneOf(flags, name, allowed) {
|
|
2217
|
+
const raw = str3(flags, name);
|
|
2218
|
+
if (raw === void 0) return void 0;
|
|
2219
|
+
if (!allowed.includes(raw)) throw new UsageError4(`--${name} debe ser ${allowed.join("|")}`);
|
|
2220
|
+
return raw;
|
|
2221
|
+
}
|
|
2222
|
+
function isoDate(flags, name) {
|
|
2223
|
+
const raw = str3(flags, name);
|
|
2224
|
+
if (raw === void 0) return void 0;
|
|
2225
|
+
const time = Date.parse(raw);
|
|
2226
|
+
if (!Number.isFinite(time)) throw new UsageError4(`--${name} debe ser una fecha ISO (2026-10-22T10:00:00Z)`);
|
|
2227
|
+
return new Date(time).toISOString();
|
|
2228
|
+
}
|
|
2229
|
+
function emit2(ctx, json, human) {
|
|
2230
|
+
if (ctx.json) ctx.io.out(JSON.stringify(json, null, 2));
|
|
2231
|
+
else for (const line of human) ctx.io.out(line);
|
|
2232
|
+
}
|
|
2233
|
+
function table2(rows) {
|
|
2234
|
+
const widths = rows[0].map((_, col) => Math.max(...rows.map((row) => (row[col] ?? "").length)));
|
|
2235
|
+
return rows.map((row) => row.map((cell, col) => col === row.length - 1 ? cell : cell.padEnd(widths[col])).join(" ").trimEnd());
|
|
2236
|
+
}
|
|
2237
|
+
async function readJsonFile(io, file) {
|
|
2238
|
+
try {
|
|
2239
|
+
return JSON.parse(await readFile(path3.resolve(io.cwd, file), "utf8"));
|
|
2240
|
+
} catch (error) {
|
|
2241
|
+
throw new UsageError4(`no se pudo leer ${file}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2242
|
+
}
|
|
2243
|
+
}
|
|
2244
|
+
async function connect(ctx, scopes) {
|
|
2245
|
+
const { io, flags } = ctx;
|
|
2246
|
+
const override = str3(flags, "base-url") ?? io.env.CUSTOMY_WHATSAPP_URL;
|
|
2247
|
+
const issuer = io.env.CUSTOMY_ACCESS_URL ?? io.env.CUSTOMY_ISSUER;
|
|
2248
|
+
const phoneId = str3(flags, "phone") ?? io.env.CUSTOMY_WHATSAPP_PHONE_ID;
|
|
2249
|
+
const { CUSTOMY_CLIENT_ID: clientId, CUSTOMY_CLIENT_SECRET: clientSecret, CUSTOMY_TOKEN: token } = io.env;
|
|
2250
|
+
const common = { ...io.fetch ? { fetch: io.fetch } : {}, ...phoneId ? { phoneId } : {} };
|
|
2251
|
+
let platform;
|
|
2252
|
+
const discovered = async () => {
|
|
2253
|
+
if (!issuer) throw new UsageError4("falta el origen de Access: define CUSTOMY_ACCESS_URL (o CUSTOMY_ISSUER)");
|
|
2254
|
+
platform ??= await discoverPlatform(issuer, io.fetch ? { fetch: io.fetch } : {});
|
|
2255
|
+
return platform;
|
|
2256
|
+
};
|
|
2257
|
+
const hostOf = async () => {
|
|
2258
|
+
if (override) return override.replace(/\/$/, "");
|
|
2259
|
+
const found = (await discovered()).products.whatsapp?.baseUrl;
|
|
2260
|
+
if (!found) throw new UsageError4(`el discovery de ${issuer} no anuncia WhatsApp: pasa --base-url o CUSTOMY_WHATSAPP_URL`);
|
|
2261
|
+
return found.replace(/\/$/, "");
|
|
2262
|
+
};
|
|
2263
|
+
if (clientId && clientSecret) {
|
|
2264
|
+
const found = await discovered();
|
|
2265
|
+
const baseUrl = await hostOf();
|
|
2266
|
+
const machineTokens = createMachineTokens({ issuer, clientId, clientSecret, platform: found, ...io.fetch ? { fetch: io.fetch } : {} });
|
|
2267
|
+
return { wa: createWhatsApp({ ...common, platform: found, machineTokens, scopes, baseUrl }), baseUrl };
|
|
2268
|
+
}
|
|
2269
|
+
if (token) {
|
|
2270
|
+
const baseUrl = await hostOf();
|
|
2271
|
+
return { wa: createWhatsApp({ ...common, accessToken: token, baseUrl }), baseUrl };
|
|
2272
|
+
}
|
|
2273
|
+
throw new UsageError4("faltan credenciales: define CUSTOMY_CLIENT_ID, CUSTOMY_CLIENT_SECRET y CUSTOMY_ACCESS_URL (una llave de Access con la audiencia customy-whatsapp), o CUSTOMY_TOKEN");
|
|
2274
|
+
}
|
|
2275
|
+
function preview(content, max = 60) {
|
|
2276
|
+
let text = "";
|
|
2277
|
+
if (typeof content === "string") text = content;
|
|
2278
|
+
else if (content && typeof content === "object") {
|
|
2279
|
+
const record = content;
|
|
2280
|
+
for (const key2 of ["text", "body", "caption", "templateName", "emoji"]) {
|
|
2281
|
+
if (typeof record[key2] === "string" && record[key2]) {
|
|
2282
|
+
text = record[key2];
|
|
2283
|
+
break;
|
|
2284
|
+
}
|
|
2285
|
+
}
|
|
2286
|
+
if (!text) text = JSON.stringify(content);
|
|
2287
|
+
}
|
|
2288
|
+
text = text.replace(/\s+/g, " ").trim();
|
|
2289
|
+
return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;
|
|
2290
|
+
}
|
|
2291
|
+
var when = (value) => value ? value.replace("T", " ").replace(/\.\d+Z$/, "Z") : "-";
|
|
2292
|
+
var numbersTable = (items) => items.length === 0 ? ["(sin n\xFAmeros)"] : table2([["ID", "N\xDAMERO", "CANAL", "ESTADO", "CONFIGURACI\xD3N", "NOMBRE"], ...items.map((n) => [n.id, n.phoneNumber, n.channel, n.status, n.setupState ?? "-", n.displayName ?? ""])]);
|
|
2293
|
+
var messagesTable = (items) => items.length === 0 ? ["(sin mensajes)"] : table2([["FECHA", "DIR", "ESTADO", "CONTRAPARTE", "TIPO", "CONTENIDO", "ERROR"], ...items.map(messageRow)]);
|
|
2294
|
+
var messageRow = (m) => [when(m.createdAt), m.direction === "inbound" ? "\u2190" : "\u2192", m.status, m.direction === "inbound" ? m.fromNumber : m.toNumber, m.messageType, preview(m.content), m.errorCode ?? ""];
|
|
2295
|
+
var conversationsTable = (items) => items.length === 0 ? ["(sin conversaciones)"] : table2([["\xDALTIMO", "CONTRAPARTE", "N\xDAMERO", "MSJ", "SIN LEER", "\xDALTIMO MENSAJE"], ...items.map((c) => [when(c.lastMessageAt), c.remoteNumber, c.phoneId, String(c.messageCount), String(c.unreadCount), `${c.lastDirection === "inbound" ? "\u2190" : "\u2192"} ${preview(c.lastContent, 50)}`])]);
|
|
2296
|
+
var templatesTable = (items) => items.length === 0 ? ["(sin plantillas)"] : table2([["ID", "NOMBRE", "IDIOMA", "CATEGOR\xCDA", "ESTADO", "N\xDAMERO"], ...items.map((t) => [t.id, t.templateName, t.language, t.category, t.status, t.phoneId])]);
|
|
2297
|
+
var SEVERITY_ORDER = ["critical", "high", "medium", "low", "info"];
|
|
2298
|
+
function findingLines(report3) {
|
|
2299
|
+
const head = `Ventana de ${report3.windowHours} h \xB7 ${report3.outboundTotal} salientes \xB7 ${report3.failedTotal} fallidos${report3.truncated ? " (conteo m\xEDnimo: hab\xEDa m\xE1s fallos que el tope le\xEDdo)" : ""}`;
|
|
2300
|
+
if (report3.findings.length === 0) return [head, "\u2713 sin problemas de entrega en la ventana"];
|
|
2301
|
+
const lines = [head, ...table2([["GRAVEDAD", "C\xD3DIGO", "MSJ", "TENDENCIA", "CAUSA"], ...report3.findings.map((f) => [f.severity, f.code, String(f.count), f.trend, f.title])])];
|
|
2302
|
+
for (const f of report3.findings) {
|
|
2303
|
+
lines.push("", `${f.code} \u2014 ${f.title}`, ` qu\xE9 pasa: ${f.explanation}`, ` qu\xE9 hacer: ${f.recommendation}${f.needsAction ? " [requiere acci\xF3n]" : f.retryable ? " [se reintenta solo]" : ""}`);
|
|
2304
|
+
if (f.affectedNumbers.length) lines.push(` n\xFAmeros: ${f.affectedNumbers.join(", ")}`);
|
|
2305
|
+
if (f.evidence.length) lines.push(` ejemplos: ${f.evidence.slice(0, 3).map((e) => e.messageId).join(", ")}`);
|
|
2306
|
+
}
|
|
2307
|
+
return lines;
|
|
2308
|
+
}
|
|
2309
|
+
var webhooksTable = (items) => items.length === 0 ? ["(sin endpoints de webhook)"] : table2([["ID", "ESTADO", "EVENTOS", "\xDALTIMA ENTREGA", "FALLOS", "SECRETO", "URL"], ...items.map((w) => [
|
|
2310
|
+
w.id,
|
|
2311
|
+
w.status === "disabled" ? `desactivado${w.disabledReason ? ` (${w.disabledReason})` : ""}` : "activo",
|
|
2312
|
+
w.events.length === 0 ? "todos" : w.events.join(","),
|
|
2313
|
+
when(w.lastDeliveredAt),
|
|
2314
|
+
String(w.failuresInRow),
|
|
2315
|
+
`${w.secretPreview}${w.rotating ? " (rotando)" : ""}`,
|
|
2316
|
+
w.url
|
|
2317
|
+
])]);
|
|
2318
|
+
var deliveryRow = (d) => [
|
|
2319
|
+
when(d.createdAt),
|
|
2320
|
+
d.status,
|
|
2321
|
+
d.event,
|
|
2322
|
+
d.endpointId,
|
|
2323
|
+
`${d.attempts}${d.redeliveries ? `+${d.redeliveries}r` : ""}`,
|
|
2324
|
+
d.responseStatus === null ? "-" : String(d.responseStatus),
|
|
2325
|
+
d.latencyMs === null ? "-" : `${d.latencyMs} ms`,
|
|
2326
|
+
d.status === "pending" && d.nextAttemptAt ? `reintento ${when(d.nextAttemptAt)}` : d.error ?? ""
|
|
2327
|
+
];
|
|
2328
|
+
var deliveriesTable = (items) => items.length === 0 ? ["(sin entregas)"] : table2([["FECHA", "ESTADO", "EVENTO", "ENDPOINT", "INTENTOS", "HTTP", "LATENCIA", "DETALLE"], ...items.map(deliveryRow)]);
|
|
2329
|
+
function context2(io, flags) {
|
|
2330
|
+
return { io, flags, json: bool2(flags, "json") };
|
|
2331
|
+
}
|
|
2332
|
+
async function numbers(args, io) {
|
|
2333
|
+
const [action, ...rest] = args;
|
|
2334
|
+
if (action === "list") {
|
|
2335
|
+
const { flags } = parse4(rest, { status: "string", channel: "string" }, { min: 0, max: 0 });
|
|
2336
|
+
const ctx = context2(io, flags);
|
|
2337
|
+
const { wa } = await connect(ctx, ["whatsapp:numbers:read"]);
|
|
2338
|
+
const result = await wa.numbers.list({ ...str3(flags, "status") ? { status: str3(flags, "status") } : {}, ...oneOf(flags, "channel", ["cloud_api", "baileys", "whatsmeow"]) ? { channel: oneOf(flags, "channel", ["cloud_api", "baileys", "whatsmeow"]) } : {} });
|
|
2339
|
+
emit2(ctx, result, numbersTable(result.items));
|
|
2340
|
+
return WHATSAPP_EXIT.ok;
|
|
2341
|
+
}
|
|
2342
|
+
if (action === "status") {
|
|
2343
|
+
const { flags, rest: positional } = parse4(rest, {}, { min: 0, max: 1 });
|
|
2344
|
+
const ctx = context2(io, flags);
|
|
2345
|
+
const { wa } = await connect(ctx, ["whatsapp:numbers:read", "whatsapp:readiness:read"]);
|
|
2346
|
+
const [items, readiness2] = await Promise.all([
|
|
2347
|
+
positional[0] ? wa.numbers.get(positional[0]).then((item) => [item]) : wa.numbers.list().then((r) => [...r.items]),
|
|
2348
|
+
wa.readiness.get().catch((error) => {
|
|
2349
|
+
if (error instanceof CustomyWhatsAppError && error.status === 403) return null;
|
|
2350
|
+
throw error;
|
|
2351
|
+
})
|
|
2352
|
+
]);
|
|
2353
|
+
const human = [...numbersTable(items)];
|
|
2354
|
+
for (const n of items) {
|
|
2355
|
+
if (n.coexistence?.action) human.push("", `${n.phoneNumber}: ${n.coexistence.action.title} \u2014 ${n.coexistence.action.detail}`);
|
|
2356
|
+
}
|
|
2357
|
+
if (readiness2) {
|
|
2358
|
+
human.push("", `Readiness: ${readiness2.status} (${readiness2.mode})${readiness2.canSendMessage ? " \xB7 puede enviar" : " \xB7 NO puede enviar"}`);
|
|
2359
|
+
for (const check2 of readiness2.checks) human.push(` ${check2.status === "ok" ? "\u2713" : check2.status === "warning" ? "!" : "\u2717"} ${check2.title}${check2.status === "ok" ? "" : ` \u2014 ${check2.detail}${check2.action ? ` (${check2.action.label})` : ""}`}`);
|
|
2360
|
+
} else human.push("", "Readiness: sin el scope whatsapp:readiness:read en la llave");
|
|
2361
|
+
emit2(ctx, { numbers: items, readiness: readiness2 }, human);
|
|
2362
|
+
return WHATSAPP_EXIT.ok;
|
|
2363
|
+
}
|
|
2364
|
+
if (action === "connect") {
|
|
2365
|
+
const { flags } = parse4(rest, { name: "string", "external-id": "string", "redirect-url": "string", "connection-type": "list", "expires-in": "string", "branding-file": "string", "dry-run": "boolean" }, { min: 0, max: 0 });
|
|
2366
|
+
const ctx = context2(io, flags);
|
|
2367
|
+
const types = list2(flags, "connection-type");
|
|
2368
|
+
for (const type of types) if (type !== "cloud_api" && type !== "business_app") throw new UsageError4("--connection-type debe ser cloud_api|business_app");
|
|
2369
|
+
const expiresIn = int2(flags, "expires-in", 300, 30 * 86400);
|
|
2370
|
+
const branding = str3(flags, "branding-file") ? await jsonObjectFile(io, str3(flags, "branding-file"), '{ "displayName"?, "logoUrl"?, "primaryColor"?, "locale"? }') : void 0;
|
|
2371
|
+
const input = {
|
|
2372
|
+
...str3(flags, "name") ? { name: str3(flags, "name") } : {},
|
|
2373
|
+
...str3(flags, "external-id") ? { externalCustomerId: str3(flags, "external-id") } : {},
|
|
2374
|
+
...str3(flags, "redirect-url") ? { redirectUrl: str3(flags, "redirect-url") } : {},
|
|
2375
|
+
...types.length ? { connectionTypes: types } : {},
|
|
2376
|
+
...expiresIn ? { expiresInSeconds: expiresIn } : {},
|
|
2377
|
+
...branding ? { branding } : {}
|
|
2378
|
+
};
|
|
2379
|
+
if (bool2(flags, "dry-run")) return dryRun(ctx, "POST", "/v1/numbers/connect", input);
|
|
2380
|
+
const { wa } = await connect(ctx, ["whatsapp:numbers:connect"]);
|
|
2381
|
+
const link = await wa.numbers.connect(input);
|
|
2382
|
+
emit2(ctx, link, [`\u2713 enlace de conexi\xF3n para ${link.externalCustomerId}${link.expiresAt ? ` (vence ${when(link.expiresAt)})` : ""}`, "", ` ${link.url}`, "", " \xC1brelo con quien conecta el n\xFAmero: inicia sesi\xF3n con Facebook y completa Embedded Signup. La URL no se vuelve a mostrar.", ` \xBFYa conect\xF3? customy whatsapp numbers connection ${link.setupLinkId}`]);
|
|
2383
|
+
return WHATSAPP_EXIT.ok;
|
|
2384
|
+
}
|
|
2385
|
+
if (action === "connection") {
|
|
2386
|
+
const { flags, rest: positional } = parse4(rest, {}, { min: 1, max: 1 });
|
|
2387
|
+
const ctx = context2(io, flags);
|
|
2388
|
+
const { wa } = await connect(ctx, ["whatsapp:numbers:read"]);
|
|
2389
|
+
const status2 = await wa.numbers.connection(positional[0]);
|
|
2390
|
+
emit2(ctx, status2, [`${status2.setupLinkId}: ${status2.status}${status2.lastErrorCode ? ` \xB7 ${status2.lastErrorCode}` : ""}`, ...status2.result ? status2.result.numbers.map((n) => ` \u2713 ${n.phoneNumber}${n.displayName ? ` (${n.displayName})` : ""}`) : []]);
|
|
2391
|
+
return WHATSAPP_EXIT.ok;
|
|
2392
|
+
}
|
|
2393
|
+
throw new UsageError4("customy whatsapp numbers list|status [<id>]|connect|connection <id>");
|
|
2394
|
+
}
|
|
2395
|
+
var MEDIA_FLAGS = ["image", "video", "audio", "document", "sticker"];
|
|
2396
|
+
async function buildSend(ctx, flags) {
|
|
2397
|
+
const to = str3(flags, "to");
|
|
2398
|
+
if (!to) throw new UsageError4("--to es obligatorio (formato internacional, +573001234567)");
|
|
2399
|
+
const phoneId = str3(flags, "phone") ?? ctx.io.env.CUSTOMY_WHATSAPP_PHONE_ID;
|
|
2400
|
+
const base = {
|
|
2401
|
+
to,
|
|
2402
|
+
...phoneId ? { phoneId } : {},
|
|
2403
|
+
...str3(flags, "idempotency-key") ? { idempotencyKey: str3(flags, "idempotency-key") } : {},
|
|
2404
|
+
...oneOf(flags, "purpose", ["marketing", "service", "transactional"]) ? { messagePurpose: oneOf(flags, "purpose", ["marketing", "service", "transactional"]) } : {},
|
|
2405
|
+
...oneOf(flags, "consent", ["unknown", "opted_in", "opted_out"]) ? { consentStatus: oneOf(flags, "consent", ["unknown", "opted_in", "opted_out"]) } : {},
|
|
2406
|
+
...str3(flags, "consent-source") ? { consentSource: str3(flags, "consent-source") } : {},
|
|
2407
|
+
...str3(flags, "ref") ? { sourceRef: str3(flags, "ref") } : {}
|
|
2408
|
+
};
|
|
2409
|
+
const media = MEDIA_FLAGS.filter((type) => str3(flags, type) !== void 0);
|
|
2410
|
+
const kinds = [str3(flags, "text") !== void 0, str3(flags, "template") !== void 0, media.length > 0, str3(flags, "interactive-file") !== void 0].filter(Boolean).length;
|
|
2411
|
+
if (kinds !== 1 || media.length > 1) throw new UsageError4("indica exactamente un contenido: --text, --template, una media (--image|--video|--audio|--document|--sticker) o --interactive-file");
|
|
2412
|
+
if (str3(flags, "text") !== void 0) return { ...base, type: "text", text: str3(flags, "text") };
|
|
2413
|
+
if (media.length === 1) {
|
|
2414
|
+
const type = media[0];
|
|
2415
|
+
return { ...base, type, mediaUrl: str3(flags, type), ...str3(flags, "caption") ? { caption: str3(flags, "caption") } : {}, ...bool2(flags, "voice") ? { voice: true } : {} };
|
|
2416
|
+
}
|
|
2417
|
+
if (str3(flags, "template") !== void 0) {
|
|
2418
|
+
const params = {};
|
|
2419
|
+
for (const pair of list2(flags, "param")) {
|
|
2420
|
+
const at = pair.indexOf("=");
|
|
2421
|
+
if (at <= 0) throw new UsageError4(`--param espera clave=valor, recibi\xF3 "${pair}"`);
|
|
2422
|
+
params[pair.slice(0, at)] = pair.slice(at + 1);
|
|
2423
|
+
}
|
|
2424
|
+
const components = str3(flags, "components-file") ? await readJsonFile(ctx.io, str3(flags, "components-file")) : void 0;
|
|
2425
|
+
if (components !== void 0 && !Array.isArray(components)) throw new UsageError4("--components-file debe contener un arreglo JSON de componentes de Meta");
|
|
2426
|
+
return {
|
|
2427
|
+
...base,
|
|
2428
|
+
type: "template",
|
|
2429
|
+
templateName: str3(flags, "template"),
|
|
2430
|
+
...str3(flags, "language") ? { templateLanguage: str3(flags, "language") } : {},
|
|
2431
|
+
...Object.keys(params).length ? { templateParams: params } : {},
|
|
2432
|
+
...components ? { templateComponents: components } : {}
|
|
2433
|
+
};
|
|
2434
|
+
}
|
|
2435
|
+
const interactive = await readJsonFile(ctx.io, str3(flags, "interactive-file"));
|
|
2436
|
+
if (!interactive || typeof interactive !== "object" || Array.isArray(interactive)) throw new UsageError4("--interactive-file debe contener el objeto `interactive` de la Cloud API");
|
|
2437
|
+
return { ...base, type: "interactive", interactive };
|
|
2438
|
+
}
|
|
2439
|
+
async function send(args, io) {
|
|
2440
|
+
const { flags } = parse4(args, {
|
|
2441
|
+
to: "string",
|
|
2442
|
+
text: "string",
|
|
2443
|
+
template: "string",
|
|
2444
|
+
language: "string",
|
|
2445
|
+
param: "list",
|
|
2446
|
+
"components-file": "string",
|
|
2447
|
+
image: "string",
|
|
2448
|
+
video: "string",
|
|
2449
|
+
audio: "string",
|
|
2450
|
+
document: "string",
|
|
2451
|
+
sticker: "string",
|
|
2452
|
+
caption: "string",
|
|
2453
|
+
voice: "boolean",
|
|
2454
|
+
"interactive-file": "string",
|
|
2455
|
+
purpose: "string",
|
|
2456
|
+
consent: "string",
|
|
2457
|
+
"consent-source": "string",
|
|
2458
|
+
ref: "string",
|
|
2459
|
+
"idempotency-key": "string",
|
|
2460
|
+
"dry-run": "boolean"
|
|
2461
|
+
}, { min: 0, max: 0 });
|
|
2462
|
+
const ctx = context2(io, flags);
|
|
2463
|
+
const input = await buildSend(ctx, flags);
|
|
2464
|
+
if (bool2(flags, "dry-run")) {
|
|
2465
|
+
const { idempotencyKey, ...body } = input;
|
|
2466
|
+
emit2(ctx, { dryRun: true, method: "POST", path: "/v1/messages/send", idempotencyKey: idempotencyKey ?? "(se genera al enviar)", body }, [
|
|
2467
|
+
"DRY RUN (no se env\xEDa nada)",
|
|
2468
|
+
"POST /v1/messages/send",
|
|
2469
|
+
JSON.stringify(body, null, 2)
|
|
2470
|
+
]);
|
|
2471
|
+
return WHATSAPP_EXIT.ok;
|
|
2472
|
+
}
|
|
2473
|
+
const { wa, baseUrl } = await connect(ctx, ["whatsapp:messages:send"]);
|
|
2474
|
+
if (!ctx.json) io.err(`\u2192 ${baseUrl}`);
|
|
2475
|
+
const result = await wa.messages.send(input);
|
|
2476
|
+
emit2(ctx, result, [`\u2713 enviado a ${input.to}: ${result.waMessageId}${result.deliveryStatus ? ` (${result.deliveryStatus})` : ""}`, " seguir la entrega: customy whatsapp messages list --direction outbound \xB7 problemas: customy whatsapp findings"]);
|
|
2477
|
+
return WHATSAPP_EXIT.ok;
|
|
2478
|
+
}
|
|
2479
|
+
async function messages(args, io) {
|
|
2480
|
+
const [action, ...rest] = args;
|
|
2481
|
+
if (action !== "list") throw new UsageError4("customy whatsapp messages list [--phone ID --direction \u2026 --conversation ID --limit N --from ISO --to ISO]");
|
|
2482
|
+
const { flags } = parse4(rest, { direction: "string", conversation: "string", limit: "string", from: "string", to: "string" }, { min: 0, max: 0 });
|
|
2483
|
+
const ctx = context2(io, flags);
|
|
2484
|
+
const { wa } = await connect(ctx, ["whatsapp:messages:read"]);
|
|
2485
|
+
const direction = oneOf(flags, "direction", ["inbound", "outbound"]);
|
|
2486
|
+
const limit = int2(flags, "limit", 1, 200);
|
|
2487
|
+
const from = isoDate(flags, "from");
|
|
2488
|
+
const to = isoDate(flags, "to");
|
|
2489
|
+
const result = await wa.messages.list({
|
|
2490
|
+
...direction ? { direction } : {},
|
|
2491
|
+
...str3(flags, "conversation") ? { conversationId: str3(flags, "conversation") } : {},
|
|
2492
|
+
...limit ? { limit } : {},
|
|
2493
|
+
...from ? { from } : {},
|
|
2494
|
+
...to ? { to } : {}
|
|
2495
|
+
});
|
|
2496
|
+
emit2(ctx, result, messagesTable(result.items));
|
|
2497
|
+
return WHATSAPP_EXIT.ok;
|
|
2498
|
+
}
|
|
2499
|
+
async function conversations(args, io) {
|
|
2500
|
+
const [action, ...rest] = args;
|
|
2501
|
+
if (action !== "list") throw new UsageError4("customy whatsapp conversations list [--phone ID --limit N]");
|
|
2502
|
+
const { flags } = parse4(rest, { limit: "string" }, { min: 0, max: 0 });
|
|
2503
|
+
const ctx = context2(io, flags);
|
|
2504
|
+
const { wa } = await connect(ctx, ["whatsapp:messages:read"]);
|
|
2505
|
+
const limit = int2(flags, "limit", 1, 100);
|
|
2506
|
+
const result = await wa.conversations.list(limit ? { limit } : {});
|
|
2507
|
+
emit2(ctx, result, conversationsTable(result.items));
|
|
2508
|
+
return WHATSAPP_EXIT.ok;
|
|
2509
|
+
}
|
|
2510
|
+
var defaultSleep = (ms, signal) => new Promise((resolve) => {
|
|
2511
|
+
const timer = setTimeout(resolve, ms);
|
|
2512
|
+
signal?.addEventListener("abort", () => {
|
|
2513
|
+
clearTimeout(timer);
|
|
2514
|
+
resolve();
|
|
2515
|
+
}, { once: true });
|
|
2516
|
+
});
|
|
2517
|
+
async function tail(args, io) {
|
|
2518
|
+
const { flags } = parse4(args, { direction: "string", interval: "string", count: "string", since: "string" }, { min: 0, max: 0 });
|
|
2519
|
+
const ctx = context2(io, flags);
|
|
2520
|
+
const { wa } = await connect(ctx, ["whatsapp:messages:read"]);
|
|
2521
|
+
const direction = oneOf(flags, "direction", ["inbound", "outbound"]);
|
|
2522
|
+
const intervalMs = (int2(flags, "interval", 0, 3600) ?? 3) * 1e3;
|
|
2523
|
+
const maxCount = int2(flags, "count", 1, 1e5);
|
|
2524
|
+
let cursor = isoDate(flags, "since") ?? new Date(Date.now() - 6e4).toISOString();
|
|
2525
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2526
|
+
let printed = 0;
|
|
2527
|
+
const sleep = io.sleep ?? defaultSleep;
|
|
2528
|
+
if (!ctx.json) io.err(`siguiendo mensajes${direction ? ` ${direction === "inbound" ? "entrantes" : "salientes"}` : ""} desde ${cursor} (Ctrl+C para salir)`);
|
|
2529
|
+
while (!io.signal?.aborted) {
|
|
2530
|
+
const page = await wa.messages.list({ from: cursor, limit: 100, ...direction ? { direction } : {} });
|
|
2531
|
+
const fresh = page.items.filter((m) => !seen.has(m.id)).reverse();
|
|
2532
|
+
for (const m of fresh) {
|
|
2533
|
+
seen.add(m.id);
|
|
2534
|
+
if (ctx.json) io.out(JSON.stringify(m));
|
|
2535
|
+
else io.out(messageRow(m).join(" ").trimEnd());
|
|
2536
|
+
printed += 1;
|
|
2537
|
+
if (maxCount !== void 0 && printed >= maxCount) return WHATSAPP_EXIT.ok;
|
|
2538
|
+
}
|
|
2539
|
+
const newest = page.items[0];
|
|
2540
|
+
if (newest && newest.createdAt > cursor) cursor = newest.createdAt;
|
|
2541
|
+
await sleep(intervalMs, io.signal);
|
|
2542
|
+
}
|
|
2543
|
+
return WHATSAPP_EXIT.ok;
|
|
2544
|
+
}
|
|
2545
|
+
function dryRun(ctx, method, path6, body) {
|
|
2546
|
+
emit2(ctx, { dryRun: true, method, path: path6, ...body === void 0 ? {} : { body } }, [
|
|
2547
|
+
"DRY RUN (no se cambia nada)",
|
|
2548
|
+
`${method} ${path6}`,
|
|
2549
|
+
...body === void 0 ? [] : [JSON.stringify(body, null, 2)]
|
|
2550
|
+
]);
|
|
2551
|
+
return WHATSAPP_EXIT.ok;
|
|
2552
|
+
}
|
|
2553
|
+
function requireYes(flags, what) {
|
|
2554
|
+
if (!bool2(flags, "yes") && !bool2(flags, "dry-run")) throw new UsageError4(`${what} es irreversible: repite con --yes para confirmarlo (o --dry-run para verlo sin hacerlo)`);
|
|
2555
|
+
}
|
|
2556
|
+
async function jsonObjectFile(io, file, shape) {
|
|
2557
|
+
const body = await readJsonFile(io, file);
|
|
2558
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) throw new UsageError4(`${file} debe ser un objeto JSON ${shape}`);
|
|
2559
|
+
return body;
|
|
2560
|
+
}
|
|
2561
|
+
var approvalLines = (s) => [
|
|
2562
|
+
`${s.templateName} (${s.language}) \xB7 ${s.id}: ${s.status}${s.metaStatus ? ` \xB7 Meta ${s.metaStatus}` : ""}${s.qualityScore ? ` \xB7 calidad ${s.qualityScore}` : ""}`,
|
|
2563
|
+
...s.rejectedReason ? [` motivo de rechazo: ${s.rejectedReason}`] : [],
|
|
2564
|
+
...s.status === "approved" ? [" \u2713 se puede enviar"] : s.status === "pending" ? [" \u2026 en revisi\xF3n de Meta: customy whatsapp templates sync lo refresca"] : [" \u2717 no se puede enviar"]
|
|
2565
|
+
];
|
|
2566
|
+
async function templates(args, io) {
|
|
2567
|
+
const [action, ...rest] = args;
|
|
2568
|
+
if (action === "list") {
|
|
2569
|
+
const { flags } = parse4(rest, { status: "string" }, { min: 0, max: 0 });
|
|
2570
|
+
const ctx = context2(io, flags);
|
|
2571
|
+
const { wa } = await connect(ctx, ["whatsapp:templates:read"]);
|
|
2572
|
+
const status2 = oneOf(flags, "status", ["approved", "pending", "rejected", "paused"]);
|
|
2573
|
+
const result = await wa.templates.list(status2 ? { status: status2 } : {});
|
|
2574
|
+
emit2(ctx, result, templatesTable(result.items));
|
|
2575
|
+
return WHATSAPP_EXIT.ok;
|
|
2576
|
+
}
|
|
2577
|
+
if (action === "get") {
|
|
2578
|
+
const { flags, rest: positional } = parse4(rest, {}, { min: 1, max: 1 });
|
|
2579
|
+
const ctx = context2(io, flags);
|
|
2580
|
+
const { wa } = await connect(ctx, ["whatsapp:templates:read"]);
|
|
2581
|
+
const template = await wa.templates.get(positional[0]);
|
|
2582
|
+
emit2(ctx, template, [...templatesTable([template]), "", JSON.stringify(template.components, null, 2)]);
|
|
2583
|
+
return WHATSAPP_EXIT.ok;
|
|
2584
|
+
}
|
|
2585
|
+
if (action === "status") {
|
|
2586
|
+
const { flags, rest: positional } = parse4(rest, {}, { min: 1, max: 1 });
|
|
2587
|
+
const ctx = context2(io, flags);
|
|
2588
|
+
const { wa } = await connect(ctx, ["whatsapp:templates:read"]);
|
|
2589
|
+
const result = await wa.templates.status(positional[0]);
|
|
2590
|
+
emit2(ctx, result, approvalLines(result));
|
|
2591
|
+
return WHATSAPP_EXIT.ok;
|
|
2592
|
+
}
|
|
2593
|
+
if (action === "sync") {
|
|
2594
|
+
const { flags } = parse4(rest, { "dry-run": "boolean" }, { min: 0, max: 0 });
|
|
2595
|
+
const ctx = context2(io, flags);
|
|
2596
|
+
if (bool2(flags, "dry-run")) return dryRun(ctx, "POST", "/v1/templates/sync", { phoneId: str3(flags, "phone") ?? io.env.CUSTOMY_WHATSAPP_PHONE_ID ?? "(el n\xFAmero por defecto)" });
|
|
2597
|
+
const { wa } = await connect(ctx, ["whatsapp:templates:manage"]);
|
|
2598
|
+
const result = await wa.templates.sync();
|
|
2599
|
+
emit2(ctx, result, ["\u2713 plantillas sincronizadas con Meta", JSON.stringify(result)]);
|
|
2600
|
+
return WHATSAPP_EXIT.ok;
|
|
2601
|
+
}
|
|
2602
|
+
if (action === "create") {
|
|
2603
|
+
const { flags } = parse4(rest, { file: "string", "dry-run": "boolean" }, { min: 0, max: 0 });
|
|
2604
|
+
const ctx = context2(io, flags);
|
|
2605
|
+
const file = str3(flags, "file");
|
|
2606
|
+
if (!file) throw new UsageError4("falta --file con { templateName, category, language?, components }");
|
|
2607
|
+
const body = await readJsonFile(io, file);
|
|
2608
|
+
if (!body || typeof body !== "object" || typeof body.templateName !== "string" || typeof body.category !== "string" || !Array.isArray(body.components)) {
|
|
2609
|
+
throw new UsageError4(`${file} debe ser { "templateName": "\u2026", "category": "UTILITY|MARKETING|AUTHENTICATION", "language"?: "es", "components": [...] }`);
|
|
2610
|
+
}
|
|
2611
|
+
const phoneId = typeof body.phoneId === "string" ? body.phoneId : str3(flags, "phone") ?? io.env.CUSTOMY_WHATSAPP_PHONE_ID;
|
|
2612
|
+
if (bool2(flags, "dry-run")) return dryRun(ctx, "POST", "/v1/templates", { ...phoneId ? { phoneId } : {}, templateName: body.templateName, category: body.category, language: body.language ?? "es", components: body.components });
|
|
2613
|
+
const { wa } = await connect(ctx, ["whatsapp:templates:manage"]);
|
|
2614
|
+
const created = await wa.templates.create({
|
|
2615
|
+
templateName: body.templateName,
|
|
2616
|
+
category: body.category,
|
|
2617
|
+
components: body.components,
|
|
2618
|
+
...typeof body.language === "string" ? { language: body.language } : {},
|
|
2619
|
+
...phoneId ? { phoneId } : {}
|
|
2620
|
+
});
|
|
2621
|
+
emit2(ctx, created, [`\u2713 plantilla ${created.templateName} (${created.id}) enviada a revisi\xF3n: ${created.status}`]);
|
|
2622
|
+
return WHATSAPP_EXIT.ok;
|
|
2623
|
+
}
|
|
2624
|
+
if (action === "edit") {
|
|
2625
|
+
const { flags, rest: positional } = parse4(rest, { file: "string", "dry-run": "boolean" }, { min: 1, max: 1 });
|
|
2626
|
+
const ctx = context2(io, flags);
|
|
2627
|
+
const file = str3(flags, "file");
|
|
2628
|
+
if (!file) throw new UsageError4("falta --file con { components?, category? } (el idioma de una plantilla enviada no cambia)");
|
|
2629
|
+
const body = await jsonObjectFile(io, file, '{ "components"?: [...], "category"?: "UTILITY|MARKETING|AUTHENTICATION" }');
|
|
2630
|
+
const patch = {
|
|
2631
|
+
...Array.isArray(body.components) ? { components: body.components } : {},
|
|
2632
|
+
...typeof body.category === "string" ? { category: body.category } : {},
|
|
2633
|
+
...typeof body.language === "string" ? { language: body.language } : {}
|
|
2634
|
+
};
|
|
2635
|
+
if (Object.keys(patch).length === 0) throw new UsageError4(`${file} no trae nada que editar: components, category o language`);
|
|
2636
|
+
if (bool2(flags, "dry-run")) return dryRun(ctx, "PATCH", `/v1/templates/${positional[0]}`, patch);
|
|
2637
|
+
const { wa } = await connect(ctx, ["whatsapp:templates:manage"]);
|
|
2638
|
+
const updated = await wa.templates.update(positional[0], patch);
|
|
2639
|
+
emit2(ctx, updated, [`\u2713 plantilla ${updated.templateName ?? positional[0]} editada: ${updated.status} (Meta la revisa de nuevo)`, " seguir la aprobaci\xF3n: customy whatsapp templates status " + positional[0]]);
|
|
2640
|
+
return WHATSAPP_EXIT.ok;
|
|
2641
|
+
}
|
|
2642
|
+
if (action === "delete") {
|
|
2643
|
+
const { flags, rest: positional } = parse4(rest, { yes: "boolean", "dry-run": "boolean" }, { min: 1, max: 1 });
|
|
2644
|
+
const ctx = context2(io, flags);
|
|
2645
|
+
requireYes(flags, `borrar la plantilla ${positional[0]} (tambi\xE9n en Meta)`);
|
|
2646
|
+
if (bool2(flags, "dry-run")) return dryRun(ctx, "DELETE", `/v1/templates/${positional[0]}`);
|
|
2647
|
+
const { wa } = await connect(ctx, ["whatsapp:templates:delete"]);
|
|
2648
|
+
const result = await wa.templates.delete(positional[0]);
|
|
2649
|
+
emit2(ctx, result, [`\u2713 plantilla ${positional[0]} borrada`]);
|
|
2650
|
+
return WHATSAPP_EXIT.ok;
|
|
2651
|
+
}
|
|
2652
|
+
throw new UsageError4("customy whatsapp templates list|get <id>|status <id>|sync|create --file|edit <id> --file|delete <id> --yes");
|
|
2653
|
+
}
|
|
2654
|
+
var broadcastsTable = (items) => items.length === 0 ? ["(sin difusiones)"] : table2([["ID", "NOMBRE", "ESTADO", "PLANTILLA", "ENVIADOS/TOTAL", "FALLIDOS", "PROGRAMADA"], ...items.map((b) => [b.id, b.name, b.status, b.templateName, `${b.sentCount}/${b.totalRecipients}`, String(b.failedCount), when(b.scheduledAt)])]);
|
|
2655
|
+
function progressLines(p) {
|
|
2656
|
+
const parts = Object.entries(p.byStatus).filter(([, n]) => n > 0).map(([status2, n]) => `${status2} ${n}`);
|
|
2657
|
+
return [`${p.broadcastId}: ${p.status} \xB7 ${p.total} destinatarios${parts.length ? ` \xB7 ${parts.join(" \xB7 ")}` : ""}`];
|
|
2658
|
+
}
|
|
2659
|
+
var recipientsTable = (items) => items.length === 0 ? ["(sin destinatarios en ese estado)"] : table2([["DESTINATARIO", "ESTADO", "CAUSA", "REINTENTO"], ...items.map((r) => [r.to, r.status, r.errorCode ?? "", r.notBefore ? when(r.notBefore) : ""])]);
|
|
2660
|
+
var RECIPIENT_STATUSES = ["pending", "sending", "sent", "delivered", "failed", "suppressed", "cancelled"];
|
|
2661
|
+
async function recipientsFromFile(io, file) {
|
|
2662
|
+
if (file.toLowerCase().endsWith(".json")) {
|
|
2663
|
+
const parsed = await readJsonFile(io, file);
|
|
2664
|
+
if (!Array.isArray(parsed)) throw new UsageError4(`${file} debe ser un arreglo JSON de n\xFAmeros o de { to, params?, consentStatus?, timezone? }`);
|
|
2665
|
+
return parsed;
|
|
2666
|
+
}
|
|
2667
|
+
try {
|
|
2668
|
+
return (await readFile(path3.resolve(io.cwd, file), "utf8")).split(/\r?\n/).map((line) => line.split("#")[0].trim()).filter(Boolean);
|
|
2669
|
+
} catch (error) {
|
|
2670
|
+
throw new UsageError4(`no se pudo leer ${file}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2671
|
+
}
|
|
2672
|
+
}
|
|
2673
|
+
async function buildBroadcast(ctx, flags) {
|
|
2674
|
+
const { io } = ctx;
|
|
2675
|
+
const fromFile = str3(flags, "file") ? await jsonObjectFile(io, str3(flags, "file"), '{ "name", "templateName", "templateLanguage"?, "recipients": [...], "scheduledAt"? }') : {};
|
|
2676
|
+
const templateName = str3(flags, "template") ?? (typeof fromFile.templateName === "string" ? fromFile.templateName : void 0);
|
|
2677
|
+
if (!templateName) throw new UsageError4("falta la plantilla: --template N (las difusiones por API siempre usan una plantilla aprobada)");
|
|
2678
|
+
const recipients = [...Array.isArray(fromFile.recipients) ? fromFile.recipients : []];
|
|
2679
|
+
recipients.push(...list2(flags, "to"));
|
|
2680
|
+
if (str3(flags, "recipients-file")) recipients.push(...await recipientsFromFile(io, str3(flags, "recipients-file")));
|
|
2681
|
+
if (recipients.length === 0) throw new UsageError4("faltan destinatarios: --to +57\u2026 (repetible), --recipients-file o recipients en --file");
|
|
2682
|
+
if (recipients.length > 1e3) throw new UsageError4(`${recipients.length} destinatarios: el m\xE1ximo es 1000 por difusi\xF3n, divide la lista`);
|
|
2683
|
+
const consent = oneOf(flags, "consent", ["unknown", "opted_in", "opted_out"]);
|
|
2684
|
+
const withConsent = consent ? recipients.map((r) => ({ ...typeof r === "string" ? { to: r } : r, consentStatus: consent })) : recipients;
|
|
2685
|
+
const scheduledAt = isoDate(flags, "schedule") ?? (typeof fromFile.scheduledAt === "string" ? fromFile.scheduledAt : void 0);
|
|
2686
|
+
const name = str3(flags, "name") ?? (typeof fromFile.name === "string" ? fromFile.name : `Difusi\xF3n ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 16).replace("T", " ")}`);
|
|
2687
|
+
const phoneId = str3(flags, "phone") ?? (typeof fromFile.phoneId === "string" ? fromFile.phoneId : void 0) ?? io.env.CUSTOMY_WHATSAPP_PHONE_ID;
|
|
2688
|
+
const language = str3(flags, "language") ?? (typeof fromFile.templateLanguage === "string" ? fromFile.templateLanguage : void 0);
|
|
2689
|
+
const purpose = oneOf(flags, "purpose", ["marketing", "service", "transactional"]);
|
|
2690
|
+
return {
|
|
2691
|
+
name,
|
|
2692
|
+
templateName,
|
|
2693
|
+
recipients: withConsent,
|
|
2694
|
+
...phoneId ? { phoneId } : {},
|
|
2695
|
+
...language ? { templateLanguage: language } : {},
|
|
2696
|
+
...Array.isArray(fromFile.templateComponents) ? { templateComponents: fromFile.templateComponents } : {},
|
|
2697
|
+
...scheduledAt ? { scheduledAt } : {},
|
|
2698
|
+
...purpose ? { messagePurpose: purpose } : {},
|
|
2699
|
+
...str3(flags, "consent-source") ? { consentSource: str3(flags, "consent-source") } : {},
|
|
2700
|
+
...str3(flags, "idempotency-key") ? { idempotencyKey: str3(flags, "idempotency-key") } : {}
|
|
2701
|
+
};
|
|
2702
|
+
}
|
|
2703
|
+
async function broadcasts(args, io) {
|
|
2704
|
+
const [action, ...rest] = args;
|
|
2705
|
+
if (action === "create") {
|
|
2706
|
+
const { flags } = parse4(rest, {
|
|
2707
|
+
file: "string",
|
|
2708
|
+
template: "string",
|
|
2709
|
+
language: "string",
|
|
2710
|
+
to: "list",
|
|
2711
|
+
"recipients-file": "string",
|
|
2712
|
+
name: "string",
|
|
2713
|
+
schedule: "string",
|
|
2714
|
+
consent: "string",
|
|
2715
|
+
purpose: "string",
|
|
2716
|
+
"consent-source": "string",
|
|
2717
|
+
"idempotency-key": "string",
|
|
2718
|
+
"dry-run": "boolean"
|
|
2719
|
+
}, { min: 0, max: 0 });
|
|
2720
|
+
const ctx = context2(io, flags);
|
|
2721
|
+
const input = await buildBroadcast(ctx, flags);
|
|
2722
|
+
if (bool2(flags, "dry-run")) {
|
|
2723
|
+
const { idempotencyKey, ...body } = input;
|
|
2724
|
+
const recipients = body.recipients.map((r) => typeof r === "string" ? { to: r } : r);
|
|
2725
|
+
emit2(ctx, { dryRun: true, method: "POST", path: "/v1/broadcasts", idempotencyKey: idempotencyKey ?? "(se genera al crear)", body: { ...body, recipients } }, [
|
|
2726
|
+
"DRY RUN (no se crea nada)",
|
|
2727
|
+
`POST /v1/broadcasts \xB7 ${recipients.length} destinatario(s)${input.scheduledAt ? ` \xB7 programada ${input.scheduledAt}` : " \xB7 sale ya"}`,
|
|
2728
|
+
JSON.stringify({ ...body, recipients: recipients.length > 5 ? [...recipients.slice(0, 5), `\u2026 +${recipients.length - 5}`] : recipients }, null, 2),
|
|
2729
|
+
"Al crearla se aplican consentimiento, horas de silencio, pacing y l\xEDmites; lo que no pueda salir queda por destinatario."
|
|
2730
|
+
]);
|
|
2731
|
+
return WHATSAPP_EXIT.ok;
|
|
2732
|
+
}
|
|
2733
|
+
const { wa, baseUrl } = await connect(ctx, ["whatsapp:broadcasts:send"]);
|
|
2734
|
+
if (!ctx.json) io.err(`\u2192 ${baseUrl}`);
|
|
2735
|
+
const result = await wa.broadcasts.create(input);
|
|
2736
|
+
emit2(ctx, result, [`\u2713 difusi\xF3n ${result.broadcastId} ${input.scheduledAt ? `programada para ${input.scheduledAt}` : "en marcha"} (${input.recipients.length} destinatarios)`, ` seguirla: customy whatsapp broadcasts status ${result.broadcastId} \xB7 fallos: --failures \xB7 detener: broadcasts cancel ${result.broadcastId} --yes`]);
|
|
2737
|
+
return WHATSAPP_EXIT.ok;
|
|
2738
|
+
}
|
|
2739
|
+
if (action === "list") {
|
|
2740
|
+
const { flags } = parse4(rest, { status: "string", limit: "string" }, { min: 0, max: 0 });
|
|
2741
|
+
const ctx = context2(io, flags);
|
|
2742
|
+
const { wa } = await connect(ctx, ["whatsapp:broadcasts:read"]);
|
|
2743
|
+
const limit = int2(flags, "limit", 1, 500);
|
|
2744
|
+
const result = await wa.broadcasts.list({ ...str3(flags, "status") ? { status: str3(flags, "status") } : {}, ...limit ? { limit } : {} });
|
|
2745
|
+
emit2(ctx, result, broadcastsTable(result.items));
|
|
2746
|
+
return WHATSAPP_EXIT.ok;
|
|
2747
|
+
}
|
|
2748
|
+
if (action === "status") {
|
|
2749
|
+
const { flags, rest: positional } = parse4(rest, { failures: "boolean", "recipient-status": "string", limit: "string" }, { min: 1, max: 1 });
|
|
2750
|
+
const ctx = context2(io, flags);
|
|
2751
|
+
const { wa } = await connect(ctx, ["whatsapp:broadcasts:read"]);
|
|
2752
|
+
const details = await wa.broadcasts.get(positional[0]);
|
|
2753
|
+
const wanted = bool2(flags, "failures") ? "failed" : oneOf(flags, "recipient-status", RECIPIENT_STATUSES);
|
|
2754
|
+
const limit = int2(flags, "limit", 1, 500);
|
|
2755
|
+
const page = wanted ? await wa.broadcasts.recipients(positional[0], { status: wanted, ...limit ? { limit } : {} }) : null;
|
|
2756
|
+
const human = [...broadcastsTable([details]), "", ...progressLines(details.progress)];
|
|
2757
|
+
if (page) human.push("", `Destinatarios ${wanted}:`, ...recipientsTable(page.items), ...page.nextCursor ? [` \u2026 hay m\xE1s: usa --limit o el SDK (broadcasts.iterateRecipients)`] : []);
|
|
2758
|
+
emit2(ctx, { ...details, ...page ? { recipients: page } : {} }, human);
|
|
2759
|
+
return WHATSAPP_EXIT.ok;
|
|
2760
|
+
}
|
|
2761
|
+
if (action === "cancel") {
|
|
2762
|
+
const { flags, rest: positional } = parse4(rest, { yes: "boolean", "dry-run": "boolean" }, { min: 1, max: 1 });
|
|
2763
|
+
const ctx = context2(io, flags);
|
|
2764
|
+
requireYes(flags, `cancelar la difusi\xF3n ${positional[0]}`);
|
|
2765
|
+
if (bool2(flags, "dry-run")) {
|
|
2766
|
+
const { wa: wa2 } = await connect(ctx, ["whatsapp:broadcasts:read"]);
|
|
2767
|
+
const progress = await wa2.broadcasts.status(positional[0]);
|
|
2768
|
+
emit2(ctx, { dryRun: true, method: "POST", path: `/v1/broadcasts/${positional[0]}/cancel`, wouldCancel: progress.byStatus.pending, progress }, [
|
|
2769
|
+
"DRY RUN (no se cancela nada)",
|
|
2770
|
+
...progressLines(progress),
|
|
2771
|
+
` se cancelar\xEDan ${progress.byStatus.pending} destinatario(s) pendientes; los ${progress.byStatus.sending} en vuelo terminan solos`
|
|
2772
|
+
]);
|
|
2773
|
+
return WHATSAPP_EXIT.ok;
|
|
2774
|
+
}
|
|
2775
|
+
const { wa } = await connect(ctx, ["whatsapp:broadcasts:cancel"]);
|
|
2776
|
+
const result = await wa.broadcasts.cancel(positional[0]);
|
|
2777
|
+
emit2(ctx, result, [result.alreadyCancelled ? `= la difusi\xF3n ${positional[0]} ya estaba cancelada` : `\u2713 difusi\xF3n ${positional[0]} cancelada: ${result.cancelledRecipients} destinatario(s) no saldr\xE1n`, ...progressLines(result)]);
|
|
2778
|
+
return WHATSAPP_EXIT.ok;
|
|
2779
|
+
}
|
|
2780
|
+
throw new UsageError4("customy whatsapp broadcasts create|list|status <id>|cancel <id> --yes");
|
|
2781
|
+
}
|
|
2782
|
+
var flowsTable = (items) => items.length === 0 ? ["(sin flujos)"] : table2([["ID", "NOMBRE", "ESTADO", "META", "N\xDAMERO"], ...items.map((f) => [f.id, f.name, f.status, f.metaFlowId ?? "-", f.phoneId])]);
|
|
2783
|
+
async function flows(args, io) {
|
|
2784
|
+
const [action, ...rest] = args;
|
|
2785
|
+
if (action === "list") {
|
|
2786
|
+
const { flags } = parse4(rest, { status: "string" }, { min: 0, max: 0 });
|
|
2787
|
+
const ctx = context2(io, flags);
|
|
2788
|
+
const { wa } = await connect(ctx, ["whatsapp:flows:read"]);
|
|
2789
|
+
const status2 = str3(flags, "status");
|
|
2790
|
+
const result = await wa.flows.list(status2 ? { status: status2 } : {});
|
|
2791
|
+
emit2(ctx, result, flowsTable(result.items));
|
|
2792
|
+
return WHATSAPP_EXIT.ok;
|
|
2793
|
+
}
|
|
2794
|
+
if (action === "get") {
|
|
2795
|
+
const { flags, rest: positional } = parse4(rest, {}, { min: 1, max: 1 });
|
|
2796
|
+
const ctx = context2(io, flags);
|
|
2797
|
+
const { wa } = await connect(ctx, ["whatsapp:flows:read"]);
|
|
2798
|
+
const flow = await wa.flows.get(positional[0]);
|
|
2799
|
+
emit2(ctx, flow, [...flowsTable([flow]), "", JSON.stringify(flow.flowJson, null, 2)]);
|
|
2800
|
+
return WHATSAPP_EXIT.ok;
|
|
2801
|
+
}
|
|
2802
|
+
if (action === "preview") {
|
|
2803
|
+
const { flags, rest: positional } = parse4(rest, {}, { min: 1, max: 1 });
|
|
2804
|
+
const ctx = context2(io, flags);
|
|
2805
|
+
const { wa } = await connect(ctx, ["whatsapp:flows:read"]);
|
|
2806
|
+
const preview2 = await wa.flows.preview(positional[0]);
|
|
2807
|
+
emit2(ctx, preview2, [`${preview2.status}${preview2.metaStatus ? ` \xB7 Meta ${preview2.metaStatus}` : ""}`, ...preview2.previewUrl ? [`vista previa: ${preview2.previewUrl}${preview2.previewExpiresAt ? ` (vence ${when(preview2.previewExpiresAt)})` : ""}`] : ["(sin vista previa: el flujo a\xFAn no est\xE1 en Meta)"], ...preview2.validationErrors.map((e) => ` \u2717 ${JSON.stringify(e)}`)]);
|
|
2808
|
+
return WHATSAPP_EXIT.ok;
|
|
2809
|
+
}
|
|
2810
|
+
if (action === "create") {
|
|
2811
|
+
const { flags } = parse4(rest, { file: "string", "dry-run": "boolean" }, { min: 0, max: 0 });
|
|
2812
|
+
const ctx = context2(io, flags);
|
|
2813
|
+
const file = str3(flags, "file");
|
|
2814
|
+
if (!file) throw new UsageError4('falta --file con { "name": "\u2026", "flowJson": { \u2026 }, "phoneId"?: "\u2026" }');
|
|
2815
|
+
const body = await jsonObjectFile(io, file, '{ "name": "\u2026", "flowJson"?: { \u2026 }, "phoneId"?: "\u2026" }');
|
|
2816
|
+
if (typeof body.name !== "string" || !body.name) throw new UsageError4(`${file} necesita "name"`);
|
|
2817
|
+
const phoneId = typeof body.phoneId === "string" ? body.phoneId : str3(flags, "phone") ?? io.env.CUSTOMY_WHATSAPP_PHONE_ID;
|
|
2818
|
+
if (bool2(flags, "dry-run")) return dryRun(ctx, "POST", "/v1/flows", { ...phoneId ? { phoneId } : {}, name: body.name, ...body.flowJson === void 0 ? {} : { flowJson: body.flowJson } });
|
|
2819
|
+
const { wa } = await connect(ctx, ["whatsapp:flows:manage"]);
|
|
2820
|
+
const created = await wa.flows.create({ name: body.name, ...phoneId ? { phoneId } : {}, ...body.flowJson === void 0 ? {} : { flowJson: body.flowJson } });
|
|
2821
|
+
emit2(ctx, created, [`\u2713 flujo ${created.name} (${created.id}) creado como ${created.status}`, ` probarlo: customy whatsapp flows preview ${created.id} \xB7 publicarlo: customy whatsapp flows publish ${created.id} --yes`]);
|
|
2822
|
+
return WHATSAPP_EXIT.ok;
|
|
2823
|
+
}
|
|
2824
|
+
if (action === "publish") {
|
|
2825
|
+
const { flags, rest: positional } = parse4(rest, { category: "list", yes: "boolean", "dry-run": "boolean" }, { min: 1, max: 1 });
|
|
2826
|
+
const ctx = context2(io, flags);
|
|
2827
|
+
requireYes(flags, `publicar el flujo ${positional[0]} (un flujo publicado ya no se edita)`);
|
|
2828
|
+
const categories = list2(flags, "category");
|
|
2829
|
+
if (bool2(flags, "dry-run")) return dryRun(ctx, "POST", `/v1/flows/${positional[0]}/publish`, categories.length ? { categories } : {});
|
|
2830
|
+
const { wa } = await connect(ctx, ["whatsapp:flows:publish"]);
|
|
2831
|
+
const published = await wa.flows.publish(positional[0], categories.length ? { categories } : {});
|
|
2832
|
+
emit2(ctx, published, [`\u2713 flujo ${published.name ?? positional[0]} publicado (${published.status})`]);
|
|
2833
|
+
return WHATSAPP_EXIT.ok;
|
|
2834
|
+
}
|
|
2835
|
+
throw new UsageError4("customy whatsapp flows list|get <id>|preview <id>|create --file|publish <id> --yes");
|
|
2836
|
+
}
|
|
2837
|
+
async function readiness(args, io) {
|
|
2838
|
+
const { flags } = parse4(args, {}, { min: 0, max: 0 });
|
|
2839
|
+
const ctx = context2(io, flags);
|
|
2840
|
+
const { wa } = await connect(ctx, ["whatsapp:readiness:read"]);
|
|
2841
|
+
const r = await wa.readiness.get();
|
|
2842
|
+
const human = [`${r.status} \xB7 ${r.mode} \xB7 ${r.canSendMessage ? "puede enviar" : "NO puede enviar"}`];
|
|
2843
|
+
for (const check2 of r.checks) human.push(`${check2.status === "ok" ? "\u2713" : check2.status === "warning" ? "!" : "\u2717"} ${check2.title}${check2.status === "ok" ? "" : ` \u2014 ${check2.detail}${check2.action ? ` (${check2.action.label}${check2.action.href ? `: ${check2.action.href}` : ""})` : ""}`}`);
|
|
2844
|
+
emit2(ctx, r, human);
|
|
2845
|
+
return WHATSAPP_EXIT.ok;
|
|
2846
|
+
}
|
|
2847
|
+
async function findings(args, io) {
|
|
2848
|
+
const { flags } = parse4(args, { hours: "string", "fail-on": "string" }, { min: 0, max: 0 });
|
|
2849
|
+
const ctx = context2(io, flags);
|
|
2850
|
+
const hours = int2(flags, "hours", 1, 720);
|
|
2851
|
+
const failOn = oneOf(flags, "fail-on", ["critical", "high", "medium", "low"]);
|
|
2852
|
+
const { wa } = await connect(ctx, ["whatsapp:findings:read"]);
|
|
2853
|
+
const report3 = await wa.findings.list(hours ? { hours } : {});
|
|
2854
|
+
emit2(ctx, report3, findingLines(report3));
|
|
2855
|
+
if (failOn) {
|
|
2856
|
+
const limit = SEVERITY_ORDER.indexOf(failOn);
|
|
2857
|
+
const hit = report3.findings.filter((f) => SEVERITY_ORDER.indexOf(f.severity) <= limit);
|
|
2858
|
+
if (hit.length > 0) {
|
|
2859
|
+
io.err(`\u2717 ${hit.length} problema(s) de gravedad ${failOn} o mayor`);
|
|
2860
|
+
return WHATSAPP_EXIT.findings;
|
|
2861
|
+
}
|
|
2862
|
+
}
|
|
2863
|
+
return WHATSAPP_EXIT.ok;
|
|
2864
|
+
}
|
|
2865
|
+
async function webhookBody(flags, io) {
|
|
2866
|
+
const file = str3(flags, "body-file");
|
|
2867
|
+
const inline = str3(flags, "body");
|
|
2868
|
+
if (file === void 0 === (inline === void 0)) throw new UsageError4("indica exactamente uno: --body-file o --body (el cuerpo CRUDO, sin re-serializar)");
|
|
2869
|
+
if (inline !== void 0) return inline;
|
|
2870
|
+
try {
|
|
2871
|
+
return await readFile(path3.resolve(io.cwd, file), "utf8");
|
|
2872
|
+
} catch (error) {
|
|
2873
|
+
throw new UsageError4(`no se pudo leer ${file}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2874
|
+
}
|
|
2875
|
+
}
|
|
2876
|
+
function secretOf(flags, io) {
|
|
2877
|
+
const name = str3(flags, "secret-env") ?? (bool2(flags, "meta") ? "META_APP_SECRET" : "CUSTOMY_WEBHOOK_SECRET");
|
|
2878
|
+
const value = io.env[name];
|
|
2879
|
+
if (!value) throw new UsageError4(`falta el secreto: define ${name} en el entorno (el secreto nunca va por la l\xEDnea de comandos; --secret-env elige otra variable)`);
|
|
2880
|
+
return value;
|
|
2881
|
+
}
|
|
2882
|
+
function webhookEvents(flags) {
|
|
2883
|
+
const events = list2(flags, "event");
|
|
2884
|
+
const unknown = events.find((event) => !WHATSAPP_WEBHOOK_EVENTS.includes(event));
|
|
2885
|
+
if (unknown) throw new UsageError4(`evento desconocido "${unknown}"; v\xE1lidos: ${WHATSAPP_WEBHOOK_EVENTS.join(", ")}`);
|
|
2886
|
+
return [...new Set(events)];
|
|
2887
|
+
}
|
|
2888
|
+
function deliveryDetailLines(d) {
|
|
2889
|
+
const lines = [
|
|
2890
|
+
`${d.status === "delivered" ? "\u2713" : d.status === "dead" ? "\u2717" : "\u2026"} ${d.id} \xB7 ${d.event} \xB7 ${d.status} \xB7 ${d.attempts} intento(s)${d.responseStatus === null ? "" : ` \xB7 HTTP ${d.responseStatus}`}${d.latencyMs === null ? "" : ` \xB7 ${d.latencyMs} ms`}${d.error ? ` \xB7 ${d.error}` : ""}`,
|
|
2891
|
+
` endpoint ${d.endpointId} \xB7 evento ${d.eventId}${d.status === "pending" && d.nextAttemptAt ? ` \xB7 pr\xF3ximo intento ${when(d.nextAttemptAt)}` : ""}`
|
|
2892
|
+
];
|
|
2893
|
+
if (d.attemptLog.length) lines.push("", ...table2([["FECHA", "INTENTO", "RESULTADO", "HTTP", "LATENCIA", "ERROR"], ...d.attemptLog.map((a) => [when(a.createdAt), String(a.attempt), a.outcome, a.responseStatus === null ? "-" : String(a.responseStatus), a.latencyMs === null ? "-" : `${a.latencyMs} ms`, a.error ?? ""])]));
|
|
2894
|
+
if (d.responseBody) lines.push("", `respuesta de tu endpoint: ${preview(d.responseBody, 300)}`);
|
|
2895
|
+
lines.push("", "cuerpo enviado (data):", JSON.stringify(d.payload, null, 2));
|
|
2896
|
+
return lines;
|
|
2897
|
+
}
|
|
2898
|
+
async function webhooksTail(args, io) {
|
|
2899
|
+
const { flags } = parse4(args, { endpoint: "string", status: "string", event: "string", interval: "string", count: "string", payload: "boolean" }, { min: 0, max: 0 });
|
|
2900
|
+
const ctx = context2(io, flags);
|
|
2901
|
+
const { wa } = await connect(ctx, ["whatsapp:webhooks"]);
|
|
2902
|
+
const status2 = oneOf(flags, "status", ["pending", "delivered", "dead"]);
|
|
2903
|
+
const intervalMs = (int2(flags, "interval", 0, 3600) ?? 3) * 1e3;
|
|
2904
|
+
const maxCount = int2(flags, "count", 1, 1e5);
|
|
2905
|
+
const filter = {
|
|
2906
|
+
limit: 100,
|
|
2907
|
+
...str3(flags, "endpoint") ? { endpointId: str3(flags, "endpoint") } : {},
|
|
2908
|
+
...status2 ? { status: status2 } : {},
|
|
2909
|
+
...str3(flags, "event") ? { event: str3(flags, "event") } : {}
|
|
2910
|
+
};
|
|
2911
|
+
const since = new Date(Date.now() - 6e4).toISOString();
|
|
2912
|
+
const known = /* @__PURE__ */ new Map();
|
|
2913
|
+
let printed = 0;
|
|
2914
|
+
let first = true;
|
|
2915
|
+
const sleep = io.sleep ?? defaultSleep;
|
|
2916
|
+
if (!ctx.json) io.err(`siguiendo entregas de webhook desde ${since} (Ctrl+C para salir)`);
|
|
2917
|
+
while (!io.signal?.aborted) {
|
|
2918
|
+
const page = await wa.webhooks.deliveries.list(filter);
|
|
2919
|
+
for (const d of [...page.items].reverse()) {
|
|
2920
|
+
const state = `${d.status}:${d.attempts}:${d.redeliveries}`;
|
|
2921
|
+
const previous = known.get(d.id);
|
|
2922
|
+
known.set(d.id, state);
|
|
2923
|
+
if (previous === state || first && previous === void 0 && d.createdAt < since) continue;
|
|
2924
|
+
const detail = flags.payload === true && previous === void 0 ? await wa.webhooks.deliveries.get(d.id).catch(() => null) : null;
|
|
2925
|
+
if (ctx.json) io.out(JSON.stringify(detail ? { ...d, payload: detail.payload } : d));
|
|
2926
|
+
else {
|
|
2927
|
+
io.out(deliveryRow(d).join(" ").trimEnd());
|
|
2928
|
+
if (detail) io.out(` ${JSON.stringify(detail.payload)}`);
|
|
2929
|
+
}
|
|
2930
|
+
printed += 1;
|
|
2931
|
+
if (maxCount !== void 0 && printed >= maxCount) return WHATSAPP_EXIT.ok;
|
|
2932
|
+
}
|
|
2933
|
+
first = false;
|
|
2934
|
+
await sleep(intervalMs, io.signal);
|
|
2935
|
+
}
|
|
2936
|
+
return WHATSAPP_EXIT.ok;
|
|
2937
|
+
}
|
|
2938
|
+
async function webhooks(args, io) {
|
|
2939
|
+
const [action, ...rest] = args;
|
|
2940
|
+
if (action === "list") {
|
|
2941
|
+
const { flags } = parse4(rest, {}, { min: 0, max: 0 });
|
|
2942
|
+
const ctx = context2(io, flags);
|
|
2943
|
+
const { wa } = await connect(ctx, ["whatsapp:webhooks"]);
|
|
2944
|
+
const result = await wa.webhooks.list();
|
|
2945
|
+
emit2(ctx, result, webhooksTable(result.items));
|
|
2946
|
+
return WHATSAPP_EXIT.ok;
|
|
2947
|
+
}
|
|
2948
|
+
if (action === "get") {
|
|
2949
|
+
const { flags, rest: positional } = parse4(rest, {}, { min: 1, max: 1 });
|
|
2950
|
+
const ctx = context2(io, flags);
|
|
2951
|
+
const { wa } = await connect(ctx, ["whatsapp:webhooks"]);
|
|
2952
|
+
const endpoint = await wa.webhooks.get(positional[0]);
|
|
2953
|
+
emit2(ctx, endpoint, [...webhooksTable([endpoint]), ...endpoint.description ? ["", endpoint.description] : []]);
|
|
2954
|
+
return WHATSAPP_EXIT.ok;
|
|
2955
|
+
}
|
|
2956
|
+
if (action === "create") {
|
|
2957
|
+
const { flags } = parse4(rest, { url: "string", event: "list", description: "string" }, { min: 0, max: 0 });
|
|
2958
|
+
const ctx = context2(io, flags);
|
|
2959
|
+
const url = str3(flags, "url");
|
|
2960
|
+
if (!url) throw new UsageError4("falta --url (https://\u2026, p\xFAblico: sin IPs privadas ni credenciales en la URL)");
|
|
2961
|
+
const events = webhookEvents(flags);
|
|
2962
|
+
const { wa } = await connect(ctx, ["whatsapp:webhooks"]);
|
|
2963
|
+
const created = await wa.webhooks.create({ url, ...events.length ? { events } : {}, ...str3(flags, "description") ? { description: str3(flags, "description") } : {} });
|
|
2964
|
+
emit2(ctx, created, [
|
|
2965
|
+
`\u2713 endpoint ${created.id} creado: ${created.url} (${created.events.length ? created.events.join(", ") : "todos los eventos"})`,
|
|
2966
|
+
` secreto de firma (se muestra UNA vez, gu\xE1rdalo ya): ${created.secret}`,
|
|
2967
|
+
" verif\xEDcalo en tu servidor con verifyWebhook(rawBody, headers, secret) de @customyai/whatsapp \xB7 probar: customy whatsapp webhooks test " + created.id
|
|
2968
|
+
]);
|
|
2969
|
+
return WHATSAPP_EXIT.ok;
|
|
2970
|
+
}
|
|
2971
|
+
if (action === "update") {
|
|
2972
|
+
const { flags, rest: positional } = parse4(rest, { url: "string", event: "list", "all-events": "boolean", description: "string", enable: "boolean", disable: "boolean" }, { min: 1, max: 1 });
|
|
2973
|
+
const ctx = context2(io, flags);
|
|
2974
|
+
if (bool2(flags, "enable") && bool2(flags, "disable")) throw new UsageError4("--enable y --disable no se combinan");
|
|
2975
|
+
if (bool2(flags, "all-events") && list2(flags, "event").length) throw new UsageError4("--all-events y --event no se combinan");
|
|
2976
|
+
const events = webhookEvents(flags);
|
|
2977
|
+
const patch = {
|
|
2978
|
+
...str3(flags, "url") ? { url: str3(flags, "url") } : {},
|
|
2979
|
+
...bool2(flags, "all-events") ? { events: [] } : events.length ? { events } : {},
|
|
2980
|
+
...str3(flags, "description") !== void 0 ? { description: str3(flags, "description") } : {},
|
|
2981
|
+
...bool2(flags, "enable") ? { status: "active" } : bool2(flags, "disable") ? { status: "disabled" } : {}
|
|
2982
|
+
};
|
|
2983
|
+
if (Object.keys(patch).length === 0) throw new UsageError4("nada que cambiar: usa --url, --event, --all-events, --description, --enable o --disable");
|
|
2984
|
+
const { wa } = await connect(ctx, ["whatsapp:webhooks"]);
|
|
2985
|
+
const updated = await wa.webhooks.update(positional[0], patch);
|
|
2986
|
+
emit2(ctx, updated, ["\u2713 actualizado", ...webhooksTable([updated])]);
|
|
2987
|
+
return WHATSAPP_EXIT.ok;
|
|
2988
|
+
}
|
|
2989
|
+
if (action === "delete") {
|
|
2990
|
+
const { flags, rest: positional } = parse4(rest, {}, { min: 1, max: 1 });
|
|
2991
|
+
const ctx = context2(io, flags);
|
|
2992
|
+
const { wa } = await connect(ctx, ["whatsapp:webhooks"]);
|
|
2993
|
+
await wa.webhooks.delete(positional[0]);
|
|
2994
|
+
emit2(ctx, { deleted: true, id: positional[0] }, [`\u2713 endpoint ${positional[0]} eliminado`]);
|
|
2995
|
+
return WHATSAPP_EXIT.ok;
|
|
2996
|
+
}
|
|
2997
|
+
if (action === "rotate") {
|
|
2998
|
+
const { flags, rest: positional } = parse4(rest, {}, { min: 1, max: 1 });
|
|
2999
|
+
const ctx = context2(io, flags);
|
|
3000
|
+
const { wa } = await connect(ctx, ["whatsapp:webhooks"]);
|
|
3001
|
+
const rotated = await wa.webhooks.rotateSecret(positional[0]);
|
|
3002
|
+
emit2(ctx, rotated, [
|
|
3003
|
+
`\u2713 secreto de ${rotated.id} rotado`,
|
|
3004
|
+
` secreto nuevo (se muestra UNA vez): ${rotated.secret}`,
|
|
3005
|
+
` el anterior sigue firmando hasta ${when(rotated.previousSecretValidUntil)}: despliega el nuevo en tu servidor antes de esa hora`
|
|
3006
|
+
]);
|
|
3007
|
+
return WHATSAPP_EXIT.ok;
|
|
3008
|
+
}
|
|
3009
|
+
if (action === "test") {
|
|
3010
|
+
const { flags, rest: positional } = parse4(rest, { wait: "boolean" }, { min: 1, max: 1 });
|
|
3011
|
+
const ctx = context2(io, flags);
|
|
3012
|
+
const { wa } = await connect(ctx, ["whatsapp:webhooks"]);
|
|
3013
|
+
const queued = await wa.webhooks.test(positional[0]);
|
|
3014
|
+
if (!bool2(flags, "wait")) {
|
|
3015
|
+
emit2(ctx, queued, [`\u2713 evento de prueba encolado (${queued.deliveryId}): customy whatsapp webhooks delivery ${queued.deliveryId}`]);
|
|
3016
|
+
return WHATSAPP_EXIT.ok;
|
|
3017
|
+
}
|
|
3018
|
+
const sleep = io.sleep ?? defaultSleep;
|
|
3019
|
+
let detail = await wa.webhooks.deliveries.get(queued.deliveryId);
|
|
3020
|
+
for (let waited = 0; detail.status === "pending" && waited < 20 && !io.signal?.aborted; waited += 1) {
|
|
3021
|
+
await sleep(1e3, io.signal);
|
|
3022
|
+
detail = await wa.webhooks.deliveries.get(queued.deliveryId);
|
|
3023
|
+
}
|
|
3024
|
+
emit2(ctx, detail, deliveryDetailLines(detail));
|
|
3025
|
+
return detail.status === "delivered" ? WHATSAPP_EXIT.ok : WHATSAPP_EXIT.failure;
|
|
3026
|
+
}
|
|
3027
|
+
if (action === "deliveries") {
|
|
3028
|
+
const { flags } = parse4(rest, { endpoint: "string", status: "string", event: "string", limit: "string" }, { min: 0, max: 0 });
|
|
3029
|
+
const ctx = context2(io, flags);
|
|
3030
|
+
const { wa } = await connect(ctx, ["whatsapp:webhooks"]);
|
|
3031
|
+
const status2 = oneOf(flags, "status", ["pending", "delivered", "dead"]);
|
|
3032
|
+
const limit = int2(flags, "limit", 1, 200);
|
|
3033
|
+
const result = await wa.webhooks.deliveries.list({
|
|
3034
|
+
...str3(flags, "endpoint") ? { endpointId: str3(flags, "endpoint") } : {},
|
|
3035
|
+
...status2 ? { status: status2 } : {},
|
|
3036
|
+
...str3(flags, "event") ? { event: str3(flags, "event") } : {},
|
|
3037
|
+
...limit ? { limit } : {}
|
|
3038
|
+
});
|
|
3039
|
+
emit2(ctx, result, deliveriesTable(result.items));
|
|
3040
|
+
return WHATSAPP_EXIT.ok;
|
|
3041
|
+
}
|
|
3042
|
+
if (action === "delivery") {
|
|
3043
|
+
const { flags, rest: positional } = parse4(rest, {}, { min: 1, max: 1 });
|
|
3044
|
+
const ctx = context2(io, flags);
|
|
3045
|
+
const { wa } = await connect(ctx, ["whatsapp:webhooks"]);
|
|
3046
|
+
const detail = await wa.webhooks.deliveries.get(positional[0]);
|
|
3047
|
+
emit2(ctx, detail, deliveryDetailLines(detail));
|
|
3048
|
+
return WHATSAPP_EXIT.ok;
|
|
3049
|
+
}
|
|
3050
|
+
if (action === "redeliver") {
|
|
3051
|
+
const { flags, rest: positional } = parse4(rest, {}, { min: 1, max: 1 });
|
|
3052
|
+
const ctx = context2(io, flags);
|
|
3053
|
+
const { wa } = await connect(ctx, ["whatsapp:webhooks"]);
|
|
3054
|
+
const result = await wa.webhooks.deliveries.redeliver(positional[0]);
|
|
3055
|
+
emit2(ctx, result, [`\u2713 ${result.id} vuelve a la cola (mismo webhook-id: tu endpoint puede deduplicar); sigue el resultado: customy whatsapp webhooks delivery ${result.id}`]);
|
|
3056
|
+
return WHATSAPP_EXIT.ok;
|
|
3057
|
+
}
|
|
3058
|
+
if (action === "tail") return webhooksTail(rest, io);
|
|
3059
|
+
if (action === "verify") {
|
|
3060
|
+
const { flags } = parse4(rest, { "body-file": "string", body: "string", header: "list", "secret-env": "string", meta: "boolean", tolerance: "string", at: "string" }, { min: 0, max: 0 });
|
|
3061
|
+
const ctx = context2(io, flags);
|
|
3062
|
+
const body = await webhookBody(flags, io);
|
|
3063
|
+
const secret = secretOf(flags, io);
|
|
3064
|
+
const headers = {};
|
|
3065
|
+
for (const pair of list2(flags, "header")) {
|
|
3066
|
+
const at2 = pair.indexOf("=");
|
|
3067
|
+
if (at2 <= 0) throw new UsageError4(`--header espera nombre=valor, recibi\xF3 "${pair}"`);
|
|
3068
|
+
headers[pair.slice(0, at2).trim().toLowerCase()] = pair.slice(at2 + 1).trim();
|
|
3069
|
+
}
|
|
3070
|
+
const tolerance = int2(flags, "tolerance", 1, 31536e3);
|
|
3071
|
+
const at = isoDate(flags, "at");
|
|
3072
|
+
try {
|
|
3073
|
+
if (bool2(flags, "meta")) {
|
|
3074
|
+
const payload = await verifyMetaSignature(body, headers, secret);
|
|
3075
|
+
emit2(ctx, { valid: true, scheme: "meta", payload }, ["\u2713 firma de Meta v\xE1lida (X-Hub-Signature-256)"]);
|
|
3076
|
+
} else {
|
|
3077
|
+
const event = await verifyWebhook(body, headers, secret, { ...tolerance ? { toleranceSeconds: tolerance } : {}, ...at ? { now: new Date(at) } : {} });
|
|
3078
|
+
emit2(ctx, { valid: true, scheme: "customy", event }, [`\u2713 firma v\xE1lida: ${String(event.type ?? "(sin type)")}${event.id ? ` (${String(event.id)})` : ""}`]);
|
|
3079
|
+
}
|
|
3080
|
+
return WHATSAPP_EXIT.ok;
|
|
3081
|
+
} catch (error) {
|
|
3082
|
+
if (!(error instanceof WebhookVerificationError)) throw error;
|
|
3083
|
+
emit2(ctx, { valid: false, reason: error.message }, [`\u2717 firma inv\xE1lida: ${error.message}`]);
|
|
3084
|
+
if (ctx.json) io.err(`\u2717 firma inv\xE1lida: ${error.message}`);
|
|
3085
|
+
return WHATSAPP_EXIT.failure;
|
|
3086
|
+
}
|
|
3087
|
+
}
|
|
3088
|
+
if (action === "sign") {
|
|
3089
|
+
const { flags } = parse4(rest, { "body-file": "string", body: "string", "secret-env": "string", meta: "boolean", id: "string" }, { min: 0, max: 0 });
|
|
3090
|
+
const ctx = context2(io, flags);
|
|
3091
|
+
const body = await webhookBody(flags, io);
|
|
3092
|
+
const secret = secretOf(flags, io);
|
|
3093
|
+
if (bool2(flags, "meta")) {
|
|
3094
|
+
const signature2 = await signMetaPayload(secret, body);
|
|
3095
|
+
emit2(ctx, { "x-hub-signature-256": signature2 }, [`x-hub-signature-256: ${signature2}`]);
|
|
3096
|
+
return WHATSAPP_EXIT.ok;
|
|
3097
|
+
}
|
|
3098
|
+
const id = str3(flags, "id") ?? `evt_${Date.now().toString(36)}`;
|
|
3099
|
+
const timestamp = Math.floor(Date.now() / 1e3);
|
|
3100
|
+
const signature = await signPayload(secret, id, timestamp, body).catch(() => {
|
|
3101
|
+
throw new UsageError4("el secreto no es base64 v\xE1lido (se espera whsec_\u2026)");
|
|
3102
|
+
});
|
|
3103
|
+
emit2(ctx, { "webhook-id": id, "webhook-timestamp": String(timestamp), "webhook-signature": signature }, [`webhook-id: ${id}`, `webhook-timestamp: ${timestamp}`, `webhook-signature: ${signature}`]);
|
|
3104
|
+
return WHATSAPP_EXIT.ok;
|
|
3105
|
+
}
|
|
3106
|
+
throw new UsageError4("customy whatsapp webhooks list|get|create|update|delete|rotate|test|deliveries|delivery|redeliver|tail|verify|sign");
|
|
3107
|
+
}
|
|
3108
|
+
function report2(error, io) {
|
|
3109
|
+
if (error instanceof UsageError4) {
|
|
3110
|
+
io.err(`error: ${error.message}`);
|
|
3111
|
+
io.err("ayuda: customy whatsapp --help");
|
|
3112
|
+
return WHATSAPP_EXIT.failure;
|
|
3113
|
+
}
|
|
3114
|
+
if (error && typeof error === "object" && "code" in error && "status" in error && typeof error.code === "string") {
|
|
3115
|
+
const e = error;
|
|
3116
|
+
io.err(`error ${e.code}${e.status ? ` [${e.status}]` : ""}: ${e.message}${e.requestId ? ` (petici\xF3n ${e.requestId})` : ""}`);
|
|
3117
|
+
const body = e.body && typeof e.body === "object" ? e.body : void 0;
|
|
3118
|
+
if (e.code === "INSUFFICIENT_SCOPE" && typeof body?.scope === "string") io.err(`falta el scope ${body.scope} en la llave de Access (audiencia ${WHATSAPP_AUDIENCE})`);
|
|
3119
|
+
if (e.code === "M2M_NOT_CONFIGURED") io.err("el servicio de WhatsApp de este entorno a\xFAn no acepta llaves de Access (falta CUSTOMY_ACCESS_ISSUER en customy-whatsapp)");
|
|
3120
|
+
if (e.retryAfterMs) io.err(`reintenta en ${Math.ceil(e.retryAfterMs / 1e3)} s`);
|
|
3121
|
+
return e.status === 401 || e.status === 403 ? WHATSAPP_EXIT.auth : WHATSAPP_EXIT.failure;
|
|
3122
|
+
}
|
|
3123
|
+
io.err(`error: ${error instanceof Error ? error.message : "fallo inesperado"}`);
|
|
3124
|
+
return WHATSAPP_EXIT.failure;
|
|
3125
|
+
}
|
|
3126
|
+
async function runWhatsAppCli(args, io) {
|
|
3127
|
+
try {
|
|
3128
|
+
const [command2, ...rest] = args;
|
|
3129
|
+
if (command2 === void 0 || command2 === "--help" || command2 === "help" || rest.includes("--help")) {
|
|
3130
|
+
io.out(WHATSAPP_HELP.join("\n"));
|
|
3131
|
+
return WHATSAPP_EXIT.ok;
|
|
3132
|
+
}
|
|
3133
|
+
switch (command2) {
|
|
3134
|
+
case "numbers":
|
|
3135
|
+
return await numbers(rest, io);
|
|
3136
|
+
case "send":
|
|
3137
|
+
return await send(rest, io);
|
|
3138
|
+
case "messages":
|
|
3139
|
+
return await messages(rest, io);
|
|
3140
|
+
case "conversations":
|
|
3141
|
+
return await conversations(rest, io);
|
|
3142
|
+
case "tail":
|
|
3143
|
+
return await tail(rest, io);
|
|
3144
|
+
case "templates":
|
|
3145
|
+
return await templates(rest, io);
|
|
3146
|
+
case "broadcasts":
|
|
3147
|
+
return await broadcasts(rest, io);
|
|
3148
|
+
case "flows":
|
|
3149
|
+
return await flows(rest, io);
|
|
3150
|
+
case "readiness":
|
|
3151
|
+
return await readiness(rest, io);
|
|
3152
|
+
case "findings":
|
|
3153
|
+
return await findings(rest, io);
|
|
3154
|
+
case "webhooks":
|
|
3155
|
+
return await webhooks(rest, io);
|
|
3156
|
+
default:
|
|
3157
|
+
throw new UsageError4(`comando desconocido: customy whatsapp ${command2}`);
|
|
3158
|
+
}
|
|
3159
|
+
} catch (error) {
|
|
3160
|
+
return report2(error, io);
|
|
3161
|
+
}
|
|
3162
|
+
}
|
|
3163
|
+
function option(args, name) {
|
|
3164
|
+
const index = args.indexOf(`--${name}`);
|
|
3165
|
+
return index >= 0 ? args[index + 1] : void 0;
|
|
3166
|
+
}
|
|
3167
|
+
async function loadManifest(args, io) {
|
|
3168
|
+
const file = path3.resolve(io.cwd, option(args, "file") ?? "customy.app.json");
|
|
3169
|
+
let raw;
|
|
3170
|
+
try {
|
|
3171
|
+
raw = JSON.parse(await readFile(file, "utf8"));
|
|
3172
|
+
} catch (error) {
|
|
3173
|
+
io.err(`no se pudo leer ${path3.relative(io.cwd, file) || file}: ${error instanceof Error ? error.message : error}`);
|
|
3174
|
+
return null;
|
|
3175
|
+
}
|
|
3176
|
+
const result = validateManifest(raw);
|
|
3177
|
+
if (!result.ok) {
|
|
3178
|
+
for (const problem of result.problems) io.err(describeProblem(problem));
|
|
3179
|
+
return null;
|
|
3180
|
+
}
|
|
3181
|
+
return result.manifest;
|
|
3182
|
+
}
|
|
3183
|
+
async function runCli(argv, io) {
|
|
3184
|
+
const [group, command2, ...args] = argv;
|
|
3185
|
+
if (group === "--help" || group === "help") {
|
|
3186
|
+
io.out(["uso: customy apps <validate|codegen|sync> [--file customy.app.json]", ...PROVISIONING_HELP, ...EXPERIMENTS_HELP, ...EXPERIENCE_HELP, ...WHATSAPP_HELP].join("\n"));
|
|
3187
|
+
return 0;
|
|
3188
|
+
}
|
|
3189
|
+
if (PROVISIONING_GROUPS.includes(group ?? "")) return runProvisioningCli(group, argv.slice(1), io);
|
|
3190
|
+
if (EXPERIMENTS_GROUPS.includes(group ?? "")) return runExperimentsCli(group, argv.slice(1), io);
|
|
3191
|
+
if (EXPERIENCE_GROUPS.includes(group ?? "")) return runExperienceCli(argv.slice(1), io);
|
|
3192
|
+
if (WHATSAPP_GROUPS.includes(group ?? "")) return runWhatsAppCli(argv.slice(1), io);
|
|
3193
|
+
if (group !== "apps" || !["validate", "codegen", "sync"].includes(command2 ?? "")) {
|
|
3194
|
+
io.err("uso: customy apps <validate|codegen|sync> [--file customy.app.json]");
|
|
3195
|
+
io.err(" customy users | audit | policy | whoami | login | flags | segments | experiments | experience | whatsapp (customy --help)");
|
|
3196
|
+
return 2;
|
|
3197
|
+
}
|
|
3198
|
+
const manifest = await loadManifest(args, io);
|
|
3199
|
+
if (!manifest) return 1;
|
|
3200
|
+
if (command2 === "validate") {
|
|
3201
|
+
io.out(`\u2713 ${manifest.key}: manifiesto app/v1 v\xE1lido (${manifest.events.length} eventos, ${manifest.capabilities.length} capabilities, ${authorizationSummary(manifest)})`);
|
|
3202
|
+
return 0;
|
|
3203
|
+
}
|
|
3204
|
+
if (command2 === "codegen") {
|
|
3205
|
+
const out = path3.resolve(io.cwd, option(args, "out") ?? "customy.generated.ts");
|
|
3206
|
+
await mkdir(path3.dirname(out), { recursive: true });
|
|
3207
|
+
await writeFile(out, generateAppTypes(manifest));
|
|
3208
|
+
io.out(`\u2713 tipos de ${manifest.key} en ${path3.relative(io.cwd, out)}`);
|
|
3209
|
+
return 0;
|
|
3210
|
+
}
|
|
3211
|
+
const workspaceEnvironmentId = option(args, "workspace-env");
|
|
3212
|
+
const accessUrl = io.env.CUSTOMY_ACCESS_URL;
|
|
3213
|
+
const token = io.env.CUSTOMY_ACCESS_TOKEN;
|
|
3214
|
+
if (!workspaceEnvironmentId || !accessUrl || !token) {
|
|
3215
|
+
io.err("sync necesita --workspace-env y las variables CUSTOMY_ACCESS_URL y CUSTOMY_ACCESS_TOKEN");
|
|
3216
|
+
return 2;
|
|
3217
|
+
}
|
|
3218
|
+
try {
|
|
3219
|
+
const result = await syncApp({
|
|
3220
|
+
manifest,
|
|
3221
|
+
accessUrl,
|
|
3222
|
+
token,
|
|
3223
|
+
workspaceEnvironmentId,
|
|
3224
|
+
reason: option(args, "reason") ?? `customy apps sync ${manifest.key}`,
|
|
3225
|
+
fetch: io.fetch
|
|
3226
|
+
});
|
|
3227
|
+
const verb = { installed: "instalada", updated: "actualizada", unchanged: "sin cambios" }[result.action];
|
|
3228
|
+
io.out(`\u2713 ${manifest.key} ${verb}: aplicaci\xF3n ${result.applicationId}, entorno ${result.environmentId}, revisi\xF3n ${result.revision} (${authorizationSummary(manifest)})`);
|
|
3229
|
+
let failed = false;
|
|
3230
|
+
for (const [product2, outcome] of Object.entries(result.reconciliation)) {
|
|
3231
|
+
if (outcome.status === "failed") {
|
|
3232
|
+
failed = true;
|
|
3233
|
+
io.err(`\u2717 ${product2}: ${outcome.code}${outcome.conflicts?.length ? ` (${outcome.conflicts.join(", ")})` : ""} \u2014 vuelve a ejecutar sync para reintentar`);
|
|
3234
|
+
} else if (outcome.status === "reconciled") {
|
|
3235
|
+
const counts = outcome.permissions !== void 0 || outcome.roles !== void 0 ? ` (${outcome.permissions ?? 0} permisos, ${outcome.roles ?? 0} roles${outcome.rolesOrphaned ? `, ${outcome.rolesOrphaned} roles hu\xE9rfanos` : ""})` : "";
|
|
3236
|
+
io.out(`\u2713 ${product2}: ${outcome.changed ? "actualizado" : "al d\xEDa"}${outcome.resourceId ? ` (${outcome.resourceId})` : ""}${counts}`);
|
|
3237
|
+
}
|
|
3238
|
+
}
|
|
3239
|
+
return failed ? 1 : 0;
|
|
3240
|
+
} catch (error) {
|
|
3241
|
+
io.err(`\u2717 sync: ${error instanceof Error ? error.message : error}`);
|
|
3242
|
+
return 1;
|
|
3243
|
+
}
|
|
3244
|
+
}
|
|
3245
|
+
|
|
3246
|
+
export { EXIT, EXPERIENCE_EXIT, EXPERIMENTS_EXIT, SyncError, WHATSAPP_EXIT, generateAppTypes, runCli, runExperienceCli, runExperimentsCli, runProvisioningCli, runWhatsAppCli, schemaToType, serializeCatalog, syncApp, validateManifest };
|