@silver886/mcp-proxy 0.2.0 → 0.2.2

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.
Files changed (40) hide show
  1. package/README.md +0 -8
  2. package/node_modules/cloudflared/LICENSE +21 -0
  3. package/node_modules/cloudflared/README.md +156 -0
  4. package/node_modules/cloudflared/bin/cloudflared +0 -0
  5. package/node_modules/cloudflared/lib/cloudflared.js +10 -0
  6. package/node_modules/cloudflared/lib/constants.js +58 -0
  7. package/node_modules/cloudflared/lib/error.js +32 -0
  8. package/node_modules/cloudflared/lib/handler.js +117 -0
  9. package/node_modules/cloudflared/lib/index.js +126 -0
  10. package/node_modules/cloudflared/lib/install.js +155 -0
  11. package/node_modules/cloudflared/lib/lib.d.ts +236 -0
  12. package/node_modules/cloudflared/lib/lib.js +45 -0
  13. package/node_modules/cloudflared/lib/regex.js +52 -0
  14. package/node_modules/cloudflared/lib/service.js +229 -0
  15. package/node_modules/cloudflared/lib/tunnel.js +164 -0
  16. package/node_modules/cloudflared/lib/types.js +16 -0
  17. package/node_modules/cloudflared/package.json +59 -0
  18. package/node_modules/cloudflared/scripts/postinstall.mjs +10 -0
  19. package/node_modules/eventsource-parser/LICENSE +21 -0
  20. package/node_modules/eventsource-parser/README.md +126 -0
  21. package/node_modules/eventsource-parser/dist/index.cjs +166 -0
  22. package/node_modules/eventsource-parser/dist/index.cjs.map +1 -0
  23. package/node_modules/eventsource-parser/dist/index.d.cts +146 -0
  24. package/node_modules/eventsource-parser/dist/index.d.ts +146 -0
  25. package/node_modules/eventsource-parser/dist/index.js +166 -0
  26. package/node_modules/eventsource-parser/dist/index.js.map +1 -0
  27. package/node_modules/eventsource-parser/dist/stream.cjs +28 -0
  28. package/node_modules/eventsource-parser/dist/stream.cjs.map +1 -0
  29. package/node_modules/eventsource-parser/dist/stream.d.cts +121 -0
  30. package/node_modules/eventsource-parser/dist/stream.d.ts +121 -0
  31. package/node_modules/eventsource-parser/dist/stream.js +29 -0
  32. package/node_modules/eventsource-parser/dist/stream.js.map +1 -0
  33. package/node_modules/eventsource-parser/package.json +92 -0
  34. package/node_modules/eventsource-parser/src/errors.ts +44 -0
  35. package/node_modules/eventsource-parser/src/index.ts +3 -0
  36. package/node_modules/eventsource-parser/src/parse.ts +395 -0
  37. package/node_modules/eventsource-parser/src/stream.ts +88 -0
  38. package/node_modules/eventsource-parser/src/types.ts +97 -0
  39. package/node_modules/eventsource-parser/stream.js +2 -0
  40. package/package.json +2 -1
@@ -0,0 +1,229 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var service_exports = {};
30
+ __export(service_exports, {
31
+ AlreadyInstalledError: () => AlreadyInstalledError,
32
+ LINUX_SERVICE_PATH: () => LINUX_SERVICE_PATH,
33
+ MACOS_SERVICE_PATH: () => MACOS_SERVICE_PATH,
34
+ NotInstalledError: () => NotInstalledError,
35
+ clean: () => clean,
36
+ current: () => current,
37
+ err: () => err,
38
+ exists: () => exists,
39
+ identifier: () => identifier,
40
+ install: () => install,
41
+ journal: () => journal,
42
+ log: () => log,
43
+ service: () => service,
44
+ service_name: () => service_name,
45
+ uninstall: () => uninstall
46
+ });
47
+ module.exports = __toCommonJS(service_exports);
48
+ var import_node_os = __toESM(require("node:os"));
49
+ var import_node_fs = __toESM(require("node:fs"));
50
+ var import_node_child_process = require("node:child_process");
51
+ var import_constants = require("./constants.js");
52
+ var import_regex = require("./regex.js");
53
+ const identifier = "com.cloudflare.cloudflared";
54
+ const service_name = "cloudflared.service";
55
+ const MACOS_SERVICE_PATH = {
56
+ PLIST: is_root() ? `/Library/LaunchDaemons/${identifier}.plist` : `${import_node_os.default.homedir()}/Library/LaunchAgents/${identifier}.plist`,
57
+ OUT: is_root() ? `/Library/Logs/${identifier}.out.log` : `${import_node_os.default.homedir()}/Library/Logs/${identifier}.out.log`,
58
+ ERR: is_root() ? `/Library/Logs/${identifier}.err.log` : `${import_node_os.default.homedir()}/Library/Logs/${identifier}.err.log`
59
+ };
60
+ const LINUX_SERVICE_PATH = {
61
+ SYSTEMD: `/etc/systemd/system/${service_name}`,
62
+ SERVICE: "/etc/init.d/cloudflared",
63
+ SERVICE_OUT: "/var/log/cloudflared.log",
64
+ SERVICE_ERR: "/var/log/cloudflared.err"
65
+ };
66
+ const service = { install, uninstall, exists, log, err, current, clean, journal };
67
+ class AlreadyInstalledError extends Error {
68
+ constructor() {
69
+ super("service is already installed");
70
+ }
71
+ }
72
+ class NotInstalledError extends Error {
73
+ constructor() {
74
+ super("service is not installed");
75
+ }
76
+ }
77
+ function install(token) {
78
+ if (!["darwin", "linux"].includes(process.platform)) {
79
+ throw new Error(`Not Implemented on platform ${process.platform}`);
80
+ }
81
+ if (exists()) {
82
+ throw new AlreadyInstalledError();
83
+ }
84
+ const args = ["service", "install"];
85
+ if (token) {
86
+ args.push(token);
87
+ }
88
+ const result = (0, import_node_child_process.spawnSync)(import_constants.bin, args);
89
+ if (result.status !== 0) {
90
+ throw new Error(`service install failed: ${result.stderr.toString()}`);
91
+ }
92
+ }
93
+ function uninstall() {
94
+ if (!["darwin", "linux"].includes(process.platform)) {
95
+ throw new Error(`Not Implemented on platform ${process.platform}`);
96
+ }
97
+ if (!exists()) {
98
+ throw new NotInstalledError();
99
+ }
100
+ const result = (0, import_node_child_process.spawnSync)(import_constants.bin, ["service", "uninstall"]);
101
+ if (result.status !== 0) {
102
+ throw new Error(`service uninstall failed: ${result.stderr.toString()}`);
103
+ }
104
+ if (process.platform === "darwin") {
105
+ import_node_fs.default.rmSync(MACOS_SERVICE_PATH.OUT);
106
+ import_node_fs.default.rmSync(MACOS_SERVICE_PATH.ERR);
107
+ } else if (process.platform === "linux" && !is_systemd()) {
108
+ import_node_fs.default.rmSync(LINUX_SERVICE_PATH.SERVICE_OUT);
109
+ import_node_fs.default.rmSync(LINUX_SERVICE_PATH.SERVICE_ERR);
110
+ }
111
+ }
112
+ function log() {
113
+ if (!exists()) {
114
+ throw new NotInstalledError();
115
+ }
116
+ if (process.platform === "darwin") {
117
+ return import_node_fs.default.readFileSync(MACOS_SERVICE_PATH.OUT, "utf8");
118
+ }
119
+ if (process.platform === "linux" && !is_systemd()) {
120
+ return import_node_fs.default.readFileSync(LINUX_SERVICE_PATH.SERVICE_OUT, "utf8");
121
+ }
122
+ throw new Error(`Not Implemented on platform ${process.platform}`);
123
+ }
124
+ function err() {
125
+ if (!exists()) {
126
+ throw new NotInstalledError();
127
+ }
128
+ if (process.platform === "darwin") {
129
+ return import_node_fs.default.readFileSync(MACOS_SERVICE_PATH.ERR, "utf8");
130
+ }
131
+ if (process.platform === "linux" && !is_systemd()) {
132
+ return import_node_fs.default.readFileSync(LINUX_SERVICE_PATH.SERVICE_ERR, "utf8");
133
+ }
134
+ throw new Error(`Not Implemented on platform ${process.platform}`);
135
+ }
136
+ function journal(n = 300) {
137
+ if (process.platform === "linux" && is_systemd()) {
138
+ const args = ["-u", service_name, "-o", "cat", "-n", n.toString()];
139
+ return (0, import_node_child_process.spawnSync)("journalctl", args).stdout.toString();
140
+ }
141
+ throw new Error(`Not Implemented on platform ${process.platform}`);
142
+ }
143
+ function current() {
144
+ var _a, _b, _c, _d;
145
+ if (!["darwin", "linux"].includes(process.platform)) {
146
+ throw new Error(`Not Implemented on platform ${process.platform}`);
147
+ }
148
+ if (!exists()) {
149
+ throw new NotInstalledError();
150
+ }
151
+ const log2 = is_systemd() ? journal() : err();
152
+ let tunnelID = "";
153
+ let connectorID = "";
154
+ const connections = [];
155
+ let metrics = "";
156
+ let config = {};
157
+ for (const line of log2.split("\n")) {
158
+ try {
159
+ if (line.match(import_regex.tunnelID_regex)) {
160
+ tunnelID = ((_a = line.match(import_regex.tunnelID_regex)) == null ? void 0 : _a[1]) ?? "";
161
+ } else if (line.match(import_regex.connectorID_regex)) {
162
+ connectorID = ((_b = line.match(import_regex.connectorID_regex)) == null ? void 0 : _b[1]) ?? "";
163
+ } else if (line.match(import_regex.conn_regex) && line.match(import_regex.location_regex) && line.match(import_regex.ip_regex) && line.match(import_regex.index_regex)) {
164
+ const [, id] = line.match(import_regex.conn_regex) ?? [];
165
+ const [, location] = line.match(import_regex.location_regex) ?? [];
166
+ const [, ip] = line.match(import_regex.ip_regex) ?? [];
167
+ const [, idx] = line.match(import_regex.index_regex) ?? [];
168
+ connections[parseInt(idx)] = { id, ip, location };
169
+ } else if (line.match(import_regex.disconnect_regex)) {
170
+ const [, idx] = line.match(import_regex.disconnect_regex) ?? [];
171
+ if (parseInt(idx) in connections) {
172
+ connections[parseInt(idx)] = { id: "", ip: "", location: "" };
173
+ }
174
+ } else if (line.match(import_regex.metrics_regex)) {
175
+ metrics = ((_c = line.match(import_regex.metrics_regex)) == null ? void 0 : _c[1]) ?? "";
176
+ } else if (line.match(import_regex.config_regex)) {
177
+ config = JSON.parse(((_d = line.match(import_regex.config_regex)) == null ? void 0 : _d[1].replace(/\\/g, "")) ?? "{}");
178
+ }
179
+ } catch (err2) {
180
+ if (process.env.VERBOSE) {
181
+ console.error("log parsing failed", err2);
182
+ }
183
+ }
184
+ }
185
+ return { tunnelID, connectorID, connections, metrics, config };
186
+ }
187
+ function clean() {
188
+ if (process.platform !== "darwin") {
189
+ throw new Error(`Not Implemented on platform ${process.platform}`);
190
+ }
191
+ if (exists()) {
192
+ throw new AlreadyInstalledError();
193
+ }
194
+ import_node_fs.default.rmSync(MACOS_SERVICE_PATH.OUT, { force: true });
195
+ import_node_fs.default.rmSync(MACOS_SERVICE_PATH.ERR, { force: true });
196
+ }
197
+ function exists() {
198
+ if (process.platform === "darwin") {
199
+ return import_node_fs.default.existsSync(MACOS_SERVICE_PATH.PLIST);
200
+ } else if (process.platform === "linux") {
201
+ return is_systemd() ? import_node_fs.default.existsSync(LINUX_SERVICE_PATH.SYSTEMD) : import_node_fs.default.existsSync(LINUX_SERVICE_PATH.SERVICE);
202
+ }
203
+ throw new Error(`Not Implemented on platform ${process.platform}`);
204
+ }
205
+ function is_root() {
206
+ var _a;
207
+ return ((_a = process.getuid) == null ? void 0 : _a.call(process)) === 0;
208
+ }
209
+ function is_systemd() {
210
+ return process.platform === "linux" && import_node_fs.default.existsSync("/run/systemd/system");
211
+ }
212
+ // Annotate the CommonJS export names for ESM import in node:
213
+ 0 && (module.exports = {
214
+ AlreadyInstalledError,
215
+ LINUX_SERVICE_PATH,
216
+ MACOS_SERVICE_PATH,
217
+ NotInstalledError,
218
+ clean,
219
+ current,
220
+ err,
221
+ exists,
222
+ identifier,
223
+ install,
224
+ journal,
225
+ log,
226
+ service,
227
+ service_name,
228
+ uninstall
229
+ });
@@ -0,0 +1,164 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var tunnel_exports = {};
20
+ __export(tunnel_exports, {
21
+ Tunnel: () => Tunnel,
22
+ build_args: () => build_args,
23
+ build_options: () => build_options,
24
+ tunnel: () => tunnel
25
+ });
26
+ module.exports = __toCommonJS(tunnel_exports);
27
+ var import_node_child_process = require("node:child_process");
28
+ var import_node_events = require("node:events");
29
+ var import_constants = require("./constants.js");
30
+ var import_handler = require("./handler.js");
31
+ class Tunnel extends import_node_events.EventEmitter {
32
+ constructor(options = ["tunnel", "--hello-world"]) {
33
+ super();
34
+ this.outputHandlers = [];
35
+ this.stop = this._stop.bind(this);
36
+ this.setupDefaultHandlers();
37
+ const args = Array.isArray(options) ? options : build_args(options);
38
+ this._process = this.createProcess(args);
39
+ this.setupEventHandlers();
40
+ }
41
+ get process() {
42
+ return this._process;
43
+ }
44
+ setupDefaultHandlers() {
45
+ new import_handler.ConnectionHandler(this);
46
+ new import_handler.TryCloudflareHandler(this);
47
+ }
48
+ /**
49
+ * Add a custom output handler
50
+ * @param handler Function to handle cloudflared output
51
+ */
52
+ addHandler(handler) {
53
+ this.outputHandlers.push(handler);
54
+ }
55
+ /**
56
+ * Remove a previously added output handler
57
+ * @param handler The handler to remove
58
+ */
59
+ removeHandler(handler) {
60
+ const index = this.outputHandlers.indexOf(handler);
61
+ if (index !== -1) {
62
+ this.outputHandlers.splice(index, 1);
63
+ }
64
+ }
65
+ processOutput(output) {
66
+ for (const handler of this.outputHandlers) {
67
+ try {
68
+ handler(output, this);
69
+ } catch (error) {
70
+ this.emit("error", error instanceof Error ? error : new Error(String(error)));
71
+ }
72
+ }
73
+ }
74
+ setupEventHandlers() {
75
+ this.on("stdout", (output) => {
76
+ this.processOutput(output);
77
+ });
78
+ this.on("stderr", (output) => {
79
+ this.processOutput(output);
80
+ });
81
+ }
82
+ createProcess(args) {
83
+ var _a, _b;
84
+ const child = (0, import_node_child_process.spawn)(import_constants.bin, args, { stdio: ["ignore", "pipe", "pipe"] });
85
+ child.on("error", (error) => this.emit("error", error));
86
+ child.on("exit", (code, signal) => this.emit("exit", code, signal));
87
+ if (process.env.VERBOSE) {
88
+ child.stdout.pipe(process.stdout);
89
+ child.stderr.pipe(process.stderr);
90
+ }
91
+ (_a = child.stdout) == null ? void 0 : _a.on("data", (data) => this.emit("stdout", data.toString()));
92
+ (_b = child.stderr) == null ? void 0 : _b.on("data", (data) => this.emit("stderr", data.toString()));
93
+ return child;
94
+ }
95
+ _stop() {
96
+ return this.process.kill("SIGINT");
97
+ }
98
+ on(event, listener) {
99
+ return super.on(event, listener);
100
+ }
101
+ once(event, listener) {
102
+ return super.once(event, listener);
103
+ }
104
+ off(event, listener) {
105
+ return super.off(event, listener);
106
+ }
107
+ emit(event, ...args) {
108
+ return super.emit(event, ...args);
109
+ }
110
+ /**
111
+ * Create a quick tunnel without a Cloudflare account.
112
+ * @param url The local service URL to connect to. If not provided, the hello world mode will be used.
113
+ * @param options The options to pass to cloudflared.
114
+ */
115
+ static quick(url, options = {}) {
116
+ const args = ["tunnel"];
117
+ if (url) {
118
+ args.push("--url", url);
119
+ } else {
120
+ args.push("--hello-world");
121
+ }
122
+ args.push(...build_options(options));
123
+ return new Tunnel(args);
124
+ }
125
+ /**
126
+ * Create a tunnel with a Cloudflare account.
127
+ * @param token The Cloudflare Tunnel token.
128
+ * @param options The options to pass to cloudflared.
129
+ */
130
+ static withToken(token, options = {}) {
131
+ options["--token"] = token;
132
+ return new Tunnel(build_args(options));
133
+ }
134
+ }
135
+ function tunnel(options = {}) {
136
+ return new Tunnel(options);
137
+ }
138
+ function build_args(options) {
139
+ const args = "--hello-world" in options ? ["tunnel"] : ["tunnel", "run"];
140
+ args.push(...build_options(options));
141
+ return args;
142
+ }
143
+ function build_options(options) {
144
+ const opts = [];
145
+ for (const [key, value] of Object.entries(options)) {
146
+ if (typeof value === "string") {
147
+ opts.push(`${key}`, value);
148
+ } else if (typeof value === "number") {
149
+ opts.push(`${key}`, value.toString());
150
+ } else if (typeof value === "boolean") {
151
+ if (value === true) {
152
+ opts.push(`${key}`);
153
+ }
154
+ }
155
+ }
156
+ return opts;
157
+ }
158
+ // Annotate the CommonJS export names for ESM import in node:
159
+ 0 && (module.exports = {
160
+ Tunnel,
161
+ build_args,
162
+ build_options,
163
+ tunnel
164
+ });
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __copyProps = (to, from, except, desc) => {
7
+ if (from && typeof from === "object" || typeof from === "function") {
8
+ for (let key of __getOwnPropNames(from))
9
+ if (!__hasOwnProp.call(to, key) && key !== except)
10
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
+ }
12
+ return to;
13
+ };
14
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
15
+ var types_exports = {};
16
+ module.exports = __toCommonJS(types_exports);
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "cloudflared",
3
+ "version": "0.7.1",
4
+ "description": "Cloudflared in Node. Which allows you to easily create HTTPS tunnels using Cloudflare's cloudflared. It provides a typed API for creating tunnels and managing the cloudflared binary installation.",
5
+ "main": "./lib/lib.js",
6
+ "types": "./lib/lib.d.ts",
7
+ "bin": "./lib/cloudflared.js",
8
+ "keywords": [
9
+ "cloudflared",
10
+ "tunnel",
11
+ "macos",
12
+ "windows",
13
+ "linux",
14
+ "cli",
15
+ "lib"
16
+ ],
17
+ "author": "JacobLinCool <jacoblincool@gmail.com> (https://github.com/JacobLinCool)",
18
+ "license": "MIT",
19
+ "files": [
20
+ "lib",
21
+ "scripts"
22
+ ],
23
+ "devDependencies": {
24
+ "@changesets/changelog-github": "^0.5.0",
25
+ "@changesets/cli": "^2.27.7",
26
+ "@eslint/eslintrc": "^3.1.0",
27
+ "@eslint/js": "^9.8.0",
28
+ "@types/node": "^22.1.0",
29
+ "@typescript-eslint/eslint-plugin": "^8.0.1",
30
+ "@typescript-eslint/parser": "^8.0.1",
31
+ "changeset": "^0.2.6",
32
+ "eslint": "^9.8.0",
33
+ "eslint-config-prettier": "^9.1.0",
34
+ "prettier": "^3.3.3",
35
+ "tsup": "^8.2.4",
36
+ "typedoc": "^0.26.5",
37
+ "typescript": "^5.5.4",
38
+ "vitest": "^2.0.5",
39
+ "cloudflared": "0.7.1"
40
+ },
41
+ "homepage": "https://github.com/JacobLinCool/node-cloudflared#readme",
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "git+https://github.com/JacobLinCool/node-cloudflared.git"
45
+ },
46
+ "bugs": {
47
+ "url": "https://github.com/JacobLinCool/node-cloudflared/issues"
48
+ },
49
+ "scripts": {
50
+ "test": "vitest",
51
+ "dev": "tsup --watch",
52
+ "build": "tsup",
53
+ "docs": "typedoc ./src/lib.ts",
54
+ "format": "prettier --write '**/*.{js,ts,jsx,tsx,json,yml,yaml,md,html}' --ignore-path .gitignore",
55
+ "lint": "eslint .",
56
+ "postinstall": "node scripts/postinstall.mjs && node lib/cloudflared.js bin install latest",
57
+ "changeset": "changeset"
58
+ }
59
+ }
@@ -0,0 +1,10 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { execSync } from "node:child_process";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
7
+
8
+ if (!fs.existsSync(path.resolve(__dirname, "..", "lib"))) {
9
+ execSync("npm run build");
10
+ }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Espen Hovlandsdal <espen@hovlandsdal.com>
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.
@@ -0,0 +1,126 @@
1
+ # eventsource-parser
2
+
3
+ [![npm version](https://img.shields.io/npm/v/eventsource-parser.svg?style=flat-square)](https://www.npmjs.com/package/eventsource-parser)[![npm bundle size](https://img.shields.io/bundlephobia/minzip/eventsource-parser?style=flat-square)](https://bundlephobia.com/result?p=eventsource-parser)[![npm weekly downloads](https://img.shields.io/npm/dw/eventsource-parser.svg?style=flat-square)](https://www.npmjs.com/package/eventsource-parser)
4
+
5
+ A streaming parser for [server-sent events/eventsource](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events), without any assumptions about how the actual stream of data is retrieved. It is intended to be a building block for [clients](https://github.com/rexxars/eventsource-client) and polyfills in javascript environments such as browsers, node.js and deno.
6
+
7
+ If you are looking for a modern client implementation, see [eventsource-client](https://github.com/rexxars/eventsource-client).
8
+
9
+ You create an instance of the parser, and _feed_ it chunks of data - partial or complete, and the parse emits parsed messages once it receives a complete message. A [TransformStream variant](#stream-usage) is also available for environments that support it (modern browsers, Node 18 and higher).
10
+
11
+ Other modules in the EventSource family:
12
+
13
+ - [eventsource-client](https://github.com/rexxars/eventsource-client): modern, feature rich eventsource client for browsers, node.js, bun, deno and other modern JavaScript environments.
14
+ - [eventsource-encoder](https://github.com/rexxars/eventsource-encoder): encodes messages in the EventSource/Server-Sent Events format.
15
+ - [eventsource](https://github.com/eventsource/eventsource): Node.js polyfill for the WhatWG EventSource API.
16
+
17
+ > [!NOTE]
18
+ > Migrating from eventsource-parser 1.x/2.x? See the [migration guide](./MIGRATE-v3.md).
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ npm install --save eventsource-parser
24
+ ```
25
+
26
+ ## Usage
27
+
28
+ ```ts
29
+ import {createParser, type EventSourceMessage} from 'eventsource-parser'
30
+
31
+ function onEvent(event: EventSourceMessage) {
32
+ console.log('Received event!')
33
+ console.log('id: %s', event.id || '<none>')
34
+ console.log('event: %s', event.event || '<none>')
35
+ console.log('data: %s', event.data)
36
+ }
37
+
38
+ const parser = createParser({onEvent})
39
+ const sseStream = getSomeReadableStream()
40
+
41
+ for await (const chunk of sseStream) {
42
+ parser.feed(chunk)
43
+ }
44
+
45
+ // If you want to re-use the parser for a new stream of events, make sure to reset it!
46
+ parser.reset()
47
+ console.log('Done!')
48
+ ```
49
+
50
+ ### Retry intervals
51
+
52
+ If the server sends a `retry` field in the event stream, the parser will call any `onRetry` callback specified to the `createParser` function:
53
+
54
+ ```ts
55
+ const parser = createParser({
56
+ onRetry(retryInterval) {
57
+ console.log('Server requested retry interval of %dms', retryInterval)
58
+ },
59
+ onEvent(event) {
60
+ // …
61
+ },
62
+ })
63
+ ```
64
+
65
+ ### Parse errors
66
+
67
+ If the parser encounters an error while parsing, it will call any `onError` callback provided to the `createParser` function:
68
+
69
+ ```ts
70
+ import {type ParseError} from 'eventsource-parser'
71
+
72
+ const parser = createParser({
73
+ onError(error: ParseError) {
74
+ console.error('Error parsing event:', error)
75
+ if (error.type === 'invalid-field') {
76
+ console.error('Field name:', error.field)
77
+ console.error('Field value:', error.value)
78
+ console.error('Line:', error.line)
79
+ } else if (error.type === 'invalid-retry') {
80
+ console.error('Invalid retry interval:', error.value)
81
+ }
82
+ },
83
+ onEvent(event) {
84
+ // …
85
+ },
86
+ })
87
+ ```
88
+
89
+ Note that `invalid-field` errors will usually be called for any invalid data - not only data shaped as `field: value`. This is because the EventSource specification says to treat anything prior to a `:` as the field name. Use the `error.line` property to get the full line that caused the error.
90
+
91
+ > [!NOTE]
92
+ > When encountering the end of a stream, calling `.reset({consume: true})` on the parser to flush any remaining data and reset the parser state. This will trigger the `onError` callback if the pending data is not a valid event.
93
+
94
+ ### Comments
95
+
96
+ The parser will ignore comments (lines starting with `:`) by default. If you want to handle comments, you can provide an `onComment` callback to the `createParser` function:
97
+
98
+ ```ts
99
+ const parser = createParser({
100
+ onComment(comment) {
101
+ console.log('Received comment:', comment)
102
+ },
103
+ onEvent(event) {
104
+ // …
105
+ },
106
+ })
107
+ ```
108
+
109
+ > [!NOTE]
110
+ > Leading whitespace is not stripped from comments, eg `: comment` will give ` comment` as the comment value, not `comment` (note the leading space).
111
+
112
+ ## Stream usage
113
+
114
+ ```ts
115
+ import {EventSourceParserStream} from 'eventsource-parser/stream'
116
+
117
+ const eventStream = response.body
118
+ .pipeThrough(new TextDecoderStream())
119
+ .pipeThrough(new EventSourceParserStream())
120
+ ```
121
+
122
+ Note that the TransformStream is exposed under a separate export (`eventsource-parser/stream`), in order to maximize compatibility with environments that do not have the `TransformStream` constructor available.
123
+
124
+ ## License
125
+
126
+ MIT © [Espen Hovlandsdal](https://espen.codes/)