fetch.cjs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports._getFetchImplementation = exports._globalFetchImplementationIsNodeFetch = exports.overrideFetchImplementation = void 0;
  4. const env_js_1 = require("../utils/env.cjs");
  5. // Wrap the default fetch call due to issues with illegal invocations
  6. // in some environments:
  7. // https://stackoverflow.com/questions/69876859/why-does-bind-fix-failed-to-execute-fetch-on-window-illegal-invocation-err
  8. // @ts-expect-error Broad typing to support a range of fetch implementations
  9. const DEFAULT_FETCH_IMPLEMENTATION = (...args) => fetch(...args);
  10. const LANGSMITH_FETCH_IMPLEMENTATION_KEY = Symbol.for("ls:fetch_implementation");
  11. /**
  12. * Overrides the fetch implementation used for LangSmith calls.
  13. * You should use this if you need to use an implementation of fetch
  14. * other than the default global (e.g. for dealing with proxies).
  15. * @param fetch The new fetch functino to use.
  16. */
  17. const overrideFetchImplementation = (fetch) => {
  18. globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] = fetch;
  19. };
  20. exports.overrideFetchImplementation = overrideFetchImplementation;
  21. const _globalFetchImplementationIsNodeFetch = () => {
  22. const fetchImpl = globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY];
  23. if (!fetchImpl)
  24. return false;
  25. // Check if the implementation has node-fetch specific properties
  26. return (typeof fetchImpl === "function" &&
  27. "Headers" in fetchImpl &&
  28. "Request" in fetchImpl &&
  29. "Response" in fetchImpl);
  30. };
  31. exports._globalFetchImplementationIsNodeFetch = _globalFetchImplementationIsNodeFetch;
  32. /**
  33. * @internal
  34. */
  35. const _getFetchImplementation = (debug) => {
  36. return async (...args) => {
  37. if (debug || (0, env_js_1.getLangSmithEnvironmentVariable)("DEBUG") === "true") {
  38. const [url, options] = args;
  39. console.log(`→ ${options?.method || "GET"} ${url}`);
  40. }
  41. const res = await (globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] ??
  42. DEFAULT_FETCH_IMPLEMENTATION)(...args);
  43. if (debug || (0, env_js_1.getLangSmithEnvironmentVariable)("DEBUG") === "true") {
  44. console.log(`← ${res.status} ${res.statusText} ${res.url}`);
  45. }
  46. return res;
  47. };
  48. };
  49. exports._getFetchImplementation = _getFetchImplementation;