rtcloud-sdk 0.0.0-stage → 1.1.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 ADDED
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ ## 1.1.0 — 01/12/2026
4
+
5
+ - **Endereço novo da API:** a biblioteca fala com `https://api.rtcloud.com.br/v1`, o endereço oficial — o endereço antigo (rtcloud.com.br/api/v1) saiu de circulação em 01/12/2026, por isso a 1.0.0 parou de funcionar. Se `baseUrl` ou `RTCLOUD_API_URL` ainda tiverem o endereço antigo, a biblioteca usa o novo sozinha.
6
+
7
+ ## 1.0.0 — 27/11/2026
8
+
9
+ - Primeira versão: aplicações, arquivos (inclusive a busca em todos os arquivos), variáveis, snapshots com restauração acompanhada, monitor, relatórios do site, domínio próprio, bancos (certificado e troca de senha) e equipes.
10
+ - Repetição automática no 503 de atualização e no 429 de leitura.
11
+ - Tipos para TypeScript.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 RT Cloud
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,95 @@
1
- # Temporary Holding Version
1
+ # rtcloud-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Biblioteca oficial da **RTCloud** para JavaScript e TypeScript. Controle suas aplicações, arquivos, variáveis, snapshots, bancos de dados e equipes pelo seu próprio código — a mesma API pública que a CLI, a extensão do VS Code e a GitHub Action usam.
4
+
5
+ - Zero dependências (usa o `fetch` do Node.js 18+).
6
+ - Tipos para TypeScript incluídos.
7
+ - Repete sozinha quando a RTCloud está publicando uma atualização (503) e quando uma leitura bate no limite (429).
8
+
9
+ ## Instalação
10
+
11
+ ```bash
12
+ npm install rtcloud-sdk
13
+ ```
14
+
15
+ ## Primeiros passos
16
+
17
+ Gere uma chave no painel: **menu da conta → Chaves de API**. Guarde em variável de ambiente — nunca no código.
18
+
19
+ ```js
20
+ import { RTCloud } from "rtcloud-sdk";
21
+
22
+ const rt = new RTCloud({ apiKey: process.env.RTCLOUD_API_KEY });
23
+
24
+ const apps = await rt.apps.list();
25
+ console.log(apps.map((a) => `${a.name}: ${a.online ? "no ar" : "parada"}`));
26
+
27
+ await rt.apps.restart("meu-bot"); // aceita o id ou o nome exato
28
+ ```
29
+
30
+ ## O que dá para fazer
31
+
32
+ | Área | Métodos |
33
+ | --- | --- |
34
+ | Conta | `account.me()`, `account.teams()`, `platform.status()` |
35
+ | Aplicações | `apps.list()`, `get`, `status`, `statusAll`, `metrics`, `logs`, `start`, `stop`, `restart`, `deployments`, `commit`, `delete` |
36
+ | Arquivos | `files.list`, `read`, `write`, `edit`, `move`, `delete`, `search` |
37
+ | Variáveis | `envs.list`, `set`, `replace`, `remove` |
38
+ | Snapshots | `snapshots.list`, `create`, `restore`, `restoreStatus`, `restoreAndWait` |
39
+ | Site | `monitor.get`, `monitor.check`, `network.analytics`, `errors`, `performance`, `purgeCache`, `domain` |
40
+ | Bancos | `databases.list`, `get`, `metrics`, `start`, `stop`, `restart`, `backups`, `createBackup`, `certificate`, `resetCredentials` |
41
+
42
+ ### Publicar uma versão nova
43
+
44
+ ```js
45
+ import { readFile } from "node:fs/promises";
46
+
47
+ const zip = await readFile("projeto.zip");
48
+ await rt.apps.commit("minha-api", zip);
49
+ ```
50
+
51
+ ### Buscar texto em todos os arquivos
52
+
53
+ ```js
54
+ const r = await rt.files.search("meu-bot", "DISCORD_TOKEN", { ext: "js" });
55
+ for (const f of r.files) console.log(f.path, f.matches);
56
+ ```
57
+
58
+ ### Editar um trecho sem reenviar o arquivo
59
+
60
+ ```js
61
+ await rt.files.edit("meu-bot", "src/config.js", [{ old: 'prefixo: "!"', new: 'prefixo: "?"' }]);
62
+ await rt.apps.restart("meu-bot");
63
+ ```
64
+
65
+ ### Restaurar um snapshot e esperar terminar
66
+
67
+ ```js
68
+ const [ultimo] = await rt.snapshots.list("minha-api");
69
+ await rt.snapshots.restoreAndWait("minha-api", ultimo.version);
70
+ ```
71
+
72
+ ## Erros
73
+
74
+ Todo erro é um `RTCloudError` com `status` (HTTP), `code` (estável) e a mensagem da API:
75
+
76
+ ```js
77
+ import { RTCloudError } from "rtcloud-sdk";
78
+
79
+ try {
80
+ await rt.apps.get("nao-existe");
81
+ } catch (e) {
82
+ if (e instanceof RTCloudError && e.code === "NOT_FOUND") console.log("Não achei essa aplicação.");
83
+ else throw e;
84
+ }
85
+ ```
86
+
87
+ ## Segurança
88
+
89
+ - A chave age como você: use só no servidor, nunca no navegador.
90
+ - Arquivos de credenciais (`.env`, chaves privadas, certificados) não passam pela API de arquivos — variáveis ficam em `envs`.
91
+ - Chaves só de leitura não executam ações nem baixam o certificado do banco.
92
+
93
+ Documentação completa: <https://docs.rtcloud.com.br/sdk-javascript> · Referência da API: <https://docs.rtcloud.com.br/referencia-api>
94
+
95
+ Licença MIT.
package/package.json CHANGED
@@ -1,6 +1,24 @@
1
1
  {
2
2
  "name": "rtcloud-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "description": "Biblioteca oficial da RTCloud para JavaScript e TypeScript: aplicações, arquivos, variáveis, snapshots, bancos e equipes pela API pública.",
5
+ "keywords": ["rtcloud", "rt cloud", "hospedagem", "api", "sdk", "deploy", "bot", "discord", "pt-br"],
6
+ "homepage": "https://docs.rtcloud.com.br/sdk-javascript",
7
+ "license": "MIT",
8
+ "author": "RT Cloud",
9
+ "type": "module",
10
+ "main": "./src/index.js",
11
+ "types": "./src/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./src/index.d.ts",
15
+ "default": "./src/index.js"
16
+ }
17
+ },
18
+ "files": ["src/", "README.md", "CHANGELOG.md", "LICENSE"],
19
+ "engines": { "node": ">=18" },
20
+ "scripts": {
21
+ "test": "node --test test/sdk.test.js"
22
+ },
23
+ "sideEffects": false
24
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,173 @@
1
+ /** Tipos da rtcloud-sdk (API pública da RTCloud: https://api.rtcloud.com.br/v1). */
2
+
3
+ export declare const VERSAO: string;
4
+
5
+ export type Metodo = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
6
+
7
+ export interface OpcoesDoCliente {
8
+ /** chave da API (rtc_…). Padrão: a variável RTCLOUD_API_KEY */
9
+ apiKey?: string;
10
+ /** padrão: https://api.rtcloud.com.br/v1 (ou RTCLOUD_API_URL) */
11
+ baseUrl?: string;
12
+ /** tempo máximo de cada pedido, em ms (padrão 60 000; commit usa pelo menos 10 min) */
13
+ timeoutMs?: number;
14
+ /** fetch próprio (testes, proxies) */
15
+ fetch?: typeof fetch;
16
+ userAgent?: string;
17
+ }
18
+
19
+ export declare class RTCloudError extends Error {
20
+ /** status HTTP (0 = sem resposta) */
21
+ status: number;
22
+ /** código estável da API: NOT_FOUND, RATE_LIMIT, FORBIDDEN, BLOCKED_PATH… */
23
+ code: string;
24
+ body: unknown;
25
+ constructor(message: string, info?: { status?: number; code?: string; body?: unknown });
26
+ }
27
+
28
+ export interface Aplicacao {
29
+ id: string;
30
+ name: string;
31
+ type: "bot" | "site";
32
+ language: string;
33
+ status: string;
34
+ online: boolean;
35
+ ram: number;
36
+ main: string;
37
+ subdomain: string | null;
38
+ url: string | null;
39
+ suspended: boolean;
40
+ ready: boolean;
41
+ createdAt: string;
42
+ owner: boolean;
43
+ role?: string;
44
+ team?: string | null;
45
+ }
46
+
47
+ export interface ItemDePasta {
48
+ name: string;
49
+ type: "file" | "directory";
50
+ size: number | null;
51
+ }
52
+
53
+ export interface ResultadoDaBusca {
54
+ query: string;
55
+ total: number;
56
+ files: Array<{ path: string; matches: number; lines: Array<{ line: number; column: number; text: string }> }>;
57
+ filesSearched: number;
58
+ truncated: boolean;
59
+ notice: string | null;
60
+ tookMs: number;
61
+ }
62
+
63
+ export interface Banco {
64
+ id: string;
65
+ name: string;
66
+ type: string;
67
+ version: string;
68
+ online: boolean;
69
+ state: string;
70
+ ram: number;
71
+ createdAt: string;
72
+ }
73
+
74
+ export interface Equipe {
75
+ id: string;
76
+ name: string;
77
+ description: string | null;
78
+ role: string;
79
+ owner: boolean;
80
+ ownerName: string | null;
81
+ members: number;
82
+ pendingInvites: number;
83
+ sharedApps: number;
84
+ createdAt: string;
85
+ }
86
+
87
+ export interface Dominio {
88
+ domain: string | null;
89
+ platformAddress: string | null;
90
+ ready: boolean;
91
+ records: Array<{ type: string; name: string; value: string; status: string; optional: boolean }>;
92
+ }
93
+
94
+ type Qualquer = Record<string, unknown>;
95
+
96
+ export declare class RTCloud {
97
+ constructor(opcoes?: OpcoesDoCliente);
98
+ readonly apiKey: string;
99
+ readonly baseUrl: string;
100
+
101
+ account: {
102
+ me(): Promise<Qualquer>;
103
+ teams(): Promise<Equipe[]>;
104
+ };
105
+ platform: {
106
+ status(): Promise<Qualquer>;
107
+ };
108
+ apps: {
109
+ list(): Promise<Aplicacao[]>;
110
+ statusAll(): Promise<Qualquer[]>;
111
+ get(id: string): Promise<Aplicacao & Qualquer>;
112
+ status(id: string): Promise<Qualquer>;
113
+ metrics(id: string, range?: "24h" | "7d"): Promise<Qualquer>;
114
+ logs(id: string): Promise<{ logs: string }>;
115
+ start(id: string): Promise<Qualquer>;
116
+ stop(id: string): Promise<Qualquer>;
117
+ restart(id: string): Promise<Qualquer>;
118
+ deployments(id: string): Promise<Qualquer[]>;
119
+ commit(id: string, zip: Blob | ArrayBuffer | Uint8Array, opcoes?: { filename?: string }): Promise<Qualquer>;
120
+ /** exclui de vez — `confirm` é o nome exato da aplicação */
121
+ delete(id: string, confirm: string): Promise<{ id: string; deleted: true; finishing: boolean }>;
122
+ };
123
+ files: {
124
+ list(id: string, path?: string): Promise<{ path: string; items: ItemDePasta[] }>;
125
+ read(id: string, path: string): Promise<{ path: string; size: number; encoding: "utf8"; content: string }>;
126
+ write(id: string, path: string, content: string): Promise<{ path: string; size: number; restartNeeded: true }>;
127
+ edit(id: string, path: string, edits: Array<{ old: string; new: string }>): Promise<Qualquer>;
128
+ move(id: string, from: string, to: string): Promise<{ from: string; to: string }>;
129
+ delete(id: string, path: string): Promise<{ path: string; deleted: boolean }>;
130
+ search(id: string, q: string, opcoes?: { caseSensitive?: boolean; wholeWord?: boolean; path?: string; ext?: string }): Promise<ResultadoDaBusca>;
131
+ };
132
+ envs: {
133
+ list(id: string): Promise<Record<string, string>>;
134
+ set(id: string, envs: Record<string, string>, opcoes?: { restart?: boolean }): Promise<{ total: number; keys: string[]; restarted: boolean }>;
135
+ replace(id: string, envs: Record<string, string>, opcoes?: { restart?: boolean }): Promise<{ total: number; keys: string[]; restarted: boolean }>;
136
+ remove(id: string, keys: string[], opcoes?: { restart?: boolean }): Promise<{ total: number; keys: string[]; restarted: boolean }>;
137
+ };
138
+ snapshots: {
139
+ list(id: string): Promise<Array<{ version: string; size: number; createdAt: string; origin: string | null; latest: boolean }>>;
140
+ create(id: string): Promise<Qualquer>;
141
+ restore(id: string, version: string): Promise<{ restored: boolean; pending: boolean; version: string; restarting: boolean }>;
142
+ restoreStatus(id: string): Promise<{ state: string; step: string | null; message: string; started_at: string | null; finished_at: string | null; version: string | null }>;
143
+ restoreAndWait(id: string, version: string, opcoes?: { intervalMs?: number; timeoutMs?: number }): Promise<Qualquer>;
144
+ };
145
+ monitor: {
146
+ get(id: string): Promise<Qualquer>;
147
+ check(id: string): Promise<Qualquer>;
148
+ };
149
+ network: {
150
+ analytics(id: string, days?: number): Promise<Qualquer>;
151
+ errors(id: string, days?: number, opcoes?: { include4xx?: boolean }): Promise<Qualquer>;
152
+ performance(id: string, days?: number): Promise<Qualquer>;
153
+ purgeCache(id: string): Promise<Qualquer>;
154
+ domain(id: string): Promise<Dominio>;
155
+ };
156
+ databases: {
157
+ list(): Promise<Banco[]>;
158
+ get(id: string): Promise<Banco & { hostname: string; port: number }>;
159
+ metrics(id: string): Promise<Qualquer>;
160
+ start(id: string): Promise<Qualquer>;
161
+ stop(id: string): Promise<Qualquer>;
162
+ restart(id: string): Promise<Qualquer>;
163
+ backups(id: string): Promise<Array<{ id: string; size: number; createdAt: string }>>;
164
+ createBackup(id: string): Promise<{ processing: boolean }>;
165
+ certificate(id: string): Promise<{ available: boolean; filename?: string; certificate: string | null }>;
166
+ resetCredentials(id: string, type: "password" | "certificate"): Promise<Qualquer>;
167
+ };
168
+
169
+ /** pedido cru, para rotas sem atalho */
170
+ request<T = unknown>(metodo: Metodo, caminho: string, opcoes?: { json?: unknown; form?: FormData; timeoutMs?: number }): Promise<T>;
171
+ }
172
+
173
+ export default RTCloud;
package/src/index.js ADDED
@@ -0,0 +1,271 @@
1
+ /**
2
+ * rtcloud-sdk — a biblioteca oficial da RTCloud para JavaScript e TypeScript.
3
+ *
4
+ * import { RTCloud } from "rtcloud-sdk";
5
+ * const rt = new RTCloud({ apiKey: process.env.RTCLOUD_API_KEY });
6
+ * const apps = await rt.apps.list();
7
+ *
8
+ * Fala com a API pública (https://api.rtcloud.com.br/v1). Toda resposta da API vem num envelope
9
+ * `{ status, response }`; aqui você recebe só o `response`. Erro vira um
10
+ * `RTCloudError` com `status` (HTTP), `code` e a mensagem da API.
11
+ *
12
+ * Repetições automáticas (as mesmas da CLI):
13
+ * · 503 "em atualização" — a RTCloud publicando uma versão nova do painel:
14
+ * o pedido nem chegou a rodar, então repete (inclusive POST) por até 5 min;
15
+ * · 429 em leitura (GET) — espera o tempo pedido (até 30 s), no máximo 2 vezes;
16
+ * · nada mais é repetido sozinho.
17
+ *
18
+ * Use só no servidor: a chave age como você. Nunca coloque a chave no
19
+ * navegador nem em código público.
20
+ */
21
+
22
+ export const VERSAO = "1.1.0";
23
+ /* 1.1.0 (01/12/2026): a API mora em api.rtcloud.com.br — o endereço antigo saiu de circulação */
24
+ const BASE_PADRAO = "https://api.rtcloud.com.br/v1";
25
+ /** O endereço antigo (rtcloud.com.br/api/v1) vira o oficial, mesmo se vier de baseUrl ou RTCLOUD_API_URL. */
26
+ const BASE_ANTIGA = /^https?:\/\/(www\.)?rtcloud\.com\.br\/api\/v1\/*$/i;
27
+ const ATUALIZACAO_MAX_MS = 5 * 60_000;
28
+
29
+ const esperar = (ms) => new Promise((r) => setTimeout(r, ms));
30
+
31
+ /** Erro devolvido pela API (ou pela rede, com status 0). */
32
+ export class RTCloudError extends Error {
33
+ constructor(message, { status = 0, code = "UNKNOWN", body = null } = {}) {
34
+ super(message);
35
+ this.name = "RTCloudError";
36
+ /** status HTTP (0 = sem resposta) */
37
+ this.status = status;
38
+ /** código estável da API: NOT_FOUND, RATE_LIMIT, FORBIDDEN… */
39
+ this.code = code;
40
+ this.body = body;
41
+ }
42
+ }
43
+
44
+ function enc(v) {
45
+ return encodeURIComponent(String(v));
46
+ }
47
+
48
+ function consulta(obj) {
49
+ const p = new URLSearchParams();
50
+ for (const [k, v] of Object.entries(obj || {})) {
51
+ if (v === undefined || v === null || v === "" || v === false) continue;
52
+ p.set(k, v === true ? "1" : String(v));
53
+ }
54
+ const s = p.toString();
55
+ return s ? `?${s}` : "";
56
+ }
57
+
58
+ export class RTCloud {
59
+ /**
60
+ * @param {{ apiKey?: string, baseUrl?: string, timeoutMs?: number, fetch?: typeof fetch, userAgent?: string }} [opcoes]
61
+ */
62
+ constructor(opcoes = {}) {
63
+ const ambiente = typeof process !== "undefined" && process.env ? process.env : {};
64
+ this.apiKey = String(opcoes.apiKey ?? ambiente.RTCLOUD_API_KEY ?? "").trim();
65
+ if (!this.apiKey) {
66
+ throw new RTCloudError("Informe a chave da API (apiKey) ou defina RTCLOUD_API_KEY. Gere uma no painel: menu da conta → Chaves de API.", {
67
+ code: "MISSING_API_KEY",
68
+ });
69
+ }
70
+ if (/^rtm_/.test(this.apiKey)) {
71
+ throw new RTCloudError("Essa é uma chave do servidor MCP (rtm_). A biblioteca usa uma chave da API (rtc_), criada em Chaves de API.", {
72
+ code: "WRONG_KEY_TYPE",
73
+ });
74
+ }
75
+ const escolhida = String(opcoes.baseUrl ?? ambiente.RTCLOUD_API_URL ?? "").trim();
76
+ this.baseUrl = (!escolhida || BASE_ANTIGA.test(escolhida) ? BASE_PADRAO : escolhida).replace(/\/+$/, "");
77
+ this.timeoutMs = Number(opcoes.timeoutMs) > 0 ? Number(opcoes.timeoutMs) : 60_000;
78
+ this._fetch = opcoes.fetch ?? globalThis.fetch;
79
+ if (typeof this._fetch !== "function") throw new RTCloudError("Este ambiente não tem fetch: use Node.js 18 ou mais novo.", { code: "NO_FETCH" });
80
+ this.userAgent = opcoes.userAgent ?? `rtcloud-sdk/${VERSAO}`;
81
+
82
+ const r = this;
83
+ /** A conta dona da chave. */
84
+ this.account = {
85
+ /** perfil, plano e uso de memória */
86
+ me: () => r.request("GET", "/users/me"),
87
+ /** equipes que você criou ou de que participa */
88
+ teams: () => r.request("GET", "/teams"),
89
+ };
90
+ /** O estado da plataforma. */
91
+ this.platform = {
92
+ status: () => r.request("GET", "/service/status"),
93
+ };
94
+ /** Aplicações. */
95
+ this.apps = {
96
+ list: () => r.request("GET", "/apps"),
97
+ /** status de todas de uma vez */
98
+ statusAll: () => r.request("GET", "/apps/status"),
99
+ get: (id) => r.request("GET", `/apps/${enc(id)}`),
100
+ status: (id) => r.request("GET", `/apps/${enc(id)}/status`),
101
+ /** @param {"24h"|"7d"} [range] */
102
+ metrics: (id, range = "24h") => r.request("GET", `/apps/${enc(id)}/metrics${consulta({ range })}`),
103
+ logs: (id) => r.request("GET", `/apps/${enc(id)}/logs`),
104
+ start: (id) => r.request("POST", `/apps/${enc(id)}/start`),
105
+ stop: (id) => r.request("POST", `/apps/${enc(id)}/stop`),
106
+ restart: (id) => r.request("POST", `/apps/${enc(id)}/restart`),
107
+ deployments: (id) => r.request("GET", `/apps/${enc(id)}/deployments`),
108
+ /**
109
+ * Publica uma versão nova a partir de um .zip.
110
+ * @param {string} id
111
+ * @param {Blob|ArrayBuffer|Uint8Array} zip
112
+ * @param {{ filename?: string }} [opcoes]
113
+ */
114
+ commit: (id, zip, opcoes = {}) => {
115
+ const form = new FormData();
116
+ const blob = zip instanceof Blob ? zip : new Blob([zip], { type: "application/zip" });
117
+ form.append("file", blob, opcoes.filename ?? "projeto.zip");
118
+ return r.request("POST", `/apps/${enc(id)}/commit`, { form, timeoutMs: Math.max(r.timeoutMs, 600_000) });
119
+ },
120
+ /** Exclui de vez. `confirm` precisa ser o nome exato da aplicação. */
121
+ delete: (id, confirm) => r.request("DELETE", `/apps/${enc(id)}`, { json: { confirm } }),
122
+ };
123
+ /** Arquivos de uma aplicação. */
124
+ this.files = {
125
+ list: (id, path = "") => r.request("GET", `/apps/${enc(id)}/files${consulta({ path })}`),
126
+ read: (id, path) => r.request("GET", `/apps/${enc(id)}/files/content${consulta({ path })}`),
127
+ /** cria ou substitui (até 1 MB) */
128
+ write: (id, path, content) => r.request("PUT", `/apps/${enc(id)}/files`, { json: { path, content } }),
129
+ /** troca trechos: edits = [{ old, new }] — cada "old" aparece uma vez */
130
+ edit: (id, path, edits) => r.request("PATCH", `/apps/${enc(id)}/files`, { json: { path, edits } }),
131
+ move: (id, from, to) => r.request("PATCH", `/apps/${enc(id)}/files`, { json: { from, to } }),
132
+ delete: (id, path) => r.request("DELETE", `/apps/${enc(id)}/files${consulta({ path })}`),
133
+ /**
134
+ * Busca texto em todos os arquivos.
135
+ * @param {{ caseSensitive?: boolean, wholeWord?: boolean, path?: string, ext?: string }} [opcoes]
136
+ */
137
+ search: (id, q, opcoes = {}) =>
138
+ r.request(
139
+ "GET",
140
+ `/apps/${enc(id)}/files/search${consulta({ q, case: opcoes.caseSensitive, word: opcoes.wholeWord, path: opcoes.path, ext: opcoes.ext })}`
141
+ ),
142
+ };
143
+ /** Variáveis de ambiente. Por padrão a aplicação reinicia para valer. */
144
+ this.envs = {
145
+ list: (id) => r.request("GET", `/apps/${enc(id)}/envs`),
146
+ /** grava só as chaves enviadas */
147
+ set: (id, envs, opcoes = {}) => r.request("POST", `/apps/${enc(id)}/envs`, { json: { envs, restart: opcoes.restart } }),
148
+ /** substitui TODAS (as que ficarem de fora são apagadas) */
149
+ replace: (id, envs, opcoes = {}) => r.request("PUT", `/apps/${enc(id)}/envs`, { json: { envs, restart: opcoes.restart } }),
150
+ remove: (id, keys, opcoes = {}) => r.request("DELETE", `/apps/${enc(id)}/envs`, { json: { keys, restart: opcoes.restart } }),
151
+ };
152
+ /** Snapshots (versões guardadas) e a restauração acompanhada. */
153
+ this.snapshots = {
154
+ list: (id) => r.request("GET", `/apps/${enc(id)}/snapshots`),
155
+ create: (id) => r.request("POST", `/apps/${enc(id)}/snapshots`),
156
+ restore: (id, version) => r.request("POST", `/apps/${enc(id)}/snapshots/restore`, { json: { version } }),
157
+ restoreStatus: (id) => r.request("GET", `/apps/${enc(id)}/snapshots/restore`),
158
+ /**
159
+ * Restaura e espera terminar (consulta o andamento a cada 5 s).
160
+ * @param {{ intervalMs?: number, timeoutMs?: number }} [opcoes]
161
+ */
162
+ restoreAndWait: async (id, version, opcoes = {}) => {
163
+ const inicio = await r.snapshots.restore(id, version);
164
+ if (!inicio?.pending) return inicio;
165
+ const intervalo = Math.max(2_000, Number(opcoes.intervalMs) || 5_000);
166
+ const limite = Date.now() + (Number(opcoes.timeoutMs) || 15 * 60_000);
167
+ while (Date.now() < limite) {
168
+ await esperar(intervalo);
169
+ const s = await r.snapshots.restoreStatus(id);
170
+ if (s?.state === "success") return s;
171
+ if (s?.state === "error") throw new RTCloudError(s.message || "A restauração falhou.", { status: 200, code: "RESTORE_FAILED", body: s });
172
+ }
173
+ throw new RTCloudError("A restauração passou do tempo de espera; ela continua rodando — confira em restoreStatus().", { code: "RESTORE_TIMEOUT" });
174
+ },
175
+ };
176
+ /** Monitor do site e sinal de vida do bot. */
177
+ this.monitor = {
178
+ get: (id) => r.request("GET", `/apps/${enc(id)}/monitor`),
179
+ check: (id) => r.request("POST", `/apps/${enc(id)}/monitor/check`),
180
+ };
181
+ /** Relatórios do site e o cache. */
182
+ this.network = {
183
+ analytics: (id, days = 1) => r.request("GET", `/apps/${enc(id)}/network/analytics${consulta({ days })}`),
184
+ errors: (id, days = 1, opcoes = {}) => r.request("GET", `/apps/${enc(id)}/network/errors${consulta({ days, include4xx: opcoes.include4xx })}`),
185
+ performance: (id, days = 1) => r.request("GET", `/apps/${enc(id)}/network/performance${consulta({ days })}`),
186
+ purgeCache: (id) => r.request("POST", `/apps/${enc(id)}/purge-cache`),
187
+ /** domínio próprio e registros de DNS */
188
+ domain: (id) => r.request("GET", `/apps/${enc(id)}/domain`),
189
+ };
190
+ /** Bancos de dados gerenciados. */
191
+ this.databases = {
192
+ list: () => r.request("GET", "/databases"),
193
+ get: (id) => r.request("GET", `/databases/${enc(id)}`),
194
+ metrics: (id) => r.request("GET", `/databases/${enc(id)}/metrics`),
195
+ start: (id) => r.request("POST", `/databases/${enc(id)}/start`),
196
+ stop: (id) => r.request("POST", `/databases/${enc(id)}/stop`),
197
+ restart: (id) => r.request("POST", `/databases/${enc(id)}/restart`),
198
+ backups: (id) => r.request("GET", `/databases/${enc(id)}/backups`),
199
+ createBackup: (id) => r.request("POST", `/databases/${enc(id)}/backups`),
200
+ /** o .pem (precisa de chave de acesso total) */
201
+ certificate: (id) => r.request("GET", `/databases/${enc(id)}/certificate`),
202
+ /** @param {"password"|"certificate"} type */
203
+ resetCredentials: (id, type) => r.request("POST", `/databases/${enc(id)}/credentials/reset`, { json: { type } }),
204
+ };
205
+ }
206
+
207
+ /**
208
+ * Pedido cru à API (para rotas que ainda não têm atalho aqui).
209
+ * @param {"GET"|"POST"|"PUT"|"PATCH"|"DELETE"} metodo
210
+ * @param {string} caminho depois de /api/v1, começando com "/"
211
+ * @param {{ json?: unknown, form?: FormData, timeoutMs?: number }} [opcoes]
212
+ */
213
+ async request(metodo, caminho, opcoes = {}) {
214
+ const url = `${this.baseUrl}${caminho}`;
215
+ const cabecalhos = { Authorization: this.apiKey, Accept: "application/json", "User-Agent": this.userAgent };
216
+ let corpo;
217
+ if (opcoes.form) corpo = opcoes.form;
218
+ else if (opcoes.json !== undefined) {
219
+ const limpo = JSON.parse(JSON.stringify(opcoes.json));
220
+ corpo = JSON.stringify(limpo);
221
+ cabecalhos["Content-Type"] = "application/json";
222
+ }
223
+ const inicio = Date.now();
224
+ let repeticoes429 = 0;
225
+ for (let tentativa = 0; ; tentativa++) {
226
+ const ac = new AbortController();
227
+ const t = setTimeout(() => ac.abort(), opcoes.timeoutMs ?? this.timeoutMs);
228
+ let res;
229
+ try {
230
+ res = await this._fetch(url, { method: metodo, headers: cabecalhos, body: corpo, signal: ac.signal });
231
+ } catch (e) {
232
+ clearTimeout(t);
233
+ const tempo = e?.name === "AbortError";
234
+ throw new RTCloudError(tempo ? "A RTCloud não respondeu a tempo." : `Sem conexão com a RTCloud: ${e?.message || e}`, {
235
+ code: tempo ? "TIMEOUT" : "NETWORK_ERROR",
236
+ });
237
+ }
238
+ clearTimeout(t);
239
+ const texto = await res.text();
240
+ let dados = null;
241
+ try {
242
+ dados = texto ? JSON.parse(texto) : null;
243
+ } catch {
244
+ dados = null;
245
+ }
246
+
247
+ if (res.ok && dados && dados.status === "success") return dados.response;
248
+ if (res.ok && !dados) return texto;
249
+
250
+ /* 503 de atualização: a RTCloud está publicando uma versão nova — o pedido não rodou */
251
+ const atualizando = res.status === 503 && (res.headers.get("x-rtcloud-atualizando") || /atualiza/i.test(dados?.message || texto));
252
+ if (atualizando && Date.now() - inicio < ATUALIZACAO_MAX_MS) {
253
+ await esperar(Math.min(15_000, 3_000 * (tentativa + 1)));
254
+ continue;
255
+ }
256
+ if (res.status === 429 && metodo === "GET" && repeticoes429 < 2) {
257
+ const seg = Number(res.headers.get("retry-after")) || Math.max(1, Number(res.headers.get("x-ratelimit-reset")) - Math.floor(Date.now() / 1000)) || 5;
258
+ repeticoes429++;
259
+ await esperar(Math.min(30, Math.max(1, seg)) * 1000);
260
+ continue;
261
+ }
262
+ throw new RTCloudError(dados?.message || `A API respondeu ${res.status}.`, {
263
+ status: res.status,
264
+ code: dados?.code || (res.status >= 500 ? "UNAVAILABLE" : "BAD_REQUEST"),
265
+ body: dados ?? texto,
266
+ });
267
+ }
268
+ }
269
+ }
270
+
271
+ export default RTCloud;