/**
 * This file is part of the NocoBase (R) project.
 * Copyright (c) 2020-2024 NocoBase Co., Ltd.
 * Authors: NocoBase Team.
 *
 * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
 * For more information, please refer to: https://www.nocobase.com/agreement.
 */

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 utils_exports = {};
__export(utils_exports, {
  encodeFile: () => encodeFile,
  encodeLocalFile: () => encodeLocalFile,
  parseResponseMessage: () => parseResponseMessage,
  parseVariables: () => parseVariables,
  sendSSEError: () => sendSSEError,
  stripToolCallTags: () => stripToolCallTags
});
module.exports = __toCommonJS(utils_exports);
var import_path = __toESM(require("path"));
var import_fs = __toESM(require("fs"));
var import_axios = __toESM(require("axios"));
var import_utils = require("@nocobase/utils");
function sendSSEError(ctx, error, errorName) {
  const body = typeof error === "string" ? error : error.message || "Unknown error";
  if (!ctx.res.headersSent) {
    ctx.set({
      "Content-Type": "text/event-stream",
      "Cache-Control": "no-cache",
      Connection: "keep-alive"
    });
    ctx.status = 200;
  }
  ctx.res.write(`data: ${JSON.stringify({ type: "error", body, errorName })}

`);
  ctx.res.end();
}
function stripToolCallTags(content) {
  if (typeof content !== "string") {
    return content;
  }
  return content.replace(/<[|｜]tool▁(?:calls▁begin|calls▁end|call▁begin|call▁end|sep)[|｜]>/g, "");
}
function parseResponseMessage(row) {
  const { content: rawContent, messageId, metadata, role, toolCalls, attachments, workContext } = row;
  const content = {
    ...rawContent ?? {},
    content: stripToolCallTags(rawContent == null ? void 0 : rawContent.content),
    messageId,
    metadata,
    attachments,
    workContext
  };
  if (toolCalls) {
    content.tool_calls = toolCalls;
  }
  return {
    key: messageId,
    content,
    role
  };
}
async function encodeLocalFile(url) {
  url = import_path.default.join(process.cwd(), url);
  const data = await import_fs.default.promises.readFile(url);
  return Buffer.from(data).toString("base64");
}
async function encodeFile(ctx, url) {
  if (!url.startsWith("http")) {
    return encodeLocalFile(url);
  }
  const referer = ctx.get("referer") || "";
  const ua = ctx.get("user-agent") || "";
  ctx.log.trace("llm message encode file", { url, referer, ua });
  const response = await import_axios.default.get(url, {
    responseType: "arraybuffer",
    headers: {
      referer,
      "User-Agent": ua
    }
  });
  return Buffer.from(response.data).toString("base64");
}
async function getUser(ctx, fields) {
  const userFields = fields.filter((f) => f && ctx.db.getFieldByPath("users." + f));
  if (!ctx.state.currentUser) {
    return;
  }
  if (!userFields.length) {
    return;
  }
  const user = await ctx.db.getRepository("users").findOne({
    filterByTk: ctx.state.currentUser.id,
    fields: userFields
  });
  return user;
}
async function parseVariables(ctx, value) {
  const re = /\{\{\$user\.([^}]+)\}\}/g;
  const userFieldsSet = /* @__PURE__ */ new Set();
  const matches = value.matchAll(re);
  for (const match of matches) {
    const key = match[1].trim();
    userFieldsSet.add(key);
  }
  const $user = await getUser(ctx, [...userFieldsSet.values()]);
  const dateVariables = (0, import_utils.getDateVars)();
  const $nDate = {};
  for (const [key, value2] of Object.entries(dateVariables)) {
    if (typeof value2 === "function") {
      $nDate[key] = value2({
        timezone: ctx.get("x-timezone"),
        now: (/* @__PURE__ */ new Date()).toISOString()
      });
    } else {
      $nDate[key] = value2;
    }
  }
  return (0, import_utils.parse)(value)({
    $user,
    $nRole: ctx.state.currentRole === "__union__" ? ctx.state.currentRoles : ctx.state.currentRole,
    $nLang: ctx.getCurrentLocale(),
    $nDate
  });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  encodeFile,
  encodeLocalFile,
  parseResponseMessage,
  parseVariables,
  sendSSEError,
  stripToolCallTags
});
