cm-tunnel 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 cm-tunnel
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 ADDED
@@ -0,0 +1,74 @@
1
+ # cm-tunnel
2
+
3
+ Exponha seu servidor HTTP local para a internet através de uma API extremamente simples. Suporta **Cloudflare** e **LocalTunnel**.
4
+
5
+ ## Instalação
6
+
7
+ ```bash
8
+ npm install cm-tunnel
9
+ ```
10
+
11
+ ## Requisitos
12
+
13
+ - Node.js >= 18
14
+ - Para usar o provedor do Cloudflare, o executável `cloudflared` deve estar instalado no sistema e disponível no `PATH`. Caso não esteja, a biblioteca emitirá um erro amigável.
15
+
16
+ ## Uso
17
+
18
+ ### API Principal
19
+
20
+ ```javascript
21
+ import tunnel from 'cm-tunnel';
22
+
23
+ try {
24
+ const t = await tunnel({
25
+ provider: 'cloudflare', // ou 'localtunnel'
26
+ port: 3000
27
+ });
28
+
29
+ console.log('Túnel público:', t.url);
30
+
31
+ t.on('ready', (url) => console.log('Pronto:', url));
32
+ t.on('close', () => console.log('Túnel fechado'));
33
+ t.on('error', (err) => console.error('Erro:', err));
34
+
35
+ } catch(err) {
36
+ console.error(err.message);
37
+ }
38
+ ```
39
+
40
+ ### API Simplificada
41
+
42
+ ```javascript
43
+ import tunnel from 'cm-tunnel';
44
+
45
+ // Usando cloudflare
46
+ const t1 = await tunnel.cloudflare({ port: 3000 });
47
+
48
+ // Usando localtunnel
49
+ const t2 = await tunnel.localtunnel({ port: 3000 });
50
+ ```
51
+
52
+ ## Objeto de Retorno
53
+
54
+ A função retorna uma Promise que resolve em um objeto `TunnelInstance` contendo:
55
+
56
+ - `provider` (string): O nome do provedor utilizado.
57
+ - `url` (string): A URL pública gerada pelo túnel.
58
+ - `port` (number): A porta local.
59
+ - `stop()` (function): Método para encerrar o túnel corretamente.
60
+ - `process` (any): Acesso ao processo interno (`ChildProcess` para cloudflare ou objeto do `localtunnel`).
61
+
62
+ O objeto retornado também é um `EventEmitter`, emitindo os eventos `ready`, `close` e `error`.
63
+
64
+ ## Adicionando novos provedores
65
+
66
+ A arquitetura de `cm-tunnel` é modular. Para adicionar um novo provedor:
67
+ 1. Crie um arquivo em `src/providers/[nome-do-provedor].ts`.
68
+ 2. Exporte como default uma classe que estenda a classe `Provider`.
69
+ 3. Implemente o método abstrato `start(): Promise<TunnelResult>`.
70
+ 4. O núcleo carregará automaticamente o novo provedor quando chamado com `provider: '[nome-do-provedor]'`.
71
+
72
+ ## Licença
73
+
74
+ MIT
@@ -0,0 +1,13 @@
1
+ import { EventEmitter } from "events";
2
+ export interface TunnelResult {
3
+ provider: string;
4
+ url: string;
5
+ port: number;
6
+ stop: () => void;
7
+ process?: unknown;
8
+ }
9
+ export declare abstract class Provider extends EventEmitter {
10
+ protected port: number;
11
+ constructor(port: number);
12
+ abstract start(): Promise<TunnelResult>;
13
+ }
@@ -0,0 +1,8 @@
1
+ import { EventEmitter } from "events";
2
+ export class Provider extends EventEmitter {
3
+ port;
4
+ constructor(port) {
5
+ super();
6
+ this.port = port;
7
+ }
8
+ }
@@ -0,0 +1,13 @@
1
+ import { EventEmitter } from "events";
2
+ import { TunnelResult } from "./Provider.js";
3
+ export interface TunnelOptions {
4
+ provider: string;
5
+ port: number;
6
+ }
7
+ export interface TunnelInstance extends TunnelResult, EventEmitter {
8
+ on(event: "ready", listener: (url: string) => void): this;
9
+ on(event: "close", listener: () => void): this;
10
+ on(event: "error", listener: (err: Error) => void): this;
11
+ on(event: string | symbol, listener: (...args: any[]) => void): this;
12
+ }
13
+ export declare function createTunnel(options: TunnelOptions): Promise<TunnelInstance>;
package/dist/Tunnel.js ADDED
@@ -0,0 +1,45 @@
1
+ import { EventEmitter } from "events";
2
+ export async function createTunnel(options) {
3
+ if (!options.port || isNaN(options.port)) {
4
+ throw new Error("Porta inválida.");
5
+ }
6
+ if (!options.provider) {
7
+ throw new Error("Provider inexistente.");
8
+ }
9
+ const providerName = options.provider.toLowerCase();
10
+ let ProviderClass;
11
+ try {
12
+ // Dynamic import to load the provider dynamically based on name
13
+ const module = await import(`./providers/${providerName}.js`);
14
+ ProviderClass = module.default;
15
+ }
16
+ catch (err) {
17
+ if (err.code === "ERR_MODULE_NOT_FOUND" ||
18
+ err.message.includes("Cannot find module") ||
19
+ err.message.includes("Unknown variable dynamic import")) {
20
+ throw new Error(`Provider inexistente: "${providerName}".`);
21
+ }
22
+ throw err;
23
+ }
24
+ const providerInstance = new ProviderClass(options.port);
25
+ // We wrap the result in an EventEmitter to match the required API
26
+ const emitter = new EventEmitter();
27
+ providerInstance.on("ready", (url) => emitter.emit("ready", url));
28
+ providerInstance.on("close", () => emitter.emit("close"));
29
+ providerInstance.on("error", (err) => emitter.emit("error", err));
30
+ try {
31
+ const result = await providerInstance.start();
32
+ // Assign properties from result to the emitter instance to conform to TunnelInstance
33
+ Object.assign(emitter, {
34
+ provider: result.provider,
35
+ url: result.url,
36
+ port: result.port,
37
+ stop: result.stop,
38
+ process: result.process,
39
+ });
40
+ return emitter;
41
+ }
42
+ catch (err) {
43
+ throw new Error(`Falha ao iniciar o túnel: ${err.message}`);
44
+ }
45
+ }
@@ -0,0 +1,9 @@
1
+ import { TunnelOptions, TunnelInstance } from "./Tunnel.js";
2
+ type OmitProvider<T> = Omit<T, "provider">;
3
+ interface TunnelAPI {
4
+ (options: TunnelOptions): Promise<TunnelInstance>;
5
+ cloudflare: (options: OmitProvider<TunnelOptions>) => Promise<TunnelInstance>;
6
+ localtunnel: (options: OmitProvider<TunnelOptions>) => Promise<TunnelInstance>;
7
+ }
8
+ declare const tunnel: TunnelAPI;
9
+ export default tunnel;
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ import { createTunnel } from "./Tunnel.js";
2
+ const tunnel = createTunnel;
3
+ tunnel.cloudflare = (options) => createTunnel({ ...options, provider: "cloudflare" });
4
+ tunnel.localtunnel = (options) => createTunnel({ ...options, provider: "localtunnel" });
5
+ export default tunnel;
@@ -0,0 +1,8 @@
1
+ import { Provider, TunnelResult } from "../Provider.js";
2
+ export default class CloudflareProvider extends Provider {
3
+ private cp;
4
+ private urlRegex;
5
+ constructor(port: number);
6
+ start(): Promise<TunnelResult>;
7
+ stop(): void;
8
+ }
@@ -0,0 +1,79 @@
1
+ import { spawn } from "child_process";
2
+ import { Provider } from "../Provider.js";
3
+ export default class CloudflareProvider extends Provider {
4
+ cp = null;
5
+ urlRegex = /(https:\/\/[a-zA-Z0-9-]+\.trycloudflare\.com)/;
6
+ constructor(port) {
7
+ super(port);
8
+ }
9
+ start() {
10
+ return new Promise((resolve, reject) => {
11
+ this.cp = spawn("cloudflared", [
12
+ "tunnel",
13
+ "--url",
14
+ `http://localhost:${this.port}`,
15
+ ]);
16
+ let isResolved = false;
17
+ this.cp.on("error", (err) => {
18
+ if (err.code === "ENOENT") {
19
+ const errorMsg = "Cloudflared não encontrado. Por favor, instale-o a partir de https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/";
20
+ if (!isResolved) {
21
+ reject(new Error(errorMsg));
22
+ }
23
+ else {
24
+ this.emit("error", new Error(errorMsg));
25
+ }
26
+ }
27
+ else {
28
+ if (!isResolved) {
29
+ reject(err);
30
+ }
31
+ else {
32
+ this.emit("error", err);
33
+ }
34
+ }
35
+ });
36
+ this.cp.stderr?.on("data", (data) => {
37
+ const text = data.toString();
38
+ const match = text.match(this.urlRegex);
39
+ if (match && match[1]) {
40
+ const url = match[1];
41
+ if (!isResolved) {
42
+ isResolved = true;
43
+ this.emit("ready", url);
44
+ resolve({
45
+ provider: "cloudflare",
46
+ url,
47
+ port: this.port,
48
+ stop: this.stop.bind(this),
49
+ process: this.cp,
50
+ });
51
+ }
52
+ }
53
+ // Detect known errors like connection refused
54
+ if (text.toLowerCase().includes("connection refused")) {
55
+ const err = new Error(`A porta ${this.port} não possui nenhum servidor ativo.`);
56
+ if (!isResolved) {
57
+ reject(err);
58
+ this.stop();
59
+ }
60
+ else {
61
+ this.emit("error", err);
62
+ }
63
+ }
64
+ });
65
+ this.cp.on("close", (code) => {
66
+ if (!isResolved && code !== 0) {
67
+ reject(new Error(`Falha ao iniciar o túnel. Cloudflared encerrou com código ${code}.`));
68
+ }
69
+ this.emit("close");
70
+ });
71
+ });
72
+ }
73
+ stop() {
74
+ if (this.cp) {
75
+ this.cp.kill();
76
+ this.cp = null;
77
+ }
78
+ }
79
+ }
@@ -0,0 +1,7 @@
1
+ import { Provider, TunnelResult } from "../Provider.js";
2
+ export default class LocalTunnelProvider extends Provider {
3
+ private tunnel;
4
+ constructor(port: number);
5
+ start(): Promise<TunnelResult>;
6
+ stop(): void;
7
+ }
@@ -0,0 +1,41 @@
1
+ import localtunnel from "localtunnel";
2
+ import { Provider } from "../Provider.js";
3
+ export default class LocalTunnelProvider extends Provider {
4
+ tunnel = null;
5
+ constructor(port) {
6
+ super(port);
7
+ }
8
+ start() {
9
+ return new Promise(async (resolve, reject) => {
10
+ try {
11
+ this.tunnel = await localtunnel({ port: this.port });
12
+ if (!this.tunnel.url) {
13
+ return reject(new Error("Falha ao obter URL do LocalTunnel."));
14
+ }
15
+ this.tunnel.on("close", () => {
16
+ this.emit("close");
17
+ });
18
+ this.tunnel.on("error", (err) => {
19
+ this.emit("error", err);
20
+ });
21
+ this.emit("ready", this.tunnel.url);
22
+ resolve({
23
+ provider: "localtunnel",
24
+ url: this.tunnel.url,
25
+ port: this.port,
26
+ stop: this.stop.bind(this),
27
+ process: this.tunnel,
28
+ });
29
+ }
30
+ catch (err) {
31
+ reject(new Error(`Falha ao iniciar o túnel LocalTunnel: ${err.message}`));
32
+ }
33
+ });
34
+ }
35
+ stop() {
36
+ if (this.tunnel) {
37
+ this.tunnel.close();
38
+ this.tunnel = null;
39
+ }
40
+ }
41
+ }
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "cm-tunnel",
3
+ "version": "1.0.0",
4
+ "description": "Exponha seu servidor HTTP local para a internet através do Cloudflare ou LocalTunnel de forma simples",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "default": "./dist/index.js"
14
+ }
15
+ },
16
+ "scripts": {
17
+ "build": "rm -rf dist && tsc",
18
+ "test": "vitest run",
19
+ "test:watch": "vitest",
20
+ "lint": "tsc --noEmit",
21
+ "format": "prettier --write \"src/**/*.ts\" \"examples/**/*.ts\" \"tests/**/*.ts\"",
22
+ "prepublishOnly": "npm run lint && npm run test && npm run build"
23
+ },
24
+ "keywords": [
25
+ "tunnel",
26
+ "cloudflare",
27
+ "localtunnel",
28
+ "ngrok",
29
+ "expose",
30
+ "http",
31
+ "localhost"
32
+ ],
33
+ "author": "",
34
+ "license": "MIT",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/your-username/cm-tunnel.git"
38
+ },
39
+ "bugs": {
40
+ "url": "https://github.com/your-username/cm-tunnel/issues"
41
+ },
42
+ "homepage": "https://github.com/your-username/cm-tunnel#readme",
43
+ "engines": {
44
+ "node": ">=18.0.0"
45
+ },
46
+ "files": [
47
+ "dist",
48
+ "README.md",
49
+ "LICENSE"
50
+ ],
51
+ "dependencies": {
52
+ "localtunnel": "^2.0.2"
53
+ },
54
+ "devDependencies": {
55
+ "@types/localtunnel": "^2.0.4",
56
+ "@types/node": "^20.12.7",
57
+ "eslint": "^9.1.1",
58
+ "prettier": "^3.2.5",
59
+ "tsup": "^8.0.2",
60
+ "typescript": "^5.4.5",
61
+ "vitest": "^1.5.0"
62
+ }
63
+ }