koigrid 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/dist/api.js +57 -3
- package/dist/commands/apps.js +194 -12
- package/dist/commands/billing.js +70 -14
- package/dist/commands/db.js +393 -17
- package/dist/commands/events.js +15 -3
- package/dist/commands/experiments.js +105 -0
- package/dist/commands/flags.js +21 -2
- package/dist/commands/network.js +28 -0
- package/dist/commands/notifications.js +2 -2
- package/dist/commands/pricing.js +37 -0
- package/dist/commands/redis.js +62 -0
- package/dist/commands/registry.js +15 -0
- package/dist/commands/rewards.js +34 -19
- package/dist/commands/sandboxes.js +506 -1
- package/dist/commands/storage.js +20 -0
- package/dist/commands/tokens.js +5 -1
- package/dist/esperar.js +41 -0
- package/dist/help.js +14 -1
- package/dist/index.js +13 -3
- package/dist/manifest.js +23 -11
- package/dist/registry.js +3 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,23 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to the koigrid CLI are documented here. Format: [Keep a Changelog](https://keepachangelog.com). Versions follow [SemVer](https://semver.org).
|
|
4
4
|
|
|
5
|
+
## [Unreleased]
|
|
6
|
+
|
|
7
|
+
## [0.9.0] — 2026-11-25
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
- **Default port comes from the image** (ficha 4d8b02da): without `--port`, the app listens on the image's single
|
|
11
|
+
`EXPOSE` port (an nginx `--dir` app goes live on 80), else 3000. A warning is shown if it clashes with one you chose.
|
|
12
|
+
- **A missing image is reported as such** (ficha 51987655): the deploy fails with `image_pull_failed` ("could not pull
|
|
13
|
+
the image") instead of a timeout, and internal timestamps no longer leak into your log.
|
|
14
|
+
- **`koigrid apps deploy` waits for the outcome** (ficha f76082de): shows each state change and ends with the URL, or with
|
|
15
|
+
the error and the last lines of the build/deploy log (exit code 1). `--no-wait` / `--detach` return at once,
|
|
16
|
+
`--timeout <min>` (default 20). With `--json` it still returns at once unless you pass `--wait` (scripts don't change).
|
|
17
|
+
|
|
18
|
+
### Added
|
|
19
|
+
- **`koigrid apps port <id> <n>`** — change an app's port after creating it (redeploys).
|
|
20
|
+
- **Help per command and subcommand**: `koigrid apps deploy --help` lists its flags (it used to print the global help).
|
|
21
|
+
|
|
5
22
|
## [0.7.0] — 2026-07-24
|
|
6
23
|
|
|
7
24
|
### Added
|
package/dist/api.js
CHANGED
|
@@ -13,10 +13,13 @@ export const USER_AGENT = `koigrid-cli/${VERSION}`;
|
|
|
13
13
|
export class ApiError extends Error {
|
|
14
14
|
status;
|
|
15
15
|
detail;
|
|
16
|
-
|
|
16
|
+
body;
|
|
17
|
+
/** `body`: el JSON de error entero, para los campos que no son `error`/`detail` (p. ej. `checkoutUrl`). */
|
|
18
|
+
constructor(status, message, detail, body) {
|
|
17
19
|
super(message);
|
|
18
20
|
this.status = status;
|
|
19
21
|
this.detail = detail;
|
|
22
|
+
this.body = body;
|
|
20
23
|
this.name = 'ApiError';
|
|
21
24
|
}
|
|
22
25
|
}
|
|
@@ -50,7 +53,7 @@ export async function api(path, opts = {}) {
|
|
|
50
53
|
}
|
|
51
54
|
catch { }
|
|
52
55
|
;
|
|
53
|
-
throw new ApiError(res.status, j?.error || `HTTP ${res.status}`, j?.detail);
|
|
56
|
+
throw new ApiError(res.status, j?.error || `HTTP ${res.status}`, j?.detail, j ?? { requestId: res.headers.get('x-request-id') ?? undefined });
|
|
54
57
|
}
|
|
55
58
|
return text;
|
|
56
59
|
}
|
|
@@ -60,6 +63,57 @@ export async function api(path, opts = {}) {
|
|
|
60
63
|
}
|
|
61
64
|
catch { /* non-json */ }
|
|
62
65
|
if (!res.ok)
|
|
63
|
-
throw new ApiError(res.status, json?.error || `HTTP ${res.status}`, json?.detail);
|
|
66
|
+
throw new ApiError(res.status, json?.error || `HTTP ${res.status}`, json?.detail, json);
|
|
64
67
|
return json;
|
|
65
68
|
}
|
|
69
|
+
/**
|
|
70
|
+
* Una respuesta NDJSON (application/x-ndjson) de la API, evento a evento según llega: la salida en directo de una orden
|
|
71
|
+
* de una VM. Sin el plazo de 30 s de `api` (un enganche dura hasta 10 min por diseño): el servidor manda un latido
|
|
72
|
+
* cada 15 s, así que 60 s sin nada es una conexión muerta. Un error HTTP antes del primer evento se lanza como en `api`.
|
|
73
|
+
*/
|
|
74
|
+
export async function apiNdjson(path, opts, alEvento) {
|
|
75
|
+
const cfg = loadConfig();
|
|
76
|
+
if (!cfg.token)
|
|
77
|
+
throw new ApiError(401, 'Not logged in. Run `koigrid login` (or set KOIGRID_TOKEN).');
|
|
78
|
+
const ctrl = new AbortController();
|
|
79
|
+
let vigia = setTimeout(() => ctrl.abort(), 60_000);
|
|
80
|
+
const res = await fetch(`${cfg.api || DEFAULT_API}${path}`, {
|
|
81
|
+
method: opts.method || 'GET',
|
|
82
|
+
headers: { 'user-agent': USER_AGENT, Authorization: `Bearer ${cfg.token}`, accept: 'application/x-ndjson', ...(opts.body ? { 'content-type': 'application/json' } : {}) },
|
|
83
|
+
body: opts.body ? JSON.stringify(opts.body) : undefined,
|
|
84
|
+
signal: ctrl.signal,
|
|
85
|
+
}).catch((e) => { throw new ApiError(0, `network error: ${e?.message || e}`); });
|
|
86
|
+
if (!res.ok || !res.body) {
|
|
87
|
+
clearTimeout(vigia);
|
|
88
|
+
const text = await res.text();
|
|
89
|
+
let j = null;
|
|
90
|
+
try {
|
|
91
|
+
j = JSON.parse(text);
|
|
92
|
+
}
|
|
93
|
+
catch { }
|
|
94
|
+
throw new ApiError(res.status, j?.error || `HTTP ${res.status}`, j?.detail, j);
|
|
95
|
+
}
|
|
96
|
+
const dec = new TextDecoder();
|
|
97
|
+
let resto = '';
|
|
98
|
+
try {
|
|
99
|
+
for await (const trozo of res.body) {
|
|
100
|
+
clearTimeout(vigia);
|
|
101
|
+
vigia = setTimeout(() => ctrl.abort(), 60_000);
|
|
102
|
+
const partes = (resto + dec.decode(trozo, { stream: true })).split('\n');
|
|
103
|
+
resto = partes.pop() ?? '';
|
|
104
|
+
for (const l of partes)
|
|
105
|
+
if (l.trim())
|
|
106
|
+
alEvento(JSON.parse(l));
|
|
107
|
+
}
|
|
108
|
+
if (resto.trim())
|
|
109
|
+
alEvento(JSON.parse(resto));
|
|
110
|
+
}
|
|
111
|
+
catch (e) {
|
|
112
|
+
if (ctrl.signal.aborted)
|
|
113
|
+
throw new ApiError(0, 'the live output stopped arriving (no heartbeat in 60 s)');
|
|
114
|
+
throw e;
|
|
115
|
+
}
|
|
116
|
+
finally {
|
|
117
|
+
clearTimeout(vigia);
|
|
118
|
+
}
|
|
119
|
+
}
|
package/dist/commands/apps.js
CHANGED
|
@@ -1,9 +1,43 @@
|
|
|
1
1
|
import { execFileSync } from 'node:child_process';
|
|
2
2
|
import { createHash } from 'node:crypto';
|
|
3
3
|
import { api } from '../api.js';
|
|
4
|
-
import { output, green } from '../output.js';
|
|
4
|
+
import { output, green, yellow, red, dim } from '../output.js';
|
|
5
|
+
import { esperarDesenlace, finalDelRegistro, debeEsperar } from '../esperar.js';
|
|
5
6
|
import { credencialRegistryDeFlags } from '../registry-flags.js';
|
|
6
7
|
import { proyectoDeFlags } from '../proyecto.js';
|
|
8
|
+
/**
|
|
9
|
+
* Espera al desenlace de un despliegue y lo cuenta (ficha f76082de): el progreso, y al final la URL o el error con el
|
|
10
|
+
* final del registro. Un fallo deja exit code 1; agotar la espera no es un fallo (el despliegue sigue) y lo dice.
|
|
11
|
+
*/
|
|
12
|
+
async function esperarYContar(appId, depId, plazoMin, json) {
|
|
13
|
+
const leer = async () => {
|
|
14
|
+
const l = ((await api(`/apps/${encodeURIComponent(appId)}/deployments`)).deployments ?? []);
|
|
15
|
+
return depId ? l.find((x) => x.id === depId) : l[0];
|
|
16
|
+
};
|
|
17
|
+
const r = await esperarDesenlace({
|
|
18
|
+
leer, dormir: (ms) => new Promise((ok) => setTimeout(ok, ms)), ahora: () => Date.now(), plazoMs: plazoMin * 60_000,
|
|
19
|
+
alCambiar: json ? undefined : (e) => console.log(dim(` · ${e}`)),
|
|
20
|
+
});
|
|
21
|
+
const url = r.final?.status === 'live' ? ((await api(`/apps/${encodeURIComponent(appId)}`)).app?.url ?? null) : null;
|
|
22
|
+
if (json) {
|
|
23
|
+
console.log(JSON.stringify({ deploymentId: r.final?.id ?? depId ?? null, appId, status: r.final?.status ?? 'unknown', url, error: r.final?.error ?? null, timedOut: r.agotado }, null, 2));
|
|
24
|
+
}
|
|
25
|
+
else if (r.agotado) {
|
|
26
|
+
console.log(yellow(`… still ${r.final?.status ?? 'starting'} after ${plazoMin} min — it keeps going. Follow it: koigrid apps deployments ${appId}`));
|
|
27
|
+
}
|
|
28
|
+
else if (r.final?.status === 'live') {
|
|
29
|
+
console.log(green(`✓ Live: ${url ?? '(no URL yet)'}`));
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
console.log(red(`✗ Deployment ${r.final?.status}${r.final?.error ? `: ${r.final.error}` : ''}`));
|
|
33
|
+
const fin = finalDelRegistro(r.final?.logs);
|
|
34
|
+
if (fin)
|
|
35
|
+
console.log(dim(`--- last lines of the build/deploy log ---\n${fin}`));
|
|
36
|
+
console.log(dim(`Full logs: koigrid apps logs ${appId} --type build`));
|
|
37
|
+
}
|
|
38
|
+
if (!r.agotado && r.final?.status !== 'live')
|
|
39
|
+
process.exitCode = 1;
|
|
40
|
+
}
|
|
7
41
|
export async function apps(a) {
|
|
8
42
|
const json = !!a.flags.json, sub = a.sub || 'ls';
|
|
9
43
|
const id = a.positionals[0];
|
|
@@ -40,6 +74,8 @@ export async function apps(a) {
|
|
|
40
74
|
bs.branch = a.flags.branch; // rama a clonar (repo); sin ella, main
|
|
41
75
|
if (a.flags.dockerfile)
|
|
42
76
|
bs.dockerfilePath = a.flags.dockerfile; // otro Dockerfile que el de la raíz de build
|
|
77
|
+
if (a.flags['release-cmd'])
|
|
78
|
+
bs.releaseCommand = a.flags['release-cmd']; // fase de release (migraciones), antes de arrancar la versión nueva
|
|
43
79
|
// Tamaño AL CREAR (POST /apps ya lo admitía): sin esto había que crear y luego `apps resize`, o sea dos
|
|
44
80
|
// despliegues, y el primero arrancaba con la memoria por defecto (un Chromium no cabe en ella).
|
|
45
81
|
const tam = {};
|
|
@@ -53,8 +89,11 @@ export async function apps(a) {
|
|
|
53
89
|
if (a.flags.ingress !== undefined && a.flags.ingress !== 'runner' && a.flags.ingress !== 'edge')
|
|
54
90
|
throw new Error("--ingress must be 'edge' (default) or 'runner'");
|
|
55
91
|
if (!name || (!image && !repo && !dir))
|
|
56
|
-
throw new Error('usage: koigrid apps deploy <name> --dir <path>|--image <img>|--repo <git-url> [--branch B] [--repo-token <t>] [--port N] [--ingress edge|runner] [--build-cmd C] [--install-cmd C] [--start-cmd C] [--root-dir D] [--node-version V] [--dockerfile PATH] [--memory <mb>] [--cpus <n>] [--project <id>] [--env KEY=VALUE ...] [--env-target all|production|preview]');
|
|
92
|
+
throw new Error('usage: koigrid apps deploy <name> --dir <path>|--image <img>|--repo <git-url> [--branch B] [--repo-token <t>] [--port N] [--ingress edge|runner] [--build-cmd C] [--install-cmd C] [--start-cmd C] [--root-dir D] [--node-version V] [--dockerfile PATH] [--release-cmd C] [--memory <mb>] [--cpus <n>] [--project <id>] [--env KEY=VALUE ...] [--env-target all|production|preview]');
|
|
57
93
|
const port = a.flags.port ? Number(a.flags.port) : 3000;
|
|
94
|
+
// Esperar al desenlace (ficha f76082de): por defecto sí (personas y agentes), --json sólo con --wait, --no-wait nunca.
|
|
95
|
+
const esperar = debeEsperar(a.flags, json);
|
|
96
|
+
const plazoMin = a.flags.timeout ? Math.max(1, Number(a.flags.timeout)) : 20;
|
|
58
97
|
// --env KEY=VAL (repetible): el entorno viaja CON la creación, así que el primer despliegue ya sale con él
|
|
59
98
|
// (ficha d62bcde4). Antes había que crear, fijar variables y redesplegar: el primer despliegue fallaba siempre.
|
|
60
99
|
const envPares = [].concat(a.flags.env ?? []);
|
|
@@ -69,7 +108,8 @@ export async function apps(a) {
|
|
|
69
108
|
// deploy --dir: empaqueta el directorio (excluye lo pesado/irrelevante) → subida presignada a koigrid →
|
|
70
109
|
// el runner lo construye igual que un repo. No requiere git ni Docker local.
|
|
71
110
|
if (dir) {
|
|
72
|
-
|
|
111
|
+
// `sourceType: 'archive'` (ficha 828d84dd): la app nace esperando su código, y así lo dice desde el primer momento.
|
|
112
|
+
const app = await api('/apps', { method: 'POST', body: { name, sourceType: 'archive', port, ...hc, ...bs, ...tam, ...ing, ...en, ...proyectoDeFlags(a) } });
|
|
73
113
|
const aid = app.app?.id || app.id;
|
|
74
114
|
const up = await api(`/apps/${encodeURIComponent(aid)}/source-upload`, { method: 'POST', body: {} });
|
|
75
115
|
const { uploadUrl, archiveKey } = up.upload;
|
|
@@ -81,7 +121,11 @@ export async function apps(a) {
|
|
|
81
121
|
const d = await api(`/apps/${encodeURIComponent(aid)}/deployments`, { method: 'POST', body: { sourceType: 'archive', archiveKey } });
|
|
82
122
|
// Devuelve el ID del DEPLOYMENT (el que aparece en GET /apps/:id/deployments), NO el del app — evita la
|
|
83
123
|
// confusión "ids CLI≠API" del journey. appId aparte, etiquetado.
|
|
84
|
-
|
|
124
|
+
if (!json)
|
|
125
|
+
console.log(green(`✓ Deploying "${name}" from ${dir}… (deployment ${String(d.deployment?.id || '').slice(0, 8)})`));
|
|
126
|
+
if (esperar)
|
|
127
|
+
return esperarYContar(aid, d.deployment?.id, plazoMin, json);
|
|
128
|
+
return json ? console.log(JSON.stringify({ deploymentId: d.deployment?.id, appId: aid, status: d.deployment?.status || 'queued', source: 'dir' }, null, 2)) : undefined;
|
|
85
129
|
}
|
|
86
130
|
const app = await api('/apps', { method: 'POST', body: { ...proyectoDeFlags(a), ...(repo ? { name, sourceType: 'git', repo, port, ...(repoToken ? { repoToken } : {}), ...hc, ...bs, ...tam, ...ing, ...en } : { name, sourceType: 'image', image, port, ...hc, ...tam, ...reg, ...ing, ...en }) } });
|
|
87
131
|
const aid = app.app?.id || app.id;
|
|
@@ -95,12 +139,18 @@ export async function apps(a) {
|
|
|
95
139
|
await new Promise((r) => setTimeout(r, 1000));
|
|
96
140
|
auto = ((await api(`/apps/${encodeURIComponent(aid)}/deployments`)).deployments ?? [])[0];
|
|
97
141
|
}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
142
|
+
if (!json)
|
|
143
|
+
console.log(green(`✓ Deploying "${name}"… (deployment ${String(auto?.id || '').slice(0, 8) || 'starting'}, automatic on create)`));
|
|
144
|
+
if (esperar)
|
|
145
|
+
return esperarYContar(aid, auto?.id, plazoMin, json);
|
|
146
|
+
return json ? console.log(JSON.stringify({ deploymentId: auto?.id ?? null, appId: aid, status: auto?.status || 'queued', automatic: true }, null, 2)) : undefined;
|
|
101
147
|
}
|
|
102
148
|
const d = await api(`/apps/${encodeURIComponent(aid)}/deployments`, { method: 'POST', body: {} });
|
|
103
|
-
|
|
149
|
+
if (!json)
|
|
150
|
+
console.log(green(`✓ Deploying "${name}"… (deployment ${String(d.deployment?.id || '').slice(0, 8)})`));
|
|
151
|
+
if (esperar)
|
|
152
|
+
return esperarYContar(aid, d.deployment?.id, plazoMin, json);
|
|
153
|
+
return json ? console.log(JSON.stringify({ deploymentId: d.deployment?.id, appId: aid, status: d.deployment?.status || 'queued' }, null, 2)) : undefined;
|
|
104
154
|
}
|
|
105
155
|
case 'deployments':
|
|
106
156
|
need('');
|
|
@@ -109,9 +159,38 @@ export async function apps(a) {
|
|
|
109
159
|
const l = r.deployments || r || [];
|
|
110
160
|
return output(l, json, { rows: l.map((x) => ({ id: x.id.slice(0, 8), status: x.status, source: x.source || '—' })), columns: ['id', 'status', 'source'] });
|
|
111
161
|
}
|
|
112
|
-
case 'logs':
|
|
162
|
+
case 'logs': {
|
|
113
163
|
need('');
|
|
114
|
-
|
|
164
|
+
// Los mismos filtros que la API (ficha d53876c6): --since/--until (ISO UTC), --replica, --runner, --q y --type build.
|
|
165
|
+
const qs = new URLSearchParams({ tail: String(a.flags.tail || 200) });
|
|
166
|
+
for (const k of ['type', 'since', 'until', 'replica', 'runner', 'q'])
|
|
167
|
+
if (typeof a.flags[k] === 'string' && a.flags[k])
|
|
168
|
+
qs.set(k, String(a.flags[k]));
|
|
169
|
+
const r = await api(`/apps/${encodeURIComponent(id)}/logs?${qs}`);
|
|
170
|
+
return console.log(json ? JSON.stringify(r, null, 2) : r.logs || '');
|
|
171
|
+
}
|
|
172
|
+
// Lo que vio el PROXY (ficha 7d10e8b8): peticiones, 5xx por código y las rutas que fallaron — también los 502/504
|
|
173
|
+
// que la app nunca registra. --hours (1-840, def. 24; más de 168 pide --bucket 1h|6h|1d) · --bucket 1m|5m|15m|1h|6h|1d (def. 5m).
|
|
174
|
+
case 'http': {
|
|
175
|
+
need(' [--hours 24] [--bucket 5m]');
|
|
176
|
+
const q = new URLSearchParams();
|
|
177
|
+
if (a.flags.hours)
|
|
178
|
+
q.set('hours', String(a.flags.hours));
|
|
179
|
+
if (a.flags.bucket)
|
|
180
|
+
q.set('bucket', String(a.flags.bucket));
|
|
181
|
+
const r = await api(`/apps/${encodeURIComponent(id)}/http${q.size ? `?${q}` : ''}`);
|
|
182
|
+
if (json)
|
|
183
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
184
|
+
const t = r.totals || {};
|
|
185
|
+
const codigos = Object.entries(t.byStatus || {}).map(([c, n]) => `${c}×${n}`).join(' ');
|
|
186
|
+
console.log(`${r.hours} h · ${t.requests ?? 0} requests · ${t.errors5xx ?? 0} 5xx${codigos ? ` (${codigos})` : ''} · availability ${t.availabilityPct ?? '—'}%`);
|
|
187
|
+
output(r.series || [], false, { rows: (r.series || []).filter((p) => p.errors5xx > 0).map((p) => ({ at: String(p.at), requests: String(p.requests), '5xx': String(p.errors5xx), 'err%': String(p.errorPct ?? '—'), p99max: String(p.p99MaxMs ?? '—') })), columns: ['at', 'requests', '5xx', 'err%', 'p99max'] });
|
|
188
|
+
if ((r.errors || []).length) {
|
|
189
|
+
console.log(`\nlatest 5xx${r.errorsOmitted ? ` (+${r.errorsOmitted} not kept individually)` : ''}:`);
|
|
190
|
+
output(r.errors, false, { rows: r.errors.slice(0, 50).map((e) => ({ at: String(e.at), status: String(e.status), method: String(e.method || '—'), path: String(e.path || '—'), ms: String(e.durationMs ?? '—') })), columns: ['at', 'status', 'method', 'path', 'ms'] });
|
|
191
|
+
}
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
115
194
|
case 'rm':
|
|
116
195
|
case 'delete':
|
|
117
196
|
need('');
|
|
@@ -137,7 +216,7 @@ export async function apps(a) {
|
|
|
137
216
|
return json ? console.log(JSON.stringify(r, null, 2)) : console.log(green(r.wasPaused ? (r.redeployed ? `✓ Resuming ${id}… (relanzando la última imagen)` : `✓ ${id} reanudada (nunca tuvo un deploy vivo: despliega con: koigrid apps deploy)`) : `✓ ${id} no estaba pausada`));
|
|
138
217
|
}
|
|
139
218
|
case 'loadtest': { // reporte de capacidad: rps + p50/p95/p99 + rodilla + señales del servidor (docs/platform/CAPACITY.md)
|
|
140
|
-
need(' [--duration <s≤600>] [--concurrency <n≤100>] [--path /] [--ramp] [--stages 3] [--warmup 3] [--paths \'[{"path":"/","weight":3}]\']');
|
|
219
|
+
need(' [--duration <s≤600>] [--concurrency <n≤100>] [--path /] [--ramp] [--stages 3] [--warmup 3] [--paths \'[{"path":"/","weight":3}]\'] [--header "X-Origin-Verify: <secreto>"]…');
|
|
141
220
|
const body = {};
|
|
142
221
|
if (a.flags.duration !== undefined)
|
|
143
222
|
body.durationSec = Number(a.flags.duration);
|
|
@@ -153,10 +232,24 @@ export async function apps(a) {
|
|
|
153
232
|
body.warmupSec = Number(a.flags.warmup);
|
|
154
233
|
if (a.flags.paths !== undefined)
|
|
155
234
|
body.paths = JSON.parse(String(a.flags.paths));
|
|
235
|
+
// --header "Nombre: valor", repetible: p. ej. el secreto de origen que exige tu CDN (si no, sólo se mide un 403).
|
|
236
|
+
if (a.flags.header !== undefined) {
|
|
237
|
+
const headers = {};
|
|
238
|
+
for (const h of [].concat(a.flags.header)) {
|
|
239
|
+
const linea = String(h);
|
|
240
|
+
const i = linea.indexOf(':');
|
|
241
|
+
if (i <= 0)
|
|
242
|
+
throw new Error(`--header necesita "Nombre: valor" (recibido sin «:»)`);
|
|
243
|
+
headers[linea.slice(0, i).trim()] = linea.slice(i + 1).trim();
|
|
244
|
+
}
|
|
245
|
+
body.headers = headers;
|
|
246
|
+
}
|
|
156
247
|
const r = await api(`/apps/${encodeURIComponent(id)}/loadtest`, { method: 'POST', body });
|
|
157
248
|
if (a.flags.json)
|
|
158
249
|
return console.log(JSON.stringify(r, null, 2));
|
|
159
250
|
console.log(green(`✓ load-test ${r.app} (${r.target})`));
|
|
251
|
+
if (r.headersSent?.length)
|
|
252
|
+
console.log(` cabeceras enviadas: ${r.headersSent.join(', ')}`);
|
|
160
253
|
console.log(` ${r.requests} reqs · ~${Math.round(r.rps)} req/s · p50 ${Math.round(r.p50)}ms · p95 ${Math.round(r.p95)}ms · p99 ${Math.round(r.p99)}ms · errores ${(r.errorRate * 100).toFixed(1)}%`);
|
|
161
254
|
if (r.coldStartP95 != null)
|
|
162
255
|
console.log(` arranque en frío (excluido del p95): ${r.coldStartP95}ms`);
|
|
@@ -407,7 +500,7 @@ export async function apps(a) {
|
|
|
407
500
|
const act = a.positionals[1];
|
|
408
501
|
if (!act) {
|
|
409
502
|
const r = await api(`/apps/${encodeURIComponent(id)}/cdn`);
|
|
410
|
-
return console.log(json ? JSON.stringify(r, null, 2) : `cdn: ${r.cdn?.enabled ? 'on' : 'off'}`);
|
|
503
|
+
return console.log(json ? JSON.stringify(r, null, 2) : `cdn: ${r.cdn?.enabled ? 'on' : 'off'}${r.cdn?.reason ? ` (${r.cdn.reason}: ${r.cdn.detail ?? ''})` : ''}`);
|
|
411
504
|
}
|
|
412
505
|
const r = await api(`/apps/${encodeURIComponent(id)}/cdn`, { method: 'PUT', body: { enabled: act === 'on' } });
|
|
413
506
|
return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ CDN ${act}`));
|
|
@@ -586,6 +679,95 @@ export async function apps(a) {
|
|
|
586
679
|
const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body: { name } });
|
|
587
680
|
return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ App renamed to "${name}"`));
|
|
588
681
|
}
|
|
682
|
+
case 'health-path': {
|
|
683
|
+
// Ruta de «lista» (readiness) de la app: la puerta del despliegue y el sondeo activo del edge. `off` la quita.
|
|
684
|
+
const ruta = a.positionals[1];
|
|
685
|
+
if (!id || !ruta)
|
|
686
|
+
throw new Error('usage: koigrid apps health-path <appId> </path|off>');
|
|
687
|
+
const healthCheckPath = ruta === 'off' ? null : ruta;
|
|
688
|
+
const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body: { healthCheckPath } });
|
|
689
|
+
return console.log(json ? JSON.stringify(r, null, 2) : green(healthCheckPath ? `✓ Health path set to ${healthCheckPath}` : '✓ Health path removed'));
|
|
690
|
+
}
|
|
691
|
+
case 'port': {
|
|
692
|
+
// Puerto del contenedor (PORT=<n>, ficha 4d8b02da): se aplica en el siguiente despliegue.
|
|
693
|
+
const n = Number(a.positionals[1]);
|
|
694
|
+
if (!id || !Number.isInteger(n) || n < 1 || n > 65535)
|
|
695
|
+
throw new Error('usage: koigrid apps port <appId> <1-65535>');
|
|
696
|
+
const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body: { port: n } });
|
|
697
|
+
return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Port set to ${n} (applies on the next deploy)`));
|
|
698
|
+
}
|
|
699
|
+
case 'release': {
|
|
700
|
+
// FASE DE RELEASE (como Heroku release / Fly release_command): corre una vez por despliegue, con la imagen y el
|
|
701
|
+
// entorno de la app, ANTES de arrancar la versión nueva. Se aplica en el siguiente despliegue. `off` la quita.
|
|
702
|
+
const orden = a.positionals.slice(1).join(' ');
|
|
703
|
+
if (!id || !orden)
|
|
704
|
+
throw new Error('usage: koigrid apps release <appId> <command|off> (e.g. "npx prisma migrate deploy")');
|
|
705
|
+
const releaseCommand = orden === 'off' ? null : orden;
|
|
706
|
+
const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body: { releaseCommand } });
|
|
707
|
+
return console.log(json ? JSON.stringify(r, null, 2) : green(releaseCommand ? `✓ Release command set; it runs on the next deploy, before the new version starts` : '✓ Release command removed'));
|
|
708
|
+
}
|
|
709
|
+
case 'build-settings': {
|
|
710
|
+
// Ajustes de build de una app EXISTENTE (antes sólo al crearla). Se aplican en el siguiente despliegue; `off` quita uno.
|
|
711
|
+
const mapa = { 'build-cmd': 'buildCommand', 'install-cmd': 'installCommand', 'start-cmd': 'startCommand', 'root-dir': 'rootDirectory', 'node-version': 'nodeVersion', dockerfile: 'dockerfilePath', 'release-cmd': 'releaseCommand' };
|
|
712
|
+
const body = {};
|
|
713
|
+
for (const [flag, campo] of Object.entries(mapa))
|
|
714
|
+
if (typeof a.flags[flag] === 'string')
|
|
715
|
+
body[campo] = a.flags[flag] === 'off' ? null : a.flags[flag];
|
|
716
|
+
if (!id || !Object.keys(body).length)
|
|
717
|
+
throw new Error('usage: koigrid apps build-settings <appId> [--build-cmd C] [--install-cmd C] [--start-cmd C] [--root-dir D] [--node-version V] [--dockerfile PATH] [--release-cmd C] (value "off" removes it; applies on the next deploy)');
|
|
718
|
+
const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body });
|
|
719
|
+
return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Build settings saved (${Object.keys(body).join(', ')}); they apply on the next deploy`));
|
|
720
|
+
}
|
|
721
|
+
case 'traffic-ramp': {
|
|
722
|
+
// Traspaso gradual al desplegar: N segundos para pasar los clientes de la versión anterior a la nueva. `off` = de golpe.
|
|
723
|
+
const v = a.positionals[1];
|
|
724
|
+
if (!id || !v)
|
|
725
|
+
throw new Error('usage: koigrid apps traffic-ramp <appId> <seconds 30-600|off>');
|
|
726
|
+
const trafficRampSeconds = v === 'off' ? 0 : Number(v);
|
|
727
|
+
if (!Number.isInteger(trafficRampSeconds))
|
|
728
|
+
throw new Error('seconds must be an integer between 30 and 600, or off');
|
|
729
|
+
const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body: { trafficRampSeconds } });
|
|
730
|
+
return console.log(json ? JSON.stringify(r, null, 2) : green(trafficRampSeconds ? `✓ Deploys will shift traffic gradually over ${trafficRampSeconds} s` : '✓ Deploys will switch traffic at once'));
|
|
731
|
+
}
|
|
732
|
+
case 'max-surge': {
|
|
733
|
+
// Despliegue por tandas: como mucho N réplicas nuevas a la vez junto a las viejas (maxSurge de Kubernetes). `off` = sin límite.
|
|
734
|
+
const v = a.positionals[1];
|
|
735
|
+
if (!id || !v)
|
|
736
|
+
throw new Error('usage: koigrid apps max-surge <appId> <replicas 1-100|off>');
|
|
737
|
+
const maxSurge = v === 'off' ? 0 : Number(v);
|
|
738
|
+
if (!Number.isInteger(maxSurge) || maxSurge < 0 || maxSurge > 100)
|
|
739
|
+
throw new Error('replicas must be an integer between 1 and 100, or off');
|
|
740
|
+
const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body: { maxSurge } });
|
|
741
|
+
if (json)
|
|
742
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
743
|
+
// Lo que dice el SERVIDOR que hará (deployBatches), no lo que se pidió: se sube para no pasar del tope de tandas
|
|
744
|
+
// y fuera del reparto del edge no hay tandas.
|
|
745
|
+
const b = r.app?.deployBatches;
|
|
746
|
+
console.log(green(maxSurge ? `✓ maxSurge ${maxSurge} saved` : '✓ Deploys will start all new replicas at once when they fit'));
|
|
747
|
+
if (b && maxSurge && b.applies && b.effectiveMaxSurge)
|
|
748
|
+
console.log(` Redeploys: ${b.batches} batch(es) of up to ${b.effectiveMaxSurge} replica(s)`);
|
|
749
|
+
if (b?.note)
|
|
750
|
+
console.log(yellow(` ⚠ ${b.note}`));
|
|
751
|
+
return;
|
|
752
|
+
}
|
|
753
|
+
case 'deploy-analysis': {
|
|
754
|
+
// Análisis entre tandas: tras cada tanda se observan N s y se deshace si las réplicas nuevas dan claramente más 5xx
|
|
755
|
+
// que las viejas a la vez (Kayenta/Flagger). `off` = apagado.
|
|
756
|
+
const v = a.positionals[1];
|
|
757
|
+
if (!id || !v)
|
|
758
|
+
throw new Error('usage: koigrid apps deploy-analysis <appId> <seconds 30-600|off>');
|
|
759
|
+
const deployAnalysisSeconds = v === 'off' ? 0 : Number(v);
|
|
760
|
+
if (!Number.isInteger(deployAnalysisSeconds))
|
|
761
|
+
throw new Error('seconds must be an integer between 30 and 600, or off');
|
|
762
|
+
const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body: { deployAnalysisSeconds } });
|
|
763
|
+
if (json)
|
|
764
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
765
|
+
const b = r.app?.deployBatches;
|
|
766
|
+
console.log(green(deployAnalysisSeconds ? `✓ Batched deploys will watch ${deployAnalysisSeconds} s of traffic after each batch` : '✓ Deploy analysis off'));
|
|
767
|
+
if (b?.analysisNote)
|
|
768
|
+
console.log(` ${b.analysisNote}`);
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
589
771
|
default: throw new Error(`unknown: apps ${sub}`);
|
|
590
772
|
}
|
|
591
773
|
}
|
package/dist/commands/billing.js
CHANGED
|
@@ -1,31 +1,87 @@
|
|
|
1
1
|
import { api } from '../api.js';
|
|
2
2
|
import { green, dim } from '../output.js';
|
|
3
|
-
// koigrid billing —
|
|
3
|
+
// koigrid billing — cómo paga la organización y el TRASPASO al pago. Ver docs/products/BILLING.md.
|
|
4
4
|
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
5
|
+
// Desde los precios por recurso (ficha 91d809ff) ya no hay planes que comprar: se paga lo reservado por horas a la
|
|
6
|
+
// tarjeta guardada. `card` no cobra: pide al proveedor el enlace para GUARDAR una tarjeta y lo imprime, porque un
|
|
7
|
+
// agente puede conducir toda una migración por API y se paraba justo aquí — el único paso que no puede dar él.
|
|
7
8
|
export async function billing(a) {
|
|
8
9
|
const json = !!a.flags.json;
|
|
9
10
|
const sub = a.sub || 'show';
|
|
10
|
-
if (sub === 'show' || sub === 'status'
|
|
11
|
+
if (sub === 'show' || sub === 'status') {
|
|
11
12
|
const r = await api('/billing');
|
|
12
13
|
if (json)
|
|
13
14
|
return console.log(JSON.stringify(r, null, 2));
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
15
|
+
const modo = { free: 'gratis (sin tarjeta)', card: 'tarjeta guardada', granted: 'concedido por koigrid (no paga)', legacy_plan: `plan antiguo '${r.plan}'` };
|
|
16
|
+
console.log(`pago: ${modo[r.paymentMode] ?? r.paymentMode}${r.cardSetupAvailable || r.cardOnFile ? '' : dim(' (cobro con tarjeta no configurado)')}`);
|
|
17
|
+
console.log(`reservado este mes (desde ${r.monthToDate?.since}): $${Number(r.monthToDate?.reservedUsd ?? 0).toFixed(2)}${r.cardOnFile ? '' : dim(' (no se cobra sin tarjeta)')}`);
|
|
18
|
+
console.log(`modo de cobro: ${r.billingMode === 'monthly' ? 'factura mensual a la tarjeta' : 'prepago (cada hora sale del saldo)'}${dim(' (koigrid billing mode prepaid|monthly)')}`);
|
|
19
|
+
const p = r.pricing?.prices ?? {};
|
|
20
|
+
console.log(dim(`tarifa: $${p.ramGbMonth}/GB RAM${p.vcpuMonth ? ` · $${p.vcpuMonth}/vCPU` : ' (vCPU compartida incluida)'} · $${p.diskGbMonth}/GB disco · $${p.objectStorageGbMonth}/GB objetos, al mes, por horas · tráfico incluido`));
|
|
17
21
|
return;
|
|
18
22
|
}
|
|
19
|
-
if (sub === '
|
|
20
|
-
const
|
|
21
|
-
if (!plan)
|
|
22
|
-
throw new Error('usage: koigrid billing upgrade <starter|pro|scale>');
|
|
23
|
-
const r = await api('/billing/checkout-session', { method: 'POST', body: { plan: String(plan) } });
|
|
23
|
+
if (sub === 'card' || sub === 'add-card') {
|
|
24
|
+
const r = await api('/billing/checkout-session', { method: 'POST', body: {} });
|
|
24
25
|
if (json)
|
|
25
26
|
return console.log(JSON.stringify(r, null, 2));
|
|
26
|
-
console.log(green(
|
|
27
|
+
console.log(green('✓ enlace para guardar una tarjeta (no se cobra nada al guardarla):'));
|
|
27
28
|
console.log(` ${r.url}`);
|
|
28
|
-
return console.log(dim(' Ábrelo tú (o pásaselo a quien
|
|
29
|
+
return console.log(dim(' Ábrelo tú (o pásaselo a quien paga): koigrid no recoge tarjetas por API.'));
|
|
30
|
+
}
|
|
31
|
+
// MONEDERO prepagado (docs/design/MONEDERO.md): `wallet` · `topup <usd>` · `auto-topup <usd>|off` · `entries`.
|
|
32
|
+
if (sub === 'wallet' || sub === 'balance') {
|
|
33
|
+
const r = (await api('/billing/wallet')).wallet;
|
|
34
|
+
if (json)
|
|
35
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
36
|
+
console.log(`saldo: $${Number(r.balanceUsd).toFixed(2)}${r.creditUsd ? ` · crédito de koigrid: $${Number(r.creditUsd).toFixed(2)} (se gasta antes)` : ''}`);
|
|
37
|
+
const at = r.autoTopUp;
|
|
38
|
+
console.log(at.enabled ? `recarga automática: $${at.amountUsd} cuando el saldo baje de $${at.thresholdUsd}` : at.disabledAfterFailures ? `recarga automática: APAGADA tras ${at.consecutiveFailures} rechazos (revisa la tarjeta y vuelve a encenderla)` : dim('recarga automática: apagada'));
|
|
39
|
+
if (r.graceUntil)
|
|
40
|
+
console.log(`⚠ saldo agotado: todo sigue hasta ${r.graceUntil}; después se pausan apps y VMs (las bases y los datos nunca)`);
|
|
41
|
+
if (!r.hourlyChargingActive)
|
|
42
|
+
console.log(dim('el cargo por horas al saldo aún no está activo'));
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
if (sub === 'topup' || sub === 'add-funds') {
|
|
46
|
+
const usd = Number(a.positionals[0] ?? a.flags.amount);
|
|
47
|
+
if (!Number.isFinite(usd) || usd <= 0)
|
|
48
|
+
throw new Error('uso: koigrid billing topup <dólares> (de 10 a 10000)');
|
|
49
|
+
const r = await api('/billing/wallet/topup', { method: 'POST', body: { amountCents: Math.round(usd * 100) } });
|
|
50
|
+
if (json)
|
|
51
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
52
|
+
console.log(green(`✓ recarga de $${Number(r.amountUsd).toFixed(2)}: ábrela para pagar (emite la factura y guarda la tarjeta para las recargas automáticas)`));
|
|
53
|
+
console.log(` ${r.url}`);
|
|
54
|
+
return console.log(dim(' koigrid no recoge tarjetas por API: la página es del proveedor de pagos.'));
|
|
55
|
+
}
|
|
56
|
+
if (sub === 'auto-topup') {
|
|
57
|
+
const v = String(a.positionals[0] ?? '');
|
|
58
|
+
const amountCents = v === 'off' ? null : Math.round(Number(v) * 100);
|
|
59
|
+
if (amountCents !== null && !(amountCents > 0))
|
|
60
|
+
throw new Error('uso: koigrid billing auto-topup <dólares>|off');
|
|
61
|
+
const r = (await api('/billing/wallet/auto-topup', { method: 'PUT', body: { amountCents } })).wallet;
|
|
62
|
+
if (json)
|
|
63
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
64
|
+
return console.log(green(amountCents === null ? '✓ recarga automática apagada' : `✓ recarga automática: $${r.autoTopUp.amountUsd} cuando el saldo baje de $${r.autoTopUp.thresholdUsd}`));
|
|
65
|
+
}
|
|
66
|
+
if (sub === 'entries' || sub === 'movements') {
|
|
67
|
+
const r = await api(`/billing/wallet/entries?limit=${Number(a.flags.limit ?? 30)}`);
|
|
68
|
+
if (json)
|
|
69
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
70
|
+
for (const e of r.entries)
|
|
71
|
+
console.log(`${e.createdAt.slice(0, 16).replace('T', ' ')} ${e.kind.padEnd(10)} ${(e.amountUsd >= 0 ? '+' : '') + Number(e.amountUsd).toFixed(4)} ${dim(e.description ?? '')}`);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
// Cómo se paga lo reservado: `mode` enseña el actual; `mode prepaid|monthly` lo cambia (owner/admin).
|
|
75
|
+
if (sub === 'mode') {
|
|
76
|
+
const nuevo = a.positionals[0];
|
|
77
|
+
const r = nuevo ? await api('/billing/mode', { method: 'PUT', body: { mode: nuevo } }) : await api('/billing/mode');
|
|
78
|
+
if (json)
|
|
79
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
80
|
+
const texto = r.billingMode === 'monthly' ? 'factura mensual a la tarjeta guardada' : 'prepago: cada hora sale del saldo del monedero';
|
|
81
|
+
return console.log(nuevo ? (r.changed ? green(`✓ modo de cobro: ${texto}`) : `ya estaba en: ${texto}`) : `modo de cobro: ${texto}${dim(' (cámbialo con: koigrid billing mode prepaid|monthly)')}`);
|
|
82
|
+
}
|
|
83
|
+
if (sub === 'upgrade' || sub === 'checkout' || sub === 'change' || sub === 'set') {
|
|
84
|
+
throw new Error('koigrid ya no vende planes: pagas lo reservado por horas. Guarda una tarjeta con `koigrid billing card` y mira precios con `koigrid pricing`.');
|
|
29
85
|
}
|
|
30
86
|
throw new Error(`unknown: billing ${sub}`);
|
|
31
87
|
}
|