export { ExportConfigError, ExportDataError, ExportFileError, ExportServiceError } from '../chunk-7XLFSPDG.mjs';
import '../chunk-BJTO5JO5.mjs';

// src/universalExport/constants.ts
var UNIVERSAL_EXPORT_VERSION = "1.0.0";
var UNIVERSAL_EXPORT_NAME = "@lyricnote/universal-export";
var DEFAULT_EXPORT_FORMAT = "csv";
var DEFAULT_CSV_DELIMITER = ",";
var DEFAULT_ENCODING = "utf-8";
var DEFAULT_ADD_BOM = true;
var DEFAULT_MAX_FILE_SIZE = 100 * 1024 * 1024;
var DEFAULT_MAX_ROWS = 1e5;
var DEFAULT_MAX_CONCURRENT_EXPORTS = 5;
var DEFAULT_EXPORT_TIMEOUT = 3e5;
var DEFAULT_CONFIG_CACHE_TTL = 3600;
var DEFAULT_RESULT_CACHE_TTL = 1800;
var EXPORT_FORMAT_EXTENSIONS = {
  csv: "csv",
  excel: "xlsx",
  json: "json"
};
var EXPORT_FORMAT_MIME_TYPES = {
  csv: "text/csv; charset=utf-8",
  excel: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  json: "application/json; charset=utf-8"
};
var API_BASE_PATH = "/api/universal-export";
var API_ENDPOINTS = {
  /** 获取配置列表 */
  GET_CONFIGS: `${API_BASE_PATH}/configs`,
  /** 创建配置 */
  CREATE_CONFIG: `${API_BASE_PATH}/configs`,
  /** 更新配置 */
  UPDATE_CONFIG: (configId) => `${API_BASE_PATH}/configs/${configId}`,
  /** 删除配置 */
  DELETE_CONFIG: (configId) => `${API_BASE_PATH}/configs/${configId}`,
  /** 触发导出 */
  EXPORT_DATA: `${API_BASE_PATH}/export`,
  /** 查询导出进度 */
  GET_PROGRESS: (exportId) => `${API_BASE_PATH}/export/${exportId}/progress`,
  /** 下载导出文件 */
  DOWNLOAD_FILE: (exportId) => `${API_BASE_PATH}/export/${exportId}/download`
};
var ERROR_CODES = {
  /** 导出配置错误 */
  EXPORT_CONFIG_ERROR: "EXPORT_CONFIG_ERROR",
  /** 导出数据错误 */
  EXPORT_DATA_ERROR: "EXPORT_DATA_ERROR",
  /** 导出文件错误 */
  EXPORT_FILE_ERROR: "EXPORT_FILE_ERROR",
  /** 网络错误 */
  NETWORK_ERROR: "NETWORK_ERROR",
  /** 超时错误 */
  TIMEOUT_ERROR: "TIMEOUT_ERROR",
  /** 未授权 */
  UNAUTHORIZED: "UNAUTHORIZED",
  /** 服务器错误 */
  SERVER_ERROR: "SERVER_ERROR"
};

// src/universalExport/utils.ts
function generateExportFileName(template, format) {
  const now = /* @__PURE__ */ new Date();
  const dateStr = now.toISOString().split("T")[0] || "";
  const timeStr = (now.toTimeString().split(" ")[0] || "").replace(/:/g, "-");
  const extension = EXPORT_FORMAT_EXTENSIONS[format];
  return template.replace("{date}", dateStr).replace("{time}", timeStr).replace("{timestamp}", now.getTime().toString()) + `.${extension}`;
}
function validateFileName(fileName) {
  const invalidChars = /[<>:"|?*\/\\]/;
  if (invalidChars.test(fileName)) {
    return false;
  }
  if (fileName.length === 0 || fileName.length > 255) {
    return false;
  }
  return true;
}
function sanitizeFileName(fileName) {
  return fileName.replace(/[<>:"|?*\/\\]/g, "_").substring(0, 255);
}
function escapeCSVField(value, delimiter = ",") {
  const valueStr = String(value || "");
  if (valueStr.includes(delimiter) || valueStr.includes('"') || valueStr.includes("\n")) {
    return `"${valueStr.replace(/"/g, '""')}"`;
  }
  return valueStr;
}
function parseCSVField(field) {
  if (field.startsWith('"') && field.endsWith('"')) {
    return field.slice(1, -1).replace(/""/g, '"');
  }
  return field;
}
var DEFAULT_FORMATTERS = {
  // 日期格式化
  date: (value) => {
    if (!value) return "";
    const date = new Date(value);
    if (isNaN(date.getTime())) return String(value);
    return date.toISOString().split("T")[0] || "";
  },
  // 时间格式化
  datetime: (value) => {
    if (!value) return "";
    const date = new Date(value);
    if (isNaN(date.getTime())) return String(value);
    return date.toLocaleString("zh-CN");
  },
  // 数字格式化
  number: (value) => {
    if (value === null || value === void 0) return "";
    return String(value);
  },
  // 货币格式化
  currency: (value) => {
    if (value === null || value === void 0) return "";
    return `\xA5${Number(value).toFixed(2)}`;
  },
  // 百分比格式化
  percentage: (value) => {
    if (value === null || value === void 0) return "";
    return `${(Number(value) * 100).toFixed(2)}%`;
  },
  // 布尔值格式化
  boolean: (value) => {
    if (value === null || value === void 0) return "";
    return value ? "\u662F" : "\u5426";
  },
  // 数组格式化
  array: (value) => {
    if (!Array.isArray(value)) return "";
    return value.join(", ");
  },
  // 对象格式化
  object: (value) => {
    if (!value || typeof value !== "object") return "";
    return JSON.stringify(value);
  }
};
function applyFormatter(value, formatter, type) {
  if (formatter) {
    return formatter(value);
  }
  if (type && DEFAULT_FORMATTERS[type]) {
    return DEFAULT_FORMATTERS[type](value);
  }
  return String(value || "");
}
function validateExportConfig(config) {
  const errors = [];
  if (!config.name || config.name.trim() === "") {
    errors.push("\u914D\u7F6E\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A");
  }
  if (!config.fields || !Array.isArray(config.fields) || config.fields.length === 0) {
    errors.push("\u81F3\u5C11\u9700\u8981\u5B9A\u4E49\u4E00\u4E2A\u5B57\u6BB5");
  }
  if (config.fields) {
    const enabledFields = config.fields.filter((f) => f.enabled);
    if (enabledFields.length === 0) {
      errors.push("\u81F3\u5C11\u9700\u8981\u542F\u7528\u4E00\u4E2A\u5B57\u6BB5");
    }
    const keys = config.fields.map((f) => f.key);
    const uniqueKeys = new Set(keys);
    if (keys.length !== uniqueKeys.size) {
      errors.push("\u5B57\u6BB5\u952E\u540D\u5FC5\u987B\u552F\u4E00");
    }
  }
  return {
    valid: errors.length === 0,
    errors
  };
}
function validateExportRequest(request) {
  const errors = [];
  if (!request.configId) {
    errors.push("\u5BFC\u51FA\u914D\u7F6EID\u4E0D\u80FD\u4E3A\u7A7A");
  }
  if (!request.dataSource) {
    errors.push("\u6570\u636E\u6E90\u4E0D\u80FD\u4E3A\u7A7A");
  }
  return {
    valid: errors.length === 0,
    errors
  };
}
function formatFileSize(bytes) {
  if (bytes === 0) return "0 B";
  const units = ["B", "KB", "MB", "GB", "TB"];
  const k = 1024;
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${(bytes / Math.pow(k, i)).toFixed(2)} ${units[i]}`;
}
function formatDuration(milliseconds) {
  if (milliseconds < 1e3) {
    return `${milliseconds}ms`;
  }
  const seconds = Math.floor(milliseconds / 1e3);
  if (seconds < 60) {
    return `${seconds}\u79D2`;
  }
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  if (minutes < 60) {
    return remainingSeconds > 0 ? `${minutes}\u5206${remainingSeconds}\u79D2` : `${minutes}\u5206\u949F`;
  }
  const hours = Math.floor(minutes / 60);
  const remainingMinutes = minutes % 60;
  return remainingMinutes > 0 ? `${hours}\u5C0F\u65F6${remainingMinutes}\u5206\u949F` : `${hours}\u5C0F\u65F6`;
}
function estimateEndTime(startTime, processedRows, totalRows) {
  if (processedRows === 0 || totalRows === 0) {
    return void 0;
  }
  const elapsed = Date.now() - startTime.getTime();
  const avgTimePerRow = elapsed / processedRows;
  const remainingRows = totalRows - processedRows;
  const remainingTime = avgTimePerRow * remainingRows;
  return new Date(Date.now() + remainingTime);
}
function getNestedValue(obj, path) {
  return path.split(".").reduce((current, key) => {
    return current && current[key] !== void 0 ? current[key] : null;
  }, obj);
}
function setNestedValue(obj, path, value) {
  const keys = path.split(".");
  const lastKey = keys.pop();
  if (!lastKey) return;
  const target = keys.reduce((current, key) => {
    if (!current[key] || typeof current[key] !== "object") {
      current[key] = {};
    }
    return current[key];
  }, obj);
  target[lastKey] = value;
}
function createExportError(code, message, details) {
  return {
    code,
    message,
    details,
    timestamp: /* @__PURE__ */ new Date()
  };
}
function formatErrorMessage(error) {
  if (error instanceof Error) {
    return error.message;
  }
  if (typeof error === "string") {
    return error;
  }
  return "\u672A\u77E5\u9519\u8BEF";
}

// src/universalExport/client.ts
var UniversalExportClient = class {
  constructor(config = {}) {
    this.config = {
      baseUrl: config.baseUrl || "",
      timeout: config.timeout || 3e4,
      headers: config.headers || {}
    };
  }
  // ============= 配置管理API =============
  /**
   * 获取模块的导出配置列表
   */
  async getConfigsByModule(moduleId, businessId) {
    const params = new URLSearchParams({ moduleId });
    if (businessId) {
      params.append("businessId", businessId);
    }
    const url = `${this.config.baseUrl}${API_ENDPOINTS.GET_CONFIGS}?${params}`;
    try {
      const response = await this.fetchWithTimeout(url, {
        method: "GET",
        headers: this.getHeaders()
      });
      if (!response.ok) {
        throw new Error(`\u83B7\u53D6\u914D\u7F6E\u5931\u8D25: ${response.statusText}`);
      }
      const data = await response.json();
      return this.transformConfigsFromAPI(data.configs || []);
    } catch (error) {
      throw createExportError(
        ERROR_CODES.NETWORK_ERROR,
        `\u83B7\u53D6\u5BFC\u51FA\u914D\u7F6E\u5931\u8D25: ${formatErrorMessage(error)}`,
        { moduleId, businessId, originalError: error }
      );
    }
  }
  /**
   * 创建导出配置
   */
  async createConfig(config) {
    const url = `${this.config.baseUrl}${API_ENDPOINTS.CREATE_CONFIG}`;
    try {
      const response = await this.fetchWithTimeout(url, {
        method: "POST",
        headers: {
          ...this.getHeaders(),
          "Content-Type": "application/json"
        },
        body: JSON.stringify(config)
      });
      if (!response.ok) {
        throw new Error(`\u521B\u5EFA\u914D\u7F6E\u5931\u8D25: ${response.statusText}`);
      }
      const data = await response.json();
      return this.transformConfigFromAPI(data.config);
    } catch (error) {
      throw createExportError(
        ERROR_CODES.NETWORK_ERROR,
        `\u521B\u5EFA\u5BFC\u51FA\u914D\u7F6E\u5931\u8D25: ${formatErrorMessage(error)}`,
        { config, originalError: error }
      );
    }
  }
  /**
   * 更新导出配置
   */
  async updateConfig(configId, updates) {
    const url = `${this.config.baseUrl}${API_ENDPOINTS.UPDATE_CONFIG(configId)}`;
    try {
      const response = await this.fetchWithTimeout(url, {
        method: "PUT",
        headers: {
          ...this.getHeaders(),
          "Content-Type": "application/json"
        },
        body: JSON.stringify(updates)
      });
      if (!response.ok) {
        throw new Error(`\u66F4\u65B0\u914D\u7F6E\u5931\u8D25: ${response.statusText}`);
      }
      const data = await response.json();
      return this.transformConfigFromAPI(data.config);
    } catch (error) {
      throw createExportError(
        ERROR_CODES.NETWORK_ERROR,
        `\u66F4\u65B0\u5BFC\u51FA\u914D\u7F6E\u5931\u8D25: ${formatErrorMessage(error)}`,
        { configId, updates, originalError: error }
      );
    }
  }
  /**
   * 删除导出配置
   */
  async deleteConfig(configId) {
    const url = `${this.config.baseUrl}${API_ENDPOINTS.DELETE_CONFIG(configId)}`;
    try {
      const response = await this.fetchWithTimeout(url, {
        method: "DELETE",
        headers: this.getHeaders()
      });
      if (!response.ok) {
        throw new Error(`\u5220\u9664\u914D\u7F6E\u5931\u8D25: ${response.statusText}`);
      }
    } catch (error) {
      throw createExportError(
        ERROR_CODES.NETWORK_ERROR,
        `\u5220\u9664\u5BFC\u51FA\u914D\u7F6E\u5931\u8D25: ${formatErrorMessage(error)}`,
        { configId, originalError: error }
      );
    }
  }
  // ============= 导出执行API =============
  /**
   * 触发数据导出
   */
  async exportData(request) {
    const url = `${this.config.baseUrl}${API_ENDPOINTS.EXPORT_DATA}`;
    try {
      const response = await this.fetchWithTimeout(url, {
        method: "POST",
        headers: {
          ...this.getHeaders(),
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          configId: request.configId,
          dataSource: typeof request.dataSource === "string" ? request.dataSource : void 0,
          queryParams: request.queryParams,
          fieldMapping: request.fieldMapping,
          filters: request.filters,
          sortBy: request.sortBy,
          pagination: request.pagination,
          customFileName: request.customFileName
        })
      });
      if (!response.ok) {
        throw new Error(`\u5BFC\u51FA\u5931\u8D25: ${response.statusText}`);
      }
      const data = await response.json();
      return this.transformExportResultFromAPI(data.result);
    } catch (error) {
      throw createExportError(
        ERROR_CODES.EXPORT_DATA_ERROR,
        `\u6570\u636E\u5BFC\u51FA\u5931\u8D25: ${formatErrorMessage(error)}`,
        { request, originalError: error }
      );
    }
  }
  /**
   * 查询导出进度
   */
  async getExportProgress(exportId) {
    const url = `${this.config.baseUrl}${API_ENDPOINTS.GET_PROGRESS(exportId)}`;
    try {
      const response = await this.fetchWithTimeout(url, {
        method: "GET",
        headers: this.getHeaders()
      });
      if (!response.ok) {
        throw new Error(`\u83B7\u53D6\u5BFC\u51FA\u8FDB\u5EA6\u5931\u8D25: ${response.statusText}`);
      }
      const data = await response.json();
      return this.transformProgressFromAPI(data.progress);
    } catch (error) {
      throw createExportError(
        ERROR_CODES.NETWORK_ERROR,
        `\u83B7\u53D6\u5BFC\u51FA\u8FDB\u5EA6\u5931\u8D25: ${formatErrorMessage(error)}`,
        { exportId, originalError: error }
      );
    }
  }
  /**
   * 下载导出文件
   */
  async downloadExportFile(exportId) {
    const url = `${this.config.baseUrl}${API_ENDPOINTS.DOWNLOAD_FILE(exportId)}`;
    try {
      const response = await this.fetchWithTimeout(url, {
        method: "GET",
        headers: this.getHeaders()
      });
      if (!response.ok) {
        throw new Error(`\u4E0B\u8F7D\u6587\u4EF6\u5931\u8D25: ${response.statusText}`);
      }
      return await response.blob();
    } catch (error) {
      throw createExportError(
        ERROR_CODES.NETWORK_ERROR,
        `\u4E0B\u8F7D\u5BFC\u51FA\u6587\u4EF6\u5931\u8D25: ${formatErrorMessage(error)}`,
        { exportId, originalError: error }
      );
    }
  }
  // ============= 私有辅助方法 =============
  /**
   * 获取请求头
   */
  getHeaders() {
    return {
      ...this.config.headers
    };
  }
  /**
   * 带超时的fetch请求
   */
  async fetchWithTimeout(url, options) {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
    try {
      const response = await fetch(url, {
        ...options,
        signal: controller.signal
      });
      return response;
    } catch (error) {
      if (error instanceof Error && error.name === "AbortError") {
        throw createExportError(ERROR_CODES.TIMEOUT_ERROR, "\u8BF7\u6C42\u8D85\u65F6", {
          url,
          timeout: this.config.timeout
        });
      }
      throw error;
    } finally {
      clearTimeout(timeoutId);
    }
  }
  /**
   * 转换API返回的配置数据
   */
  transformConfigFromAPI(apiConfig) {
    return {
      id: apiConfig.id,
      name: apiConfig.name,
      description: apiConfig.description || void 0,
      format: apiConfig.format,
      fields: apiConfig.fields,
      grouping: apiConfig.grouping,
      fileNameTemplate: apiConfig.fileNameTemplate,
      includeHeader: apiConfig.includeHeader,
      delimiter: apiConfig.delimiter,
      encoding: apiConfig.encoding,
      addBOM: apiConfig.addBOM,
      maxRows: apiConfig.maxRows || void 0,
      createdAt: new Date(apiConfig.createdAt),
      updatedAt: new Date(apiConfig.updatedAt),
      moduleId: apiConfig.moduleId,
      businessId: apiConfig.businessId || void 0,
      createdBy: apiConfig.createdBy || void 0
    };
  }
  /**
   * 转换API返回的配置列表
   */
  transformConfigsFromAPI(apiConfigs) {
    return apiConfigs.map((config) => this.transformConfigFromAPI(config));
  }
  /**
   * 转换API返回的导出结果
   */
  transformExportResultFromAPI(apiResult) {
    return {
      exportId: apiResult.exportId,
      fileName: apiResult.fileName,
      fileSize: apiResult.fileSize,
      fileUrl: apiResult.fileUrl,
      exportedRows: apiResult.exportedRows,
      startTime: new Date(apiResult.startTime),
      endTime: new Date(apiResult.endTime),
      duration: apiResult.duration,
      statistics: apiResult.statistics
    };
  }
  /**
   * 转换API返回的进度数据
   */
  transformProgressFromAPI(apiProgress) {
    return {
      exportId: apiProgress.exportId,
      status: apiProgress.status,
      progress: apiProgress.progress,
      processedRows: apiProgress.processedRows,
      totalRows: apiProgress.totalRows,
      startTime: new Date(apiProgress.startTime),
      estimatedEndTime: apiProgress.estimatedEndTime ? new Date(apiProgress.estimatedEndTime) : void 0,
      currentData: apiProgress.currentData,
      error: apiProgress.error
    };
  }
};
var universalExportClient = new UniversalExportClient();
function createExportClient(config) {
  return new UniversalExportClient(config);
}

export { API_BASE_PATH, API_ENDPOINTS, DEFAULT_ADD_BOM, DEFAULT_CONFIG_CACHE_TTL, DEFAULT_CSV_DELIMITER, DEFAULT_ENCODING, DEFAULT_EXPORT_FORMAT, DEFAULT_EXPORT_TIMEOUT, DEFAULT_FORMATTERS, DEFAULT_MAX_CONCURRENT_EXPORTS, DEFAULT_MAX_FILE_SIZE, DEFAULT_MAX_ROWS, DEFAULT_RESULT_CACHE_TTL, ERROR_CODES, EXPORT_FORMAT_EXTENSIONS, EXPORT_FORMAT_MIME_TYPES, UNIVERSAL_EXPORT_NAME, UNIVERSAL_EXPORT_VERSION, UniversalExportClient, applyFormatter, createExportClient, createExportError, escapeCSVField, estimateEndTime, formatDuration, formatErrorMessage, formatFileSize, generateExportFileName, getNestedValue, parseCSVField, sanitizeFileName, setNestedValue, universalExportClient, validateExportConfig, validateExportRequest, validateFileName };
//# sourceMappingURL=index.mjs.map
//# sourceMappingURL=index.mjs.map