cm-tunnel 1.5.0 → 1.7.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/README.md +186 -13
- package/dist/StaticServer.d.ts +26 -0
- package/dist/StaticServer.js +151 -7
- package/dist/Tunnel.d.ts +2 -0
- package/dist/cli-utils.d.ts +59 -0
- package/dist/cli-utils.js +135 -2
- package/dist/cli.js +126 -129
- package/dist/config.d.ts +7 -0
- package/dist/config.js +95 -0
- package/dist/dashboard.d.ts +23 -0
- package/dist/dashboard.js +163 -0
- package/dist/doctor.d.ts +2 -0
- package/dist/doctor.js +152 -0
- package/dist/net-utils.d.ts +6 -0
- package/dist/net-utils.js +40 -0
- package/dist/providers/cloudflare.js +3 -1
- package/package.json +5 -4
package/dist/cli.js
CHANGED
|
@@ -1,103 +1,19 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { spawnSync } from "node:child_process";
|
|
3
|
-
import {
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync, } from "node:fs";
|
|
4
4
|
import { join, resolve } from "node:path";
|
|
5
|
-
import { createConnection, createServer } from "node:net";
|
|
6
5
|
import prompts from "prompts";
|
|
7
6
|
import tunnel from "./index.js";
|
|
7
|
+
import { Dashboard } from "./dashboard.js";
|
|
8
|
+
import { runDoctor } from "./doctor.js";
|
|
9
|
+
import { CONFIG_FILE, loadConfig, loadDotEnv, saveConfig, saveTokenToEnv, } from "./config.js";
|
|
10
|
+
import { isPortFree, isPortInUse } from "./net-utils.js";
|
|
8
11
|
import { HELP, STRINGS, buildTunnelOptions, detectLang, guessMode, isValidDomain, isValidPort, normalizeDomain, normalizePrefix, parseCliArgs, } from "./cli-utils.js";
|
|
9
|
-
const CONFIG_FILE = ".cm-tunnel.json";
|
|
10
12
|
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
11
13
|
function langFromArgv() {
|
|
12
14
|
const index = process.argv.indexOf("--lang");
|
|
13
15
|
return index >= 0 ? process.argv[index + 1] : undefined;
|
|
14
16
|
}
|
|
15
|
-
function loadDotEnv() {
|
|
16
|
-
if (!existsSync(".env"))
|
|
17
|
-
return;
|
|
18
|
-
if (typeof process.loadEnvFile === "function") {
|
|
19
|
-
try {
|
|
20
|
-
process.loadEnvFile(".env");
|
|
21
|
-
return;
|
|
22
|
-
}
|
|
23
|
-
catch {
|
|
24
|
-
// Cai no parser manual abaixo.
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
try {
|
|
28
|
-
const content = readFileSync(resolve(".env"), "utf8");
|
|
29
|
-
for (const raw of content.split(/\r?\n/)) {
|
|
30
|
-
const line = raw.trim();
|
|
31
|
-
if (!line || line.startsWith("#"))
|
|
32
|
-
continue;
|
|
33
|
-
const separator = line.indexOf("=");
|
|
34
|
-
if (separator <= 0)
|
|
35
|
-
continue;
|
|
36
|
-
const key = line.slice(0, separator).trim();
|
|
37
|
-
let value = line.slice(separator + 1).trim();
|
|
38
|
-
if ((value.startsWith('"') && value.endsWith('"')) ||
|
|
39
|
-
(value.startsWith("'") && value.endsWith("'"))) {
|
|
40
|
-
value = value.slice(1, -1);
|
|
41
|
-
}
|
|
42
|
-
if (!(key in process.env)) {
|
|
43
|
-
process.env[key] = value;
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
catch {
|
|
48
|
-
// .env inválido é ignorado; o usuário ainda pode usar variáveis de ambiente.
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
function loadConfig() {
|
|
52
|
-
const file = resolve(CONFIG_FILE);
|
|
53
|
-
if (!existsSync(file))
|
|
54
|
-
return null;
|
|
55
|
-
try {
|
|
56
|
-
const data = JSON.parse(readFileSync(file, "utf8"));
|
|
57
|
-
if (data?.mode !== "site" && data?.mode !== "api" && data?.mode !== "both") {
|
|
58
|
-
return null;
|
|
59
|
-
}
|
|
60
|
-
if (data?.publish !== "quick" && data?.publish !== "domain") {
|
|
61
|
-
return null;
|
|
62
|
-
}
|
|
63
|
-
return {
|
|
64
|
-
mode: data.mode,
|
|
65
|
-
public: typeof data.public === "string" ? data.public : undefined,
|
|
66
|
-
api: typeof data.api === "string" ? data.api : undefined,
|
|
67
|
-
apiPrefix: typeof data.apiPrefix === "string" ? normalizePrefix(data.apiPrefix) : "/api",
|
|
68
|
-
publish: data.publish,
|
|
69
|
-
domain: typeof data.domain === "string" ? data.domain : undefined,
|
|
70
|
-
target: typeof data.target === "number" ? data.target : undefined,
|
|
71
|
-
port: typeof data.port === "number" ? data.port : undefined,
|
|
72
|
-
};
|
|
73
|
-
}
|
|
74
|
-
catch {
|
|
75
|
-
return null;
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
function saveConfig(plan) {
|
|
79
|
-
writeFileSync(resolve(CONFIG_FILE), `${JSON.stringify(plan, null, 2)}\n`);
|
|
80
|
-
}
|
|
81
|
-
function saveTokenToEnv(token) {
|
|
82
|
-
const file = resolve(".env");
|
|
83
|
-
let content = existsSync(file) ? readFileSync(file, "utf8") : "";
|
|
84
|
-
const line = `CLOUDFLARE_TOKEN=${token}`;
|
|
85
|
-
if (/^CLOUDFLARE_TOKEN=.*$/m.test(content)) {
|
|
86
|
-
content = content.replace(/^CLOUDFLARE_TOKEN=.*$/m, line);
|
|
87
|
-
}
|
|
88
|
-
else {
|
|
89
|
-
if (content && !content.endsWith("\n"))
|
|
90
|
-
content += "\n";
|
|
91
|
-
content += `${line}\n`;
|
|
92
|
-
}
|
|
93
|
-
writeFileSync(file, content);
|
|
94
|
-
try {
|
|
95
|
-
chmodSync(file, 0o600);
|
|
96
|
-
}
|
|
97
|
-
catch {
|
|
98
|
-
// Em sistemas sem suporte a chmod, segue normalmente.
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
17
|
function starterHtml(lang) {
|
|
102
18
|
const language = lang === "pt" ? "pt-BR" : "en";
|
|
103
19
|
const title = lang === "pt" ? "Meu site" : "My site";
|
|
@@ -121,30 +37,21 @@ const STARTER_API = `export default function handler(req, res) {
|
|
|
121
37
|
res.json({ ok: true, method: req.method, time: new Date().toISOString() });
|
|
122
38
|
}
|
|
123
39
|
`;
|
|
40
|
+
const STARTER_API_SERVER = `import http from 'node:http';
|
|
41
|
+
|
|
42
|
+
const port = Number(process.env.PORT);
|
|
43
|
+
|
|
44
|
+
const server = http.createServer((req, res) => {
|
|
45
|
+
res.setHeader('Content-Type', 'application/json');
|
|
46
|
+
res.end(JSON.stringify({ ok: true, url: req.url }));
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
server.listen(port, '127.0.0.1');
|
|
50
|
+
`;
|
|
124
51
|
function onCancel(s) {
|
|
125
52
|
console.log(`\n${s.cancelled}`);
|
|
126
53
|
process.exit(0);
|
|
127
54
|
}
|
|
128
|
-
function isPortFree(port) {
|
|
129
|
-
return new Promise((resolvePort) => {
|
|
130
|
-
const server = createServer();
|
|
131
|
-
server.once("error", () => resolvePort(false));
|
|
132
|
-
server.once("listening", () => {
|
|
133
|
-
server.close(() => resolvePort(true));
|
|
134
|
-
});
|
|
135
|
-
server.listen(port, "127.0.0.1");
|
|
136
|
-
});
|
|
137
|
-
}
|
|
138
|
-
function isPortInUse(port) {
|
|
139
|
-
return new Promise((resolvePort) => {
|
|
140
|
-
const socket = createConnection({ port, host: "127.0.0.1" });
|
|
141
|
-
socket.once("connect", () => {
|
|
142
|
-
socket.destroy();
|
|
143
|
-
resolvePort(true);
|
|
144
|
-
});
|
|
145
|
-
socket.once("error", () => resolvePort(false));
|
|
146
|
-
});
|
|
147
|
-
}
|
|
148
55
|
async function askText(s, message, initial, validate) {
|
|
149
56
|
const res = await prompts({ type: "text", name: "value", message, initial, validate }, { onCancel: () => onCancel(s) });
|
|
150
57
|
return String(res.value ?? "").trim();
|
|
@@ -173,7 +80,7 @@ async function askPort(s, message, initial) {
|
|
|
173
80
|
}, { onCancel: () => onCancel(s) });
|
|
174
81
|
return Number(res.value);
|
|
175
82
|
}
|
|
176
|
-
async function ensureFolder(s, lang, dir, kind, yes, dryRun) {
|
|
83
|
+
async function ensureFolder(s, lang, dir, kind, yes, dryRun, apiMode = "handlers") {
|
|
177
84
|
if (!dir)
|
|
178
85
|
return;
|
|
179
86
|
if (dryRun)
|
|
@@ -191,6 +98,9 @@ async function ensureFolder(s, lang, dir, kind, yes, dryRun) {
|
|
|
191
98
|
if (kind === "site") {
|
|
192
99
|
writeFileSync(join(abs, "index.html"), starterHtml(lang));
|
|
193
100
|
}
|
|
101
|
+
else if (apiMode === "server") {
|
|
102
|
+
writeFileSync(join(abs, "index.js"), STARTER_API_SERVER);
|
|
103
|
+
}
|
|
194
104
|
else {
|
|
195
105
|
writeFileSync(join(abs, "hello.js"), STARTER_API);
|
|
196
106
|
}
|
|
@@ -225,6 +135,10 @@ async function main() {
|
|
|
225
135
|
console.log(`cm-tunnel ${pkg.version}`);
|
|
226
136
|
return;
|
|
227
137
|
}
|
|
138
|
+
if (opts.command === "doctor") {
|
|
139
|
+
process.exitCode = await runDoctor(lang);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
228
142
|
if (!process.stdin.isTTY && !opts.yes) {
|
|
229
143
|
throw new Error(s.needTty);
|
|
230
144
|
}
|
|
@@ -286,9 +200,44 @@ async function main() {
|
|
|
286
200
|
const apiPath = target || mode === "site"
|
|
287
201
|
? undefined
|
|
288
202
|
: await chooseFolder(s, "api", opts.api, saved?.api, opts.yes);
|
|
203
|
+
let apiMode;
|
|
204
|
+
let apiEntry;
|
|
205
|
+
if (!target && mode !== "site" && apiPath) {
|
|
206
|
+
const detectedEntry = ["index.js", "server.js", "app.js"]
|
|
207
|
+
.map((file) => join(apiPath, file))
|
|
208
|
+
.find((file) => existsSync(resolve(file)));
|
|
209
|
+
const suggestedApiMode = detectedEntry ? "server" : "handlers";
|
|
210
|
+
apiMode =
|
|
211
|
+
opts.apiMode ??
|
|
212
|
+
saved?.apiMode ??
|
|
213
|
+
(opts.yes
|
|
214
|
+
? suggestedApiMode
|
|
215
|
+
: await askSelect(s, s.apiModePrompt, [
|
|
216
|
+
{ title: s.apiModeHandlers, value: "handlers" },
|
|
217
|
+
{ title: s.apiModeServer, value: "server" },
|
|
218
|
+
], suggestedApiMode === "server" ? 1 : 0));
|
|
219
|
+
if (apiMode === "server") {
|
|
220
|
+
const defaultEntry = opts.apiEntry ??
|
|
221
|
+
saved?.apiEntry ??
|
|
222
|
+
detectedEntry ??
|
|
223
|
+
join(apiPath, "index.js");
|
|
224
|
+
apiEntry =
|
|
225
|
+
opts.apiEntry ??
|
|
226
|
+
saved?.apiEntry ??
|
|
227
|
+
(opts.yes
|
|
228
|
+
? defaultEntry
|
|
229
|
+
: await askText(s, s.apiEntryPrompt, defaultEntry));
|
|
230
|
+
}
|
|
231
|
+
}
|
|
289
232
|
if (!target) {
|
|
290
|
-
await ensureFolder(s, lang, publicPath, "site", opts.yes, opts.dryRun);
|
|
291
|
-
await ensureFolder(s, lang, apiPath, "api", opts.yes, opts.dryRun);
|
|
233
|
+
await ensureFolder(s, lang, publicPath, "site", opts.yes, opts.dryRun, apiMode);
|
|
234
|
+
await ensureFolder(s, lang, apiPath, "api", opts.yes, opts.dryRun, apiMode);
|
|
235
|
+
}
|
|
236
|
+
if (apiMode === "server" &&
|
|
237
|
+
apiEntry &&
|
|
238
|
+
!opts.dryRun &&
|
|
239
|
+
!existsSync(resolve(apiEntry))) {
|
|
240
|
+
throw new Error(s.apiEntryInvalid(apiEntry));
|
|
292
241
|
}
|
|
293
242
|
let publish;
|
|
294
243
|
if (opts.quick) {
|
|
@@ -357,6 +306,8 @@ async function main() {
|
|
|
357
306
|
mode,
|
|
358
307
|
public: publicPath,
|
|
359
308
|
api: apiPath,
|
|
309
|
+
apiMode,
|
|
310
|
+
apiEntry,
|
|
360
311
|
apiPrefix: normalizePrefix(opts.apiPrefix ?? saved?.apiPrefix),
|
|
361
312
|
publish,
|
|
362
313
|
domain,
|
|
@@ -372,7 +323,9 @@ async function main() {
|
|
|
372
323
|
console.log(` ${s.summarySite(publicPath)}`);
|
|
373
324
|
}
|
|
374
325
|
if (mode !== "site" && apiPath) {
|
|
375
|
-
console.log(` ${
|
|
326
|
+
console.log(` ${apiMode === "server"
|
|
327
|
+
? s.summaryApiServer(apiPath, apiEntry ?? "")
|
|
328
|
+
: s.summaryApi(apiPath, plan.apiPrefix)}`);
|
|
376
329
|
}
|
|
377
330
|
}
|
|
378
331
|
console.log(` ${publish === "quick"
|
|
@@ -386,33 +339,77 @@ async function main() {
|
|
|
386
339
|
console.log(s.cancelled);
|
|
387
340
|
return;
|
|
388
341
|
}
|
|
389
|
-
if (opts.save && !opts.dryRun) {
|
|
390
|
-
saveConfig(plan);
|
|
391
|
-
console.log(s.savedConfig(CONFIG_FILE));
|
|
392
|
-
}
|
|
393
342
|
if (opts.dryRun) {
|
|
394
343
|
console.log(s.dryRun);
|
|
395
344
|
return;
|
|
396
345
|
}
|
|
397
|
-
|
|
398
|
-
const
|
|
399
|
-
|
|
400
|
-
if (
|
|
401
|
-
console.log(
|
|
346
|
+
const useDashboard = opts.command === "dashboard" && !!process.stdout.isTTY;
|
|
347
|
+
const wantLogs = opts.logs || opts.command === "dashboard";
|
|
348
|
+
const dashboard = useDashboard ? new Dashboard(lang, plan) : null;
|
|
349
|
+
if (opts.command === "dashboard" && !process.stdout.isTTY) {
|
|
350
|
+
console.log(s.dashboardNoTty);
|
|
351
|
+
}
|
|
352
|
+
const tunnelOptions = buildTunnelOptions(plan, token);
|
|
353
|
+
if (wantLogs) {
|
|
354
|
+
const logSink = (chunk) => {
|
|
355
|
+
if (dashboard) {
|
|
356
|
+
dashboard.push(chunk);
|
|
357
|
+
}
|
|
358
|
+
else {
|
|
359
|
+
process.stdout.write(chunk);
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
tunnelOptions.onLog = logSink;
|
|
363
|
+
if (tunnelOptions.serve) {
|
|
364
|
+
tunnelOptions.serve.onLog = logSink;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
if (dashboard) {
|
|
368
|
+
dashboard.start();
|
|
402
369
|
}
|
|
403
370
|
else {
|
|
404
|
-
|
|
405
|
-
|
|
371
|
+
console.log(s.starting);
|
|
372
|
+
}
|
|
373
|
+
let t;
|
|
374
|
+
try {
|
|
375
|
+
t = await tunnel(tunnelOptions);
|
|
376
|
+
}
|
|
377
|
+
catch (err) {
|
|
378
|
+
dashboard?.stop();
|
|
379
|
+
throw err;
|
|
380
|
+
}
|
|
381
|
+
if (dashboard) {
|
|
382
|
+
dashboard.setLocalPort(t.port);
|
|
383
|
+
dashboard.setUrl(t.url);
|
|
384
|
+
}
|
|
385
|
+
else {
|
|
386
|
+
console.log(s.tunnelUrl(t.url));
|
|
387
|
+
if (target) {
|
|
388
|
+
console.log(` ${s.summaryServer(target)}`);
|
|
406
389
|
}
|
|
407
|
-
|
|
408
|
-
|
|
390
|
+
else {
|
|
391
|
+
if (mode !== "api" && publicPath) {
|
|
392
|
+
console.log(` ${s.siteServed(publicPath)}`);
|
|
393
|
+
}
|
|
394
|
+
if (mode !== "site" && apiPath) {
|
|
395
|
+
console.log(` ${apiMode === "server"
|
|
396
|
+
? s.summaryApiServer(apiPath, apiEntry ?? "")
|
|
397
|
+
: s.apiServed(apiPath, plan.apiPrefix)}`);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
if (publish === "domain" && domain && port) {
|
|
401
|
+
console.log(` ${s.domainHint(domain, port)}`);
|
|
409
402
|
}
|
|
403
|
+
console.log(s.pressCtrlC);
|
|
410
404
|
}
|
|
411
|
-
|
|
412
|
-
|
|
405
|
+
// Só salva a configuração depois que o túnel subiu com sucesso.
|
|
406
|
+
if (opts.save) {
|
|
407
|
+
saveConfig(plan);
|
|
408
|
+
if (!dashboard)
|
|
409
|
+
console.log(s.savedConfig(CONFIG_FILE));
|
|
413
410
|
}
|
|
414
|
-
console.log(s.pressCtrlC);
|
|
415
411
|
const stop = () => {
|
|
412
|
+
dashboard?.stop();
|
|
416
413
|
t.stop();
|
|
417
414
|
process.exit(0);
|
|
418
415
|
};
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type Plan } from './cli-utils.js';
|
|
2
|
+
export declare const CONFIG_FILE = ".cm-tunnel.json";
|
|
3
|
+
/** Carrega `.env` do diretório atual (com fallback para Node < 20.12). */
|
|
4
|
+
export declare function loadDotEnv(): void;
|
|
5
|
+
export declare function loadConfig(): Plan | null;
|
|
6
|
+
export declare function saveConfig(plan: Plan): void;
|
|
7
|
+
export declare function saveTokenToEnv(token: string): void;
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { normalizePrefix } from './cli-utils.js';
|
|
4
|
+
export const CONFIG_FILE = '.cm-tunnel.json';
|
|
5
|
+
/** Carrega `.env` do diretório atual (com fallback para Node < 20.12). */
|
|
6
|
+
export function loadDotEnv() {
|
|
7
|
+
if (!existsSync('.env'))
|
|
8
|
+
return;
|
|
9
|
+
if (typeof process.loadEnvFile === 'function') {
|
|
10
|
+
try {
|
|
11
|
+
process.loadEnvFile('.env');
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
// Cai no parser manual abaixo.
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
try {
|
|
19
|
+
const content = readFileSync(resolve('.env'), 'utf8');
|
|
20
|
+
for (const raw of content.split(/\r?\n/)) {
|
|
21
|
+
const line = raw.trim();
|
|
22
|
+
if (!line || line.startsWith('#'))
|
|
23
|
+
continue;
|
|
24
|
+
const separator = line.indexOf('=');
|
|
25
|
+
if (separator <= 0)
|
|
26
|
+
continue;
|
|
27
|
+
const key = line.slice(0, separator).trim();
|
|
28
|
+
let value = line.slice(separator + 1).trim();
|
|
29
|
+
if ((value.startsWith('"') && value.endsWith('"')) ||
|
|
30
|
+
(value.startsWith("'") && value.endsWith("'"))) {
|
|
31
|
+
value = value.slice(1, -1);
|
|
32
|
+
}
|
|
33
|
+
if (!(key in process.env)) {
|
|
34
|
+
process.env[key] = value;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
// .env inválido é ignorado; o usuário ainda pode usar variáveis de ambiente.
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
export function loadConfig() {
|
|
43
|
+
const file = resolve(CONFIG_FILE);
|
|
44
|
+
if (!existsSync(file))
|
|
45
|
+
return null;
|
|
46
|
+
try {
|
|
47
|
+
const data = JSON.parse(readFileSync(file, 'utf8'));
|
|
48
|
+
if (data?.mode !== 'site' && data?.mode !== 'api' && data?.mode !== 'both') {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
if (data?.publish !== 'quick' && data?.publish !== 'domain') {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
return {
|
|
55
|
+
mode: data.mode,
|
|
56
|
+
public: typeof data.public === 'string' ? data.public : undefined,
|
|
57
|
+
api: typeof data.api === 'string' ? data.api : undefined,
|
|
58
|
+
apiMode: data.apiMode === 'server' || data.apiMode === 'handlers'
|
|
59
|
+
? data.apiMode
|
|
60
|
+
: undefined,
|
|
61
|
+
apiEntry: typeof data.apiEntry === 'string' ? data.apiEntry : undefined,
|
|
62
|
+
apiPrefix: typeof data.apiPrefix === 'string' ? normalizePrefix(data.apiPrefix) : '/api',
|
|
63
|
+
publish: data.publish,
|
|
64
|
+
domain: typeof data.domain === 'string' ? data.domain : undefined,
|
|
65
|
+
target: typeof data.target === 'number' ? data.target : undefined,
|
|
66
|
+
port: typeof data.port === 'number' ? data.port : undefined,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
export function saveConfig(plan) {
|
|
74
|
+
writeFileSync(resolve(CONFIG_FILE), `${JSON.stringify(plan, null, 2)}\n`);
|
|
75
|
+
}
|
|
76
|
+
export function saveTokenToEnv(token) {
|
|
77
|
+
const file = resolve('.env');
|
|
78
|
+
let content = existsSync(file) ? readFileSync(file, 'utf8') : '';
|
|
79
|
+
const line = `CLOUDFLARE_TOKEN=${token}`;
|
|
80
|
+
if (/^CLOUDFLARE_TOKEN=.*$/m.test(content)) {
|
|
81
|
+
content = content.replace(/^CLOUDFLARE_TOKEN=.*$/m, line);
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
if (content && !content.endsWith('\n'))
|
|
85
|
+
content += '\n';
|
|
86
|
+
content += `${line}\n`;
|
|
87
|
+
}
|
|
88
|
+
writeFileSync(file, content);
|
|
89
|
+
try {
|
|
90
|
+
chmodSync(file, 0o600);
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
// Em sistemas sem suporte a chmod, segue normalmente.
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type Lang, type Plan } from './cli-utils.js';
|
|
2
|
+
export declare class Dashboard {
|
|
3
|
+
private lang;
|
|
4
|
+
private plan;
|
|
5
|
+
private logs;
|
|
6
|
+
private partial;
|
|
7
|
+
private url;
|
|
8
|
+
private localPort?;
|
|
9
|
+
private status;
|
|
10
|
+
private renderTimer;
|
|
11
|
+
private readonly enabled;
|
|
12
|
+
private readonly color;
|
|
13
|
+
constructor(lang: Lang, plan: Plan);
|
|
14
|
+
get isEnabled(): boolean;
|
|
15
|
+
push(chunk: string): void;
|
|
16
|
+
private scheduleRender;
|
|
17
|
+
setUrl(url: string): void;
|
|
18
|
+
setLocalPort(port: number): void;
|
|
19
|
+
start(): void;
|
|
20
|
+
stop(): void;
|
|
21
|
+
private paint;
|
|
22
|
+
private render;
|
|
23
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { STRINGS } from './cli-utils.js';
|
|
2
|
+
const MAX_LOG_LINES = 10;
|
|
3
|
+
const RESET = '\x1b[0m';
|
|
4
|
+
const BOLD = '\x1b[1m';
|
|
5
|
+
const DIM = '\x1b[2m';
|
|
6
|
+
const GREEN = '\x1b[32m';
|
|
7
|
+
const YELLOW = '\x1b[33m';
|
|
8
|
+
const RED = '\x1b[31m';
|
|
9
|
+
const HIDE_CURSOR = '\x1b[?25l';
|
|
10
|
+
const SHOW_CURSOR = '\x1b[?25h';
|
|
11
|
+
const CLEAR = '\x1b[2J\x1b[H';
|
|
12
|
+
function stripAnsi(text) {
|
|
13
|
+
return text
|
|
14
|
+
.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '')
|
|
15
|
+
.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g, '');
|
|
16
|
+
}
|
|
17
|
+
function truncate(text, width) {
|
|
18
|
+
if (text.length <= width)
|
|
19
|
+
return text;
|
|
20
|
+
return `${text.slice(0, Math.max(0, width - 1))}…`;
|
|
21
|
+
}
|
|
22
|
+
function modeLabel(plan, s) {
|
|
23
|
+
if (plan.target)
|
|
24
|
+
return s.dashboardModeTarget(plan.target);
|
|
25
|
+
if (plan.mode === 'site')
|
|
26
|
+
return s.dashboardModeSite;
|
|
27
|
+
if (plan.mode === 'api') {
|
|
28
|
+
return plan.apiMode === 'server'
|
|
29
|
+
? s.dashboardModeApiServer
|
|
30
|
+
: s.dashboardModeApi;
|
|
31
|
+
}
|
|
32
|
+
return plan.apiMode === 'server'
|
|
33
|
+
? s.dashboardModeBothServer
|
|
34
|
+
: s.dashboardModeBoth;
|
|
35
|
+
}
|
|
36
|
+
function publishLabel(plan, s) {
|
|
37
|
+
if (plan.publish === 'quick')
|
|
38
|
+
return s.dashboardPublishQuick;
|
|
39
|
+
return s.dashboardPublishDomain(plan.domain ?? '?');
|
|
40
|
+
}
|
|
41
|
+
export class Dashboard {
|
|
42
|
+
lang;
|
|
43
|
+
plan;
|
|
44
|
+
logs = [];
|
|
45
|
+
partial = '';
|
|
46
|
+
url = '';
|
|
47
|
+
localPort;
|
|
48
|
+
status = 'starting';
|
|
49
|
+
renderTimer = null;
|
|
50
|
+
enabled;
|
|
51
|
+
color;
|
|
52
|
+
constructor(lang, plan) {
|
|
53
|
+
this.lang = lang;
|
|
54
|
+
this.plan = plan;
|
|
55
|
+
this.enabled = !!process.stdout.isTTY;
|
|
56
|
+
this.color = this.enabled && !process.env.NO_COLOR;
|
|
57
|
+
}
|
|
58
|
+
get isEnabled() {
|
|
59
|
+
return this.enabled;
|
|
60
|
+
}
|
|
61
|
+
push(chunk) {
|
|
62
|
+
const text = stripAnsi(chunk).replace(/\r/g, '');
|
|
63
|
+
this.partial += text;
|
|
64
|
+
const lines = this.partial.split('\n');
|
|
65
|
+
this.partial = lines.pop() ?? '';
|
|
66
|
+
for (const line of lines) {
|
|
67
|
+
if (line.trim())
|
|
68
|
+
this.logs.push(line);
|
|
69
|
+
}
|
|
70
|
+
if (this.logs.length > MAX_LOG_LINES) {
|
|
71
|
+
this.logs = this.logs.slice(-MAX_LOG_LINES);
|
|
72
|
+
}
|
|
73
|
+
if (this.enabled)
|
|
74
|
+
this.scheduleRender();
|
|
75
|
+
}
|
|
76
|
+
scheduleRender() {
|
|
77
|
+
if (this.renderTimer)
|
|
78
|
+
return;
|
|
79
|
+
this.renderTimer = setTimeout(() => {
|
|
80
|
+
this.renderTimer = null;
|
|
81
|
+
this.render();
|
|
82
|
+
}, 100);
|
|
83
|
+
}
|
|
84
|
+
setUrl(url) {
|
|
85
|
+
this.url = url;
|
|
86
|
+
this.status = 'online';
|
|
87
|
+
if (this.enabled)
|
|
88
|
+
this.render();
|
|
89
|
+
}
|
|
90
|
+
setLocalPort(port) {
|
|
91
|
+
this.localPort = port;
|
|
92
|
+
if (this.enabled)
|
|
93
|
+
this.scheduleRender();
|
|
94
|
+
}
|
|
95
|
+
start() {
|
|
96
|
+
if (!this.enabled)
|
|
97
|
+
return;
|
|
98
|
+
process.stdout.write(HIDE_CURSOR);
|
|
99
|
+
this.render();
|
|
100
|
+
}
|
|
101
|
+
stop() {
|
|
102
|
+
if (this.renderTimer) {
|
|
103
|
+
clearTimeout(this.renderTimer);
|
|
104
|
+
this.renderTimer = null;
|
|
105
|
+
}
|
|
106
|
+
if (!this.enabled)
|
|
107
|
+
return;
|
|
108
|
+
this.status = 'stopped';
|
|
109
|
+
this.render();
|
|
110
|
+
process.stdout.write(`${SHOW_CURSOR}\n`);
|
|
111
|
+
}
|
|
112
|
+
paint(text, code) {
|
|
113
|
+
return this.color ? `${code}${text}${RESET}` : text;
|
|
114
|
+
}
|
|
115
|
+
render() {
|
|
116
|
+
if (!this.enabled)
|
|
117
|
+
return;
|
|
118
|
+
const s = STRINGS[this.lang];
|
|
119
|
+
const width = Math.max(40, Math.min(process.stdout.columns || 100, 120));
|
|
120
|
+
const line = (text) => truncate(text, width);
|
|
121
|
+
const statusText = this.status === 'online'
|
|
122
|
+
? s.dashboardOnline
|
|
123
|
+
: this.status === 'stopped'
|
|
124
|
+
? s.dashboardStopped
|
|
125
|
+
: s.dashboardStarting;
|
|
126
|
+
const statusColor = this.status === 'online'
|
|
127
|
+
? GREEN
|
|
128
|
+
: this.status === 'stopped'
|
|
129
|
+
? RED
|
|
130
|
+
: YELLOW;
|
|
131
|
+
const output = [
|
|
132
|
+
`${this.paint(s.dashboardTitle, BOLD)} ${this.paint(`● ${statusText}`, statusColor)}`,
|
|
133
|
+
'',
|
|
134
|
+
];
|
|
135
|
+
if (this.url) {
|
|
136
|
+
output.push(line(this.paint(s.dashboardUrl(this.url), BOLD)));
|
|
137
|
+
}
|
|
138
|
+
output.push(line(`Modo: ${modeLabel(this.plan, s)}`));
|
|
139
|
+
output.push(line(`Pub: ${publishLabel(this.plan, s)}`));
|
|
140
|
+
if (this.plan.target) {
|
|
141
|
+
output.push(line(s.dashboardLocal(`http://localhost:${this.plan.target}`)));
|
|
142
|
+
}
|
|
143
|
+
else if (this.localPort) {
|
|
144
|
+
output.push(line(s.dashboardLocal(`http://localhost:${this.localPort}`)));
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
output.push(line(s.dashboardAwaitingLocal));
|
|
148
|
+
}
|
|
149
|
+
output.push('');
|
|
150
|
+
output.push(this.paint(s.dashboardLogs, DIM));
|
|
151
|
+
if (this.logs.length === 0) {
|
|
152
|
+
output.push(this.paint(` ${s.dashboardWaitingLogs}`, DIM));
|
|
153
|
+
}
|
|
154
|
+
else {
|
|
155
|
+
for (const log of this.logs) {
|
|
156
|
+
output.push(this.paint(` ${log}`, DIM));
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
output.push('');
|
|
160
|
+
output.push(this.paint(s.dashboardCtrlC, DIM));
|
|
161
|
+
process.stdout.write(`${CLEAR}${output.join('\n')}\n`);
|
|
162
|
+
}
|
|
163
|
+
}
|
package/dist/doctor.d.ts
ADDED