/**
 * 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 import_pdf = require("@langchain/community/document_loaders/fs/pdf");
var import_pptx = require("@langchain/community/document_loaders/fs/pptx");
var import_docx = require("@langchain/community/document_loaders/fs/docx");
var import_node_worker_threads = require("node:worker_threads");
var import_text = require("./vendor/langchain/document_loaders/fs/text");
var _a;
const loadPdf = async (blob) => {
  const loader = new import_pdf.PDFLoader(blob);
  return loader.load();
};
const loadDoc = async (blob, type) => {
  const loader = new import_docx.DocxLoader(blob, { type });
  return loader.load();
};
const loadPpt = async (blob) => {
  const loader = new import_pptx.PPTXLoader(blob);
  return loader.load();
};
const loadTxt = async (blob) => {
  const loader = new import_text.TextLoader(blob);
  return loader.load();
};
const loadByExtname = async (payload) => {
  const blob = new Blob([Buffer.from(payload.buffer)], { type: payload.mimeType ?? "application/octet-stream" });
  switch (payload.extname) {
    case ".pdf":
      return loadPdf(blob);
    case ".ppt":
    case ".pptx":
      return loadPpt(blob);
    case ".doc":
      return loadDoc(blob, "doc");
    case ".docx":
      return loadDoc(blob, "docx");
    case ".txt":
      return loadTxt(blob);
    default:
      return [];
  }
};
(_a = import_node_worker_threads.parentPort) == null ? void 0 : _a.on("message", async (payload) => {
  var _a2;
  try {
    const documents = await loadByExtname(payload);
    const response = {
      documents: documents.map((doc) => ({
        pageContent: doc.pageContent,
        metadata: doc.metadata,
        id: doc.id
      }))
    };
    import_node_worker_threads.parentPort.postMessage(response);
  } catch (error) {
    const response = {
      error: String((error == null ? void 0 : error.stack) || error)
    };
    (_a2 = import_node_worker_threads.parentPort) == null ? void 0 : _a2.postMessage(response);
  }
});
