index.cjs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: !0 });
  3. var eventsourceParser = require("eventsource-parser");
  4. class ErrorEvent extends Event {
  5. /**
  6. * Constructs a new `ErrorEvent` instance. This is typically not called directly,
  7. * but rather emitted by the `EventSource` object when an error occurs.
  8. *
  9. * @param type - The type of the event (should be "error")
  10. * @param errorEventInitDict - Optional properties to include in the error event
  11. */
  12. constructor(type, errorEventInitDict) {
  13. var _a, _b;
  14. super(type), this.code = (_a = errorEventInitDict == null ? void 0 : errorEventInitDict.code) != null ? _a : void 0, this.message = (_b = errorEventInitDict == null ? void 0 : errorEventInitDict.message) != null ? _b : void 0;
  15. }
  16. /**
  17. * Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance,
  18. * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
  19. * we explicitly include the properties in the `inspect` method.
  20. *
  21. * This is automatically called by Node.js when you `console.log` an instance of this class.
  22. *
  23. * @param _depth - The current depth
  24. * @param options - The options passed to `util.inspect`
  25. * @param inspect - The inspect function to use (prevents having to import it from `util`)
  26. * @returns A string representation of the error
  27. */
  28. [Symbol.for("nodejs.util.inspect.custom")](_depth, options, inspect) {
  29. return inspect(inspectableError(this), options);
  30. }
  31. /**
  32. * Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance,
  33. * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
  34. * we explicitly include the properties in the `inspect` method.
  35. *
  36. * This is automatically called by Deno when you `console.log` an instance of this class.
  37. *
  38. * @param inspect - The inspect function to use (prevents having to import it from `util`)
  39. * @param options - The options passed to `Deno.inspect`
  40. * @returns A string representation of the error
  41. */
  42. [Symbol.for("Deno.customInspect")](inspect, options) {
  43. return inspect(inspectableError(this), options);
  44. }
  45. }
  46. function syntaxError(message) {
  47. const DomException = globalThis.DOMException;
  48. return typeof DomException == "function" ? new DomException(message, "SyntaxError") : new SyntaxError(message);
  49. }
  50. function flattenError(err) {
  51. return err instanceof Error ? "errors" in err && Array.isArray(err.errors) ? err.errors.map(flattenError).join(", ") : "cause" in err && err.cause instanceof Error ? `${err}: ${flattenError(err.cause)}` : err.message : `${err}`;
  52. }
  53. function inspectableError(err) {
  54. return {
  55. type: err.type,
  56. message: err.message,
  57. code: err.code,
  58. defaultPrevented: err.defaultPrevented,
  59. cancelable: err.cancelable,
  60. timeStamp: err.timeStamp
  61. };
  62. }
  63. var __typeError = (msg) => {
  64. throw TypeError(msg);
  65. }, __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg), __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value), __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value), __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method), _readyState, _url, _redirectUrl, _withCredentials, _fetch, _reconnectInterval, _reconnectTimer, _lastEventId, _controller, _parser, _onError, _onMessage, _onOpen, _EventSource_instances, connect_fn, _onFetchResponse, _onFetchError, getRequestOptions_fn, _onEvent, _onRetryChange, failConnection_fn, scheduleReconnect_fn, _reconnect;
  66. class EventSource extends EventTarget {
  67. constructor(url, eventSourceInitDict) {
  68. var _a, _b;
  69. super(), __privateAdd(this, _EventSource_instances), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, __privateAdd(this, _readyState), __privateAdd(this, _url), __privateAdd(this, _redirectUrl), __privateAdd(this, _withCredentials), __privateAdd(this, _fetch), __privateAdd(this, _reconnectInterval), __privateAdd(this, _reconnectTimer), __privateAdd(this, _lastEventId, null), __privateAdd(this, _controller), __privateAdd(this, _parser), __privateAdd(this, _onError, null), __privateAdd(this, _onMessage, null), __privateAdd(this, _onOpen, null), __privateAdd(this, _onFetchResponse, async (response) => {
  70. var _a2;
  71. __privateGet(this, _parser).reset();
  72. const { body, redirected, status, headers } = response;
  73. if (status === 204) {
  74. __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close();
  75. return;
  76. }
  77. if (redirected ? __privateSet(this, _redirectUrl, new URL(response.url)) : __privateSet(this, _redirectUrl, void 0), status !== 200) {
  78. __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, `Non-200 status code (${status})`, status);
  79. return;
  80. }
  81. if (!(headers.get("content-type") || "").startsWith("text/event-stream")) {
  82. __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, 'Invalid content type, expected "text/event-stream"', status);
  83. return;
  84. }
  85. if (__privateGet(this, _readyState) === this.CLOSED)
  86. return;
  87. __privateSet(this, _readyState, this.OPEN);
  88. const openEvent = new Event("open");
  89. if ((_a2 = __privateGet(this, _onOpen)) == null || _a2.call(this, openEvent), this.dispatchEvent(openEvent), typeof body != "object" || !body || !("getReader" in body)) {
  90. __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid response body, expected a web ReadableStream", status), this.close();
  91. return;
  92. }
  93. const decoder = new TextDecoder(), reader = body.getReader();
  94. let open = !0;
  95. do {
  96. const { done, value } = await reader.read();
  97. value && __privateGet(this, _parser).feed(decoder.decode(value, { stream: !done })), done && (open = !1, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this));
  98. } while (open);
  99. }), __privateAdd(this, _onFetchError, (err) => {
  100. __privateSet(this, _controller, void 0), !(err.name === "AbortError" || err.type === "aborted") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError(err));
  101. }), __privateAdd(this, _onEvent, (event) => {
  102. typeof event.id == "string" && __privateSet(this, _lastEventId, event.id);
  103. const messageEvent = new MessageEvent(event.event || "message", {
  104. data: event.data,
  105. origin: __privateGet(this, _redirectUrl) ? __privateGet(this, _redirectUrl).origin : __privateGet(this, _url).origin,
  106. lastEventId: event.id || ""
  107. });
  108. __privateGet(this, _onMessage) && (!event.event || event.event === "message") && __privateGet(this, _onMessage).call(this, messageEvent), this.dispatchEvent(messageEvent);
  109. }), __privateAdd(this, _onRetryChange, (value) => {
  110. __privateSet(this, _reconnectInterval, value);
  111. }), __privateAdd(this, _reconnect, () => {
  112. __privateSet(this, _reconnectTimer, void 0), __privateGet(this, _readyState) === this.CONNECTING && __privateMethod(this, _EventSource_instances, connect_fn).call(this);
  113. });
  114. try {
  115. if (url instanceof URL)
  116. __privateSet(this, _url, url);
  117. else if (typeof url == "string")
  118. __privateSet(this, _url, new URL(url, getBaseURL()));
  119. else
  120. throw new Error("Invalid URL");
  121. } catch {
  122. throw syntaxError("An invalid or illegal string was specified");
  123. }
  124. __privateSet(this, _parser, eventsourceParser.createParser({
  125. onEvent: __privateGet(this, _onEvent),
  126. onRetry: __privateGet(this, _onRetryChange)
  127. })), __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _reconnectInterval, 3e3), __privateSet(this, _fetch, (_a = eventSourceInitDict == null ? void 0 : eventSourceInitDict.fetch) != null ? _a : globalThis.fetch), __privateSet(this, _withCredentials, (_b = eventSourceInitDict == null ? void 0 : eventSourceInitDict.withCredentials) != null ? _b : !1), __privateMethod(this, _EventSource_instances, connect_fn).call(this);
  128. }
  129. /**
  130. * Returns the state of this EventSource object's connection. It can have the values described below.
  131. *
  132. * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)
  133. *
  134. * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface,
  135. * defined in the TypeScript `dom` library.
  136. *
  137. * @public
  138. */
  139. get readyState() {
  140. return __privateGet(this, _readyState);
  141. }
  142. /**
  143. * Returns the URL providing the event stream.
  144. *
  145. * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)
  146. *
  147. * @public
  148. */
  149. get url() {
  150. return __privateGet(this, _url).href;
  151. }
  152. /**
  153. * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.
  154. *
  155. * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)
  156. */
  157. get withCredentials() {
  158. return __privateGet(this, _withCredentials);
  159. }
  160. /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
  161. get onerror() {
  162. return __privateGet(this, _onError);
  163. }
  164. set onerror(value) {
  165. __privateSet(this, _onError, value);
  166. }
  167. /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
  168. get onmessage() {
  169. return __privateGet(this, _onMessage);
  170. }
  171. set onmessage(value) {
  172. __privateSet(this, _onMessage, value);
  173. }
  174. /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
  175. get onopen() {
  176. return __privateGet(this, _onOpen);
  177. }
  178. set onopen(value) {
  179. __privateSet(this, _onOpen, value);
  180. }
  181. addEventListener(type, listener, options) {
  182. const listen = listener;
  183. super.addEventListener(type, listen, options);
  184. }
  185. removeEventListener(type, listener, options) {
  186. const listen = listener;
  187. super.removeEventListener(type, listen, options);
  188. }
  189. /**
  190. * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.
  191. *
  192. * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)
  193. *
  194. * @public
  195. */
  196. close() {
  197. __privateGet(this, _reconnectTimer) && clearTimeout(__privateGet(this, _reconnectTimer)), __privateGet(this, _readyState) !== this.CLOSED && (__privateGet(this, _controller) && __privateGet(this, _controller).abort(), __privateSet(this, _readyState, this.CLOSED), __privateSet(this, _controller, void 0));
  198. }
  199. }
  200. _readyState = /* @__PURE__ */ new WeakMap(), _url = /* @__PURE__ */ new WeakMap(), _redirectUrl = /* @__PURE__ */ new WeakMap(), _withCredentials = /* @__PURE__ */ new WeakMap(), _fetch = /* @__PURE__ */ new WeakMap(), _reconnectInterval = /* @__PURE__ */ new WeakMap(), _reconnectTimer = /* @__PURE__ */ new WeakMap(), _lastEventId = /* @__PURE__ */ new WeakMap(), _controller = /* @__PURE__ */ new WeakMap(), _parser = /* @__PURE__ */ new WeakMap(), _onError = /* @__PURE__ */ new WeakMap(), _onMessage = /* @__PURE__ */ new WeakMap(), _onOpen = /* @__PURE__ */ new WeakMap(), _EventSource_instances = /* @__PURE__ */ new WeakSet(), /**
  201. * Connect to the given URL and start receiving events
  202. *
  203. * @internal
  204. */
  205. connect_fn = function() {
  206. __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _controller, new AbortController()), __privateGet(this, _fetch)(__privateGet(this, _url), __privateMethod(this, _EventSource_instances, getRequestOptions_fn).call(this)).then(__privateGet(this, _onFetchResponse)).catch(__privateGet(this, _onFetchError));
  207. }, _onFetchResponse = /* @__PURE__ */ new WeakMap(), _onFetchError = /* @__PURE__ */ new WeakMap(), /**
  208. * Get request options for the `fetch()` request
  209. *
  210. * @returns The request options
  211. * @internal
  212. */
  213. getRequestOptions_fn = function() {
  214. var _a;
  215. const init = {
  216. // [spec] Let `corsAttributeState` be `Anonymous`…
  217. // [spec] …will have their mode set to "cors"…
  218. mode: "cors",
  219. redirect: "follow",
  220. headers: { Accept: "text/event-stream", ...__privateGet(this, _lastEventId) ? { "Last-Event-ID": __privateGet(this, _lastEventId) } : void 0 },
  221. cache: "no-store",
  222. signal: (_a = __privateGet(this, _controller)) == null ? void 0 : _a.signal
  223. };
  224. return "window" in globalThis && (init.credentials = this.withCredentials ? "include" : "same-origin"), init;
  225. }, _onEvent = /* @__PURE__ */ new WeakMap(), _onRetryChange = /* @__PURE__ */ new WeakMap(), /**
  226. * Handles the process referred to in the EventSource specification as "failing a connection".
  227. *
  228. * @param error - The error causing the connection to fail
  229. * @param code - The HTTP status code, if available
  230. * @internal
  231. */
  232. failConnection_fn = function(message, code) {
  233. var _a;
  234. __privateGet(this, _readyState) !== this.CLOSED && __privateSet(this, _readyState, this.CLOSED);
  235. const errorEvent = new ErrorEvent("error", { code, message });
  236. (_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent);
  237. }, /**
  238. * Schedules a reconnection attempt against the EventSource endpoint.
  239. *
  240. * @param message - The error causing the connection to fail
  241. * @param code - The HTTP status code, if available
  242. * @internal
  243. */
  244. scheduleReconnect_fn = function(message, code) {
  245. var _a;
  246. if (__privateGet(this, _readyState) === this.CLOSED)
  247. return;
  248. __privateSet(this, _readyState, this.CONNECTING);
  249. const errorEvent = new ErrorEvent("error", { code, message });
  250. (_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent), __privateSet(this, _reconnectTimer, setTimeout(__privateGet(this, _reconnect), __privateGet(this, _reconnectInterval)));
  251. }, _reconnect = /* @__PURE__ */ new WeakMap(), /**
  252. * ReadyState representing an EventSource currently trying to connect
  253. *
  254. * @public
  255. */
  256. EventSource.CONNECTING = 0, /**
  257. * ReadyState representing an EventSource connection that is open (eg connected)
  258. *
  259. * @public
  260. */
  261. EventSource.OPEN = 1, /**
  262. * ReadyState representing an EventSource connection that is closed (eg disconnected)
  263. *
  264. * @public
  265. */
  266. EventSource.CLOSED = 2;
  267. function getBaseURL() {
  268. const doc = "document" in globalThis ? globalThis.document : void 0;
  269. return doc && typeof doc == "object" && "baseURI" in doc && typeof doc.baseURI == "string" ? doc.baseURI : void 0;
  270. }
  271. exports.ErrorEvent = ErrorEvent;
  272. exports.EventSource = EventSource;
  273. //# sourceMappingURL=index.cjs.map