/**
 * 资源类型
 */ function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
/**
 * 资源优先级
 */ export var ResourcePriority = /*#__PURE__*/ function(ResourcePriority) {
    /**
   * 高优先级 - 关键资源
   */ ResourcePriority["HIGH"] = "high";
    /**
   * 中优先级 - 重要资源
   */ ResourcePriority["MEDIUM"] = "medium";
    /**
   * 低优先级 - 非关键资源
   */ ResourcePriority["LOW"] = "low";
    /**
   * 自动 - 由浏览器决定
   */ ResourcePriority["AUTO"] = "auto";
    return ResourcePriority;
}({});
/**
 * 资源加载器类
 */ export class ResourceLoader {
    /**
   * 获取动态并发数（基于网络状况）
   */ getDynamicConcurrency() {
        if (typeof navigator === 'undefined' || !('connection' in navigator)) {
            return this.maxConcurrentLoads;
        }
        const connection = navigator.connection;
        if (!connection) {
            return this.maxConcurrentLoads;
        }
        // 根据网络类型调整并发数
        const effectiveType = connection.effectiveType;
        switch(effectiveType){
            case 'slow-2g':
            case '2g':
                return 2;
            case '3g':
                return 4;
            case '4g':
            default:
                return this.maxConcurrentLoads;
        }
    }
    /**
   * 加载脚本
   */ async loadScript(options) {
        const { url, ...rest } = options;
        return this.loadResource({
            ...rest,
            type: 'script',
            url
        });
    }
    /**
   * 加载样式
   */ async loadStyle(options) {
        const { url, ...rest } = options;
        return this.loadResource({
            ...rest,
            type: 'style',
            url
        });
    }
    /**
   * 预加载资源
   */ preload(options) {
        if (typeof document === 'undefined') {
            return;
        }
        const link = document.createElement('link');
        link.rel = 'preload';
        link.href = options.url;
        link.as = this.getResourceAs(options.type);
        if (options.priority) {
            link.setAttribute('fetchpriority', options.priority);
        }
        if (options.crossOrigin) {
            link.crossOrigin = options.crossOrigin;
        }
        if (options.integrity) {
            link.integrity = options.integrity;
        }
        document.head.appendChild(link);
    }
    /**
   * 预取资源
   */ prefetch(options) {
        if (typeof document === 'undefined') {
            return;
        }
        const link = document.createElement('link');
        link.rel = 'prefetch';
        link.href = options.url;
        if (options.priority) {
            link.setAttribute('fetchpriority', options.priority);
        }
        document.head.appendChild(link);
    }
    /**
   * 加载资源
   */ async loadResource(options) {
        const { url, type, onLoad, onError } = options;
        // 如果已经加载过，直接返回
        if (this.loadedResources.has(url)) {
            onLoad?.();
            return;
        }
        // 如果正在加载，等待加载完成
        if (this.loadingResources.has(url)) {
            await this.loadingResources.get(url);
            onLoad?.();
            return;
        }
        // 创建加载 Promise
        const loadPromise = this.doLoadResource({
            ...options,
            type,
            url
        });
        // 保存加载 Promise
        this.loadingResources.set(url, loadPromise);
        try {
            await loadPromise;
            this.loadedResources.add(url);
            onLoad?.();
        } catch (error) {
            const err = error instanceof Error ? error : new Error(String(error));
            onError?.(err);
            throw err;
        } finally{
            this.loadingResources.delete(url);
        }
    }
    /**
   * 执行资源加载
   */ doLoadResource(options) {
        return new Promise((resolve, reject)=>{
            if (typeof document === 'undefined') {
                reject(new Error('资源加载需要在浏览器环境中执行'));
                return;
            }
            const { url, type, async = true, defer, crossOrigin, integrity } = options;
            if (type === 'script') {
                const script = document.createElement('script');
                script.src = url;
                script.async = async;
                if (defer !== undefined) {
                    script.defer = defer;
                }
                if (crossOrigin) {
                    script.crossOrigin = crossOrigin;
                }
                if (integrity) {
                    script.integrity = integrity;
                }
                script.onload = ()=>resolve();
                script.onerror = ()=>reject(new Error(`Failed to load script: ${url}`));
                document.head.appendChild(script);
            } else if (type === 'style') {
                const link = document.createElement('link');
                link.rel = 'stylesheet';
                link.href = url;
                if (crossOrigin) {
                    link.crossOrigin = crossOrigin;
                }
                if (integrity) {
                    link.integrity = integrity;
                }
                link.onload = ()=>resolve();
                link.onerror = ()=>reject(new Error(`Failed to load stylesheet: ${url}`));
                document.head.appendChild(link);
            } else {
                reject(new Error(`Unsupported resource type: ${type}`));
            }
        });
    }
    /**
   * 获取资源 as 属性值
   */ getResourceAs(type) {
        const asMap = {
            script: 'script',
            style: 'style',
            image: 'image',
            font: 'font',
            prefetch: 'fetch',
            preload: 'fetch'
        };
        return asMap[type] || 'fetch';
    }
    /**
   * 使用 requestIdleCallback 加载低优先级资源
   */ loadWhenIdle(options, timeout) {
        if (typeof requestIdleCallback !== 'undefined') {
            requestIdleCallback(()=>{
                this.loadResource(options).catch((error)=>{
                    console.warn('Idle resource load failed:', error);
                });
            }, {
                timeout
            });
        } else {
            // 降级方案：延迟加载
            setTimeout(()=>{
                this.loadResource(options).catch((error)=>{
                    console.warn('Delayed resource load failed:', error);
                });
            }, 1000);
        }
    }
    /**
   * 批量加载资源（按优先级）
   */ async loadResources(resources) {
        // 按优先级排序
        const sortedResources = this.sortByPriority(resources);
        // 按优先级分组
        const highPriority = sortedResources.filter((r)=>r.priority === "high" || !r.priority);
        const mediumPriority = sortedResources.filter((r)=>r.priority === "medium");
        const lowPriority = sortedResources.filter((r)=>r.priority === "low");
        const results = [];
        // 先加载高优先级资源（并行，但限制并发数）
        if (highPriority.length > 0) {
            const highResults = await this.loadResourcesWithConcurrencyLimit(highPriority);
            results.push(...highResults);
        }
        // 然后加载中优先级资源
        if (mediumPriority.length > 0) {
            const mediumResults = await this.loadResourcesWithConcurrencyLimit(mediumPriority);
            results.push(...mediumResults);
        }
        // 最后加载低优先级资源（使用空闲时间）
        if (lowPriority.length > 0) {
            // 低优先级资源在空闲时加载
            for (const resource of lowPriority){
                this.loadWhenIdle(resource);
            }
        }
        return results;
    }
    /**
   * 按优先级排序资源
   */ sortByPriority(resources) {
        const priorityOrder = {
            ["high"]: 0,
            ["medium"]: 1,
            ["low"]: 2,
            ["auto"]: 3
        };
        return [
            ...resources
        ].sort((a, b)=>{
            const aPriority = priorityOrder[a.priority || "auto"] ?? 3;
            const bPriority = priorityOrder[b.priority || "auto"] ?? 3;
            return aPriority - bPriority;
        });
    }
    /**
   * 限制并发数的资源加载（优化版本）
   */ async loadResourcesWithConcurrencyLimit(resources, concurrency) {
        const maxConcurrency = concurrency ?? this.getDynamicConcurrency();
        const results = [];
        const executing = new Set();
        for (const resource of resources){
            // 如果达到并发限制，等待一个任务完成
            if (executing.size >= maxConcurrency) {
                await Promise.race(executing);
            }
            const promise = this.loadResource(resource).finally(()=>{
                executing.delete(promise);
            });
            executing.add(promise);
            results.push(promise);
        }
        // 等待所有任务完成
        await Promise.all(results);
        return [];
    }
    /**
   * 检查资源是否已加载
   */ isLoaded(url) {
        return this.loadedResources.has(url);
    }
    constructor(){
        _define_property(this, "loadedResources", new Set());
        _define_property(this, "loadingResources", new Map());
        _define_property(this, "maxConcurrentLoads", 6); // 最大并发加载数（默认值）
    }
}
/**
 * 默认资源加载器实例
 */ export const resourceLoader = new ResourceLoader();

//# sourceMappingURL=resourceLoader.js.map