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: add proxy support by leveraging EnvHttpProxyAgent from undici #299

Merged
merged 10 commits into from
Aug 23, 2024
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
22 changes: 15 additions & 7 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import validator from "validator";
import { EventSource } from "undici";
import {
fetch as undiciFetch,
EventSource,
EnvHttpProxyAgent,
type ErrorEvent,
type MessageEvent,
} from "undici";
import url from "url";
import querystring from "querystring";

Expand All @@ -23,7 +29,7 @@ class Client {
source,
target,
logger = console,
fetch = global.fetch,
fetch = undiciFetch,
}: Options) {
this.source = source;
this.target = target;
Expand All @@ -35,10 +41,11 @@ class Client {
}
}

static async createChannel({ fetch = global.fetch } = {}) {
static async createChannel({ fetch = undiciFetch } = {}) {
const response = await fetch("https://smee.io/new", {
method: "HEAD",
redirect: "manual",
dispatcher: new EnvHttpProxyAgent(),
});
const address = response.headers.get("location");
if (!address) {
Expand All @@ -47,7 +54,7 @@ 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);
Expand Down Expand Up @@ -76,7 +83,6 @@ class Client {
const response = await this.fetch(url.format(target), {
method: "POST",
mode: data["sec-fetch-mode"],
cache: "default",
body,
headers,
});
Expand All @@ -90,12 +96,14 @@ class Client {
this.logger.info("Connected", this.events.url);
}

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

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

// Reconnect immediately
(events as any).reconnectInterval = 0; // This isn't a valid property of EventSource
Expand Down