import http from "@ohos:net.http";
import type { WarmupManifest } from './WarmupManifest';
class BjcCov {
    coverage: {
        [key: string]: string | number;
    };
    constructor(covData: object) {
        const gcv = "__coverage__";
        let coverage = globalThis[gcv] || (globalThis[gcv] = {});
        if (!coverage[covData.path] && true) {
            coverage[covData.path] = covData;
        }
        this.coverage = coverage[covData.path];
    }
    instrumentFunction(func: number) {
        this.coverage.functions[func].count++;
        this.coverage.functions[func].regions[0].count++;
    }
    instrumentRegion(func: number, region: number) {
        this.coverage.functions[func].regions[region].count++;
    }
    instrumentReturn(func: number, retIdx: number) {
        this.coverage.functions[func].returnes[retIdx].count++;
    }
    instrumentBranch(func: number, branch: number, trueOrFalse: boolean) {
        if (trueOrFalse) {
            this.coverage.functions[func].branches[branch].trueCount++;
            for (let r of Object.values(this.coverage.functions[func].branches[branch].group)) {
                if (r !== branch) {
                    this.coverage.functions[func].branches[r as number].falseCount++;
                }
            }
        }
        else {
            this.coverage.functions[func].branches[branch].falseCount++;
        }
        /** 缓存是否过期。 */
    }
}
let bjccovms5u83u8 = new BjcCov({ version: "bjc v1.0.0", versionCode: 10000, path: "tencentqianwebview/src/main/ets/internal/prewarm/ManifestStore.ets", hash: "1f8498d28673d75abc5d17d4c8c23f77dc815eefd30aec96c57002c08afc54b2", lineCnt: 176, count: 0, projectPath: "", functions: { 0: { name: "anonymous_0", count: 0, regions: { 0: { startLoc: { line: 7, col: 37 }, endLoc: { line: 7, col: 96 }, count: 0, ignored: 0 } }, branches: {}, ignored: 0, index: 0 }, 1: { name: "ManifestStore.setManifestUrl", count: 0, regions: { 0: { startLoc: { line: 30, col: 3 }, endLoc: { line: 32, col: 4 }, count: 0, ignored: 0 }, 1: { startLoc: { line: 31, col: 5 }, endLoc: { line: 32, col: 4 }, count: 0, ignored: 0 } }, branches: {}, ignored: 0, index: 1 }, 2: { name: "ManifestStore.getManifest", count: 0, regions: { 0: { startLoc: { line: 35, col: 3 }, endLoc: { line: 37, col: 4 }, count: 0, ignored: 0 }, 1: { startLoc: { line: 36, col: 5 }, endLoc: { line: 37, col: 4 }, count: 0, ignored: 0 } }, branches: {}, ignored: 0, index: 2 }, 3: { name: "ManifestStore.isStale", count: 0, regions: { 0: { startLoc: { line: 40, col: 3 }, endLoc: { line: 42, col: 4 }, count: 0, ignored: 0 }, 1: { startLoc: { line: 41, col: 5 }, endLoc: { line: 42, col: 4 }, count: 0, ignored: 0 } }, branches: {}, ignored: 0, index: 3 }, 4: { name: "ManifestStore.ensureFresh", count: 0, regions: { 0: { startLoc: { line: 50, col: 3 }, endLoc: { line: 68, col: 4 }, count: 0, ignored: 0 }, 1: { startLoc: { line: 51, col: 33 }, endLoc: { line: 59, col: 6 }, count: 0, ignored: 0 }, 2: { startLoc: { line: 52, col: 34 }, endLoc: { line: 54, col: 8 }, count: 0, ignored: 0 }, 3: { startLoc: { line: 55, col: 27 }, endLoc: { line: 57, col: 8 }, count: 0, ignored: 0 }, 4: { startLoc: { line: 61, col: 32 }, endLoc: { line: 66, col: 6 }, count: 0, ignored: 0 }, 5: { startLoc: { line: 63, col: 60 }, endLoc: { line: 65, col: 8 }, count: 0, ignored: 0 }, 6: { startLoc: { line: 67, col: 5 }, endLoc: { line: 68, col: 4 }, count: 0, ignored: 0 }, 7: { startLoc: { line: 58, col: 7 }, endLoc: { line: 59, col: 6 }, count: 0, ignored: 0 } }, branches: { 0: { startLoc: { line: 51, col: 9 }, endLoc: { line: 51, col: 31 }, trueCount: 0, falseCount: 0, group: {}, ignored: 0 }, 1: { startLoc: { line: 52, col: 11 }, endLoc: { line: 52, col: 32 }, trueCount: 0, falseCount: 0, group: {}, ignored: 0 }, 2: { startLoc: { line: 55, col: 11 }, endLoc: { line: 55, col: 25 }, trueCount: 0, falseCount: 0, group: {}, ignored: 0 }, 3: { startLoc: { line: 61, col: 9 }, endLoc: { line: 61, col: 30 }, trueCount: 0, falseCount: 0, group: {}, ignored: 0 }, 4: { startLoc: { line: 63, col: 11 }, endLoc: { line: 63, col: 58 }, trueCount: 0, falseCount: 0, group: {}, ignored: 0 } }, ignored: 0, index: 4 }, 5: { name: "ManifestStore.fetch", count: 0, regions: { 0: { startLoc: { line: 71, col: 3 }, endLoc: { line: 141, col: 4 }, count: 0, ignored: 0 }, 1: { startLoc: { line: 72, col: 59 }, endLoc: { line: 74, col: 6 }, count: 0, ignored: 0 }, 2: { startLoc: { line: 75, col: 5 }, endLoc: { line: 141, col: 4 }, count: 0, ignored: 0 } }, branches: { 0: { startLoc: { line: 72, col: 9 }, endLoc: { line: 72, col: 57 }, trueCount: 0, falseCount: 0, group: {}, ignored: 0 } }, ignored: 0, index: 5 }, 6: { name: "anonymous_1", count: 0, regions: { 0: { startLoc: { line: 85, col: 7 }, endLoc: { line: 139, col: 8 }, count: 0, ignored: 0 }, 1: { startLoc: { line: 88, col: 13 }, endLoc: { line: 125, col: 10 }, count: 0, ignored: 0 }, 2: { startLoc: { line: 125, col: 11 }, endLoc: { line: 127, col: 10 }, count: 0, ignored: 0 }, 3: { startLoc: { line: 127, col: 19 }, endLoc: { line: 138, col: 10 }, count: 0, ignored: 0 }, 4: { startLoc: { line: 89, col: 50 }, endLoc: { line: 91, col: 12 }, count: 0, ignored: 0 }, 5: { startLoc: { line: 92, col: 42 }, endLoc: { line: 94, col: 12 }, count: 0, ignored: 0 }, 6: { startLoc: { line: 99, col: 34 }, endLoc: { line: 101, col: 12 }, count: 0, ignored: 0 }, 7: { startLoc: { line: 103, col: 62 }, endLoc: { line: 105, col: 12 }, count: 0, ignored: 0 }, 8: { startLoc: { line: 122, col: 31 }, endLoc: { line: 124, col: 12 }, count: 0, ignored: 0 }, 9: { startLoc: { line: 128, col: 15 }, endLoc: { line: 130, col: 12 }, count: 0, ignored: 0 }, 10: { startLoc: { line: 130, col: 13 }, endLoc: { line: 132, col: 12 }, count: 0, ignored: 0 }, 11: { startLoc: { line: 135, col: 25 }, endLoc: { line: 137, col: 12 }, count: 0, ignored: 0 } }, branches: { 0: { startLoc: { line: 89, col: 15 }, endLoc: { line: 89, col: 48 }, trueCount: 0, falseCount: 0, group: {}, ignored: 0 }, 1: { startLoc: { line: 92, col: 15 }, endLoc: { line: 92, col: 40 }, trueCount: 0, falseCount: 0, group: {}, ignored: 0 }, 2: { startLoc: { line: 96, col: 32 }, endLoc: { line: 98, col: 17 }, trueCount: 0, falseCount: 0, group: {}, ignored: 0 }, 3: { startLoc: { line: 99, col: 15 }, endLoc: { line: 99, col: 32 }, trueCount: 0, falseCount: 0, group: {}, ignored: 0 }, 4: { startLoc: { line: 103, col: 15 }, endLoc: { line: 103, col: 60 }, trueCount: 0, falseCount: 0, group: {}, ignored: 0 }, 5: { startLoc: { line: 106, col: 38 }, endLoc: { line: 106, col: 89 }, trueCount: 0, falseCount: 0, group: {}, ignored: 0 }, 6: { startLoc: { line: 122, col: 15 }, endLoc: { line: 122, col: 29 }, trueCount: 0, falseCount: 0, group: {}, ignored: 0 }, 7: { startLoc: { line: 135, col: 15 }, endLoc: { line: 135, col: 23 }, trueCount: 0, falseCount: 0, group: {}, ignored: 0 } }, ignored: 0, index: 6 }, 7: { name: "anonymous_2", count: 0, regions: { 0: { startLoc: { line: 114, col: 29 }, endLoc: { line: 120, col: 12 }, count: 0, ignored: 0 }, 1: { startLoc: { line: 115, col: 17 }, endLoc: { line: 117, col: 14 }, count: 0, ignored: 0 }, 2: { startLoc: { line: 117, col: 15 }, endLoc: { line: 119, col: 14 }, count: 0, ignored: 0 } }, branches: {}, ignored: 0, index: 7 }, 8: { name: "anonymous_3", count: 0, regions: { 0: { startLoc: { line: 144, col: 28 }, endLoc: { line: 144, col: 62 }, count: 0, ignored: 0 } }, branches: {}, ignored: 0, index: 8 }, 9: { name: "anonymous_4", count: 0, regions: { 0: { startLoc: { line: 144, col: 65 }, endLoc: { line: 146, col: 4 }, count: 0, ignored: 0 } }, branches: {}, ignored: 0, index: 9 }, 10: { name: "parseMaxAge", count: 0, regions: { 0: { startLoc: { line: 149, col: 3 }, endLoc: { line: 174, col: 4 }, count: 0, ignored: 0 }, 1: { startLoc: { line: 150, col: 9 }, endLoc: { line: 171, col: 6 }, count: 0, ignored: 0 }, 2: { startLoc: { line: 171, col: 7 }, endLoc: { line: 173, col: 6 }, count: 0, ignored: 0 }, 3: { startLoc: { line: 153, col: 30 }, endLoc: { line: 155, col: 8 }, count: 0, ignored: 0 }, 4: { startLoc: { line: 156, col: 57 }, endLoc: { line: 158, col: 8 }, count: 0, ignored: 0 }, 5: { startLoc: { line: 161, col: 20 }, endLoc: { line: 163, col: 8 }, count: 0, ignored: 0 }, 6: { startLoc: { line: 167, col: 43 }, endLoc: { line: 169, col: 8 }, count: 0, ignored: 0 }, 7: { startLoc: { line: 170, col: 7 }, endLoc: { line: 171, col: 6 }, count: 0, ignored: 0 } }, branches: { 0: { startLoc: { line: 153, col: 11 }, endLoc: { line: 153, col: 28 }, trueCount: 0, falseCount: 0, group: {}, ignored: 0 }, 1: { startLoc: { line: 156, col: 11 }, endLoc: { line: 156, col: 55 }, trueCount: 0, falseCount: 0, group: {}, ignored: 0 }, 2: { startLoc: { line: 161, col: 11 }, endLoc: { line: 161, col: 18 }, trueCount: 0, falseCount: 0, group: {}, ignored: 0 }, 3: { startLoc: { line: 167, col: 11 }, endLoc: { line: 167, col: 41 }, trueCount: 0, falseCount: 0, group: {}, ignored: 0 } }, ignored: 0, index: 10 } }, exeLine: { 0: 1, 1: 2, 2: 7, 3: 18, 4: 20, 5: 22, 6: 23, 7: 24, 8: 25, 9: 26, 10: 27, 11: 30, 12: 31, 13: 35, 14: 36, 15: 40, 16: 41, 17: 50, 18: 51, 19: 52, 20: 53, 21: 55, 22: 56, 23: 58, 24: 61, 25: 63, 26: 64, 27: 67, 28: 71, 29: 72, 30: 73, 31: 75, 32: 76, 33: 77, 34: 78, 35: 79, 36: 80, 37: 81, 38: 82, 39: 83, 40: 85, 41: 86, 42: 87, 43: 88, 44: 89, 45: 90, 46: 92, 47: 93, 48: 95, 49: 96, 50: 97, 51: 98, 52: 99, 53: 100, 54: 102, 55: 103, 56: 104, 57: 106, 58: 107, 59: 108, 60: 109, 61: 110, 62: 112, 63: 113, 64: 114, 65: 115, 66: 116, 67: 117, 68: 122, 69: 123, 70: 125, 71: 127, 72: 128, 73: 129, 74: 130, 75: 135, 76: 136, 77: 144, 78: 149, 79: 150, 80: 151, 81: 152, 82: 153, 83: 154, 84: 156, 85: 157, 86: 159, 87: 160, 88: 161, 89: 162, 90: 164, 91: 165, 92: 166, 93: 167, 94: 168, 95: 170, 96: 171, 97: 172 } });
/**
 * manifest 就绪回调。`versionChanged` 表示本次拉取的 version 与旧缓存不同。
 */
export type ManifestReadyCallback = (manifest: WarmupManifest, versionChanged: boolean) => void;
/**
 * manifest 拉取 / 缓存 / 新鲜度管理（进程内单例语义，由 Prewarmer 持有）。
 *
 * 策略（design.md Decision 5）：
 * - 内存缓存整个 session；TTL 读自响应头 `Cache-Control: max-age`，缺省 300s。
 * - `ensureFresh`：缺失则拉取并排队回调；已有但过期则后台重拉（stale-while-revalidate）。
 * - `isFetching` 保护：每 TTL 窗口最多一次重拉。
 * - 拉取失败静默 no-op。
 */
export class ManifestStore {
    /** pending 回调队列上限。弱网下 ensureFresh 可能多次入队，设上限防御异常累积。 */
    private static readonly MAX_PENDING: number = 16;
    private manifest: WarmupManifest | null = null;
    private lastFetchAtMs: number = 0;
    private ttlMs: number = 300000;
    private isFetching: boolean = false;
    private manifestUrl: string = '';
    private pending: ManifestReadyCallback[] = [];
    /** 设置 manifest URL（environment 映射或显式覆盖的结果）。 */
    public setManifestUrl(url: string): void {
        bjccovms5u83u8.instrumentFunction(1);
        bjccovms5u83u8.instrumentRegion(1, 1);
        this.manifestUrl = url;
    }
    /** 当前缓存的 manifest（可能为 null 或略旧）。 */
    public getManifest(): WarmupManifest | null {
        bjccovms5u83u8.instrumentFunction(2);
        bjccovms5u83u8.instrumentRegion(2, 1);
        return this.manifest;
    }
    /** 缓存是否过期。 */
    public isStale(): boolean {
        bjccovms5u83u8.instrumentFunction(3);
        bjccovms5u83u8.instrumentRegion(3, 1);
        return (Date.now() - this.lastFetchAtMs) > this.ttlMs;
    }
    /**
     * 确保 manifest 可用且新鲜。
     * - 无缓存：触发拉取，`onReady` 排队等 manifest 到达后回调（pending replay）。
     * - 有缓存但过期：后台重拉（不阻塞），并在成功后回调 `onReady`（用于 version 变化通知）。
     * - 有缓存且新鲜：立即以当前缓存回调 `onReady`。
     */
    public ensureFresh(onReady?: ManifestReadyCallback): void {
        bjccovms5u83u8.instrumentFunction(4);
        if (this.manifest !== null) {
            bjccovms5u83u8.instrumentBranch(4, 0, true);
            bjccovms5u83u8.instrumentRegion(4, 1);
            if (onReady !== undefined) {
                bjccovms5u83u8.instrumentBranch(4, 1, true);
                bjccovms5u83u8.instrumentRegion(4, 2);
                onReady(this.manifest, false);
            }
            else {
                bjccovms5u83u8.instrumentBranch(4, 1, false);
            }
            if (this.isStale()) {
                bjccovms5u83u8.instrumentBranch(4, 2, true);
                bjccovms5u83u8.instrumentRegion(4, 3);
                this.fetch();
            }
            else {
                bjccovms5u83u8.instrumentBranch(4, 2, false);
            }
            bjccovms5u83u8.instrumentRegion(4, 7);
            return;
        }
        // 无缓存：排队 + 拉取
        else {
            bjccovms5u83u8.instrumentBranch(4, 0, false);
        }
        // 无缓存：排队 + 拉取
        if (onReady !== undefined) {
            bjccovms5u83u8.instrumentBranch(4, 3, true);
            bjccovms5u83u8.instrumentRegion(4, 4);
            // 上限保护：超限直接丢弃新回调，避免弱网下 pending 无界增长。
            if (this.pending.length < ManifestStore.MAX_PENDING) {
                bjccovms5u83u8.instrumentBranch(4, 4, true);
                bjccovms5u83u8.instrumentRegion(4, 5);
                this.pending.push(onReady);
            }
            else {
                bjccovms5u83u8.instrumentBranch(4, 4, false);
            }
        }
        else {
            bjccovms5u83u8.instrumentBranch(4, 3, false);
        }
        bjccovms5u83u8.instrumentRegion(4, 6);
        this.fetch();
    }
    /** 后台拉取 manifest（带 isFetching 保护，失败静默）。 */
    private fetch(): void {
        bjccovms5u83u8.instrumentFunction(5);
        if (this.isFetching || this.manifestUrl.length === 0) {
            bjccovms5u83u8.instrumentBranch(5, 0, true);
            bjccovms5u83u8.instrumentRegion(5, 1);
            return;
        }
        else {
            bjccovms5u83u8.instrumentBranch(5, 0, false);
        }
        bjccovms5u83u8.instrumentRegion(5, 2);
        this.isFetching = true;
        const request = http.createHttp();
        request.request(this.manifestUrl, {
            method: http.RequestMethod.GET,
            header: { 'Accept': 'application/json' },
            connectTimeout: 8000,
            readTimeout: 8000
        }, (err: Object | undefined, resp: http.HttpResponse): void => {
            bjccovms5u83u8.instrumentFunction(6);
            this.isFetching = false;
            let success: boolean = false;
            try {
                bjccovms5u83u8.instrumentRegion(6, 1);
                if (err !== undefined && err !== null) {
                    bjccovms5u83u8.instrumentBranch(6, 0, true);
                    bjccovms5u83u8.instrumentRegion(6, 4);
                    return;
                }
                else {
                    bjccovms5u83u8.instrumentBranch(6, 0, false);
                }
                if (resp.responseCode !== 200) {
                    bjccovms5u83u8.instrumentBranch(6, 1, true);
                    bjccovms5u83u8.instrumentRegion(6, 5);
                    return;
                }
                else {
                    bjccovms5u83u8.instrumentBranch(6, 1, false);
                }
                this.ttlMs = ManifestStore.parseMaxAge(resp.header) ?? 300000;
                const body: string = typeof resp.result === 'string'
                    ? (bjccovms5u83u8.instrumentBranch(6, 2, true), resp.result as string) : (bjccovms5u83u8.instrumentBranch(6, 2, false), '');
                if (body.length === 0) {
                    bjccovms5u83u8.instrumentBranch(6, 3, true);
                    bjccovms5u83u8.instrumentRegion(6, 6);
                    return;
                }
                else {
                    bjccovms5u83u8.instrumentBranch(6, 3, false);
                }
                const parsed: WarmupManifest = JSON.parse(body) as WarmupManifest;
                if (parsed === null || parsed.hosts === undefined) {
                    bjccovms5u83u8.instrumentBranch(6, 4, true);
                    bjccovms5u83u8.instrumentRegion(6, 7);
                    return;
                }
                else {
                    bjccovms5u83u8.instrumentBranch(6, 4, false);
                }
                const oldVersion: string = this.manifest !== null ? (bjccovms5u83u8.instrumentBranch(6, 5, true), this.manifest.version) : (bjccovms5u83u8.instrumentBranch(6, 5, false), '');
                const versionChanged: boolean = oldVersion.length > 0 && oldVersion !== parsed.version;
                this.manifest = parsed;
                this.lastFetchAtMs = Date.now();
                success = true;
                // pending replay
                const callbacks: ManifestReadyCallback[] = this.pending;
                this.pending = [];
                callbacks.forEach((cb: ManifestReadyCallback): void => {
                    bjccovms5u83u8.instrumentFunction(7);
                    try {
                        bjccovms5u83u8.instrumentRegion(7, 1);
                        cb(parsed, false);
                    }
                    catch (_e) {
                        bjccovms5u83u8.instrumentRegion(7, 2);
                    }
                });
                // version 变化通知（用于去重重置）
                if (versionChanged) {
                    bjccovms5u83u8.instrumentBranch(6, 6, true);
                    bjccovms5u83u8.instrumentRegion(6, 8);
                    this.onVersionChanged(parsed);
                }
                else {
                    bjccovms5u83u8.instrumentBranch(6, 6, false);
                }
            }
            catch (_e) {
                bjccovms5u83u8.instrumentRegion(6, 2);
            }
            finally {
                bjccovms5u83u8.instrumentRegion(6, 3);
                try {
                    bjccovms5u83u8.instrumentRegion(6, 9);
                    request.destroy();
                }
                catch (_e2) {
                    bjccovms5u83u8.instrumentRegion(6, 10);
                }
                // 拉取失败：清空 pending（符合"失败静默不回调"契约），避免回调无界累积。
                // 下次 ensureFresh 会重新入队重试；去重状态未更新故不会误判已预热。
                if (!success) {
                    bjccovms5u83u8.instrumentBranch(6, 7, true);
                    bjccovms5u83u8.instrumentRegion(6, 11);
                    this.pending = [];
                }
                else {
                    bjccovms5u83u8.instrumentBranch(6, 7, false);
                }
            }
        });
    }
    /** version 变化钩子，由 Prewarmer 注入用于清理去重状态。 */
    public onVersionChanged: (manifest: WarmupManifest) => void = (): void => {
        bjccovms5u83u8.instrumentFunction(9);
    };
    /** 解析 `Cache-Control: max-age=NNN` → 毫秒；无则返回 null。 */
    private static parseMaxAge(header: Object): number | null {
        bjccovms5u83u8.instrumentFunction(10);
        try {
            bjccovms5u83u8.instrumentRegion(10, 1);
            const h: Record<string, any> = header as Record<string, any>;
            let raw: any = h['cache-control'];
            if (raw === undefined) {
                bjccovms5u83u8.instrumentBranch(10, 0, true);
                bjccovms5u83u8.instrumentRegion(10, 3);
                raw = h['Cache-Control'];
            }
            else {
                bjccovms5u83u8.instrumentBranch(10, 0, false);
            }
            if (raw === undefined || typeof raw !== 'string') {
                bjccovms5u83u8.instrumentBranch(10, 1, true);
                bjccovms5u83u8.instrumentRegion(10, 4);
                return null;
            }
            else {
                bjccovms5u83u8.instrumentBranch(10, 1, false);
            }
            const cc: string = (raw as string).toLowerCase();
            const idx: number = cc.indexOf('max-age=');
            if (idx < 0) {
                bjccovms5u83u8.instrumentBranch(10, 2, true);
                bjccovms5u83u8.instrumentRegion(10, 5);
                return null;
            }
            else {
                bjccovms5u83u8.instrumentBranch(10, 2, false);
            }
            const rest: string = cc.substring(idx + 8);
            const match: string = rest.split(',')[0].trim();
            const seconds: number = parseInt(match, 10);
            if (isNaN(seconds) || seconds <= 0) {
                bjccovms5u83u8.instrumentBranch(10, 3, true);
                bjccovms5u83u8.instrumentRegion(10, 6);
                return null;
            }
            else {
                bjccovms5u83u8.instrumentBranch(10, 3, false);
            }
            bjccovms5u83u8.instrumentRegion(10, 7);
            return seconds * 1000;
        }
        catch (_e) {
            bjccovms5u83u8.instrumentRegion(10, 2);
            return null;
        }
    }
}
