/**
 * Undici 适配器
 * 
 * 基于 undici 库的适配器实现（Node.js 环境，高性能）
 */ /**
 * 创建 Undici 适配器
 */ export async function undiciAdapter() {
    // 动态导入 undici（按需加载）
    // 使用多种方式尝试导入，以兼容不同的构建工具
    let undici;
    let importError = null;
    // 方法1：使用 Function 构造函数（避免构建时解析）
    try {
        // @ts-ignore - undici 是可选依赖
        undici = await new Function('return import("undici")')();
    } catch (error) {
        importError = error;
        // 方法2：直接使用动态导入（某些构建工具可能需要这种方式）
        try {
            // @ts-ignore - undici 是可选依赖
            undici = await import("undici");
        } catch (error2) {
            importError = error2;
        }
    }
    // 如果两种方法都失败，检查是否是模块未找到错误
    if (!undici || !undici.request) {
        if (importError instanceof Error) {
            const errorMessage = importError.message.toLowerCase();
            // 检查是否是模块未找到相关的错误
            const isModuleNotFound = errorMessage.includes('cannot find module') || errorMessage.includes('cannot resolve') || errorMessage.includes('module not found') || errorMessage.includes('failed to resolve') || errorMessage.includes('does not exist') || errorMessage.includes('failed to fetch dynamically imported module') || errorMessage.includes('loading chunk') || errorMessage.includes('networkerror') || errorMessage.includes('undici') && (errorMessage.includes('resolve') || errorMessage.includes('find') || errorMessage.includes('not found'));
            if (isModuleNotFound) {
                // 模块未找到，抛出友好的依赖缺失错误
                const { createDependencyError } = await import("../utils/dependencyCheck");
                const errorMessage = createDependencyError('undici', {
                    adapterName: 'undici',
                    environment: 'node'
                });
                throw new Error(errorMessage);
            }
        }
        throw new Error('undici 库导入失败，请检查安装是否正确');
    }
    return {
        name: 'undici',
        capabilities: {
            supportsAbort: true,
            supportsTimeout: true,
            supportsProgress: false,
            supportsInterceptors: false
        },
        async request (options) {
            const { url, method = 'GET', headers = {}, query, body, timeout, signal } = options;
            // 构建完整 URL
            let fullUrl = url;
            if (query) {
                const searchParams = new URLSearchParams();
                for (const [key, value] of Object.entries(query)){
                    if (value !== null && value !== undefined) {
                        searchParams.append(key, String(value));
                    }
                }
                const queryString = searchParams.toString();
                if (queryString) {
                    fullUrl += (fullUrl.includes('?') ? '&' : '?') + queryString;
                }
            }
            // 构建请求头
            const requestHeaders = {};
            for (const [key, value] of Object.entries(headers)){
                requestHeaders[key] = String(value);
            }
            // 构建请求体
            let requestBody;
            if (body !== undefined && body !== null) {
                if (typeof body === 'string') {
                    requestBody = body;
                } else if (body instanceof ArrayBuffer) {
                    requestBody = Buffer.from(body);
                } else if (Buffer.isBuffer(body)) {
                    requestBody = body;
                } else {
                    // 对象转换为 JSON
                    requestHeaders['Content-Type'] = requestHeaders['Content-Type'] || 'application/json';
                    requestBody = JSON.stringify(body);
                }
            }
            // 构建 undici 选项
            // @ts-ignore - undici 类型定义
            const undiciOptions = {
                method: method,
                headers: requestHeaders,
                body: requestBody,
                signal: signal
            };
            // 如果设置了超时，使用 AbortController
            let abortController;
            let timeoutId;
            if (timeout && timeout > 0) {
                abortController = new AbortController();
                timeoutId = setTimeout(()=>{
                    abortController.abort();
                }, timeout);
                undiciOptions.signal = abortController.signal;
            }
            try {
                // 执行请求
                const undiciResponse = await undici.request(fullUrl, undiciOptions);
                // 解析响应数据
                let data;
                const responseType = options.responseType || 'json';
                switch(responseType){
                    case 'text':
                        data = await undiciResponse.body.text();
                        break;
                    case 'blob':
                        data = await undiciResponse.body.blob();
                        break;
                    case 'arrayBuffer':
                        data = await undiciResponse.body.arrayBuffer();
                        break;
                    case 'formData':
                        data = await undiciResponse.body.formData();
                        break;
                    case 'json':
                    default:
                        try {
                            data = await undiciResponse.body.json();
                        } catch  {
                            // 如果 JSON 解析失败，返回空对象
                            data = {};
                        }
                        break;
                }
                // 构建响应头对象
                const responseHeaders = {};
                for (const [key, value] of Object.entries(undiciResponse.headers)){
                    responseHeaders[key] = Array.isArray(value) ? value.join(', ') : String(value);
                }
                // 检查 HTTP 状态码
                if (undiciResponse.statusCode >= 400) {
                    throw new Error(`HTTP ${undiciResponse.statusCode} ${undiciResponse.statusText || ''}`);
                }
                // 返回响应对象
                return {
                    data,
                    status: undiciResponse.statusCode,
                    statusText: undiciResponse.statusText || '',
                    headers: responseHeaders,
                    raw: undiciResponse
                };
            } catch (error) {
                // 清理超时定时器
                if (timeoutId) {
                    clearTimeout(timeoutId);
                }
                // 重新抛出错误
                throw error;
            }
        }
    };
}

//# sourceMappingURL=undiciAdapter.js.map