Skip to content

Commit

Permalink
feat: add proxy support by leveraging EnvHttpProxyAgent from undici (#…
Browse files Browse the repository at this point in the history
…299)

Fixes #194

---------

Co-authored-by: Aras Abbasi <[email protected]>
  • Loading branch information
wolfy1339 and Uzlopak authored Aug 23, 2024
1 parent a47e91e commit b0247a1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
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

0 comments on commit b0247a1

Please sign in to comment.