var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
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
));

// node_modules/secure-json-parse/index.js
var require_secure_json_parse = __commonJS({
  "node_modules/secure-json-parse/index.js"(exports, module) {
    "use strict";
    var hasBuffer = typeof Buffer !== "undefined";
    var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
    var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
    function _parse(text, reviver, options) {
      if (options == null) {
        if (reviver !== null && typeof reviver === "object") {
          options = reviver;
          reviver = void 0;
        }
      }
      if (hasBuffer && Buffer.isBuffer(text)) {
        text = text.toString();
      }
      if (text && text.charCodeAt(0) === 65279) {
        text = text.slice(1);
      }
      const obj = JSON.parse(text, reviver);
      if (obj === null || typeof obj !== "object") {
        return obj;
      }
      const protoAction = options && options.protoAction || "error";
      const constructorAction = options && options.constructorAction || "error";
      if (protoAction === "ignore" && constructorAction === "ignore") {
        return obj;
      }
      if (protoAction !== "ignore" && constructorAction !== "ignore") {
        if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
          return obj;
        }
      } else if (protoAction !== "ignore" && constructorAction === "ignore") {
        if (suspectProtoRx.test(text) === false) {
          return obj;
        }
      } else {
        if (suspectConstructorRx.test(text) === false) {
          return obj;
        }
      }
      return filter(obj, { protoAction, constructorAction, safe: options && options.safe });
    }
    function filter(obj, { protoAction = "error", constructorAction = "error", safe } = {}) {
      let next = [obj];
      while (next.length) {
        const nodes = next;
        next = [];
        for (const node of nodes) {
          if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) {
            if (safe === true) {
              return null;
            } else if (protoAction === "error") {
              throw new SyntaxError("Object contains forbidden prototype property");
            }
            delete node.__proto__;
          }
          if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
            if (safe === true) {
              return null;
            } else if (constructorAction === "error") {
              throw new SyntaxError("Object contains forbidden prototype property");
            }
            delete node.constructor;
          }
          for (const key in node) {
            const value = node[key];
            if (value && typeof value === "object") {
              next.push(value);
            }
          }
        }
      }
      return obj;
    }
    function parse(text, reviver, options) {
      const stackTraceLimit = Error.stackTraceLimit;
      Error.stackTraceLimit = 0;
      try {
        return _parse(text, reviver, options);
      } finally {
        Error.stackTraceLimit = stackTraceLimit;
      }
    }
    function safeParse(text, reviver) {
      const stackTraceLimit = Error.stackTraceLimit;
      Error.stackTraceLimit = 0;
      try {
        return _parse(text, reviver, { safe: true });
      } catch (_e) {
        return null;
      } finally {
        Error.stackTraceLimit = stackTraceLimit;
      }
    }
    module.exports = parse;
    module.exports.default = parse;
    module.exports.parse = parse;
    module.exports.safeParse = safeParse;
    module.exports.scan = filter;
  }
});

// node_modules/@ai-sdk/provider-utils/dist/index.mjs
import { customAlphabet } from "nanoid/non-secure";
var import_secure_json_parse = __toESM(require_secure_json_parse(), 1);
var generateId = customAlphabet(
  "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
  7
);
function convertUint8ArrayToBase64(array) {
  let latin1string = "";
  for (let i = 0; i < array.length; i++) {
    latin1string += String.fromCodePoint(array[i]);
  }
  return globalThis.btoa(latin1string);
}

// src/utils.ts
import { z as z2 } from "zod";

// src/server/types/tracer.generated.ts
import { z } from "zod";
var chatRoleSchema = z.union([
  z.literal("system"),
  z.literal("user"),
  z.literal("assistant"),
  z.literal("function"),
  z.literal("tool"),
  z.literal("unknown")
]);
var functionCallSchema = z.object({
  name: z.string().optional(),
  arguments: z.string().optional()
});
var toolCallSchema = z.object({
  id: z.string(),
  type: z.string(),
  function: functionCallSchema
});
var rAGChunkSchema = z.object({
  document_id: z.string().optional().nullable(),
  chunk_id: z.string().optional().nullable(),
  content: z.union([z.string(), z.record(z.any()), z.array(z.any())])
});
var chatRichContentSchema = z.union([
  z.object({
    type: z.literal("text"),
    text: z.string().optional()
  }),
  z.object({
    type: z.literal("image_url"),
    image_url: z.object({
      url: z.string(),
      detail: z.union([z.literal("auto"), z.literal("low"), z.literal("high")]).optional()
    }).optional()
  }),
  z.object({
    type: z.literal("tool_call"),
    toolName: z.string().optional(),
    toolCallId: z.string().optional(),
    args: z.string().optional()
  }),
  z.object({
    type: z.literal("tool_result"),
    toolName: z.string().optional(),
    toolCallId: z.string().optional(),
    result: z.any().optional()
  })
]);
var typedValueTextSchema = z.object({
  type: z.literal("text"),
  value: z.string()
});
var typedValueRawSchema = z.object({
  type: z.literal("raw"),
  value: z.string()
});
var jSONSerializableSchema = z.union([
  z.string(),
  z.number(),
  z.boolean(),
  z.record(z.any()),
  z.array(z.any())
]).nullable();
var typedValueJsonSchema = z.object({
  type: z.literal("json"),
  value: jSONSerializableSchema
});
var moneySchema = z.object({
  currency: z.string(),
  amount: z.number()
});
var evaluationResultSchema = z.object({
  status: z.union([
    z.literal("processed"),
    z.literal("skipped"),
    z.literal("error")
  ]),
  passed: z.boolean().optional().nullable(),
  score: z.number().optional().nullable(),
  label: z.string().optional().nullable(),
  details: z.string().optional().nullable(),
  cost: moneySchema.optional().nullable()
});
var typedValueGuardrailResultSchema = z.object({
  type: z.literal("guardrail_result"),
  value: evaluationResultSchema
});
var typedValueEvaluationResultSchema = z.object({
  type: z.literal("evaluation_result"),
  value: evaluationResultSchema
});
var errorCaptureSchema = z.object({
  has_error: z.literal(true),
  message: z.string(),
  stacktrace: z.array(z.string())
});
var spanMetricsSchema = z.object({
  prompt_tokens: z.number().optional().nullable(),
  completion_tokens: z.number().optional().nullable(),
  tokens_estimated: z.boolean().optional().nullable(),
  cost: z.number().optional().nullable()
});
var reservedSpanParamsSchema = z.object({
  frequency_penalty: z.number().optional().nullable(),
  logit_bias: z.record(z.number()).optional().nullable(),
  logprobs: z.boolean().optional().nullable(),
  top_logprobs: z.number().optional().nullable(),
  max_tokens: z.number().optional().nullable(),
  n: z.number().optional().nullable(),
  presence_penalty: z.number().optional().nullable(),
  seed: z.number().optional().nullable(),
  stop: z.union([z.string(), z.array(z.string())]).optional().nullable(),
  stream: z.boolean().optional().nullable(),
  temperature: z.number().optional().nullable(),
  top_p: z.number().optional().nullable(),
  tools: z.array(z.record(z.any())).optional().nullable(),
  tool_choice: z.union([z.record(z.any()), z.string()]).optional().nullable(),
  parallel_tool_calls: z.boolean().optional().nullable(),
  functions: z.array(z.record(z.any())).optional().nullable(),
  user: z.string().optional().nullable()
});
var spanParamsSchema = reservedSpanParamsSchema.and(z.record(z.any()));
var spanTimestampsSchema = z.object({
  started_at: z.number(),
  first_token_at: z.number().optional().nullable(),
  finished_at: z.number()
});
var spanTypesSchema = z.union([
  z.literal("span"),
  z.literal("llm"),
  z.literal("chain"),
  z.literal("tool"),
  z.literal("agent"),
  z.literal("rag"),
  z.literal("guardrail"),
  z.literal("evaluation"),
  z.literal("workflow"),
  z.literal("component"),
  z.literal("module"),
  z.literal("server"),
  z.literal("client"),
  z.literal("producer"),
  z.literal("consumer"),
  z.literal("task"),
  z.literal("unknown")
]);
var traceInputSchema = z.object({
  value: z.string(),
  satisfaction_score: z.number().optional()
});
var traceOutputSchema = z.object({
  value: z.string()
});
var primitiveTypeSchema = z.union([z.string(), z.number(), z.boolean(), z.undefined()]).nullable();
var reservedTraceMetadataSchema = z.object({
  thread_id: z.string().optional().nullable(),
  user_id: z.string().optional().nullable(),
  customer_id: z.string().optional().nullable(),
  labels: z.array(z.string()).optional().nullable(),
  topic_id: z.string().optional().nullable(),
  subtopic_id: z.string().optional().nullable(),
  sdk_version: z.string().optional().nullable(),
  sdk_language: z.string().optional().nullable()
});
var customMetadataSchema = z.record(
  z.union([
    primitiveTypeSchema,
    z.array(primitiveTypeSchema),
    z.record(primitiveTypeSchema),
    z.record(z.record(primitiveTypeSchema))
  ])
);
var traceMetadataSchema = reservedTraceMetadataSchema.and(customMetadataSchema);
var eventSchema = z.object({
  event_id: z.string(),
  event_type: z.string(),
  project_id: z.string(),
  metrics: z.record(z.number()),
  event_details: z.record(z.string()),
  trace_id: z.string(),
  timestamps: z.object({
    started_at: z.number(),
    inserted_at: z.number(),
    updated_at: z.number()
  })
});
var elasticSearchEventSchema = eventSchema.omit({ metrics: true, event_details: true }).and(
  z.object({
    metrics: z.array(
      z.object({
        key: z.string(),
        value: z.number()
      })
    ),
    event_details: z.array(
      z.object({
        key: z.string(),
        value: z.string()
      })
    )
  })
);
var evaluationStatusSchema = z.union([
  z.literal("scheduled"),
  z.literal("in_progress"),
  z.literal("error"),
  z.literal("skipped"),
  z.literal("processed")
]);
var trackEventRESTParamsValidatorSchema = eventSchema.omit({
  event_id: true,
  project_id: true,
  timestamps: true,
  event_details: true
}).and(
  z.object({
    event_id: z.string().optional(),
    event_details: z.record(z.string()).optional(),
    timestamp: z.number().optional()
  })
);
var contextsSchema = z.object({
  traceId: z.string(),
  contexts: z.array(rAGChunkSchema)
});
var chatMessageSchema = z.object({
  role: chatRoleSchema.optional(),
  content: z.union([z.string(), z.array(chatRichContentSchema)]).optional().nullable(),
  function_call: functionCallSchema.optional().nullable(),
  tool_calls: z.array(toolCallSchema).optional().nullable(),
  tool_call_id: z.string().optional().nullable(),
  name: z.string().optional().nullable()
});
var typedValueChatMessagesSchema = z.object({
  type: z.literal("chat_messages"),
  value: z.array(chatMessageSchema)
});
var spanInputOutputSchema = z.lazy(
  () => z.union([
    typedValueTextSchema,
    typedValueChatMessagesSchema,
    typedValueGuardrailResultSchema,
    typedValueEvaluationResultSchema,
    typedValueJsonSchema,
    typedValueRawSchema,
    z.object({
      type: z.literal("list"),
      value: z.array(spanInputOutputSchema)
    })
  ])
);
var baseSpanSchema = z.object({
  span_id: z.string(),
  parent_id: z.string().optional().nullable(),
  trace_id: z.string(),
  type: spanTypesSchema,
  name: z.string().optional().nullable(),
  input: spanInputOutputSchema.optional().nullable(),
  output: spanInputOutputSchema.optional().nullable(),
  error: errorCaptureSchema.optional().nullable(),
  timestamps: spanTimestampsSchema,
  metrics: spanMetricsSchema.optional().nullable(),
  params: spanParamsSchema.optional().nullable()
});
var lLMSpanSchema = baseSpanSchema.extend({
  type: z.literal("llm"),
  vendor: z.string().optional().nullable(),
  model: z.string().optional().nullable()
});
var rAGSpanSchema = baseSpanSchema.extend({
  type: z.literal("rag"),
  contexts: z.array(rAGChunkSchema)
});
var spanSchema = z.union([
  lLMSpanSchema,
  rAGSpanSchema,
  baseSpanSchema
]);
var spanInputOutputValidatorSchema = spanInputOutputSchema.and(
  z.object({
    value: z.any()
  })
);
var spanValidatorSchema = z.union([
  lLMSpanSchema.omit({ input: true, output: true, params: true }),
  rAGSpanSchema.omit({ input: true, output: true, params: true }),
  baseSpanSchema.omit({ input: true, output: true, params: true })
]).and(
  z.object({
    input: spanInputOutputValidatorSchema.optional().nullable(),
    output: spanInputOutputValidatorSchema.optional().nullable(),
    params: z.record(z.any()).optional().nullable()
  })
);
var evaluationSchema = z.object({
  evaluation_id: z.string(),
  evaluator_id: z.string(),
  span_id: z.string().optional().nullable(),
  name: z.string(),
  type: z.string().optional().nullable(),
  is_guardrail: z.boolean().optional().nullable(),
  status: evaluationStatusSchema,
  passed: z.boolean().optional().nullable(),
  score: z.number().optional().nullable(),
  label: z.string().optional().nullable(),
  details: z.string().optional().nullable(),
  error: errorCaptureSchema.optional().nullable(),
  retries: z.number().optional().nullable(),
  timestamps: z.object({
    inserted_at: z.number().optional().nullable(),
    started_at: z.number().optional().nullable(),
    finished_at: z.number().optional().nullable(),
    updated_at: z.number().optional().nullable()
  })
});
var rESTEvaluationSchema = evaluationSchema.omit({
  evaluation_id: true,
  evaluator_id: true,
  status: true,
  timestamps: true,
  retries: true
}).and(
  z.object({
    evaluation_id: z.string().optional().nullable(),
    evaluator_id: z.string().optional().nullable(),
    status: z.union([
      z.literal("processed"),
      z.literal("skipped"),
      z.literal("error")
    ]).optional().nullable(),
    timestamps: z.object({
      started_at: z.number().optional().nullable(),
      finished_at: z.number().optional().nullable()
    }).optional().nullable()
  })
);
var collectorRESTParamsSchema = z.object({
  trace_id: z.union([z.string(), z.undefined()]).optional().nullable(),
  spans: z.array(spanSchema),
  metadata: z.object({
    user_id: z.union([z.string(), z.undefined()]).optional().nullable(),
    thread_id: z.union([z.string(), z.undefined()]).optional().nullable(),
    customer_id: z.union([z.string(), z.undefined()]).optional().nullable(),
    labels: z.union([z.array(z.string()), z.undefined()]).optional().nullable(),
    sdk_version: z.union([z.string(), z.undefined()]).optional().nullable(),
    sdk_language: z.union([z.string(), z.undefined()]).optional().nullable()
  }).and(customMetadataSchema).optional(),
  expected_output: z.string().optional().nullable(),
  evaluations: z.array(rESTEvaluationSchema).optional()
});
var collectorRESTParamsValidatorSchema = collectorRESTParamsSchema.omit({ spans: true });
var traceSchema = z.object({
  trace_id: z.string(),
  project_id: z.string(),
  metadata: traceMetadataSchema,
  timestamps: z.object({
    started_at: z.number(),
    inserted_at: z.number(),
    updated_at: z.number()
  }),
  input: traceInputSchema.optional(),
  output: traceOutputSchema.optional(),
  contexts: z.array(rAGChunkSchema).optional(),
  expected_output: z.object({
    value: z.string()
  }).optional(),
  metrics: z.object({
    first_token_ms: z.number().optional().nullable(),
    total_time_ms: z.number().optional().nullable(),
    prompt_tokens: z.number().optional().nullable(),
    completion_tokens: z.number().optional().nullable(),
    total_cost: z.number().optional().nullable(),
    tokens_estimated: z.boolean().optional().nullable()
  }).optional(),
  error: errorCaptureSchema.optional().nullable(),
  indexing_md5s: z.array(z.string()).optional(),
  events: z.array(eventSchema).optional(),
  evaluations: z.array(evaluationSchema).optional()
});
var traceWithSpansSchema = traceSchema.and(
  z.object({
    spans: z.array(spanSchema)
  })
);

// src/utils.ts
var convertImageToUrl = (image, mimeType) => {
  try {
    return image instanceof URL ? image.toString() : typeof image === "string" ? image : `data:${mimeType != null ? mimeType : "image/jpeg"};base64,${convertUint8ArrayToBase64(
      image
    )}`;
  } catch (e) {
    console.error("[LangWatch] error converting vercel ui image to url:", e);
    return "";
  }
};
function convertFromVercelAIMessages(messages) {
  var _a;
  const lwMessages = [];
  for (const { role, content } of messages) {
    switch (role) {
      case "system": {
        lwMessages.push({ role: "system", content });
        break;
      }
      case "user": {
        if (Array.isArray(content) && content.length === 1 && ((_a = content[0]) == null ? void 0 : _a.type) === "text") {
          lwMessages.push({ role: "user", content: content[0].text });
          break;
        }
        lwMessages.push({
          role: "user",
          content: Array.isArray(content) ? content.map((part) => {
            switch (part.type) {
              case "text": {
                return { type: "text", text: part.text };
              }
              case "image": {
                return {
                  type: "image_url",
                  image_url: {
                    url: convertImageToUrl(part.image, part.mimeType)
                  }
                };
              }
              default: {
                return part;
              }
            }
          }) : content
        });
        break;
      }
      case "assistant": {
        let text = "";
        const toolCalls = [];
        if (Array.isArray(content)) {
          for (const part of content) {
            switch (part.type) {
              case "text": {
                text += part.text;
                break;
              }
              case "tool-call": {
                toolCalls.push({
                  id: part.toolCallId,
                  type: "function",
                  function: {
                    name: part.toolName,
                    arguments: JSON.stringify(part.args)
                  }
                });
                break;
              }
              default: {
                const _exhaustiveCheck = part;
                throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
              }
            }
          }
        } else {
          text = content;
        }
        lwMessages.push({
          role: "assistant",
          content: text,
          tool_calls: toolCalls.length > 0 ? toolCalls : void 0
        });
        break;
      }
      case "tool": {
        for (const toolResponse of content) {
          lwMessages.push({
            role: "tool",
            tool_call_id: toolResponse.toolCallId,
            content: JSON.stringify(toolResponse.result)
          });
        }
        break;
      }
      default: {
        const _exhaustiveCheck = role;
        throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
      }
    }
  }
  return lwMessages;
}
var captureError = (error) => {
  if (error && typeof error === "object" && "has_error" in error && "message" in error && "stacktrace" in error) {
    return error;
  } else if (error instanceof Error) {
    return {
      has_error: true,
      message: error.message,
      stacktrace: error.stack ? error.stack.split("\n") : []
    };
  } else if (typeof error === "object" && error !== null) {
    const err = error;
    const message = typeof err.message === "string" ? err.message : "An unknown error occurred";
    const stacktrace = typeof err.stack === "string" ? err.stack.split("\n") : Array.isArray(err.stack) && err.stack.length > 0 && typeof err.stack[0] === "string" ? err.stack : ["No stack trace available"];
    return {
      has_error: true,
      message,
      stacktrace
    };
  } else {
    return {
      has_error: true,
      message: String(error),
      stacktrace: []
    };
  }
};
var autoconvertTypedValues = (value) => {
  if (typeof value === "string") {
    return { type: "text", value };
  }
  const chatMessages = z2.array(chatMessageSchema).safeParse(value);
  if (Array.isArray(value) && chatMessages.success) {
    return {
      type: "chat_messages",
      value: chatMessages.data
    };
  }
  try {
    JSON.stringify(value);
    return { type: "json", value };
  } catch (e) {
    return { type: "raw", value };
  }
};

export {
  __spreadValues,
  __spreadProps,
  reservedSpanParamsSchema,
  reservedTraceMetadataSchema,
  spanSchema,
  collectorRESTParamsSchema,
  convertFromVercelAIMessages,
  captureError,
  autoconvertTypedValues
};
//# sourceMappingURL=chunk-FWBCQQYZ.mjs.map