index.browser.cjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: !0 });
  3. var defaultOptionsValidator = require("./_chunks/defaultOptionsValidator-CXwrNjme.cjs"), parseHeaders = require("parse-headers");
  4. function _interopDefaultCompat(e) {
  5. return e && typeof e == "object" && "default" in e ? e : { default: e };
  6. }
  7. var parseHeaders__default = /* @__PURE__ */ _interopDefaultCompat(parseHeaders);
  8. const middlewareReducer = (middleware) => function(hook, defaultValue, ...args) {
  9. const bailEarly = hook === "onError";
  10. let value = defaultValue;
  11. for (let i = 0; i < middleware[hook].length; i++) {
  12. const handler = middleware[hook][i];
  13. if (value = handler(value, ...args), bailEarly && !value)
  14. break;
  15. }
  16. return value;
  17. };
  18. function createPubSub() {
  19. const subscribers = /* @__PURE__ */ Object.create(null);
  20. let nextId = 0;
  21. function subscribe(subscriber) {
  22. const id = nextId++;
  23. return subscribers[id] = subscriber, function() {
  24. delete subscribers[id];
  25. };
  26. }
  27. function publish(event) {
  28. for (const id in subscribers)
  29. subscribers[id](event);
  30. }
  31. return {
  32. publish,
  33. subscribe
  34. };
  35. }
  36. const channelNames = [
  37. "request",
  38. "response",
  39. "progress",
  40. "error",
  41. "abort"
  42. ], middlehooks = [
  43. "processOptions",
  44. "validateOptions",
  45. "interceptRequest",
  46. "finalizeOptions",
  47. "onRequest",
  48. "onResponse",
  49. "onError",
  50. "onReturn",
  51. "onHeaders"
  52. ];
  53. function createRequester(initMiddleware, httpRequest) {
  54. const loadedMiddleware = [], middleware = middlehooks.reduce(
  55. (ware, name) => (ware[name] = ware[name] || [], ware),
  56. {
  57. processOptions: [defaultOptionsValidator.processOptions],
  58. validateOptions: [defaultOptionsValidator.validateOptions]
  59. }
  60. );
  61. function request(opts) {
  62. const onResponse = (reqErr, res, ctx) => {
  63. let error = reqErr, response = res;
  64. if (!error)
  65. try {
  66. response = applyMiddleware("onResponse", res, ctx);
  67. } catch (err) {
  68. response = null, error = err;
  69. }
  70. error = error && applyMiddleware("onError", error, ctx), error ? channels.error.publish(error) : response && channels.response.publish(response);
  71. }, channels = channelNames.reduce((target, name) => (target[name] = createPubSub(), target), {}), applyMiddleware = middlewareReducer(middleware), options = applyMiddleware("processOptions", opts);
  72. applyMiddleware("validateOptions", options);
  73. const context = { options, channels, applyMiddleware };
  74. let ongoingRequest;
  75. const unsubscribe = channels.request.subscribe((ctx) => {
  76. ongoingRequest = httpRequest(ctx, (err, res) => onResponse(err, res, ctx));
  77. });
  78. channels.abort.subscribe(() => {
  79. unsubscribe(), ongoingRequest && ongoingRequest.abort();
  80. });
  81. const returnValue = applyMiddleware("onReturn", channels, context);
  82. return returnValue === channels && channels.request.publish(context), returnValue;
  83. }
  84. return request.use = function(newMiddleware) {
  85. if (!newMiddleware)
  86. throw new Error("Tried to add middleware that resolved to falsey value");
  87. if (typeof newMiddleware == "function")
  88. throw new Error(
  89. "Tried to add middleware that was a function. It probably expects you to pass options to it."
  90. );
  91. if (newMiddleware.onReturn && middleware.onReturn.length > 0)
  92. throw new Error(
  93. "Tried to add new middleware with `onReturn` handler, but another handler has already been registered for this event"
  94. );
  95. return middlehooks.forEach((key) => {
  96. newMiddleware[key] && middleware[key].push(newMiddleware[key]);
  97. }), loadedMiddleware.push(newMiddleware), request;
  98. }, request.clone = () => createRequester(loadedMiddleware, httpRequest), initMiddleware.forEach(request.use), request;
  99. }
  100. var __accessCheck = (obj, member, msg) => {
  101. if (!member.has(obj))
  102. throw TypeError("Cannot " + msg);
  103. }, __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __privateAdd = (obj, member, value) => {
  104. if (member.has(obj))
  105. throw TypeError("Cannot add the same private member more than once");
  106. member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
  107. }, __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value), _method, _url, _resHeaders, _headers, _controller, _init, _useAbortSignal;
  108. class FetchXhr {
  109. constructor() {
  110. this.readyState = 0, this.responseType = "", __privateAdd(this, _method, void 0), __privateAdd(this, _url, void 0), __privateAdd(this, _resHeaders, void 0), __privateAdd(this, _headers, {}), __privateAdd(this, _controller, void 0), __privateAdd(this, _init, {}), __privateAdd(this, _useAbortSignal, void 0);
  111. }
  112. // eslint-disable-next-line @typescript-eslint/no-unused-vars -- _async is only declared for typings compatibility
  113. open(method, url, _async) {
  114. __privateSet(this, _method, method), __privateSet(this, _url, url), __privateSet(this, _resHeaders, ""), this.readyState = 1, this.onreadystatechange(), __privateSet(this, _controller, void 0);
  115. }
  116. abort() {
  117. __privateGet(this, _controller) && __privateGet(this, _controller).abort();
  118. }
  119. getAllResponseHeaders() {
  120. return __privateGet(this, _resHeaders);
  121. }
  122. setRequestHeader(name, value) {
  123. __privateGet(this, _headers)[name] = value;
  124. }
  125. // Allow setting extra fetch init options, needed for runtimes such as Vercel Edge to set `cache` and other options in React Server Components
  126. setInit(init, useAbortSignal = !0) {
  127. __privateSet(this, _init, init), __privateSet(this, _useAbortSignal, useAbortSignal);
  128. }
  129. send(body) {
  130. const textBody = this.responseType !== "arraybuffer", options = {
  131. ...__privateGet(this, _init),
  132. method: __privateGet(this, _method),
  133. headers: __privateGet(this, _headers),
  134. body
  135. };
  136. typeof AbortController == "function" && __privateGet(this, _useAbortSignal) && (__privateSet(this, _controller, new AbortController()), typeof EventTarget < "u" && __privateGet(this, _controller).signal instanceof EventTarget && (options.signal = __privateGet(this, _controller).signal)), typeof document < "u" && (options.credentials = this.withCredentials ? "include" : "omit"), fetch(__privateGet(this, _url), options).then((res) => (res.headers.forEach((value, key) => {
  137. __privateSet(this, _resHeaders, __privateGet(this, _resHeaders) + `${key}: ${value}\r
  138. `);
  139. }), this.status = res.status, this.statusText = res.statusText, this.readyState = 3, textBody ? res.text() : res.arrayBuffer())).then((resBody) => {
  140. typeof resBody == "string" ? this.responseText = resBody : this.response = resBody, this.readyState = 4, this.onreadystatechange();
  141. }).catch((err) => {
  142. var _a;
  143. if (err.name === "AbortError") {
  144. this.onabort();
  145. return;
  146. }
  147. (_a = this.onerror) == null || _a.call(this, err);
  148. });
  149. }
  150. }
  151. _method = /* @__PURE__ */ new WeakMap(), _url = /* @__PURE__ */ new WeakMap(), _resHeaders = /* @__PURE__ */ new WeakMap(), _headers = /* @__PURE__ */ new WeakMap(), _controller = /* @__PURE__ */ new WeakMap(), _init = /* @__PURE__ */ new WeakMap(), _useAbortSignal = /* @__PURE__ */ new WeakMap();
  152. const adapter = typeof XMLHttpRequest == "function" ? "xhr" : "fetch", XmlHttpRequest = adapter === "xhr" ? XMLHttpRequest : FetchXhr, httpRequester = (context, callback) => {
  153. var _a;
  154. const opts = context.options, options = context.applyMiddleware("finalizeOptions", opts), timers = {}, injectedResponse = context.applyMiddleware("interceptRequest", void 0, {
  155. adapter,
  156. context
  157. });
  158. if (injectedResponse) {
  159. const cbTimer = setTimeout(callback, 0, null, injectedResponse);
  160. return { abort: () => clearTimeout(cbTimer) };
  161. }
  162. let xhr = new XmlHttpRequest();
  163. xhr instanceof FetchXhr && typeof options.fetch == "object" && xhr.setInit(options.fetch, (_a = options.useAbortSignal) != null ? _a : !0);
  164. const headers = options.headers, delays = options.timeout;
  165. let aborted = !1, loaded = !1, timedOut = !1;
  166. if (xhr.onerror = (event) => {
  167. onError(
  168. new Error(
  169. `Request error while attempting to reach ${options.url}${event.lengthComputable ? `(${event.loaded} of ${event.total} bytes transferred)` : ""}`
  170. )
  171. );
  172. }, xhr.ontimeout = (event) => {
  173. onError(
  174. new Error(
  175. `Request timeout while attempting to reach ${options.url}${event.lengthComputable ? `(${event.loaded} of ${event.total} bytes transferred)` : ""}`
  176. )
  177. );
  178. }, xhr.onabort = () => {
  179. stopTimers(!0), aborted = !0;
  180. }, xhr.onreadystatechange = () => {
  181. resetTimers(), !(aborted || xhr.readyState !== 4) && xhr.status !== 0 && onLoad();
  182. }, xhr.open(
  183. options.method,
  184. options.url,
  185. !0
  186. // Always async
  187. ), xhr.withCredentials = !!options.withCredentials, headers && xhr.setRequestHeader)
  188. for (const key in headers)
  189. headers.hasOwnProperty(key) && xhr.setRequestHeader(key, headers[key]);
  190. return options.rawBody && (xhr.responseType = "arraybuffer"), context.applyMiddleware("onRequest", { options, adapter, request: xhr, context }), xhr.send(options.body || null), delays && (timers.connect = setTimeout(() => timeoutRequest("ETIMEDOUT"), delays.connect)), { abort };
  191. function abort() {
  192. aborted = !0, xhr && xhr.abort();
  193. }
  194. function timeoutRequest(code) {
  195. timedOut = !0, xhr.abort();
  196. const error = new Error(
  197. code === "ESOCKETTIMEDOUT" ? `Socket timed out on request to ${options.url}` : `Connection timed out on request to ${options.url}`
  198. );
  199. error.code = code, context.channels.error.publish(error);
  200. }
  201. function resetTimers() {
  202. delays && (stopTimers(), timers.socket = setTimeout(() => timeoutRequest("ESOCKETTIMEDOUT"), delays.socket));
  203. }
  204. function stopTimers(force) {
  205. (force || aborted || xhr.readyState >= 2 && timers.connect) && clearTimeout(timers.connect), timers.socket && clearTimeout(timers.socket);
  206. }
  207. function onError(error) {
  208. if (loaded)
  209. return;
  210. stopTimers(!0), loaded = !0, xhr = null;
  211. const err = error || new Error(`Network error while attempting to reach ${options.url}`);
  212. err.isNetworkError = !0, err.request = options, callback(err);
  213. }
  214. function reduceResponse() {
  215. return {
  216. body: xhr.response || (xhr.responseType === "" || xhr.responseType === "text" ? xhr.responseText : ""),
  217. url: options.url,
  218. method: options.method,
  219. headers: parseHeaders__default.default(xhr.getAllResponseHeaders()),
  220. statusCode: xhr.status,
  221. statusMessage: xhr.statusText
  222. };
  223. }
  224. function onLoad() {
  225. if (!(aborted || loaded || timedOut)) {
  226. if (xhr.status === 0) {
  227. onError(new Error("Unknown XHR error"));
  228. return;
  229. }
  230. stopTimers(), loaded = !0, callback(null, reduceResponse());
  231. }
  232. }
  233. }, getIt = (initMiddleware = [], httpRequest = httpRequester) => createRequester(initMiddleware, httpRequest), environment = "browser";
  234. exports.adapter = adapter;
  235. exports.environment = environment;
  236. exports.getIt = getIt;
  237. //# sourceMappingURL=index.browser.cjs.map