traceable.cjs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.ROOT = exports.AsyncLocalStorageProviderSingleton = void 0;
  4. exports.getCurrentRunTree = getCurrentRunTree;
  5. exports.withRunTree = withRunTree;
  6. exports.isTraceableFunction = isTraceableFunction;
  7. const run_trees_js_1 = require("../run_trees.cjs");
  8. class MockAsyncLocalStorage {
  9. getStore() {
  10. return undefined;
  11. }
  12. run(_, callback) {
  13. return callback();
  14. }
  15. }
  16. const TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage");
  17. const mockAsyncLocalStorage = new MockAsyncLocalStorage();
  18. class AsyncLocalStorageProvider {
  19. getInstance() {
  20. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  21. return globalThis[TRACING_ALS_KEY] ?? mockAsyncLocalStorage;
  22. }
  23. initializeGlobalInstance(instance) {
  24. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  25. if (globalThis[TRACING_ALS_KEY] === undefined) {
  26. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  27. globalThis[TRACING_ALS_KEY] = instance;
  28. }
  29. }
  30. }
  31. exports.AsyncLocalStorageProviderSingleton = new AsyncLocalStorageProvider();
  32. function getCurrentRunTree(permitAbsentRunTree = false) {
  33. const runTree = exports.AsyncLocalStorageProviderSingleton.getInstance().getStore();
  34. if (!permitAbsentRunTree && !(0, run_trees_js_1.isRunTree)(runTree)) {
  35. throw new Error("Could not get the current run tree.\n\nPlease make sure you are calling this method within a traceable function and that tracing is enabled.");
  36. }
  37. return runTree;
  38. }
  39. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  40. function withRunTree(runTree, fn) {
  41. const storage = exports.AsyncLocalStorageProviderSingleton.getInstance();
  42. return new Promise((resolve, reject) => {
  43. storage.run(runTree, () => void Promise.resolve(fn()).then(resolve).catch(reject));
  44. });
  45. }
  46. exports.ROOT = Symbol.for("langsmith:traceable:root");
  47. function isTraceableFunction(x
  48. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  49. ) {
  50. return typeof x === "function" && "langsmith:traceable" in x;
  51. }