Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: v3 #307

Draft
wants to merge 15 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,6 @@ jobs:
node-version:
- 18
- 20
- 21
- 22
os:
- ubuntu-latest
Expand Down
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ Run `smee --help` for usage.
### Node Client

```js
const SmeeClient = require('smee-client')
import SmeeClient from 'smee-client'

const smee = new SmeeClient({
source: 'https://smee.io/abc123',
Expand All @@ -40,3 +40,7 @@ const events = smee.start()
// Stop forwarding events
events.close()
```

#### Proxy Servers

By default, the `SmeeClient` API client makes use of the standard proxy server environment variables.
53 changes: 30 additions & 23 deletions bin/smee.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,41 @@
#!/usr/bin/env node

const { program } = require('commander')
const { version } = require('../package.json')
import { program } from "commander";
import { readFile } from "node:fs/promises";
import Client from "../index.js";

const Client = require('..')
const { version } = JSON.parse(
await readFile(new URL("../package.json", import.meta.url)),
);

program
.version(version, '-v, --version')
.usage('[options]')
.option('-u, --url <url>', 'URL of the webhook proxy service. Default: https://smee.io/new')
.option('-t, --target <target>', 'Full URL (including protocol and path) of the target service the events will forwarded to. Default: http://127.0.0.1:PORT/PATH')
.option('-p, --port <n>', 'Local HTTP server port', process.env.PORT || 3000)
.option('-P, --path <path>', 'URL path to post proxied requests to`', '/')
.parse(process.argv)

const opts = program.opts()

const {
target = `http://127.0.0.1:${opts.port}${opts.path}`
} = opts

async function setup () {
let source = opts.url
.version(version, "-v, --version")
.usage("[options]")
.option(
"-u, --url <url>",
"URL of the webhook proxy service. Default: https://smee.io/new",
)
.option(
"-t, --target <target>",
"Full URL (including protocol and path) of the target service the events will forwarded to. Default: http://127.0.0.1:PORT/PATH",
)
.option("-p, --port <n>", "Local HTTP server port", process.env.PORT || 3000)
.option("-P, --path <path>", "URL path to post proxied requests to`", "/")
.parse(process.argv);

const opts = program.opts();

const { target = `http://127.0.0.1:${opts.port}${opts.path}` } = opts;

async function setup() {
let source = opts.url;

if (!source) {
source = await Client.createChannel()
source = await Client.createChannel();
}

const client = new Client({ source, target })
client.start()
const client = new Client({ source, target });
client.start();
}

setup()
setup();
67 changes: 39 additions & 28 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import validator from "validator";
import EventSource from "eventsource";
import url from "url";
import querystring from "querystring";
import {
fetch as undiciFetch,
EventSource,
EnvHttpProxyAgent,
type ErrorEvent,
type MessageEvent,
} from "undici";
import url from "node:url";
import querystring from "node:querystring";

type Severity = "info" | "error";

Expand All @@ -12,33 +18,36 @@ interface Options {
fetch?: any;
}

const proxyAgent = new EnvHttpProxyAgent();

class Client {
source: string;
target: string;
fetch: typeof global.fetch;
logger: Pick<Console, Severity>;
events!: EventSource;
#source: string;
#target: string;
#fetch: typeof undiciFetch;
#logger: Pick<Console, Severity>;
#events!: EventSource;

constructor({
source,
target,
logger = console,
fetch = global.fetch,
fetch = undiciFetch,
}: Options) {
this.source = source;
this.target = target;
this.logger = logger!;
this.fetch = fetch;
this.#source = source;
this.#target = target;
this.#logger = logger!;
this.#fetch = fetch;

if (!validator.isURL(this.source)) {
if (!validator.isURL(this.#source)) {
throw new Error("The provided URL is invalid.");
}
}

static async createChannel({ fetch = global.fetch } = {}) {
static async createChannel({ fetch = undiciFetch } = {}) {
const response = await fetch("https://smee.io/new", {
method: "HEAD",
redirect: "manual",
dispatcher: proxyAgent,
});
const address = response.headers.get("location");
if (!address) {
Expand All @@ -47,10 +56,10 @@ class Client {
return address;
}

async onmessage(msg: any) {
async onmessage(msg: MessageEvent<string>) {
const data = JSON.parse(msg.data);

const target = url.parse(this.target, true);
const target = url.parse(this.#target, true);
const mergedQuery = { ...target.query, ...data.query };
target.search = querystring.stringify(mergedQuery);

Expand All @@ -73,29 +82,31 @@ class Client {
headers["content-type"] = "application/json";

try {
const response = await this.fetch(url.format(target), {
const response = await this.#fetch(url.format(target), {
method: "POST",
mode: data["sec-fetch-mode"],
cache: "default",
body,
headers,
dispatcher: proxyAgent,
});
this.logger.info(`POST ${response.url} - ${response.status}`);
this.#logger.info(`POST ${response.url} - ${response.status}`);
} catch (err) {
this.logger.error(err);
this.#logger.error(err);
}
}

onopen() {
this.logger.info("Connected", this.events.url);
this.#logger.info("Connected", this.#events.url);
}

onerror(err: any) {
this.logger.error(err);
onerror(err: ErrorEvent) {
this.#logger.error(err);
}

start() {
const events = new EventSource(this.source);
const events = new EventSource(this.#source, {
dispatcher: proxyAgent,
});

// Reconnect immediately
(events as any).reconnectInterval = 0; // This isn't a valid property of EventSource
Expand All @@ -104,11 +115,11 @@ class Client {
events.addEventListener("open", this.onopen.bind(this));
events.addEventListener("error", this.onerror.bind(this));

this.logger.info(`Forwarding ${this.source} to ${this.target}`);
this.events = events;
this.#logger.info(`Forwarding ${this.#source} to ${this.#target}`);
this.#events = events;

return events;
}
}

export = Client;
export default Client;
62 changes: 34 additions & 28 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 5 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"version": "0.0.0-development",
"description": "Client to proxy webhooks to localhost",
"main": "index.js",
"type": "module",
"bin": {
"smee": "./bin/smee.js"
},
Expand All @@ -13,8 +14,8 @@
],
"scripts": {
"build": "tsc -p tsconfig.json",
"lint": "prettier --check \"index.ts\" \"test/**/*.ts\" package.json tsconfig.json --end-of-line auto",
"lint:fix": "prettier --write \"index.ts\" \"test/**/*.ts\" package.json tsconfig.json --end-of-line auto",
"lint": "prettier --check \"index.ts\" \"test/**/*.ts\" bin/smee.js package.json tsconfig.json --end-of-line auto",
"lint:fix": "prettier --write \"index.ts\" \"test/**/*.ts\" bin/smee.js package.json tsconfig.json --end-of-line auto",
"test": "vitest run",
"test:coverage": "vitest run --coverage",
"test:dev": "vitest --ui --coverage"
Expand All @@ -24,13 +25,12 @@
"license": "ISC",
"dependencies": {
"commander": "^12.0.0",
"eventsource": "^2.0.2",
"undici": "6.19.8",
"validator": "^13.11.0"
},
"devDependencies": {
"@octokit/tsconfig": "^3.0.0",
"@types/eventsource": "^1.1.15",
"@types/node": "^20.0.0",
"@types/node": "^18.19.14",
"@types/validator": "^13.11.6",
"@vitest/coverage-v8": "^2.0.0",
"fastify": "^5.0.0",
Expand Down
2 changes: 1 addition & 1 deletion test/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import Client from "../index";
import Client from "../index.ts";
import { describe, test, expect } from "vitest";
import { fastify as Fastify } from "fastify";

Expand Down
4 changes: 1 addition & 3 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
"extends": "@octokit/tsconfig",

"compilerOptions": {
"verbatimModuleSyntax": false,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"pretty": true,
Expand All @@ -12,8 +11,7 @@
"noImplicitAny": true,
"esModuleInterop": true,
"declaration": true,
"allowJs": true,
"lib": ["es2023", "dom"]
"allowJs": true
},
"include": ["./*"],
"files": ["index.ts"]
Expand Down