var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var opentelemetry_exports = {};
__export(opentelemetry_exports, {
  otelRetypeSpans: () => otelRetypeSpans,
  otelSpan: () => otelSpan,
  otelSpanAncestors: () => otelSpanAncestors,
  otelSpanCount: () => otelSpanCount,
  otelSpanDescendants: () => otelSpanDescendants,
  otelSpans: () => otelSpans,
  otelTrace: () => otelTrace,
  otelTraceCount: () => otelTraceCount,
  otelTraceTreeMapData: () => otelTraceTreeMapData,
  otelTraces: () => otelTraces,
  otelTruncateSpans: () => otelTruncateSpans
});
module.exports = __toCommonJS(opentelemetry_exports);
var import_map = __toESM(require("@babel/runtime-corejs3/core-js/map"));
var import_map2 = __toESM(require("@babel/runtime-corejs3/core-js/instance/map"));
var import_filter = __toESM(require("@babel/runtime-corejs3/core-js/instance/filter"));
var import_reduce = __toESM(require("@babel/runtime-corejs3/core-js/instance/reduce"));
var import_set = __toESM(require("@babel/runtime-corejs3/core-js/set"));
var import_sort = __toESM(require("@babel/runtime-corejs3/core-js/instance/sort"));
var import_find = __toESM(require("@babel/runtime-corejs3/core-js/instance/find"));
var import_graphql_server = require("@cedarjs/graphql-server");
var import_db = require("../../lib/db");
var import_logger = require("../../lib/logger");
var import_opentelemetry = require("../../lib/opentelemetry");
const otelSpans = async () => {
  const incompleteData = await import_db.db.oTelTraceSpan.findMany({
    orderBy: {
      startTimeNano: "desc"
    },
    take: 300,
    include: {
      attributes: true,
      events: {
        include: {
          attributes: true
        }
      },
      links: {
        include: {
          attributes: true
        }
      },
      scope: {
        include: {
          attributes: true
        }
      },
      resource: {
        include: {
          attributes: true
        }
      },
      type: true
    }
  });
  const attributes = await import_db.db.$queryRaw`SELECT id, [value] FROM OTelTraceAttribute;`;
  const attributeValueMap = new import_map.default();
  for (let i = 0; i < attributes.length; i++) {
    attributeValueMap.set(attributes[i].id, attributes[i].value);
  }
  const completeData = [];
  for (let i = 0; i < incompleteData.length; i++) {
    var _context, _context2, _context4, _context6;
    completeData.push({
      ...incompleteData[i],
      startTimeNano: incompleteData[i].startTimeNano.toString(),
      endTimeNano: incompleteData[i].endTimeNano.toString(),
      attributes: (0, import_map2.default)(_context = incompleteData[i].attributes).call(_context, (attribute) => ({
        ...attribute,
        value: JSON.parse(attributeValueMap.get(attribute.id))
      })),
      events: (0, import_map2.default)(_context2 = incompleteData[i].events).call(_context2, (event) => {
        var _context3;
        return {
          ...event,
          startTimeNano: event.startTimeNano.toString(),
          attributes: (0, import_map2.default)(_context3 = event.attributes).call(_context3, (attribute) => ({
            ...attribute,
            value: JSON.parse(attributeValueMap.get(attribute.id))
          }))
        };
      }),
      links: (0, import_map2.default)(_context4 = incompleteData[i].links).call(_context4, (link) => {
        var _context5;
        return {
          ...link,
          attributes: (0, import_map2.default)(_context5 = link.attributes).call(_context5, (attribute) => ({
            ...attribute,
            value: JSON.parse(attributeValueMap.get(attribute.id))
          }))
        };
      }),
      resource: {
        ...incompleteData[i].resource,
        attributes: (0, import_map2.default)(_context6 = incompleteData[i].resource.attributes).call(_context6, (attribute) => ({
          ...attribute,
          value: JSON.parse(attributeValueMap.get(attribute.id))
        }))
      }
    });
  }
  return completeData;
};
const otelSpan = async ({
  id
}) => {
  var _context7, _context8, _context0, _context10;
  const originalData = await import_db.db.oTelTraceSpan.findUnique({
    where: {
      spanId: id
    },
    include: {
      attributes: true,
      events: {
        include: {
          attributes: true
        }
      },
      links: {
        include: {
          attributes: true
        }
      },
      scope: {
        include: {
          attributes: true
        }
      },
      resource: {
        include: {
          attributes: true
        }
      },
      type: true
    }
  });
  if (originalData === null) {
    throw new import_graphql_server.ValidationError("No span with that ID found");
  }
  const attributes = await import_db.db.$queryRaw`SELECT id, [value] FROM OTelTraceAttribute;`;
  const attributeValueMap = new import_map.default();
  for (let i = 0; i < attributes.length; i++) {
    attributeValueMap.set(attributes[i].id, attributes[i].value);
  }
  const completeData = {
    ...originalData,
    startTimeNano: originalData.startTimeNano.toString(),
    endTimeNano: originalData.endTimeNano.toString(),
    attributes: (0, import_map2.default)(_context7 = originalData.attributes).call(_context7, (attribute) => ({
      ...attribute,
      value: JSON.parse(attributeValueMap.get(attribute.id))
    })),
    events: (0, import_map2.default)(_context8 = originalData.events).call(_context8, (event) => {
      var _context9;
      return {
        ...event,
        startTimeNano: event.startTimeNano.toString(),
        attributes: (0, import_map2.default)(_context9 = event.attributes).call(_context9, (attribute) => ({
          ...attribute,
          value: JSON.parse(attributeValueMap.get(attribute.id))
        }))
      };
    }),
    links: (0, import_map2.default)(_context0 = originalData.links).call(_context0, (link) => {
      var _context1;
      return {
        ...link,
        attributes: (0, import_map2.default)(_context1 = link.attributes).call(_context1, (attribute) => ({
          ...attribute,
          value: JSON.parse(attributeValueMap.get(attribute.id))
        }))
      };
    }),
    resource: {
      ...originalData.resource,
      attributes: (0, import_map2.default)(_context10 = originalData.resource.attributes).call(_context10, (attribute) => ({
        ...attribute,
        value: JSON.parse(attributeValueMap.get(attribute.id))
      }))
    }
  };
  return completeData;
};
const otelSpanAncestors = async ({
  id
}) => {
  var _context11;
  const rawAncestorIDs = await import_db.db.$queryRaw`WITH RECURSIVE span_hierarchy AS (
      SELECT spanId, parentId
      FROM OTelTraceSpan
      WHERE spanId = ${id}
      UNION ALL
      SELECT s.spanId, s.parentId
      FROM OTelTraceSpan s
      JOIN span_hierarchy sh ON s.spanId = sh.parentId
    )
    SELECT spanId
    FROM span_hierarchy;`;
  const ancestorIDs = (0, import_filter.default)(_context11 = (0, import_map2.default)(rawAncestorIDs).call(rawAncestorIDs, (ancestor) => ancestor.spanId)).call(_context11, (ancestor) => ancestor !== id);
  const rawData = await import_db.db.oTelTraceSpan.findMany({
    where: {
      spanId: {
        in: ancestorIDs
      }
    },
    orderBy: {
      startTimeNano: "asc"
    },
    include: {
      attributes: true,
      events: {
        include: {
          attributes: true
        }
      },
      links: {
        include: {
          attributes: true
        }
      },
      scope: {
        include: {
          attributes: true
        }
      },
      resource: {
        include: {
          attributes: true
        }
      },
      type: true
    }
  });
  const attributes = await import_db.db.$queryRaw`SELECT id, [value] FROM OTelTraceAttribute;`;
  const attributeValueMap = new import_map.default();
  for (let i = 0; i < attributes.length; i++) {
    attributeValueMap.set(attributes[i].id, attributes[i].value);
  }
  const completeData = (0, import_map2.default)(rawData).call(rawData, (data) => {
    var _context12, _context13, _context15, _context17;
    return {
      ...data,
      startTimeNano: data.startTimeNano.toString(),
      endTimeNano: data.endTimeNano.toString(),
      attributes: (0, import_map2.default)(_context12 = data.attributes).call(_context12, (attribute) => ({
        ...attribute,
        value: JSON.parse(attributeValueMap.get(attribute.id))
      })),
      events: (0, import_map2.default)(_context13 = data.events).call(_context13, (event) => {
        var _context14;
        return {
          ...event,
          startTimeNano: event.startTimeNano.toString(),
          attributes: (0, import_map2.default)(_context14 = event.attributes).call(_context14, (attribute) => ({
            ...attribute,
            value: JSON.parse(attributeValueMap.get(attribute.id))
          }))
        };
      }),
      links: (0, import_map2.default)(_context15 = data.links).call(_context15, (link) => {
        var _context16;
        return {
          ...link,
          attributes: (0, import_map2.default)(_context16 = link.attributes).call(_context16, (attribute) => ({
            ...attribute,
            value: JSON.parse(attributeValueMap.get(attribute.id))
          }))
        };
      }),
      resource: {
        ...data.resource,
        attributes: (0, import_map2.default)(_context17 = data.resource.attributes).call(_context17, (attribute) => ({
          ...attribute,
          value: JSON.parse(attributeValueMap.get(attribute.id))
        }))
      }
    };
  });
  return completeData;
};
const otelSpanDescendants = async ({
  id
}) => {
  var _context18;
  const rawDescendantIDs = await import_db.db.$queryRaw`WITH RECURSIVE span_hierarchy AS (
        SELECT spanId, parentId
        FROM OTelTraceSpan
        WHERE spanId = ${id}
        UNION ALL
        SELECT s.spanId, s.parentId
        FROM OTelTraceSpan s
        JOIN span_hierarchy sh ON s.parentId = sh.spanId
      )
      SELECT spanId
      FROM span_hierarchy;
  `;
  const descendantIDs = (0, import_filter.default)(_context18 = (0, import_map2.default)(rawDescendantIDs).call(rawDescendantIDs, (descendant) => descendant.spanId)).call(_context18, (descendant) => descendant !== id);
  const rawData = await import_db.db.oTelTraceSpan.findMany({
    where: {
      spanId: {
        in: descendantIDs
      }
    },
    orderBy: {
      startTimeNano: "asc"
    },
    include: {
      attributes: true,
      events: {
        include: {
          attributes: true
        }
      },
      links: {
        include: {
          attributes: true
        }
      },
      scope: {
        include: {
          attributes: true
        }
      },
      resource: {
        include: {
          attributes: true
        }
      },
      type: true
    }
  });
  const attributes = await import_db.db.$queryRaw`SELECT id, [value] FROM OTelTraceAttribute;`;
  const attributeValueMap = new import_map.default();
  for (let i = 0; i < attributes.length; i++) {
    attributeValueMap.set(attributes[i].id, attributes[i].value);
  }
  const completeData = (0, import_map2.default)(rawData).call(rawData, (data) => {
    var _context19, _context20, _context22, _context24;
    return {
      ...data,
      startTimeNano: data.startTimeNano.toString(),
      endTimeNano: data.endTimeNano.toString(),
      attributes: (0, import_map2.default)(_context19 = data.attributes).call(_context19, (attribute) => ({
        ...attribute,
        value: JSON.parse(attributeValueMap.get(attribute.id))
      })),
      events: (0, import_map2.default)(_context20 = data.events).call(_context20, (event) => {
        var _context21;
        return {
          ...event,
          startTimeNano: event.startTimeNano.toString(),
          attributes: (0, import_map2.default)(_context21 = event.attributes).call(_context21, (attribute) => ({
            ...attribute,
            value: JSON.parse(attributeValueMap.get(attribute.id))
          }))
        };
      }),
      links: (0, import_map2.default)(_context22 = data.links).call(_context22, (link) => {
        var _context23;
        return {
          ...link,
          attributes: (0, import_map2.default)(_context23 = link.attributes).call(_context23, (attribute) => ({
            ...attribute,
            value: JSON.parse(attributeValueMap.get(attribute.id))
          }))
        };
      }),
      resource: {
        ...data.resource,
        attributes: (0, import_map2.default)(_context24 = data.resource.attributes).call(_context24, (attribute) => ({
          ...attribute,
          value: JSON.parse(attributeValueMap.get(attribute.id))
        }))
      }
    };
  });
  return completeData;
};
const otelTruncateSpans = async () => {
  try {
    await import_db.db.oTelTraceSpan.deleteMany();
  } catch (error) {
    import_logger.logger.error(error);
    return false;
  }
  return true;
};
const otelRetypeSpans = async () => {
  try {
    const ids = await import_db.db.oTelTraceSpan.findMany({
      select: {
        id: true
      }
    });
    for (let i = 0; i < ids.length; i++) {
      await (0, import_opentelemetry.retypeSpan)({
        id: ids[i].id
      });
    }
  } catch (error) {
    import_logger.logger.error(error);
    return false;
  }
  return true;
};
const bigIntMin = (...args) => (0, import_reduce.default)(args).call(args, (m, e) => e < m ? e : m);
const otelTraces = async (args, obj) => {
  const spans = await otelSpans(args, obj);
  const traceIds = new import_set.default();
  for (let i = 0; i < spans.length; i++) {
    traceIds.add(spans[i].traceId);
  }
  const traces = [];
  for (const traceId of traceIds) {
    const traceSpans = (0, import_filter.default)(spans).call(spans, (span) => span.traceId === traceId);
    traces.push({
      id: traceId,
      spans: traceSpans
    });
  }
  return (0, import_sort.default)(traces).call(traces, (a, b) => {
    var _context25, _context26;
    const aStartTime = bigIntMin(...(0, import_map2.default)(_context25 = a.spans).call(_context25, (span) => BigInt(span.startTimeNano)));
    const bStartTime = bigIntMin(...(0, import_map2.default)(_context26 = b.spans).call(_context26, (span) => BigInt(span.startTimeNano)));
    return aStartTime > bStartTime ? -1 : aStartTime < bStartTime ? 1 : 0;
  });
};
const otelTrace = async ({
  id
}) => {
  const spans = await otelSpans();
  const traceSpans = (0, import_filter.default)(spans).call(spans, (span) => span.traceId === id);
  return {
    id,
    spans: traceSpans
  };
};
const buildTreeEntry = (spanId, spans) => {
  const span = (0, import_find.default)(spans).call(spans, (span2) => span2.spanId === spanId);
  const children = (0, import_filter.default)(spans).call(spans, (span2) => span2.parentId === spanId);
  if (children.length === 0) {
    return {
      name: span.name,
      durationMilli: Number(BigInt(span.endTimeNano) - BigInt(span.startTimeNano)) / 1e6
    };
  }
  return {
    name: span.name,
    children: (0, import_map2.default)(children).call(children, (child) => buildTreeEntry(child.spanId, spans)),
    durationMilli: Number(BigInt(span.endTimeNano) - BigInt(span.startTimeNano)) / 1e6
  };
};
const otelTraceTreeMapData = async ({
  id
}, obj) => {
  var _context27;
  const trace = await otelTrace({
    id
  }, obj);
  const _rootSpans = (0, import_filter.default)(_context27 = trace.spans).call(_context27, (span) => span.parentId === null);
  const data = {
    name: trace.id,
    children: []
  };
  for (let i = 0; i < _rootSpans.length; i++) {
    data.children.push(buildTreeEntry(_rootSpans[i].spanId, trace.spans));
  }
  return data;
};
const otelSpanCount = async () => {
  return await import_db.db.oTelTraceSpan.count();
};
const otelTraceCount = async () => {
  return (await import_db.db.oTelTraceSpan.findMany({
    distinct: ["traceId"]
  })).length;
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  otelRetypeSpans,
  otelSpan,
  otelSpanAncestors,
  otelSpanCount,
  otelSpanDescendants,
  otelSpans,
  otelTrace,
  otelTraceCount,
  otelTraceTreeMapData,
  otelTraces,
  otelTruncateSpans
});
//# sourceMappingURL=opentelemetry.js.map
