☰

cloomobile

基于 MapoMagpie/comic-looms 成果重写,专为手机端精简重写的漫画阅读器油猴脚本(支持横向日漫翻页/纵向长条滚动/跨章无缝懒加载)

이 스크립트를 설치하려면 Tampermonkey, Greasemonkey 또는 Violentmonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey 또는 Violentmonkey와 같은 확장 프로그램을 먼저 설치해야 합니다.

이 스크립트를 설치하려면 Tampermonkey 또는 Violentmonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey 또는 Userscripts와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 유저 스크립트 관리자 확장 프로그램이 필요합니다.

(이미 유저 스크립트 관리자가 설치되어 있습니다. 설치를 진행합니다!)

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

(이미 유저 스타일 관리자가 설치되어 있습니다. 설치를 진행합니다!)

// ==UserScript==
// @name         cloomobile
// @namespace    cloomobile
// @version      0.1.2
// @description  基于 MapoMagpie/comic-looms 成果重写,专为手机端精简重写的漫画阅读器油猴脚本(支持横向日漫翻页/纵向长条滚动/跨章无缝懒加载)
// @license      MIT
// @match        *://*.github.com/*
// @match        *://github.com/*
// @match        *://*.hdoujin.org/*
// @match        *://hdoujin.org/*
// @match        *://*.kuaikanmanhua.com/*
// @match        *://kuaikanmanhua.com/*
// @match        *://*.seqingman.com/*
// @match        *://seqingman.com/*
// @match        https://*.artstation.com/*
// @match        https://*.copymanga.tv/*
// @match        https://*.instagram.com/*
// @match        https://*.mangacopy.com/*
// @match        https://*.manhuagui.com/*
// @match        https://*.pinterest.com/*
// @match        https://*.pixiv.net/*
// @match        https://*.wnacg.com/*
// @match        https://*.wnacg.ru/*
// @match        https://18comic.org/*
// @match        https://18comic.vip/*
// @match        https://jmcomic.me/*
// @match        https://jmcomic1.me/*
// @match        https://3hentai.net/*
// @match        https://akuma.moe/*
// @match        https://arca.live/*
// @match        https://asmhentai.com/*
// @match        https://bato.to/*
// @match        https://booru.allthefallen.moe/*
// @match        https://cosplaytele.com/*
// @match        https://www.cosplaytele.com/*
// @match        https://danbooru.donmai.us/*
// @match        https://e-hentai.org/*
// @match        https://exhentai.org/*
// @match        https://e621.net/*
// @match        https://eahentai.com/*
// @match        https://gelbooru.com/*
// @match        https://hanime1.me/comic/*
// @match        https://hentainexus.com/*
// @match        https://hentaizap.com/*
// @match        https://hitomi.la/*
// @match        https://hoshino.one/*
// @match        https://i.jandan.net/*
// @match        https://jandan.net/*
// @match        https://imhentai.xxx/*
// @match        https://komiic.com/*
// @match        https://konachan.com/*
// @match        https://kone.gg/*
// @match        https://m.mh160mh.com/kanmanhua/*
// @match        https://mangadex.org/*
// @match        https://mangapark.com/*
// @match        https://mangatoto.com/*
// @match        https://movie.douban.com/*
// @match        https://www.douban.com/*
// @match        https://mycomic.com/*
// @match        https://nhentai.net/*
// @match        https://nhentai.xxx/*
// @match        https://niyaniya.moe/*
// @match        https://shupogaki.moe/*
// @match        https://pawchive.pw/*
// @match        https://redgifs.com/users/*
// @match        https://www.redgifs.com/users/*
// @match        https://rokuhentai.com/*
// @match        https://rule34.us/*
// @match        https://rule34.xxx/*
// @match        https://se8.us/*
// @match        https://steamcommunity.com/*
// @match        https://twitter.com/*
// @match        https://x.com/*
// @match        https://www.bilibili.com/*
// @match        https://www.colamanga.com/*
// @match        https://www.ykmh.net/manhua/*
// @match        https://yabai.si/*
// @match        https://yande.re/*
// @require      https://cdn.jsdelivr.net/npm/@zip.js/[email protected]/dist/zip.min.js
// @connect      *
// @grant        GM.xmlHttpRequest
// @grant        GM_getValue
// @grant        GM_registerMenuCommand
// @grant        GM_setValue
// @grant        GM_xmlhttpRequest
// @grant        unsafeWindow
// @run-at       document-idle
// ==/UserScript==

(function(_zip_js_zip_js) {
	"use strict";
	var __create = Object.create;
	var __defProp$1 = Object.defineProperty;
	var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
	var __getOwnPropNames = Object.getOwnPropertyNames;
	var __getProtoOf = Object.getPrototypeOf;
	var __hasOwnProp = Object.prototype.hasOwnProperty;
	var __copyProps = (to, from, except, desc) => {
		if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
			key = keys[i];
			if (!__hasOwnProp.call(to, key) && key !== except) __defProp$1(to, key, {
				get: ((k) => from[k]).bind(null, key),
				enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
			});
		}
		return to;
	};
	var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp$1(target, "default", {
		value: mod,
		enumerable: true
	}) : target, mod));
	_zip_js_zip_js = __toESM(_zip_js_zip_js);
	var __defProp = Object.defineProperty;
	var __exportAll = (all, no_symbols) => {
		let target = {};
		for (var name in all) __defProp(target, name, {
			get: all[name],
			enumerable: true
		});
		if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
		return target;
	};
	var GalleryMeta = class {
		url;
		title;
		originTitle;
		downloader;
		tags;
		constructor(url, title) {
			this.url = url;
			this.title = title;
			this.tags = {};
			this.downloader = "https://github.com/MapoMagpie/comic-looms";
		}
	};
	var EventBus = class {
		listeners = new Map();
		subscribe(event, fn) {
			let set = this.listeners.get(event);
			if (!set) {
				set = new Set();
				this.listeners.set(event, set);
			}
			set.add(fn);
			return () => set?.delete(fn);
		}
		emit(event, ...args) {
			const set = this.listeners.get(event);
			if (!set) return void 0;
			let lastResult;
			for (const fn of set) try {
				lastResult = fn(...args);
			} catch (err) {
				console.warn(`[cloomobile] event(${event}) handler error:`, err);
			}
			return lastResult;
		}
		reset() {
			this.listeners.clear();
		}
	};
	var EBUS = new EventBus();
	var DEFAULT_THUMBNAIL = "data:image/gif;base64,R0lGODlhAQABAIAAAMLCwgAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==";
	var EXTENSION_REGEXP = /\.(\w+)[^/]*$|twimg.*format=(\w+)/;
	var NodeAction = class {
		state = "init";
		icon;
		description;
		func;
		reusable;
		data;
		constructor(icon, description, func, reusable = false) {
			this.icon = icon;
			this.description = description;
			this.func = func;
			this.reusable = reusable;
		}
		async run(node, trigger) {
			if (this.state === "processing" || this.state === "done" && !this.reusable) return;
			this.state = "processing";
			try {
				await this.func(this, node, trigger);
				this.state = "done";
				EBUS.emit("notify-message", "info", `${this.icon} 操作成功`, 1500);
			} catch (error) {
				this.state = "error";
				EBUS.emit("notify-message", "error", `操作失败: ${error}`);
			}
		}
	};
	var ImageNode = class {
		thumbnailSrc;
		href;
		title;
		delaySRC;
		_originSrc;
		blobSrc;
		mimeType;
		picked = true;
		rect;
		tags = new Set();
		actions = [];
		openEmbeddedMedia;
		get originSrc() {
			return this._originSrc;
		}
		set originSrc(v) {
			this._originSrc = v;
			this.updateTagByExtension();
		}
		constructor(thumbnailSrc, href, title, delaySRC, originSrc, wh) {
			this.href = href;
			this.title = title;
			this.delaySRC = delaySRC;
			this.rect = wh;
			this.thumbnailSrc = thumbnailSrc;
			this.originSrc = originSrc;
		}
		setTags(...tags) {
			tags.forEach((t) => this.tags.add(t));
		}
		updateTagByExtension() {
			const src = this.originSrc || this.thumbnailSrc;
			if (!src) return;
			const ext = src.match(EXTENSION_REGEXP)?.find((match, i) => i > 0 && match);
			if (ext) this.updateTagByPrefix("ext:" + ext);
		}
		updateTagByPrefix(tag) {
			if (this.tags.has(tag)) return;
			const prefix = tag.split(":").shift();
			if (!prefix) return;
			const found = Array.from(this.tags).find((t) => t.startsWith(prefix));
			if (found) this.tags.delete(found);
			this.tags.add(tag);
		}
		ratio() {
			if (this.rect && this.rect.h > 0) return this.rect.w / this.rect.h;
			return .7;
		}
	};
	var _GM_xhr = typeof GM_xmlhttpRequest !== "undefined" ? GM_xmlhttpRequest : typeof GM !== "undefined" && GM?.xmlHttpRequest ? GM.xmlHttpRequest.bind(GM) : void 0;
	var _GM_getValue = typeof GM_getValue !== "undefined" ? GM_getValue : ((_key, defaultVal) => defaultVal);
	var _GM_setValue = typeof GM_setValue !== "undefined" ? GM_setValue : (() => {});
	var _GM_registerMenuCommand = typeof GM_registerMenuCommand !== "undefined" ? GM_registerMenuCommand : void 0;
	var CONFIG_KEY = "cloomobile_conf_v1";
	var DEFAULT_CONFIG = {
		readMode: "horizontal",
		rtl: true,
		autoDetectMode: true,
		lastHorizontalMode: "horizontal",
		autoFullscreen: true,
		autoOpen: false,
		fetchOriginal: false,
		threads: 3,
		preloadCount: 4,
		timeout: 25,
		excludeVideo: false,
		reverseMultipleImagesPost: false,
		pixivRecordReading: false,
		pixivAscendWorks: false,
		pixivMirrorHost: "",
		ehentaiTitlePrefer: "japanese",
		ehentaiMirrorHost: "",
		hitomiFormat: "auto",
		debug: false
	};
	var transient = {
		imgSrcCSP: false,
		originalPolicy: ""
	};
	function getConf() {
		try {
			const raw = _GM_getValue(CONFIG_KEY, "");
			if (!raw) return { ...DEFAULT_CONFIG };
			const parsed = typeof raw === "string" ? JSON.parse(raw) : raw;
			return {
				...DEFAULT_CONFIG,
				...parsed
			};
		} catch {
			return { ...DEFAULT_CONFIG };
		}
	}
	function saveConf(patch, current) {
		const merged = {
			...current ?? getConf(),
			...patch
		};
		try {
			_GM_setValue(CONFIG_KEY, JSON.stringify(merged));
		} catch (err) {
			console.warn("[cloomobile] saveConf failed:", err);
		}
		return merged;
	}
	var Debouncer = class {
		tids;
		mode;
		lastExecTime;
		constructor(mode) {
			this.tids = {};
			this.lastExecTime = Date.now();
			this.mode = mode || "debounce";
		}
		addEvent(id, event, timeout) {
			if (this.mode === "throttle") {
				const now = Date.now();
				if (now - this.lastExecTime >= timeout) {
					this.lastExecTime = now;
					event();
				}
			} else if (this.mode === "debounce") {
				window.clearTimeout(this.tids[id]);
				this.tids[id] = window.setTimeout(event, timeout);
			}
		}
	};
	var Adapter = class {
		matchers = [];
		matcher;
		conf;
		constructor() {
			this.conf = getConf();
		}
		addSetup(setup) {
			this.matchers.push(setup);
			if (!this.matcher) this.matchUrl(setup, window.location.href);
		}
		matchUrl(setup, url) {
			if (setup.workURLs.some((regex) => regex.test(url))) {
				this.matcher = setup;
				return true;
			}
			return false;
		}
		findMatcher(url = window.location.href) {
			this.matcher = void 0;
			for (const setup of this.matchers) if (this.matchUrl(setup, url)) return setup;
		}
		updateConf(patch) {
			this.conf = saveConf(patch, this.conf);
		}
	};
	var ADAPTER = new Adapter();
	function evLog(level, msg, ...info) {
		if (level === "debug" && !ADAPTER.conf.debug) return;
		if (level === "error") console.warn("[cloomobile]", msg, ...info);
		else console.info("[cloomobile]", msg, ...info);
	}
	var I18nEntry = class {
		text;
		constructor(text) {
			this.text = text;
		}
		get() {
			return this.text;
		}
		toString() {
			return this.text;
		}
	};
	var i18n = {
		failFetchReason1: new I18nEntry("连接 {{domain}} 被拒绝,请检查脚本管理器跨域权限"),
		currentArtWorks: new I18nEntry("当前作品"),
		latestArtWorks: "最新作品",
		beforeLastReading: new I18nEntry("上次阅读之前"),
		afterLastReading: new I18nEntry("上次阅读之后"),
		allArtWorks: new I18nEntry("全部作品"),
		mergedChapters: new I18nEntry("全章节连读")
	};
	var GM_XHR = _GM_xhr;
	function xhrWapper(url, respType, cb, headers, timeout) {
		if (!GM_XHR) throw new Error("当前脚本管理器不支持 GM_xmlhttpRequest API");
		return GM_XHR({
			method: "GET",
			url,
			timeout: timeout || 6e4,
			responseType: respType,
			nocache: false,
			revalidate: false,
			headers: {
				Referer: window.location.href,
				"Cache-Control": "public, max-age=2592000, immutable",
				...headers
			},
			...cb
		})?.abort;
	}
	function simpleFetch(url, respType, headers) {
		return new Promise((resolve, reject) => {
			try {
				xhrWapper(url, respType, {
					onload: (response) => resolve(response.response),
					onerror: (error) => reject(error)
				}, headers ?? {}, 15e3);
			} catch (error) {
				reject(error);
			}
		});
	}
	async function batchFetch(requests, concurrency, respType = "text") {
		const results = new Array(requests.length);
		let i = 0;
		while (i < requests.length) {
			const batchPromises = requests.slice(i, i + concurrency).map((request, index) => window.fetch(request).then((resp) => {
				if (resp.ok) switch (respType) {
					case "text": return resp.text();
					case "json": return resp.json();
					case "arraybuffer": return resp.arrayBuffer();
				}
				throw new Error(`failed to fetch ${request}: ${resp.status} ${resp.statusText}`);
			}).then((raw) => results[index + i] = raw).catch((reason) => results[index + i] = new Error(String(reason))));
			await Promise.all(batchPromises);
			i += concurrency;
		}
		return results;
	}
	var Result = class {
		value;
		error;
		chapterID;
		static ok(value) {
			return { value };
		}
		static err(error) {
			return { error };
		}
	};
	var SubData = class {
		directory;
		list;
		extra;
		constructor(directory, list, extra) {
			this.directory = directory;
			this.list = list;
			this.extra = extra;
		}
		get byteLength() {
			return this.list.map((sd) => sd.data.byteLength).reduce((prev, curr) => prev + curr, 0);
		}
	};
	var BaseMatcher = class {
		async *fetchChapters() {
			return [new Chapter(0, "第 1 话", window.location.href)];
		}
		async fetchImageData(imf) {
			if (imf.node.originSrc?.startsWith("blob:")) return await fetch(imf.node.originSrc).then((resp) => resp.blob().then((b) => [b, 200]));
			return new Promise((resolve, reject) => {
				const debouncer = new Debouncer();
				const timeout = () => {
					debouncer.addEvent("XHR_TIMEOUT", () => {
						imf.abort();
						reject(new Error("图片加载超时"));
					}, ADAPTER.conf.timeout * 1e3);
				};
				try {
					imf.abortSignal = xhrWapper(imf.node.originSrc, "blob", {
						onload: (response) => {
							const data = response.response;
							try {
								imf.setDownloadState({ readyState: response.readyState });
							} catch (error) {
								evLog("error", "setDownloadState error:", error);
							}
							imf.abortSignal = void 0;
							resolve([data, response.status]);
						},
						onerror: (response) => {
							imf.abortSignal = void 0;
							if (response.status === 0) {
								const domain = response.error?.match(/(https?:\/\/.*?)\/.*/)?.[1] ?? "";
								reject(new Error(i18n.failFetchReason1.get().replace("{{domain}}", domain)));
							} else reject(new Error(`HTTP ${response.status}`));
						},
						onprogress: (response) => {
							imf.setDownloadState({
								total: response.total,
								loaded: response.loaded,
								readyState: response.readyState
							});
							timeout();
						},
						onloadstart: () => {
							imf.setDownloadState(imf.downloadState);
						}
					}, imf.matcher.headers(imf.node));
					timeout();
				} catch (error) {
					reject(error);
				}
			});
		}
		title(chapter) {
			const meta = this.galleryMeta(chapter[0]);
			return meta.originTitle || meta.title || document.title || "漫画阅读";
		}
		galleryMeta(_chapter) {
			return new GalleryMeta(window.location.href, document.title || "漫画阅读");
		}
		async processData(data, contentType, _node) {
			return [data, contentType];
		}
		headers(_node) {
			return {};
		}
		appendNewChapters(_url, _old) {
			throw new Error("当前站点不支持手动追加章节");
		}
	};
	var FetchState = function(FetchState) {
		FetchState[FetchState["FAILED"] = 0] = "FAILED";
		FetchState[FetchState["URL"] = 1] = "URL";
		FetchState[FetchState["DATA"] = 2] = "DATA";
		FetchState[FetchState["DONE"] = 3] = "DONE";
		return FetchState;
	}({});
	var IMGFetcher = class {
		index;
		node;
		stage = 1;
		tryTimes = 0;
		lock = false;
		data;
		contentType;
		downloadState = {
			total: 100,
			loaded: 0,
			readyState: 0
		};
		matcher;
		chapterIndex;
		chapterID;
		failedReason;
		abortSignal;
		onStateChange;
		constructor(index, node, matcher, chapterIndex, chapterID) {
			this.index = index;
			this.node = node;
			this.matcher = matcher;
			this.chapterIndex = chapterIndex;
			this.chapterID = chapterID;
		}
		setDownloadState(newState) {
			this.downloadState = {
				...this.downloadState,
				...newState
			};
			this.onStateChange?.(this);
		}
		async start(forceRetry = false) {
			if (this.lock) return false;
			if (forceRetry) {
				this.abort();
				this.stage = this.node.originSrc ? 2 : 1;
				this.failedReason = void 0;
			}
			if (this.stage === 3) return true;
			this.lock = true;
			this.failedReason = void 0;
			this.onStateChange?.(this);
			try {
				await this.fetchImage();
				this.onStateChange?.(this);
				return true;
			} catch (error) {
				this.failedReason = error instanceof Error ? error.message : String(error);
				this.stage = 0;
				evLog("error", `IMG-FETCHER [${this.chapterIndex}:${this.index}] failed:`, error);
				this.onStateChange?.(this);
				return false;
			} finally {
				this.lock = false;
			}
		}
		async fetchImage() {
			const stepOnce = async () => {
				try {
					if (this.stage === 0 || this.stage === 1) {
						const meta = await this.matcher.fetchOriginMeta(this.node, this.tryTimes > 0 || this.stage === 0, this.chapterID);
						this.node.originSrc = meta.url;
						if (meta.title) this.node.title = meta.title;
						if (meta.href) this.node.href = meta.href;
						this.stage = 2;
					}
					if (this.stage === 2) {
						const raw = await this.matcher.fetchImageData(this);
						if (!raw) throw new Error(`图片数据为空: ${this.node.originSrc}`);
						let bytes = new Uint8Array(await raw[0].arrayBuffer());
						let mime = raw[0].type || "image/jpeg";
						[bytes, mime] = await this.matcher.processData(bytes, mime, this.node);
						this.data = bytes;
						this.contentType = mime;
						this.node.mimeType = mime;
						if (mime.startsWith("text") && !(bytes instanceof SubData)) throw new Error(`返回了非图片内容 (${mime})`);
						if (!(bytes instanceof SubData)) {
							if (this.node.blobSrc?.startsWith("blob:")) URL.revokeObjectURL(this.node.blobSrc);
							this.node.blobSrc = transient.imgSrcCSP ? this.node.originSrc : URL.createObjectURL(new Blob([bytes], { type: mime }));
						}
						this.stage = 3;
					}
					return null;
				} catch (err) {
					this.stage = 0;
					return err instanceof Error ? err : new Error(String(err));
				}
			};
			this.tryTimes = 0;
			let lastErr = null;
			while (this.tryTimes < 2) {
				lastErr = await stepOnce();
				if (!lastErr) return;
				this.tryTimes++;
			}
			throw lastErr;
		}
		abort() {
			this.abortSignal?.();
			this.abortSignal = void 0;
		}
		releaseBlob() {
			if (this.node.blobSrc?.startsWith("blob:")) {
				URL.revokeObjectURL(this.node.blobSrc);
				this.node.blobSrc = void 0;
			}
			this.data = void 0;
			if (this.stage === 3) this.stage = this.node.originSrc ? 2 : 1;
		}
	};
	var Chapter = class {
		id;
		title;
		source;
		queue = [];
		filteredQueue = [];
		thumbimg;
		sourceIter;
		done = false;
		onclick;
		meta;
		constructor(id, title, source, thumbimg) {
			this.id = id;
			this.title = title;
			this.source = source;
			this.thumbimg = thumbimg;
		}
		get displayTitle() {
			return Array.isArray(this.title) ? this.title.join(" / ") : this.title;
		}
	};
	var PageFetcher = class {
		chapters = [];
		chapterIndex = 0;
		matcher;
		callbacks;
		appendPromises = new Map();
		activeDownloads = 0;
		pendingFetchQueue = [];
		aborted = false;
		constructor(matcher, callbacks = {}) {
			this.matcher = matcher;
			this.callbacks = callbacks;
		}
		abort() {
			this.aborted = true;
			this.pendingFetchQueue = [];
			for (const ch of this.chapters) for (const imf of ch.queue) {
				imf.abort();
				imf.releaseBlob();
			}
		}
		async init() {
			this.callbacks.onLoadingState?.(true, "正在解析章节信息…");
			try {
				const iter = this.matcher.fetchChapters();
				let firstBatch = true;
				while (!this.aborted) {
					const res = await iter.next();
					if (res.value && res.value.length > 0) {
						this.registerChapters(res.value);
						if (firstBatch) {
							firstBatch = false;
							const initialIdx = this.detectCurrentChapterIndex();
							await this.loadChapterInitial(initialIdx);
						}
					}
					if (res.done) break;
				}
				if (this.chapters.length === 0) throw new Error("未解析到可用章节");
			} catch (err) {
				const msg = err instanceof Error ? err.message : String(err);
				EBUS.emit("notify-message", "error", `解析失败: ${msg}`, 4e3);
			} finally {
				this.callbacks.onLoadingState?.(false);
			}
		}
		detectCurrentChapterIndex() {
			const href = window.location.href;
			const exact = this.chapters.findIndex((c) => c.source && c.source === href);
			if (exact >= 0) return exact;
			return 0;
		}
		registerChapters(list) {
			for (const ch of list) {
				ch.sourceIter = this.matcher.fetchPagesSource(ch);
				this.chapters.push(ch);
			}
			this.callbacks.onChaptersUpdated?.(this.chapters);
		}
		async switchToChapter(index) {
			if (index < 0 || index >= this.chapters.length) return false;
			this.chapterIndex = index;
			const ch = this.chapters[index];
			this.callbacks.onChapterChanged?.(index, ch);
			return await this.loadChapterInitial(index);
		}
		async ensureChapterStarted(index) {
			if (index < 0 || index >= this.chapters.length) return false;
			if (this.chapters[index].queue.length > 0) return true;
			return await this.appendNextPage(index);
		}
		async loadChapterInitial(index) {
			const ch = this.chapters[index];
			this.chapterIndex = index;
			if (ch.queue.length === 0) {
				this.callbacks.onLoadingState?.(true, `正在加载「${ch.displayTitle}」…`);
				try {
					await this.appendNextPage(index);
				} finally {
					this.callbacks.onLoadingState?.(false);
				}
			} else this.callbacks.onPagesAppended?.(index, [], ch.done);
			this.scheduleImagePreload(index, 0);
			return ch.queue.length > 0;
		}
		onActivePage(chapterIndex, pageIndex) {
			const ch = this.chapters[chapterIndex];
			if (!ch || this.aborted) return;
			this.chapterIndex = chapterIndex;
			EBUS.emit("ifq-do", pageIndex, ch.queue[pageIndex]);
			this.scheduleImagePreload(chapterIndex, pageIndex);
			if (!ch.done && pageIndex + 6 >= ch.queue.length) this.appendNextPage(chapterIndex);
		}
		scheduleImagePreload(chapterIndex, centerIndex) {
			const ch = this.chapters[chapterIndex];
			if (!ch) return;
			const preload = ADAPTER.conf.preloadCount;
			const targets = [];
			const addIfPending = (idx) => {
				const imf = ch.queue[idx];
				if (imf && imf.stage !== FetchState.DONE && imf.stage !== FetchState.FAILED && !imf.lock) targets.push(imf);
			};
			addIfPending(centerIndex);
			for (let offset = 1; offset <= preload; offset++) addIfPending(centerIndex + offset);
			if (centerIndex > 0) addIfPending(centerIndex - 1);
			this.pendingFetchQueue = targets;
			this.pumpDownloadQueue();
		}
		pumpDownloadQueue() {
			if (this.aborted) return;
			const maxThreads = Math.max(1, ADAPTER.conf.threads);
			while (this.activeDownloads < maxThreads && this.pendingFetchQueue.length > 0) {
				const next = this.pendingFetchQueue.shift();
				if (next.stage === FetchState.DONE || next.lock) continue;
				this.activeDownloads++;
				next.start().finally(() => {
					this.activeDownloads--;
					this.pumpDownloadQueue();
				});
			}
		}
		async appendNextPage(chapterIndex) {
			const inflight = this.appendPromises.get(chapterIndex);
			if (inflight) return inflight;
			const task = this.appendNextPageInner(chapterIndex).finally(() => {
				this.appendPromises.delete(chapterIndex);
			});
			this.appendPromises.set(chapterIndex, task);
			return task;
		}
		async appendNextPageInner(chapterIndex) {
			const ch = this.chapters[chapterIndex];
			if (!ch || ch.done || this.aborted) return false;
			if (!ch.sourceIter) ch.sourceIter = this.matcher.fetchPagesSource(ch);
			try {
				const next = await ch.sourceIter.next();
				if (next.value?.error) {
					ch.done = true;
					throw next.value.error;
				}
				let added = [];
				if (next.value?.value !== void 0) added = await this.parseAndAppend(ch, chapterIndex, next.value.value, next.value.chapterID);
				if (next.done) ch.done = true;
				this.callbacks.onPagesAppended?.(chapterIndex, added, ch.done);
				if (added.length === 0 && !ch.done && !this.aborted) return await this.appendNextPageInner(chapterIndex);
				return added.length > 0;
			} catch (err) {
				evLog("error", "appendNextPage error:", err);
				const msg = err instanceof Error ? err.message : String(err);
				EBUS.emit("notify-message", "error", `加载页面失败: ${msg}`, 3e3);
				return false;
			}
		}
		async parseAndAppend(ch, chapterIndex, pageSource, chapterID) {
			const cid = chapterID ?? ch.id;
			let nodes = [];
			let lastErr;
			for (let attempt = 0; attempt < 2; attempt++) try {
				nodes = await this.matcher.parseImgNodes(pageSource, cid);
				lastErr = void 0;
				break;
			} catch (err) {
				lastErr = err;
			}
			if (lastErr) throw lastErr;
			if (!nodes || nodes.length === 0 || this.aborted) return [];
			const baseLen = ch.queue.length;
			const fetchers = nodes.map((node, idx) => new IMGFetcher(baseLen + idx, node, this.matcher, chapterIndex, cid));
			ch.queue.push(...fetchers);
			ch.filteredQueue = ch.queue;
			return fetchers;
		}
	};
	var _18comic_exports = __exportAll({});
	function toMD5(s) {
		return md5(s);
	}
	function get_num(gid, page) {
		gid = window.atob(gid);
		page = window.atob(page);
		let n = toMD5(gid + page).slice(-1).charCodeAt(0);
		if (parseInt(gid) >= 268850 && parseInt(gid) <= 421925) n %= 10;
		else if (parseInt(gid) >= 421926) n %= 8;
		if (n < 10) return 2 + 2 * n;
		else return 10;
	}
	function drawImage(ctx, e, gid, page) {
		const width = e.width;
		const height = e.height;
		const s = get_num(window.btoa(gid), window.btoa(page));
		const l = parseInt((height % s).toString());
		const r = width;
		for (let m = 0; m < s; m++) {
			let c = Math.floor(height / s);
			let g = c * m;
			const w = height - c * (m + 1) - l;
			0 == m ? c += l : g += l;
			ctx.drawImage(e, 0, w, r, c, 0, g, r, c);
		}
	}
	var Comic18Matcher = class extends BaseMatcher {
		meta;
		async *fetchChapters() {
			const ret = [];
			const thumb = document.querySelector(".thumb-overlay > img");
			const chapters = Array.from(document.querySelectorAll(".visible-lg .episode > ul > a"));
			if (chapters.length > 0) chapters.forEach((ch, i) => {
				const title = Array.from(ch.querySelector("li")?.childNodes || []).map((n) => n.textContent?.trim()).filter(Boolean).map((n) => n);
				const url = new URL(ch.href);
				url.searchParams.set("read_mode", "read-by-page");
				ret.push(new Chapter(i, title, url.href, thumb?.src));
			});
			else {
				const first = document.querySelector(".visible-lg .read-block")?.firstElementChild;
				if (first === void 0) throw new Error("No page found");
				let href = "";
				if (first instanceof HTMLAnchorElement) href = first.href;
				else href = first.getAttribute("href") || "";
				if (!href || href.startsWith("javascript")) throw new Error("未能找到阅读按钮!");
				if (href.startsWith("#coinbuycomic")) throw new Error("此漫画需要硬币解锁!请点击开始阅读按钮进行解锁。");
				const url = new URL(href);
				url.searchParams.set("read_mode", "read-by-page");
				ret.push(new Chapter(0, "Default", url.href));
			}
			return ret;
		}
		async *fetchPagesSource(chapter) {
			yield Result.ok(chapter.source);
		}
		async parseImgNodes(source) {
			const list = [];
			const raw = await window.fetch(source).then((resp) => resp.text()).then((text) => new DOMParser().parseFromString(text, "text/html")).catch(Error);
			if (raw instanceof Error) throw new Error("请求页面失败: " + source + "  " + raw.message, { cause: raw.cause });
			const elements = Array.from(raw.querySelectorAll(".owl-carousel-page > .center > img"));
			if (elements.length === 0) throw new Error("未能从该页面获取有效的图片," + source);
			for (const element of elements) {
				const src = element.getAttribute("data-src");
				if (!src) {
					evLog("error", "warn: cannot find img src", element);
					continue;
				}
				const title = src.split("/").pop();
				list.push(new ImageNode("", src, title, void 0, src));
			}
			return list;
		}
		async processData(data, contentType, node) {
			const matches = node.originSrc.match(/(\d+)\/(\d+)\.(\w+)/);
			const gid = matches[1];
			if (Number(gid) < 220980) return [data, contentType];
			const page = matches[2];
			if (matches[3] === "gif") return [data, contentType];
			const img = await createImageBitmap(new Blob([data], { type: contentType }));
			const canvas = document.createElement("canvas");
			canvas.width = img.width;
			canvas.height = img.height;
			drawImage(canvas.getContext("2d"), img, gid, page);
			return new Promise((resolve) => canvas.toBlob((blob) => {
				if (!blob) throw new Error("canvas.toBlob was given a null value");
				blob.arrayBuffer().then((buf) => resolve([new Uint8Array(buf), blob.type])).finally(() => canvas.remove());
			}, contentType));
		}
		galleryMeta() {
			if (this.meta) return this.meta;
			const title = document.querySelector(".panel-heading h2")?.textContent || document.title || "UNTITLE";
			this.meta = new GalleryMeta(window.location.href, title);
			this.meta.originTitle = title;
			const tagTrList = document.querySelectorAll("div.tag-block > span");
			const tags = {};
			tagTrList.forEach((tr) => {
				const cat = tr.getAttribute("data-type")?.trim();
				if (cat) {
					const values = Array.from(tr.querySelectorAll("a")).map((a) => a.textContent).filter(Boolean);
					if (values.length > 0) tags[cat] = values;
				}
			});
			this.meta.tags = tags;
			return this.meta;
		}
		async fetchOriginMeta(node, retry) {
			let src = node.originSrc;
			if (retry) {
				const matches = src.match(/\/\/cdn-msp(\d)?\./);
				let num = 1;
				if (matches !== null && matches.length > 0) {
					num = parseInt(matches[1] ?? "1");
					if (isNaN(num)) num = 1;
					num++;
					num = num % 3;
					num = num === 0 ? num = 3 : num;
				}
				src = src.replace(/\/\/cdn-msp(\d)?\./, `//cdn-msp${num === 1 ? "" : num}.`);
			}
			return { url: src };
		}
	};
	ADAPTER.addSetup({
		name: "禁漫",
		workURLs: [
			/(18|jm)comic.*?\/album\/\d+/,
			/jm18c-.*?\/album\/\d+/,
			/comic18j-codi.net\/album\/\d+/
		],
		match: ["https://18comic.vip/*"],
		constructor: () => new Comic18Matcher()
	});
	var _3hentai_exports = __exportAll({});
	var Hentai3Matcher = class extends BaseMatcher {
		async *fetchPagesSource() {
			yield Result.ok(document);
		}
		async parseImgNodes(doc) {
			const elements = Array.from(doc.querySelectorAll(".single-thumb > a"));
			const digits = elements.length.toString().length;
			const nodes = elements.map((elem, i) => {
				const href = elem.href;
				const img = elem.querySelector("img.lazy");
				if (!img) throw new Error("cannot find image element");
				const thumb = img.getAttribute("data-src") ?? "";
				const ext = thumb.split(".").pop() ?? "jpg";
				return new ImageNode(thumb, href, (i + 1).toString().padStart(digits, "0") + "." + ext, void 0, void 0, {
					w: img.width,
					h: img.height
				});
			});
			if (nodes.length === 0) throw new Error("cannot find images by css selector: .single-thumb > a");
			const firstImageDoc = await window.fetch(nodes[0].href).then((resp) => resp.text()).then((text) => new DOMParser().parseFromString(text, "text/html")).catch(Error);
			if (firstImageDoc instanceof Error) throw firstImageDoc;
			const pagesRaw = Array.from(firstImageDoc.querySelectorAll("script")).find((elem) => elem.textContent?.trimStart().startsWith("var readerPages "))?.textContent?.match(/var readerPages = JSON\.parse\(atob\("(.*)?\"\)\)/)?.[1];
			if (pagesRaw) {
				const pages = JSON.parse(window.atob(pagesRaw));
				nodes.forEach((node, i) => {
					const page = pages.pages[(i + 1).toString()];
					if (!page) return;
					node.title = page.f ?? node.title;
					node.originSrc = pages.baseUriImg.replace("%s", page.f);
					node.rect = {
						w: page.w,
						h: page.h
					};
				});
			}
			return nodes;
		}
		async fetchOriginMeta(node) {
			if (node.originSrc) return { url: node.originSrc };
			const doc = await window.fetch(node.href).then((resp) => resp.text()).then((text) => new DOMParser().parseFromString(text, "text/html")).catch(Error);
			if (doc instanceof Error) throw doc;
			const image = doc.querySelector(".js-main-img");
			if (!image) throw new Error("cannot find image from: " + node.href);
			return {
				url: image.src,
				title: image.src.split("/").pop() ?? node.title
			};
		}
		meta;
		galleryMeta() {
			if (this.meta) return this.meta;
			const title = document.querySelector("#main-info > h1")?.textContent ?? document.title;
			const meta = new GalleryMeta(window.location.href, title);
			Array.from(document.querySelectorAll(".tag-container.field-name")).forEach((elem) => {
				const cate = elem.firstChild?.textContent?.trim()?.replace(":", "")?.toLowerCase();
				const filterElem = Array.from(elem.querySelectorAll("span.filter-elem"));
				if (cate && filterElem.length > 0) {
					const tags = filterElem.map((elem) => elem.textContent?.trim()).filter(Boolean);
					meta.tags[cate] = tags;
				}
			});
			this.meta = meta;
			return this.meta;
		}
	};
	ADAPTER.addSetup({
		name: "3Hentai",
		workURLs: [/3hentai.net\/d\/\d+$/],
		constructor: () => new Hentai3Matcher()
	});
	var akuma_exports = __exportAll({});
	var AkumaMatcher = class extends BaseMatcher {
		originImages;
		index = 0;
		meta;
		title() {
			return this.galleryMeta().title;
		}
		galleryMeta() {
			if (!this.meta) this.meta = this.initGalleryMeta(document);
			return this.meta;
		}
		initGalleryMeta(doc) {
			const title = doc.querySelector("header.entry-header > h1")?.textContent ?? doc.title;
			const meta = new GalleryMeta(window.location.href, title);
			meta.originTitle = doc.querySelector("header.entry-header > span")?.textContent || void 0;
			meta.tags = Array.from(doc.querySelectorAll("ul.info-list > li.meta-data")).reduce((prev, curr) => {
				const cat = curr.querySelector("span.data")?.textContent?.replace(":", "").toLowerCase().trim();
				if (cat) prev[cat] = Array.from(curr.querySelectorAll("span.value")).map((v) => v.textContent?.trim()).filter(Boolean);
				return prev;
			}, {});
			return meta;
		}
		async *fetchPagesSource() {
			const csrf = document.querySelector("meta[name='csrf-token'][content]")?.content;
			if (!csrf) throw new Error("cannot get csrf token form this page");
			this.originImages = await window.fetch(window.location.href, {
				headers: {
					"X-CSRF-TOKEN": csrf,
					"X-Requested-With": "XMLHttpRequest",
					"Sec-Fetch-Dest": "empty"
				},
				method: "POST"
			}).then((res) => res.json());
			const pagRaw = Array.from(document.querySelectorAll("body > script")).find((s) => s.textContent?.trimStart().startsWith("var ajx"))?.textContent?.match(/pag = (\{.*?\}),/s)?.[1];
			if (!pagRaw) throw new Error("cannot get page info");
			const pag = JSON.parse(pagRaw.replaceAll(/(\w+) :/g, "\"$1\":"));
			let idx = pag.idx;
			yield Result.ok(document);
			while (idx * pag.stp < pag.cnt) {
				const res = await window.fetch(pag.act, {
					headers: {
						"X-CSRF-TOKEN": csrf,
						"X-Requested-With": "XMLHttpRequest",
						"Sec-Fetch-Dest": "empty",
						"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
					},
					method: "POST",
					body: `index=${idx}`
				});
				if (!res.ok) yield Result.err(new Error(`fetch thumbnails failed, status: ${res.statusText}`));
				idx++;
				yield Result.ok(await res.text().then((text) => new DOMParser().parseFromString(text, "text/html")));
			}
		}
		async parseImgNodes(doc) {
			const items = Array.from(doc.querySelectorAll("li > a.page-item"));
			if (items.length === 0) throw new Error("cannot find thumbnails");
			const ret = [];
			const digits = this.originImages.length.toString().length;
			for (const item of items) {
				const origin = this.originImages[this.index];
				const href = item.href;
				const thumb = item.firstElementChild.src;
				const ext = origin.split(".").pop() ?? "jpg";
				const originSrc = thumb.slice(0, thumb.indexOf("tbn")) + origin;
				const title = (this.index + 1).toString().padStart(digits, "0");
				ret.push(new ImageNode(thumb, href, `${title}.${ext}`, void 0, originSrc));
				this.index++;
			}
			return ret;
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
	};
	ADAPTER.addSetup({
		name: "Akuma.moe",
		workURLs: [/akuma.moe\/g\/\w+\/?$/],
		match: ["https://akuma.moe/*"],
		preloadAllPages: true,
		constructor: () => new AkumaMatcher()
	});
	var arca_exports = __exportAll({});
	var ArcaMatcher = class extends BaseMatcher {
		async *fetchPagesSource() {
			yield Result.ok(document);
		}
		async parseImgNodes(doc) {
			const elements = Array.from(doc.querySelectorAll(`.article-content img:not(.arca-emoticon):not(.twemoji), .article-content video:not(.arca-emoticon)`));
			const nodes = [];
			const digits = elements.length.toString().length;
			elements.forEach((element, i) => {
				if (element.tagName.toLowerCase() === "img") {
					const img = element;
					if (img.src && img.style.width !== "0px") {
						const src = img.src;
						const href = new URL(src);
						const ext = href.pathname.split(".").pop();
						href.searchParams.set("type", "orig");
						const title = (i + 1).toString().padStart(digits, "0") + "." + ext;
						nodes.push(new ImageNode(src, href.href, title, void 0, href.href));
					}
				} else if (element.tagName.toLowerCase() === "video") {
					const video = element;
					const preview = video.src || video.getAttribute("data-originalurl") || "";
					if (preview) {
						const ext = new URL(preview).pathname.split(".").pop() ?? "mp4";
						const original = video.getAttribute("data-originalurl") ?? (() => {
							const url = new URL(preview);
							url.searchParams.set("type", "orig");
							return url.href;
						})();
						const title = (i + 1).toString().padStart(digits, "0") + "." + ext;
						const node = new ImageNode(video.poster || "", original, title, void 0, preview);
						node.mimeType = "video/" + ext;
						nodes.push(node);
					}
				}
			});
			return nodes;
		}
		async fetchOriginMeta(node) {
			if (node.mimeType?.startsWith("video")) return { url: ADAPTER.conf.fetchOriginal ? node.href : node.originSrc };
			return { url: ADAPTER.conf.fetchOriginal ? node.href : node.thumbnailSrc };
		}
	};
	ADAPTER.addSetup({
		name: "Arcalive",
		workURLs: [/arca.live\/b\/\w*\/\d+/],
		match: ["https://arca.live/*"],
		constructor: () => new ArcaMatcher()
	});
	var artstation_exports = __exportAll({});
	var ArtStationMatcher = class extends BaseMatcher {
		pageData = new Map();
		info = {
			username: "",
			projects: 0,
			assets: 0
		};
		tags = {};
		galleryMeta() {
			const meta = new GalleryMeta(window.location.href, `artstaion-${this.info.username}-w${this.info.projects}-p${this.info.assets}`);
			meta.tags = this.tags;
			return meta;
		}
		async *fetchPagesSource() {
			const { id, username } = await this.fetchArtistInfo();
			this.info.username = username;
			let page = 0;
			while (true) {
				page++;
				try {
					const projects = await this.fetchProjects(username, id.toString(), page);
					if (!projects || projects.length === 0) break;
					yield Result.ok(projects);
				} catch (error) {
					page--;
					yield Result.err(error);
				}
			}
		}
		async parseImgNodes(projects) {
			const assets = await batchFetch(projects.map((p) => `https://www.artstation.com/projects/${p.hash_id}.json`), 10, "json");
			const ret = [];
			for (const asset of assets) {
				if (asset instanceof Error) {
					evLog("error", asset.message);
					EBUS.emit("notify-message", "error", asset.message, 8e3);
					continue;
				}
				this.info.projects++;
				this.tags[asset.slug] = asset.tags;
				for (let i = 0; i < asset.assets.length; i++) {
					const a = asset.assets[i];
					if (a.asset_type === "cover") continue;
					const thumb = a.image_url.replace("/large/", "/small/");
					const ext = a.image_url.match(/\.(\w+)\?\d+$/)?.[1] ?? "jpg";
					const title = `${asset.slug}-${i + 1}.${ext}`;
					let originSrc = a.image_url;
					if (a.has_embedded_player && a.player_embedded) {
						if (a.player_embedded.includes("youtube")) continue;
						originSrc = a.player_embedded;
					}
					this.info.assets++;
					ret.push(new ImageNode(thumb, asset.permalink, title, void 0, originSrc, {
						w: a.width,
						h: a.height
					}));
				}
			}
			return ret;
		}
		async fetchOriginMeta(node) {
			if (node.originSrc?.startsWith("<iframe")) {
				const iframe = node.originSrc.match(/src=['"](.*?)['"]\s/)?.[1];
				if (!iframe) throw new Error("cannot match video clip url");
				const source = (await window.fetch(iframe).then((res) => res.text()).then((text) => new DOMParser().parseFromString(text, "text/html"))).querySelector("video > source");
				if (!source) throw new Error("cannot find video element");
				return { url: source.src };
			}
			return { url: node.originSrc };
		}
		async processData(data, contentType) {
			if (contentType.startsWith("binary") || contentType.startsWith("text")) return [data, "video/mp4"];
			return [data, contentType];
		}
		async fetchArtistInfo() {
			const user = window.location.pathname.slice(1).split("/").shift();
			if (!user) throw new Error("cannot match artist's username");
			return await window.fetch(`https://www.artstation.com/users/${user}/quick.json`).then((res) => res.json());
		}
		async fetchProjects(user, id, page) {
			const url = `https://www.artstation.com/users/${user}/projects.json?user_id=${id}&page=${page}`;
			return (await window.fetch(url).then((res) => res.json())).data;
		}
	};
	ADAPTER.addSetup({
		name: "Art Station",
		workURLs: [/artstation.com\/[-\w]+(\/albums\/\d+)?$/],
		match: ["https://www.artstation.com/*"],
		constructor: () => new ArtStationMatcher()
	});
	var asmhentai_exports = __exportAll({});
	var AsmHentaiMatcher = class extends BaseMatcher {
		async *fetchPagesSource() {
			const csrf = document.querySelector("meta[name=\"csrf-token\"]")?.getAttribute("content");
			if (!csrf) throw new Error("cannot find csrf_token");
			const loadID = document.querySelector("#load_id")?.value;
			if (!loadID) throw new Error("cannot find load_id");
			const loadDir = document.querySelector("#load_dir")?.value;
			if (!loadDir) throw new Error("cannot find load_dir");
			const pages = document.querySelector("#t_pages")?.value;
			if (!pages) throw new Error("cannot find t_pages");
			const api = window.location.origin + "/inc/thumbs_loader.php";
			const raw = await window.fetch(api, {
				"headers": {
					"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
					"X-Requested-With": "XMLHttpRequest"
				},
				"body": `_token=${csrf}&id=${loadID}&dir=${loadDir}&visible_pages=0&t_pages=${pages}&type=2`,
				"method": "POST"
			}).then((resp) => resp.text()).catch(Error);
			if (raw instanceof Error) throw raw;
			yield Result.ok(raw);
		}
		async parseImgNodes(raw) {
			const infos = Array.from(raw.matchAll(/<a href="(.*?)".*data-src="(.*?)"/g)).filter((m) => m.length === 3).map((m) => [m[1], m[2]]);
			const digits = infos.length.toString().length;
			return infos.map((info, i) => new ImageNode(info[1], window.location.origin + info[0], (i + 1).toString().padStart(digits, "0")));
		}
		async fetchOriginMeta(node) {
			const href = node.href;
			const doc = await window.fetch(href).then((resp) => resp.text()).then((text) => new DOMParser().parseFromString(text, "text/html")).catch(Error);
			if (doc instanceof Error) throw doc;
			const src = doc.querySelector("#fimg")?.getAttribute("data-src");
			if (!src) throw new Error("cannot find image from: " + href);
			const ext = src.split(".").pop() ?? "jpg";
			return {
				url: src,
				title: node.title + "." + ext
			};
		}
		meta;
		galleryMeta() {
			if (this.meta) return this.meta;
			const title = document.querySelector(".right > .info > h1")?.textContent ?? document.title;
			const meta = new GalleryMeta(window.location.href, title);
			meta.originTitle = document.querySelector(".right > .info > h2")?.textContent ?? void 0;
			Array.from(document.querySelectorAll(".right > .info > ul > .tags")).forEach((elem) => {
				const cate = elem.querySelector("h3")?.textContent?.trim().replace(":", "").toLowerCase();
				if (cate) {
					const tags = Array.from(elem.querySelectorAll(".tag_list > a > span")).map((span) => span.firstChild?.textContent ?? void 0).filter(Boolean);
					if (tags.length > 0) meta.tags[cate] = tags;
				}
			});
			this.meta = meta;
			return this.meta;
		}
	};
	ADAPTER.addSetup({
		name: "AsmHentai",
		workURLs: [/asmhentai.com\/g\/\d+\/?$/],
		match: ["https://asmhentai.com/*"],
		constructor: () => new AsmHentaiMatcher()
	});
	function uuid() {
		return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
			const r = Math.random() * 16 | 0;
			return (c == "x" ? r : r & 3 | 8).toString(16);
		});
	}
	function transactionId() {
		return window.btoa(uuid());
	}
	function b64DecodeUnicode(str) {
		return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
			return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
		}).join(""));
	}
	function sleep$1(ms) {
		return new Promise((resolve) => setTimeout(resolve, ms));
	}
	var bilibili_exports = __exportAll({});
	var colamanga_exports = __exportAll({});
	var EXTRACT_C_DATA = /var C_DATA='(.*?)'/;
	function decrypt$1(key, raw) {
		const cryptoJS = CryptoJS;
		if (!cryptoJS) throw new Error("cryptoJS undefined");
		var keyenc = cryptoJS.enc.Utf8.parse(key);
		var ret = cryptoJS.AES.decrypt(raw, keyenc, {
			mode: cryptoJS.mode.ECB,
			padding: cryptoJS.pad.Pkcs7
		});
		return cryptoJS.enc.Utf8.stringify(ret).toString();
	}
	function parseBase64ToUtf8(raw) {
		const decodedBytes = Uint8Array.from(atob(raw), (char) => char.charCodeAt(0));
		return new TextDecoder().decode(decodedBytes);
	}
	function initColamangaKeys() {
		return new Promise((resolve, reject) => {
			const jsURL = "https://www.colamanga.com/js/custom.js";
			const elem = document.createElement("script");
			elem.addEventListener("load", async () => {
				try {
					resolve(parseKeys(await window.fetch(jsURL).then((res) => res.text())));
				} catch (reason) {
					reject(reason);
				}
			});
			elem.src = jsURL;
			elem.type = "text/javascript";
			document.querySelector("head").append(elem);
		});
	}
	function initColaMangaKeyMap() {
		return new Promise((resolve, reject) => {
			const jsURL = "https://www.colamanga.com/js/manga.read.js";
			const elem = document.createElement("script");
			elem.addEventListener("load", async () => {
				try {
					const text = await window.fetch(jsURL).then((res) => res.text());
					let fun;
					const matches = text.matchAll(/if\(_0x\w+==(0x\w+)\)return (_0x\w+)\((0x\w+)\);/gm);
					const keymap = {};
					let isEmpty = true;
					for (const m of matches) {
						const key = m[1];
						const fn = m[2];
						const pam = m[3];
						if (!fun) {
							const name = findTheFunction(text, fn)?.[0]?.[0] ?? fn;
							console.log("colamanga, the function name: ", name);
							fun = new Function("p", `return ${name}(p)`);
						}
						const val = fun(pam);
						keymap[parseInt(key)] = val;
						isEmpty = false;
					}
					if (isEmpty) throw new Error("cannot init key map from " + jsURL);
					resolve([keymap, parseGetActualKeyFunction(text)]);
				} catch (reason) {
					reject(reason);
				}
			});
			elem.src = jsURL;
			elem.type = "text/javascript";
			document.querySelector("head").append(elem);
		});
	}
	var ColaMangaMatcher = class extends BaseMatcher {
		infoMap = {};
		keymap;
		keys = [
			"dDeIieDgQpwVQZsJ",
			"54bilXmmMoYBqBcI",
			"KcmiZ8owmiBoPRMf",
			"4uOJvtnq5YYIKZWA",
			"lVfo0i0o4g3V78Rt",
			"i8XLTfT8Mvu1Fcv2"
		];
		getActualK;
		async *fetchChapters() {
			this.keys = await initColamangaKeys();
			[this.keymap, this.getActualK] = await initColaMangaKeyMap();
			const thumbimg = document.querySelector("dt.fed-part-rows > a")?.getAttribute("data-original") || void 0;
			return Array.from(document.querySelectorAll(".all_data_list .fed-part-rows > li > a")).map((a, index) => new Chapter(index, a.title, a.href, thumbimg));
		}
		async *fetchPagesSource(source) {
			yield Result.ok(source.source);
		}
		async parseImgNodes(page, _chapterID) {
			const cdata = (await window.fetch(page).then((res) => res.text())).match(EXTRACT_C_DATA)?.[1];
			if (!cdata) throw new Error("cannot find C_DATA from page: " + page);
			let infoRaw;
			for (const k of this.keys) try {
				infoRaw = decrypt$1(k, parseBase64ToUtf8(cdata));
				break;
			} catch (_error) {
				evLog("error", _error.toString());
			}
			if (!infoRaw) throw new Error("colamanga decrypt C_DATA failed");
			infoRaw = infoRaw.replace("};", "},");
			infoRaw = infoRaw.replaceAll("info=", "info:");
			infoRaw = "{" + infoRaw + "}";
			infoRaw = infoRaw.replaceAll(/(\w+):/g, "\"$1\":");
			const info = JSON.parse(infoRaw);
			const [count, path] = decryptInfo(info.mh_info.enc_code1, info.mh_info.enc_code2, info.mh_info.mhid, this.keys);
			if (count === void 0 || path === void 0) throw new Error("colamanga decrypt mh_info failed");
			const nodes = [];
			const href = window.location.origin + info.mh_info.webPath + info.mh_info.pageurl;
			this.infoMap[href] = info;
			for (let start = info.mh_info.startimg; start <= parseInt(count); start++) {
				const [name, url] = getImageURL(start, path, info);
				nodes.push(new ImageNode("", href, name, void 0, url));
			}
			return nodes;
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
		headers() {
			return {
				"Referer": window.location.href,
				"Origin": window.location.origin
			};
		}
		decryptImageData(data, keyType, imgKey, keymap, keys) {
			let kRaw;
			if (keyType !== "" && keyType !== "0") kRaw = keymap[parseInt(keyType)];
			else for (const k of keys) try {
				kRaw = decrypt$1(k, imgKey);
				break;
			} catch (_error) {
				evLog("error", _error.toString());
			}
			const encArray = { ciphertext: convertUint8ArrayToWordArray(data) };
			const cryptoJS = CryptoJS;
			const actualK = this.getActualK?.(kRaw);
			const key = cryptoJS.enc.Utf8.parse(actualK);
			return convertWordArrayToUint8Array(cryptoJS.AES.decrypt(encArray, key, {
				iv: cryptoJS.enc.Utf8.parse("0000000000000000"),
				mode: cryptoJS.mode.CBC,
				padding: cryptoJS.pad.Pkcs7
			}));
		}
	};
	function convertUint8ArrayToWordArray(data) {
		let words = [];
		let i = 0;
		let len = data.length;
		while (i < len) words.push(data[i++] << 24 | data[i++] << 16 | data[i++] << 8 | data[i++]);
		return {
			sigBytes: words.length * 4,
			words
		};
	}
	function convertWordArrayToUint8Array(data) {
		const len = data.words.length;
		const u8_array = new Uint8Array(len << 2);
		let offset = 0;
		let word;
		for (let i = 0; i < len; i++) {
			word = data.words[i];
			u8_array[offset++] = word >> 24;
			u8_array[offset++] = word >> 16 & 255;
			u8_array[offset++] = word >> 8 & 255;
			u8_array[offset++] = word & 255;
		}
		return u8_array;
	}
	function decryptInfo(countEncCode, pathEncCode, mhid, keys) {
		let count;
		for (const k of keys) try {
			count = decrypt$1(k, parseBase64ToUtf8(countEncCode));
			if (count == "" || isNaN(parseInt(count))) throw new Error("colamanga failed decrypt image count");
			break;
		} catch (_error) {
			evLog("error", _error.toString());
		}
		let path;
		for (const k of keys) try {
			path = decrypt$1(k, parseBase64ToUtf8(pathEncCode));
			if (path == "" || !path.startsWith(mhid + "/")) throw new Error("colamanga failed decrypt image path");
			break;
		} catch (_error) {
			evLog("error", _error.toString());
		}
		return [count, path];
	}
	function getImageURL(index, path, info) {
		const start = (info.mh_info.startimg + index - 1).toString().padStart(4, "0");
		let imgName = start + ".jpg";
		if (info.image_info.imgKey != void 0 && info.image_info.imgKey != "") imgName = start + ".enc.webp";
		const host = window.location.host.replace("www.", "");
		const url = "https://img" + info.mh_info.use_server + "." + host + "/comic/" + encodeURI(path) + imgName;
		return [imgName, url];
	}
	function parseKeys(raw) {
		const matches = raw.matchAll(/window(\[\w+\(0x[^)]+\)\]){2}\(((\w+)(\(0x[^)]+\))?),/gm);
		const keys = [];
		for (const m of matches) {
			const kv = m[3];
			const pv = m[4];
			if (!kv) continue;
			for (const [fn, param] of findTheFunction(raw, kv, pv)) {
				if (fn === null || param === null) continue;
				const key = new Function("return " + fn + param)();
				if (keys.includes(key)) continue;
				keys.push(key);
			}
		}
		return keys;
	}
	function parseGetActualKeyFunction(raw) {
		const evalExpression = raw.match(/(eval\(function.*?\)\)\)),_0x/)?.[1];
		return new Function("ksddd", `
        var actualKey = ksddd;
        ${evalExpression};
        return actualKey;
      `);
	}
	function findTheFunction(raw, val, param) {
		const reg = new RegExp(val + `=((\\w+)(\\([^)]+\\))?)[,; ]`, "gm");
		const matches = raw.matchAll(reg);
		const ret = [];
		let empty = true;
		for (const m of matches) {
			empty = false;
			const k = m[2];
			const p = m[3];
			if (p) param = p;
			if (k) ret.push(...findTheFunction(raw, k, param));
		}
		if (empty && raw.includes("function " + val)) ret.push([val, param ?? null]);
		return ret;
	}
	ADAPTER.addSetup({
		name: "colamanga",
		workURLs: [/colamanga.com\/manga-\w*\/?$/],
		match: ["https://www.colamanga.com/*"],
		constructor: () => new ColaMangaMatcher()
	});
	var cosplaytele_parser_exports = __exportAll({
		cosplayAlbums: () => cosplayAlbums,
		cosplayCover: () => cosplayCover,
		cosplayImages: () => cosplayImages,
		cosplayPlayers: () => cosplayPlayers,
		videosFirst: () => videosFirst
	});
	function videosFirst(videos, images) {
		return [...videos, ...images];
	}
	function cosplayCover(doc, base) {
		const backgroundURL = (doc.querySelector(".blog-featured-title .title-bg")?.getAttribute("style"))?.match(/background-image\s*:\s*url\(\s*["']?(.*?)["']?\s*\)/i)?.[1];
		const featured = doc.querySelector(".entry-image img, article .wp-post-image");
		const candidates = [
			backgroundURL,
			featured?.getAttribute("data-src"),
			featured?.getAttribute("src"),
			doc.querySelector("meta[property=\"og:image\"]")?.getAttribute("content")
		];
		for (const candidate of candidates) {
			const url = imageURL(candidate ?? null, base);
			if (url) return url;
		}
	}
	function cosplayPlayers(doc, base) {
		const players = Array.from(doc.querySelectorAll(".entry-content iframe[src]")).map((frame) => httpURL(frame.getAttribute("src"), base));
		return [...new Set(players.filter((url) => !!url && /^https:\/\/cossora\.stream\/embed\/[\w-]+$/.test(url)))];
	}
	function httpURL(value, base) {
		if (!value) return void 0;
		try {
			const url = new URL(value, base);
			return /^https?:$/.test(url.protocol) ? url.href : void 0;
		} catch {
			return;
		}
	}
	function imageURL(value, base) {
		const url = httpURL(value, base);
		return url && /\.(?:jpe?g|png|webp|gif|avif)(?:\?|$)/i.test(url) ? url : void 0;
	}
	function cosplayImages(doc, base) {
		const seen = new Set();
		const result = [];
		const images = doc.querySelectorAll(".entry-content .gallery img, .entry-content .wp-block-gallery img");
		for (const img of Array.from(images)) {
			const thumbnail = imageURL(img.getAttribute("data-src"), base) ?? imageURL(img.getAttribute("src"), base);
			const url = imageURL(img.closest("a")?.getAttribute("href") ?? null, base) ?? imageURL(img.getAttribute("data-full-url"), base) ?? thumbnail;
			if (!url || seen.has(url)) continue;
			seen.add(url);
			const filename = new URL(url).pathname.split("/").pop() || `${result.length + 1}.jpg`;
			result.push({
				url,
				thumbnail: thumbnail ?? url,
				title: filename
			});
		}
		return result;
	}
	function cosplayAlbums(doc, base) {
		const result = [];
		const seen = new Set();
		for (const title of Array.from(doc.querySelectorAll("#content .post-title, main .post-title, #content .entry-title, main .entry-title"))) {
			const url = httpURL((title.querySelector("a") ?? title.closest("a"))?.getAttribute("href") ?? null, base);
			if (!url || new URL(url).origin !== new URL(base).origin || seen.has(url)) continue;
			seen.add(url);
			const img = title.closest(".post-item, article")?.querySelector("img");
			const cover = imageURL(img?.getAttribute("data-src") ?? img?.getAttribute("src") ?? null, base);
			result.push({
				url,
				title: title.textContent?.trim() || url,
				cover
			});
		}
		return result;
	}
	var cosplaytele_exports = __exportAll({});
	var PLAYER_CARD = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"640\" height=\"360\"><rect width=\"640\" height=\"360\" fill=\"#171717\"/><text x=\"320\" y=\"165\" text-anchor=\"middle\" fill=\"white\" font-size=\"34\">JW PLAYER VIDEO</text><text x=\"320\" y=\"215\" text-anchor=\"middle\" fill=\"white\" font-size=\"22\">Hover thumbnail and click ▶ to play</text></svg>";
	var PLAYER_THUMB = `data:image/svg+xml,${encodeURIComponent(PLAYER_CARD)}`;
	if (location.hostname === "cossora.stream" && location.pathname.startsWith("/embed/") && window.parent !== window) {
		let parentOrigin = "";
		try {
			parentOrigin = new URL(document.referrer).origin;
		} catch {}
		if (/^https:\/\/(?:www\.)?cosplaytele\.com$/.test(parentOrigin)) window.addEventListener("keydown", (event) => {
			if (event.key !== "Escape") return;
			event.preventDefault();
			event.stopImmediatePropagation();
			window.parent.postMessage({ type: "comic-looms-close-player" }, parentOrigin);
		}, true);
	}
	var activePlayer;
	function openPlayer(url, sourcePage) {
		if (activePlayer?.open) return;
		const previousFocus = document.activeElement;
		const dialog = document.createElement("dialog");
		activePlayer = dialog;
		const abort = new AbortController();
		dialog.style.cssText = "padding:12px;background:#171717;color:white;border:0;width:90vw;max-width:1200px;";
		const close = document.createElement("button");
		close.textContent = "关闭视频 / Close";
		const original = document.createElement("a");
		original.textContent = "在新标签页打开原文章播放 / Open original article";
		original.href = sourcePage;
		original.target = "_blank";
		original.rel = "noopener";
		original.style.cssText = "display:inline-block;margin:8px 16px;color:#9bd5ff;";
		const frame = document.createElement("iframe");
		frame.src = url;
		frame.title = "Cosplaytele JW Player";
		frame.allowFullscreen = true;
		frame.allow = "fullscreen; picture-in-picture";
		frame.style.cssText = "display:block;width:100%;height:75vh;border:0;margin-top:8px;";
		dialog.append(close, original, frame);
		dialog.addEventListener("click", (event) => {
			if (event.target === dialog) dialog.close();
		});
		close.onclick = () => dialog.close();
		dialog.addEventListener("cancel", (event) => {
			event.preventDefault();
			dialog.close();
		});
		window.addEventListener("keydown", (event) => {
			if (event.key !== "Escape") return;
			event.preventDefault();
			event.stopImmediatePropagation();
			dialog.close();
		}, {
			capture: true,
			signal: abort.signal
		});
		window.addEventListener("message", (event) => {
			if (event.origin === "https://cossora.stream" && event.source === frame.contentWindow && event.data?.type === "comic-looms-close-player") dialog.close();
		}, { signal: abort.signal });
		dialog.addEventListener("close", () => {
			abort.abort();
			frame.remove();
			dialog.remove();
			activePlayer = void 0;
			previousFocus?.focus();
		}, { once: true });
		document.body.append(dialog);
		dialog.showModal();
		close.focus();
	}
	var CosplayteleMatcher = class extends BaseMatcher {
		async *fetchChapters() {
			if (document.querySelector(".entry-content .gallery, .entry-content .wp-block-gallery") || cosplayPlayers(document, location.href).length) {
				yield [new Chapter(0, document.querySelector("h1.entry-title, h1")?.textContent?.trim() || document.title, location.href)];
				return;
			}
			const albums = cosplayAlbums(document, location.href);
			if (!albums.length) throw new Error("Cosplaytele: no galleries found on this page");
			yield albums.map((album, id) => new Chapter(id, album.title, album.url, album.cover));
		}
		async *fetchPagesSource(chapter) {
			let doc = document;
			if (chapter.source !== location.href) {
				const response = await fetch(chapter.source);
				if (!response.ok) throw new Error(`Cosplaytele HTTP ${response.status}`);
				doc = new DOMParser().parseFromString(await response.text(), "text/html");
			}
			const images = cosplayImages(doc, chapter.source);
			const videos = [];
			if (!ADAPTER.conf.excludeVideo) {
				const players = cosplayPlayers(doc, chapter.source);
				const thumbnail = cosplayCover(doc, chapter.source) || PLAYER_THUMB;
				for (const [index, embed] of players.entries()) videos.push({
					url: thumbnail === PLAYER_THUMB ? DEFAULT_THUMBNAIL : thumbnail,
					thumbnail,
					title: `JW Player ${index + 1} — hover and click ▶ (stream, not a download)`,
					embed,
					sourcePage: chapter.source
				});
			}
			if (!images.length && !videos.length) throw new Error("Cosplaytele: no gallery images or videos found");
			yield Result.ok(videosFirst(videos, images));
		}
		async parseImgNodes(images) {
			return images.map((img) => {
				const node = new ImageNode(img.thumbnail, img.embed ?? img.url, img.title, void 0, img.url);
				if (img.embed) {
					node.picked = false;
					node.openEmbeddedMedia = () => openPlayer(img.embed, img.sourcePage ?? location.href);
					node.actions.push(new NodeAction("▶", "Play in original JW Player", async () => openPlayer(img.embed, img.sourcePage ?? location.href)));
				}
				return node;
			});
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
		async fetchImageData(imf) {
			if (imf.node.openEmbeddedMedia) return [new Blob([PLAYER_CARD], { type: "image/svg+xml" }), 200];
			return super.fetchImageData(imf);
		}
		galleryMeta(chapter) {
			return new GalleryMeta(chapter.source, Array.isArray(chapter.title) ? chapter.title.join(" ") : chapter.title);
		}
	};
	ADAPTER.addSetup({
		name: "Cosplaytele",
		workURLs: [/^https:\/\/(?:www\.)?cosplaytele\.com\//],
		match: ["https://cosplaytele.com/*", "https://www.cosplaytele.com/*"],
		constructor: () => new CosplayteleMatcher()
	});
	var danbooru_exports = __exportAll({});
	var DanbooruMatcher = class extends BaseMatcher {
		tags = {};
		blacklistTags = [];
		count = 0;
		async *fetchPagesSource() {
			let doc = document;
			this.blacklistTags = this.getBlacklist(doc);
			yield Result.ok(doc);
			let tryTimes = 0;
			while (true) {
				const url = this.nextPage(doc);
				if (!url) break;
				try {
					doc = await window.fetch(url).then((res) => res.text()).then((text) => new DOMParser().parseFromString(text, "text/html"));
				} catch (e) {
					tryTimes++;
					if (tryTimes > 3) yield Result.err(new Error(`fetch next page failed, ${e}`));
					continue;
				}
				tryTimes = 0;
				yield Result.ok(doc);
			}
		}
		async fetchOriginMeta(node) {
			const cached = this.cachedOriginMeta(node.href);
			if (cached) return cached;
			let url = null;
			const doc = await window.fetch(node.href).then((res) => res.text()).then((text) => new DOMParser().parseFromString(text, "text/html"));
			if (ADAPTER.conf.fetchOriginal) url = this.getOriginalURL(doc);
			if (!url) url = this.getNormalURL(doc);
			if (!url) throw new Error("Cannot find origin image or video url");
			let title;
			const ext = url.split(".").pop()?.match(/^\w+/)?.[0];
			const id = this.extractIDFromHref(node.href);
			if (ext && id) title = `${id}.${ext}`;
			return {
				url,
				title
			};
		}
		cachedOriginMeta(_href) {
			return null;
		}
		async parseImgNodes(doc) {
			const list = [];
			this.queryList(doc).forEach((ele) => {
				const [imgNode, tags] = this.toImgNode(ele);
				if (!imgNode) return;
				this.count++;
				if (tags !== "") {
					const tagList = tags.trim().replaceAll(": ", ":").split(" ").map((v) => v.trim()).filter((v) => v !== "");
					if (this.blacklistTags.findIndex((t) => tagList.includes(t)) >= 0) return;
					this.tags[imgNode.title.split(".")[0]] = tagList;
				}
				list.push(imgNode);
			});
			return list;
		}
		galleryMeta() {
			const tags = new URL(window.location.href).searchParams.get("tags")?.trim();
			const meta = new GalleryMeta(window.location.href, `${this.site().toLowerCase().replace(" ", "-")}_${tags}_${this.count}`);
			meta.tags = this.tags;
			return meta;
		}
	};
	var DanbooruDonmaiMatcher = class extends DanbooruMatcher {
		site() {
			return "danbooru";
		}
		nextPage(doc) {
			return doc.querySelector(".paginator a.paginator-next")?.href || null;
		}
		queryList(doc) {
			return Array.from(doc.querySelectorAll(".posts-container > article"));
		}
		getBlacklist(doc) {
			return doc.querySelector("meta[name='blacklisted-tags']")?.getAttribute("content")?.split(",") || [];
		}
		toImgNode(ele) {
			const anchor = ele.querySelector("a");
			if (!anchor) {
				evLog("error", "warn: cannot find anchor element", anchor);
				return [null, ""];
			}
			const img = anchor.querySelector("img");
			if (!img) {
				evLog("error", "warn: cannot find img element", img);
				return [null, ""];
			}
			const href = anchor.getAttribute("href");
			if (!href) {
				evLog("error", "warn: cannot find href", anchor);
				return [null, ""];
			}
			return [new ImageNode(img.src, href, `${ele.getAttribute("data-id") || ele.id}.jpg`), ele.getAttribute("data-tags") || ""];
		}
		getOriginalURL(doc) {
			return doc.querySelector("#image-resize-notice > a")?.href || null;
		}
		getNormalURL(doc) {
			return doc.querySelector("#image")?.getAttribute("src") || null;
		}
		extractIDFromHref(href) {
			return href.match(/posts\/(\d+)/)?.[1];
		}
	};
	var Rule34Matcher = class extends DanbooruMatcher {
		site() {
			return "rule34";
		}
		nextPage(doc) {
			if (window.location.search.includes("page=favorites")) {
				const u = doc.querySelector("#paginator a[name=next]")?.getAttribute("onclick")?.match(/location='(.*)?'/)?.[1] || null;
				return u ? window.location.origin + "/" + u : u;
			} else return doc.querySelector(".pagination a[alt=next]")?.href || null;
		}
		queryList(doc) {
			if (window.location.search.includes("page=favorites")) return Array.from(doc.querySelectorAll("#content .thumb a"));
			else return Array.from(doc.querySelectorAll(".image-list > .thumb:not(.blacklisted-image) > a"));
		}
		getBlacklist(doc) {
			return doc.querySelector("meta[name='blacklisted-tags']")?.getAttribute("content")?.split(",") || [];
		}
		toImgNode(ele) {
			const img = ele.querySelector("img");
			if (!img) {
				evLog("error", "warn: cannot find img element", img);
				return [null, ""];
			}
			const href = ele.getAttribute("href");
			if (!href) {
				evLog("error", "warn: cannot find href", ele);
				return [null, ""];
			}
			const node = new ImageNode(img.src, href, `${ele.id}.jpg`);
			const id = href.match(/id=(\d+)/)?.[1];
			if (id) {
				const addFav = new NodeAction("♥", "Add to favorites", async () => {
					fetch(`${window.location.origin}/index.php?page=post&s=vote&id=${id}&type=up`);
					if (await fetch(`${window.location.origin}/public/addfav.php?id=${id}`).then((resp) => resp.text()) === "2") {
						EBUS.emit("notify-message", "error", "You are not logged in");
						throw new Error("You are not logged in");
					}
				});
				node.actions.push(addFav);
			}
			return [node, img.getAttribute("alt") || ""];
		}
		getOriginalURL(doc) {
			const raw = doc.querySelector("#note-container + script")?.textContent?.trim().replace("image = ", "").replace(";", "").replaceAll("'", "\"");
			try {
				if (raw) {
					const info = JSON.parse(raw);
					return `${info.domain}/${info.base_dir}/${info.dir}/${info.img}`;
				}
			} catch (error) {
				evLog("error", "get original url failed", error);
			}
			return null;
		}
		getNormalURL(doc) {
			const element = doc.querySelector("#image,#gelcomVideoPlayer > source");
			return element?.getAttribute("src") || element?.getAttribute("data-cfsrc") || null;
		}
		extractIDFromHref(href) {
			return href.match(/id=(\d+)/)?.[1];
		}
	};
	var GelBooruMatcher = class extends DanbooruMatcher {
		site() {
			return "gelbooru";
		}
		nextPage(doc) {
			const href = doc.querySelector("#paginator a[alt=next]")?.href;
			if (href) return href;
			return doc.querySelector("#paginator b + a")?.href || null;
		}
		queryList(doc) {
			return Array.from(doc.querySelectorAll(".thumbnail-container > article.thumbnail-preview:not(.blacklisted-image) > a"));
		}
		getBlacklist(doc) {
			return doc.querySelector("meta[name='blacklisted-tags']")?.getAttribute("content")?.split(",") || [];
		}
		toImgNode(ele) {
			const img = ele.querySelector("img");
			if (!img) {
				evLog("error", "warn: cannot find img element", img);
				return [null, ""];
			}
			const href = ele.getAttribute("href");
			if (!href) {
				evLog("error", "warn: cannot find href", ele);
				return [null, ""];
			}
			const node = new ImageNode(img.src, href, `${ele.id}.jpg`);
			const id = href.match(/id=(\d+)/)?.[1];
			if (id) {
				const addFav = new NodeAction("♥", "Add to favorites", async () => {
					fetch(`${window.location.origin}/index.php?page=post&s=vote&id=${id}&type=up`);
					if (await fetch(`${window.location.origin}/public/addfav.php?id=${id}`).then((resp) => resp.text()) === "2") {
						EBUS.emit("notify-message", "error", "You are not logged in");
						throw new Error("You are not logged in");
					}
				});
				node.actions.push(addFav);
			}
			const tags = img.title.split(" ").map((t) => t.trim()).filter((t) => t && !(t.startsWith("score") || t.startsWith("rating"))).map((t) => "tag:" + t);
			node.setTags(...tags);
			return [node, img.getAttribute("alt") || ""];
		}
		getOriginalURL(doc) {
			return doc.querySelector("head > meta[property='og:image']")?.getAttribute("content") || null;
		}
		getNormalURL(doc) {
			const img = doc.querySelector("#image");
			if (img?.src) return img.src;
			const vidSources = Array.from(doc.querySelectorAll("#gelcomVideoPlayer > source"));
			if (vidSources.length === 0) return null;
			return vidSources.find((s) => s.type.endsWith("mp4"))?.src || vidSources[0].src;
		}
		extractIDFromHref(href) {
			return href.match(/id=(\d+)/)?.[1];
		}
	};
	var E621Matcher = class extends DanbooruMatcher {
		cache = new Map();
		nextPage(doc) {
			return doc.querySelector(".pagination #paginator-next")?.href ?? null;
		}
		getOriginalURL() {
			throw new Error("Method not implemented.");
		}
		getNormalURL() {
			throw new Error("Method not implemented.");
		}
		extractIDFromHref() {
			throw new Error("Method not implemented.");
		}
		getBlacklist(doc) {
			const content = doc.querySelector("meta[name='blacklisted-tags']")?.getAttribute("content");
			if (!content) return [];
			return content.slice(1, -1).split(",").map((s) => s.slice(1, -1));
		}
		queryList(doc) {
			transient.imgSrcCSP = true;
			return Array.from(doc.querySelectorAll(".posts-container > article"));
		}
		toImgNode(ele) {
			const src = ele.getAttribute("data-preview-url");
			if (!src) return [null, ""];
			const tags = ele.getAttribute("data-tags");
			const id = ele.getAttribute("data-id");
			const normal = ele.getAttribute("data-sample-url");
			const original = ele.getAttribute("data-file-url");
			const fileExt = ele.getAttribute("data-file-ext") || void 0;
			if (!normal || !original || !id) return [null, ""];
			const href = `${window.location.origin}/posts/${id}`;
			const width = ele.getAttribute("data-width");
			const height = ele.getAttribute("data-height");
			let wh = void 0;
			if (width && height) wh = {
				w: parseInt(width),
				h: parseInt(height)
			};
			this.cache.set(href, {
				normal,
				original,
				id,
				fileExt
			});
			return [new ImageNode(src, href, `${id}.jpg`, void 0, void 0, wh), tags || ""];
		}
		cachedOriginMeta(href) {
			const cached = this.cache.get(href);
			if (!cached) throw new Error("miss origin meta: " + href);
			const ext = cached.fileExt ?? cached.original.split(".").pop() ?? "jpg";
			if (ADAPTER.conf.fetchOriginal || [
				"webm",
				"webp",
				"mp4"
			].includes(ext)) return {
				url: cached.original,
				title: `${cached.id}.${ext}`
			};
			return {
				url: cached.normal,
				title: `${cached.id}.${cached.normal.split(".").pop()}`
			};
		}
		site() {
			return "e621";
		}
	};
	var ATFMatcher = class extends DanbooruMatcher {
		site() {
			return "AllTheFallen";
		}
		baseUrl = "https://booru.allthefallen.moe";
		getBlacklist(doc) {
			const ul = doc.querySelector("ul#blacklist-list");
			if (!ul) return [];
			return Array.from(ul.querySelectorAll("li a")).map((a) => a.textContent?.trim()).filter((text) => !!text && text.length > 0);
		}
		nextPage(doc) {
			const nextP = doc.querySelector("a.paginator-next");
			const path = nextP ? nextP.getAttribute("href") : null;
			if (!path) return null;
			return new URL(path, this.baseUrl).href;
		}
		queryList(doc) {
			return Array.from(doc.querySelectorAll(".posts-container > article:not(.blacklisted-active)"));
		}
		toImgNode(ele) {
			const img = ele.querySelector("img");
			if (!img) {
				evLog("error", "warn: cannot find img element", img);
				return [null, ""];
			}
			const href = ele.querySelector("a")?.getAttribute("href") ?? null;
			if (!href) {
				evLog("error", "warn: cannot find href", ele);
				return [null, ""];
			}
			const node = new ImageNode(img.src, href, `${ele.id}.jpg`);
			const match1 = href.match(/\/posts\/(\d+)/);
			if (match1 ? `post_${match1[1]}` : void 0) {
				const addFav = new NodeAction("♥", "Add to favorites", async () => {
					EBUS.emit("notify-message", "error", "Not implemented");
					throw new Error("Not implemented");
				});
				node.actions.push(addFav);
			}
			const tags = img.title.split(" ").map((t) => t.trim()).filter((t) => t && !(t.startsWith("score") || t.startsWith("rating"))).map((t) => "tag:" + t);
			node.setTags(...tags);
			return [node, img.getAttribute("alt") || ""];
		}
		getOriginalURL(doc) {
			return doc.querySelector("li#post-option-download > a")?.getAttribute("href")?.split("?")[0] ?? null;
		}
		getNormalURL(doc) {
			return doc.getElementById("image")?.getAttribute("src") ?? null;
		}
		extractIDFromHref(href) {
			return href.match(/\/posts\/(\d+)/)?.[1];
		}
	};
	var Rule34USMatcher = class extends DanbooruMatcher {
		nextPage(doc) {
			let href = doc.querySelector(".pagination a[alt=next]")?.href;
			if (!href) href = doc.querySelector(".pagination b + a")?.href;
			return href ?? null;
		}
		getOriginalURL(doc) {
			return this.getNormalURL(doc);
		}
		getNormalURL(doc) {
			const videoSource = doc.querySelector(".container .content_push video source");
			if (videoSource) return videoSource.src;
			return doc.querySelector(".container .content_push img")?.src ?? null;
		}
		extractIDFromHref(href) {
			return href.match(/id=(\d+)/)?.[1];
		}
		getBlacklist() {
			return [];
		}
		queryList(doc) {
			return Array.from(doc.querySelectorAll(".thumbail-container > div > a"));
		}
		toImgNode(ele) {
			const elem = ele;
			const imgElem = elem.querySelector("img");
			if (!imgElem) return [null, ""];
			const href = elem.href;
			const thumb = imgElem.src;
			const tags = imgElem.title;
			const node = new ImageNode(thumb, href, elem.id + ".jpg");
			if (/\bvideo\b/.test(tags)) node.mimeType = "video/mp4";
			const id = href.match(/id=(\d+)/)?.[1];
			if (id) {
				if (/r=favorites/.test(window.location.href)) {
					const delFav = new NodeAction("X", "Delete to favorites", async () => {
						await fetch(`${window.location.origin}/index.php?r=favorites/delete&id=${id}`);
					});
					node.actions.push(delFav);
				} else {
					const addFav = new NodeAction("♥", "Add to favorites", async () => {
						fetch(`${window.location.origin}/index.php?r=posts/vote&id=${id}&type=up`);
						if (await fetch(`${window.location.origin}/index.php?r=favorites/create&id=${id}`).then((resp) => resp.text()) === "2") {
							EBUS.emit("notify-message", "error", "You are not logged in");
							throw new Error("You are not logged in");
						}
					});
					node.actions.push(addFav);
				}
			}
			return [node, tags];
		}
		site() {
			return "Rule34US";
		}
	};
	ADAPTER.addSetup({
		name: "e621",
		workURLs: [/e621.net\/((posts|favorites)(?!\/)|$)/],
		match: ["https://e621.net/*"],
		constructor: () => new E621Matcher()
	});
	ADAPTER.addSetup({
		name: "rule34",
		workURLs: [/rule34.xxx\/index.php\?page=(post&s=list|favorites&s=view)/],
		match: ["https://rule34.xxx/*"],
		constructor: () => new Rule34Matcher()
	});
	ADAPTER.addSetup({
		name: "rule34.US",
		workURLs: [/rule34.us\/index.php\?r=posts\/index/, /rule34.us\/index.php\?r=favorites\/view/],
		match: ["https://rule34.us/*"],
		constructor: () => new Rule34USMatcher()
	});
	ADAPTER.addSetup({
		name: "gelbooru",
		workURLs: [/gelbooru.com\/index.php\?page=post&s=list/],
		match: ["https://gelbooru.com/*"],
		constructor: () => new GelBooruMatcher()
	});
	ADAPTER.addSetup({
		name: "danbooru",
		workURLs: [/danbooru.donmai.us\/(posts(?!\/)|$)/],
		match: ["https://danbooru.donmai.us/*"],
		constructor: () => new DanbooruDonmaiMatcher()
	});
	ADAPTER.addSetup({
		name: "AllTheFallen",
		workURLs: [/booru.allthefallen.moe\/(posts(?!\/)|$)/],
		match: ["https://booru.allthefallen.moe/*"],
		constructor: () => new ATFMatcher()
	});
	var douban_exports = __exportAll({});
	var DP = new DOMParser();
	var DoubanMatcher = class extends BaseMatcher {
		chapterCount = 0;
		meta;
		galleryMeta(chapter) {
			return this.meta ?? super.galleryMeta(chapter);
		}
		initGalleryMeta() {
			const title = document.querySelector("#content h1")?.textContent ?? document.title;
			this.meta = new GalleryMeta(window.location.href, title.trim());
		}
		async *pages_of_albums(doc, path, page_number = 0) {
			let next_page = doc.querySelector("#content  div.article  div.paginator span.next > a")?.href;
			page_number += 1;
			yield {
				page_number,
				owner_name: doc.querySelector("#content h1").innerText.trim(),
				path
			};
			if (next_page) {
				const d = await fetch(next_page).then((resp) => resp.text()).then((text) => DP.parseFromString(text, "text/html"));
				yield* this.pages_of_albums(d, next_page, page_number);
			}
		}
		async albums_in_page(page) {
			const d = await fetch(page.path).then((resp) => resp.text()).then((text) => DP.parseFromString(text, "text/html"));
			return Array.from(d.querySelectorAll(".albumlst")).map((x) => {
				let t = x.querySelector(".albumlst_r .pl").innerText.match(/(\d+)张照片\s+(.+)(创建|更新)/);
				return {
					"title": (x.querySelector(".albumlst_r .pl2 a")?.innerText ?? document.title).trim(),
					"path": x.querySelector(".album_photo").getAttribute("href"),
					"photo_count": +t[1],
					"date": t[2]
				};
			});
		}
		async *fetchChapters() {
			this.initGalleryMeta();
			const thumbimg = document.querySelector("#db-usr-profile > div.pic > a > img")?.getAttribute("src") || void 0;
			let chapterCount = 0;
			if (window.location.href.match(/subject|album|personage/)) {
				chapterCount = 1;
				const chapters = [];
				chapters.push(new Chapter(chapterCount, document.title, window.location.href, thumbimg));
				this.chapterCount = chapterCount;
				yield chapters;
			} else for await (const album_page of this.pages_of_albums(document, window.location.href)) {
				let albums = await this.albums_in_page(album_page);
				for (const album of albums) {
					const chapters = [];
					chapterCount += 1;
					chapters.push(new Chapter(chapterCount, album["title"], album["path"], thumbimg));
					this.chapterCount = chapterCount;
					yield chapters;
				}
			}
		}
		async *fetchPagesSource(ch) {
			let next_page = ch.source;
			while (next_page) {
				let doc = await fetch(next_page).then((resp) => resp.text()).then((text) => DP.parseFromString(text, "text/html"));
				yield Result.ok(doc);
				next_page = doc.querySelector("#content  div.article  div.paginator span.next > a")?.href ?? "";
			}
		}
		async parseImgNodes(doc) {
			return Array.from(doc.querySelectorAll(".article img")).map((img) => {
				const orig_src = img.src.replace(/(.*\/view\/photo)(.+)(public\/.*)\.(.+)/, "$1/l/$3.webp");
				const title = (img.alt ? img.alt + "_" : "") + orig_src.replace(/.*\/(.+)/, "$1");
				return new ImageNode(img.src, img.parentNode.href, title, void 0, orig_src);
			});
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
	};
	ADAPTER.addSetup({
		name: "豆瓣",
		workURLs: [
			/douban.com\/people\/[^\/]+\/photos/,
			/douban.com\/photos\/album\//,
			/douban.com\/personage\/[^\/]+\/photos.*/,
			/movie.douban.com\/subject\/[^\/]+\/photos.*/
		],
		match: ["https://www.douban.com/*", "https://movie.douban.com/*"],
		constructor: () => new DoubanMatcher()
	});
	var eahentai_exports = __exportAll({});
	function eahentaiGetURL(uri) {
		return "https://i.eahentai.com/file/ea-gallery/" + encodeURI(uri).replace(/,/g, "%2C").replace(/&/g, "%26").replace(/\+/g, "%2B").replace(/%20/g, "+");
	}
	var EahentaiMatcher = class extends BaseMatcher {
		meta;
		async *fetchPagesSource() {
			const galleryID = window.location.href.match(/eahentai.com\/a\/(\d+)/)?.[1];
			if (!galleryID) throw new Error("cannot get gallery id from url: " + window.location.href);
			const api = `${window.location.origin}/api/image/album/${galleryID}`;
			const data = await window.fetch(api, { "referrer": window.location.href }).then((resp) => resp.json());
			if (!data || data.length === 0) throw new Error("cannot fetch album data from: " + api);
			const data1 = data[0];
			const meta = new GalleryMeta(window.location.href, data1.title);
			meta.tags["tags"] = data1.tags.split("|");
			meta.tags["author"] = [data1.author];
			meta.tags["albumType"] = data1.albumType.split("|");
			meta.tags["characters"] = data1.characters?.split("|") ?? [];
			this.meta = meta;
			yield Result.ok(data[0]);
		}
		async parseImgNodes(data) {
			return data.images.map((img, i) => {
				const thumb = eahentaiGetURL(img.thumbnailUri);
				const href = `${window.location.origin}/a/${data.albumID}/${i}`;
				const ext = img.imageUri.split(".").pop() ?? "jpg";
				const origin = eahentaiGetURL(img.imageUri);
				return new ImageNode(thumb, href, img.title + "." + ext, void 0, origin);
			});
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
		galleryMeta(chapter) {
			return this.meta ?? super.galleryMeta(chapter);
		}
	};
	ADAPTER.addSetup({
		name: "eahentai",
		workURLs: [/eahentai.com\/a\/\d+\/?$/],
		match: ["https://eahentai.com/*"],
		constructor: () => new EahentaiMatcher()
	});
	function parseImagePositions(styles) {
		return styles.map((st) => {
			const [x, y] = st.backgroundPosition.split(" ").map((v) => Math.abs(parseInt(v)));
			if (isNaN(x)) throw new Error("invalid background position");
			return {
				x,
				y,
				width: parseInt(st.width),
				height: parseInt(st.height)
			};
		});
	}
	function splitSpriteImage(image, positions) {
		const canvas = document.createElement("canvas");
		const ctx = canvas.getContext("2d");
		const result = [];
		for (const pos of positions) {
			canvas.width = pos.width;
			canvas.height = pos.height;
			ctx.drawImage(image, pos.x, pos.y, pos.width, pos.height, 0, 0, pos.width, pos.height);
			result.push(canvas.toDataURL());
		}
		canvas.remove();
		return result;
	}
	async function splitImagesFromUrl(url, positions) {
		let data;
		for (let i = 0; i < 3; i++) try {
			data = await simpleFetch(url, "blob");
			break;
		} catch (err) {
			evLog("error", "fetch thumbnail failed, ", err);
		}
		if (!data) throw new Error("load sprite image error");
		url = URL.createObjectURL(data);
		const img = await new Promise((resolve, reject) => {
			const img = new Image();
			img.onload = () => resolve(img);
			img.onerror = () => reject(new Error("load sprite image error"));
			img.src = url;
		});
		URL.revokeObjectURL(url);
		return splitSpriteImage(img, positions);
	}
	function replaceHost(url, host) {
		if (!host) return url;
		if (!host.startsWith("http")) host = "https://" + host;
		if (!host.endsWith("/")) host = host + "/";
		return url.replace(/https?:\/\/[^\/]*\//, host);
	}
	var ehentai_exports = __exportAll({});
	var regulars = {
		normal: /\<img\sid=\"img\"\ssrc=\"(.*?)\"\sstyle/,
		original: /\<a href=\"((https?:\/\/[^\/]*)?\/fullimg[^"\\]*)\"\>/,
		nlValue: /\<a\shref=\"\#\"\sid=\"loadfail\"\sonclick=\"return\snl\(\'(.*)\'\)\"\>/,
		isMPV: /https?:\/\/e[-x]hentai(55ld2wyap5juskbm67czulomrouspdacjamjeloj7ugjbsad)?\.(org|onion)\/mpv\/\w+\/\w+\/#page\w/,
		mpvImageList: /imagelist\s=\s(\[.*?\])/,
		sprite: /url\((.*?)\)/,
		workURL: /e[-x]hentai(.*)?.(org|onion)\/g\/\w+/
	};
	var EHMatcher = class extends BaseMatcher {
		docMap = {};
		title(chapters) {
			const meta = chapters[0].meta || this.galleryMeta(chapters[0]);
			let title = "";
			if (ADAPTER.conf.ehentaiTitlePrefer === "japanese") title = meta.originTitle || meta.title || "UNTITLE";
			else title = meta.title || meta.originTitle || "UNTITLE";
			if (chapters.length > 1) title += "+" + chapters.length + "chapters";
			return title;
		}
		galleryMeta(chapter) {
			if (chapter.meta) return chapter.meta;
			const doc = this.docMap[chapter.id];
			const titleList = doc.querySelectorAll("#gd2 h1");
			let title;
			let originTitle;
			if (titleList && titleList.length > 0) {
				title = titleList[0].textContent || void 0;
				if (titleList.length > 1) originTitle = titleList[1].textContent || void 0;
			}
			chapter.meta = new GalleryMeta(window.location.href, title || "UNTITLE");
			chapter.meta.originTitle = originTitle;
			const tagTrList = doc.querySelectorAll("#taglist tr");
			const tags = {};
			const category = doc.querySelector("#gdc > div")?.textContent;
			if (category) tags["category"] = [category];
			const uploader = doc.querySelector("#gdn > a")?.textContent;
			if (uploader) tags["uploader"] = [uploader];
			Array.from(doc.querySelectorAll("#gdd > table:not([hidden]) tr")).forEach((tr) => {
				const cat = tr.querySelector(".gdt1")?.textContent?.replace(":", "")?.toLowerCase();
				let value = tr.querySelector(".gdt2")?.textContent;
				if (cat && value) {
					if (cat === "parent" || cat === "父级") value = tr.querySelector(".gdt2 a")?.href ?? value;
					if (cat === "language" || cat === "语言") return;
					tags[cat] = [value];
				}
			});
			tagTrList.forEach((tr) => {
				const tds = tr.childNodes;
				const cat = tds[0].textContent;
				if (cat && tds[1]) {
					const list = [];
					tds[1].childNodes.forEach((ele) => {
						if (ele.textContent) list.push(ele.textContent);
					});
					tags[cat.replace(":", "")] = list;
				}
			});
			chapter.meta.tags = tags;
			return chapter.meta;
		}
		async *fetchChapters() {
			const chapter = new Chapter(0, "Default", window.location.href);
			this.docMap[0] = document;
			this.galleryMeta(chapter);
			chapter.title = chapter.meta.title;
			return [chapter];
		}
		async appendNewChapters(url, old) {
			if (!regulars.workURL.test(url)) throw new Error("invaild gallery url");
			const doc = await window.fetch(url).then((response) => response.text()).then((text) => new DOMParser().parseFromString(text, "text/html"));
			let lastID = old[old.length - 1]?.id || 0;
			lastID = lastID + 1;
			const chapter = new Chapter(lastID, "NewChapter-" + lastID, url);
			this.docMap[lastID] = doc;
			this.galleryMeta(chapter);
			chapter.title = chapter.meta.title;
			return [chapter];
		}
		async parseImgNodes(source) {
			const list = [];
			const doc = await window.fetch(source).then((response) => response.text()).then((text) => new DOMParser().parseFromString(text, "text/html"));
			if (!doc) throw new Error("warn: eh matcher failed to get document from source page!");
			const getHref = (href) => {
				if (href.startsWith("/")) href = window.location.origin + href;
				if (ADAPTER.conf.ehentaiMirrorHost) href = replaceHost(href, ADAPTER.conf.ehentaiMirrorHost);
				return href;
			};
			let isSprite = false;
			let getNodeInfo = (node) => {
				const anchor = node.firstElementChild;
				const image = anchor.firstElementChild;
				const title = image.getAttribute("title")?.replace(/Page\s\d+[:_]\s*/, "") || "untitle.jpg";
				return {
					thumbnailImage: image.src,
					title,
					href: getHref(anchor.href),
					wh: extractRectFromSrc(image.src) || {
						w: 100,
						h: 100
					},
					style: node.style,
					backgroundImage: null,
					delaySrc: void 0
				};
			};
			let query = doc.querySelectorAll("#gdt .gdtl");
			if (!query || query.length == 0) {
				query = doc.querySelectorAll("#gdt .gdtm > div");
				isSprite = query?.length > 0;
				getNodeInfo = (node) => {
					const anchor = node.firstElementChild;
					const title = anchor.firstElementChild.getAttribute("title")?.replace(/Page\s\d+[:_]\s*/, "") || "untitle.jpg";
					return {
						backgroundImage: node.style.background.match(regulars.sprite)?.[1]?.replaceAll("\"", "") || null,
						title,
						href: getHref(anchor.href),
						wh: extractRectFromStyle(node.style) ?? {
							w: 100,
							h: 100
						},
						style: node.style,
						thumbnailImage: "",
						delaySrc: void 0
					};
				};
			}
			if (!query || query.length == 0) {
				query = doc.querySelectorAll("#gdt > a");
				isSprite = query?.length > 0;
				getNodeInfo = (node) => {
					const anchor = node;
					let div = anchor.firstElementChild;
					if (!div.style.background || div.childElementCount > 0) div = div.firstElementChild;
					const title = div.getAttribute("title")?.replace(/Page\s\d+[:_]\s*/, "") || "untitle.jpg";
					return {
						backgroundImage: div.style.background.match(regulars.sprite)?.[1]?.replaceAll("\"", "") || null,
						title,
						href: getHref(anchor.href),
						wh: extractRectFromStyle(div.style) ?? {
							w: 100,
							h: 100
						},
						style: div.style,
						thumbnailImage: "",
						delaySrc: void 0
					};
				};
			}
			if (!query || query.length == 0) throw new Error("warn: failed query image nodes!");
			const nodeInfos = [];
			const nodes = Array.from(query);
			const n0 = getNodeInfo(nodes[0]);
			if (regulars.isMPV.test(n0.href)) {
				isSprite = true;
				const mpvDoc = await window.fetch(n0.href).then((response) => response.text()).then((text) => new DOMParser().parseFromString(text, "text/html"));
				const imageList = JSON.parse(mpvDoc.querySelector("#pane_outer + script")?.innerHTML.match(regulars.mpvImageList)?.[1] ?? "[]");
				const thumbnails = Array.from(mpvDoc.querySelectorAll("#pane_thumbs > a > div"));
				const gid = location.pathname.split("/")[2];
				for (let i = 0; i < imageList.length; i++) {
					const info = imageList[i];
					const backgroundImage = info.t.match(/\((http.*)\)/)?.[1] || null;
					thumbnails[i].style.background = "url" + info.t;
					const ni = {
						backgroundImage,
						title: info.n,
						href: `${ADAPTER.conf.ehentaiMirrorHost || window.location.origin}/s/${info.k}/${gid}-${i + 1}`,
						wh: extractRectFromStyle(thumbnails[i].style) ?? {
							w: 100,
							h: 100
						},
						style: thumbnails[i].style,
						thumbnailImage: "",
						delaySrc: void 0
					};
					nodeInfos.push(ni);
				}
			} else nodes.forEach((node) => nodeInfos.push(getNodeInfo(node)));
			if (isSprite) {
				const spriteURLs = [];
				for (let i = 0; i < nodeInfos.length; i++) {
					const info = nodeInfos[i];
					if (!info.backgroundImage) {
						evLog("error", "e-hentai miss node, ", info);
						continue;
					}
					if (spriteURLs.length === 0 || spriteURLs[spriteURLs.length - 1].url !== info.backgroundImage) spriteURLs.push({
						url: info.backgroundImage,
						range: [{
							index: i,
							style: info.style
						}]
					});
					else spriteURLs[spriteURLs.length - 1].range.push({
						index: i,
						style: info.style
					});
				}
				spriteURLs.forEach(({ url, range }) => {
					url = url.startsWith("http") ? url : window.location.origin + url;
					if (range.length === 1) nodeInfos[range[0].index].thumbnailImage = url;
					else {
						const reso = [];
						for (let i = 0; i < range.length; i++) nodeInfos[range[i].index].delaySrc = new Promise((resolve, reject) => reso.push({
							resolve,
							reject
						}));
						splitImagesFromUrl(url, parseImagePositions(range.map((n) => n.style))).then((ret) => {
							for (let i = 0; i < ret.length; i++) reso[i].resolve(ret[i]);
						}).catch((err) => reso.forEach((r) => r.reject(err)));
					}
				});
			}
			for (let i = 0; i < nodeInfos.length; i++) {
				const info = nodeInfos[i];
				list.push(new ImageNode(info.thumbnailImage, info.href, info.title, info.delaySrc, void 0, info.wh));
			}
			return list;
		}
		async *fetchPagesSource(chapter) {
			const doc = this.docMap[chapter.id];
			const fristImageHref = doc.querySelector("#gdt a")?.getAttribute("href");
			if (fristImageHref && regulars.isMPV.test(fristImageHref)) {
				yield Result.ok(window.location.href);
				return;
			}
			const pages = Array.from(doc.querySelectorAll(".gtb td a")).filter((a) => a.href).map((a) => a.href);
			if (pages.length === 0) throw new Error("cannot found next page elements");
			let lastPage = 0;
			let url;
			for (const page of pages) {
				const u = new URL(page);
				const num = parseInt(u.searchParams.get("p") || "0");
				if (num >= lastPage) {
					lastPage = num;
					url = u;
				}
			}
			if (!url) throw new Error("cannot found next page elements again");
			url.searchParams.delete("p");
			yield Result.ok(url.href);
			for (let p = 1; p < lastPage + 1; p++) {
				url.searchParams.set("p", p.toString());
				yield Result.ok(url.href);
			}
		}
		async fetchOriginMeta(node, retry) {
			if (node.href.startsWith("/")) node.href = window.location.origin + node.href;
			let text;
			if (ADAPTER.conf.ehentaiMirrorHost) {
				node.href = replaceHost(node.href, ADAPTER.conf.ehentaiMirrorHost);
				text = await simpleFetch(node.href, "text").catch(Error);
			} else text = await window.fetch(node.href).then((resp) => resp.text()).catch(Error);
			if (text instanceof Error || !text) throw new Error(`fetch source page error, ${text.toString()}`);
			let src;
			if (ADAPTER.conf.fetchOriginal) {
				src = regulars.original.exec(text)?.[1].replace(/&amp;/g, "&");
				const nl = node.href.includes("?") ? node.href.split("?").pop() : void 0;
				if (src && nl) src += "?" + nl;
			}
			if (!src) src = regulars.normal.exec(text)?.[1];
			if (retry) {
				const nlValue = regulars.nlValue.exec(text)?.[1];
				if (nlValue) {
					node.href = node.href + (node.href.includes("?") ? "&" : "?") + "nl=" + nlValue;
					evLog("info", `IMG-FETCHER retry url:${node.href}`);
					src = (await this.fetchOriginMeta(node, false)).url;
				} else evLog("error", `Cannot matching the nlValue, content: ${text}`);
			}
			if (!src) {
				evLog("error", "cannot matching the image url from content:\n", text);
				throw new Error(`cannot matching the image url from content. (the content is showing up in console(F12 open it)`);
			}
			if (!src.startsWith("http")) src = (ADAPTER.conf.ehentaiMirrorHost || window.location.origin) + src;
			if (src.endsWith("509.gif")) throw new Error("509, Image limits Exceeded, Please reset your Quota!");
			let title = node.title;
			const titleSP = title.split(".");
			const srcSP = src.split(".");
			if (titleSP.length > 1 && srcSP.length > 1) {
				titleSP[titleSP.length - 1] = srcSP.pop();
				title = titleSP.join(".");
			}
			title = title.replace(/\?nl=.*$/, "");
			return {
				url: src,
				href: node.href,
				title
			};
		}
		async fetchImageData(imf) {
			const ret = await super.fetchImageData(imf).catch(Error);
			if (ret === null) throw new Error("fetch image failed, got null");
			if (ret instanceof Error) throw ret;
			const [data, status] = ret;
			if (data.type.startsWith("text")) {
				if (data.size === 1329) throw new Error("Downloading original images requires being logged in, please try logging in or disable \"raw image\"");
				const str = new TextDecoder().decode(await data.arrayBuffer());
				if (str && str.startsWith("Downloading original")) throw new Error(str.trim());
			}
			if (data.size === 0 && (status < 200 || status >= 400)) throw new Error(`status ${status}` + (ADAPTER.conf.ehentaiMirrorHost ? `, This mirror site [${ADAPTER.conf.ehentaiMirrorHost}] may not support downloading the original image.` : ""));
			return ret;
		}
	};
	function extractRectFromSrc(src) {
		if (!src) return void 0;
		const matches = src.match(/\/\w+-\d+-(\d+)-(\d+)-/);
		if (matches && matches.length === 3) return {
			w: parseInt(matches[1]),
			h: parseInt(matches[2])
		};
		else return;
	}
	function extractRectFromStyle(style) {
		const wh = {
			w: parseInt(style.width),
			h: parseInt(style.height)
		};
		if (isNaN(wh.w) || isNaN(wh.h)) return void 0;
		return wh;
	}
	ADAPTER.addSetup({
		name: "e-hentai",
		workURLs: [regulars.workURL],
		preloadAllPages: true,
		constructor: () => new EHMatcher()
	});
	var github_exports = __exportAll({});
	var GithubMatcher = class extends BaseMatcher {
		async *fetchPagesSource() {
			const ret = Array.from(document.querySelectorAll(".markdown-body img")).map((img, i) => {
				const src = img.src;
				if (!src) return void 0;
				return {
					name: src.split("/").pop() ?? i + 1 + ".jpg",
					url: src
				};
			}).filter((img) => img !== void 0).filter((img) => !img.url.endsWith("svg"));
			yield Result.ok(ret);
		}
		async parseImgNodes(images) {
			return images.map((img) => new ImageNode("", img.url, img.name, void 0, img.url));
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
	};
	ADAPTER.addSetup({
		match: ["github.com"],
		name: "Github",
		workURLs: [/github.com\/MapoMagpie\/comic-looms$/],
		constructor: () => new GithubMatcher()
	});
	var hanime1_exports = __exportAll({});
	var Hanime1Matcher = class extends BaseMatcher {
		meta;
		galleryMeta() {
			return this.meta;
		}
		parseMeta() {
			const title = document.querySelector(".comics-panel-margin h3.title")?.textContent?.replaceAll(/\s/g, "");
			const originTItle = document.querySelector(".comics-panel-margin h4.title")?.textContent?.replaceAll(/\s/g, "");
			const meta = new GalleryMeta(window.location.href, title ?? document.title);
			meta.originTitle = originTItle ?? void 0;
			Array.from(document.querySelectorAll(".comics-panel-margin .comics-metadata-margin-top h5")).forEach((ele) => {
				let cat = ele.firstChild?.textContent ?? "misc";
				cat = cat.trim().replace(/::/, "");
				const tags = Array.from(ele.querySelectorAll("a")).map((t) => t.textContent?.trim()).filter(Boolean);
				meta.tags[cat] = tags;
			});
			this.meta = meta;
		}
		async *fetchPagesSource() {
			this.parseMeta();
			yield Result.ok(document);
		}
		async parseImgNodes(doc) {
			const items = Array.from(doc.querySelectorAll(".comics-panel-margin > a"));
			const item0 = items[0];
			const f = {
				j: "jpg",
				p: "png",
				g: "gif",
				w: "webp"
			};
			let prefix = "", extensions = void 0;
			if (item0) {
				const page0 = await window.fetch(item0.href).then((res) => res.text()).then((raw) => new DOMParser().parseFromString(raw, "text/html"));
				const img = page0.querySelector("#comic-content-wrapper img");
				prefix = img?.getAttribute("prefix") ?? img?.getAttribute("data-prefix") ?? "";
				const raw = page0.querySelector("#comic-content-wrapper script")?.textContent?.match(/extensions.innerHTML = '(.*)?'/)?.[1]?.replaceAll("&quot;", "\"");
				extensions = raw ? JSON.parse(raw) : void 0;
			}
			const digits = items.length.toString().length;
			return items.map((item, index) => {
				const href = item.href;
				const thumb = item.querySelector("img")?.getAttribute("data-srcset") || "";
				let ext = "jpg";
				let src = prefix && extensions ? `${prefix}${extensions[index]}.${ext}` : void 0;
				if (prefix && extensions && prefix.includes("nhentai")) {
					const fk = extensions?.[index] ?? "j";
					ext = f[fk] ?? "jpg";
					src = `${prefix}${index + 1}.${ext}`;
				}
				return new ImageNode(thumb, href, (index + 1).toString().padStart(digits, "0") + "." + ext, void 0, src);
			});
		}
		async fetchOriginMeta(node, retry) {
			if (!retry && node.originSrc) return { url: node.originSrc };
			const img = (await window.fetch(node.href).then((res) => res.text()).then((raw) => new DOMParser().parseFromString(raw, "text/html"))).querySelector("#comic-content-wrapper img");
			if (!img) throw new Error("cannot find img from " + node.href);
			return { url: img.src };
		}
		headers() {
			return {
				"Origin": "",
				"Referer": ""
			};
		}
	};
	ADAPTER.addSetup({
		name: "hanime1.me",
		workURLs: [/hanime1.me\/comic\/\d+\/?$/],
		match: ["https://hanime1.me/comic/*"],
		constructor: () => new Hanime1Matcher()
	});
	var hdoujin_exports = __exportAll({});
	var HDoujinMatcher = class extends BaseMatcher {
		meta;
		galleryMeta() {
			return this.meta;
		}
		tagNamespace(namespace) {
			return {
				1: "artist",
				2: "cricle",
				3: "parody",
				7: "uploader",
				8: "male_tags",
				9: "female_tags",
				11: "languages"
			}[namespace] ?? namespace.toString();
		}
		createMeta(gallery) {
			const meta = new GalleryMeta(window.location.href, gallery.title);
			meta.originTitle = gallery.subtitle;
			for (const tag of gallery.tags) {
				const tagName = this.tagNamespace(tag.namespace);
				if (!meta.tags[tagName]) meta.tags[tagName] = [];
				meta.tags[tagName].push(tag.name);
			}
			return meta;
		}
		async *fetchPagesSource(source) {
			const crt = window.localStorage.getItem("clearance");
			if (!crt) throw new Error("cannot get clearance from local storage");
			const id = source.source.match(/\/g\/(\d+\/\w+)/)?.[1];
			const gallery = await window.fetch(`https://api.hdoujin.org/books/detail/${id}`).then((resp) => resp.json()).then((data) => data).catch(Error);
			if (gallery instanceof Error) throw gallery;
			this.meta = this.createMeta(gallery);
			const archives = await window.fetch(`https://api.hdoujin.org/books/detail/${id}?crt=${crt}`, { method: "POST" }).then((resp) => resp.json()).then((data) => data).catch(Error);
			if (archives instanceof Error) throw archives;
			let archive = archives.data[0];
			let size = "0";
			if (!ADAPTER.conf.fetchOriginal) {
				const resolution = JSON.parse(window.localStorage.getItem("reader") ?? "{\"resolution\":1280}").resolution ?? 1280;
				if (archives.data[resolution]) {
					archive = archives.data[resolution];
					size = resolution.toString();
				}
			}
			const largeImages = await window.fetch(`https://api.hdoujin.org/books/data/${id}/${archive.id}/${archive.key}/${size}?crt=${crt}`).then((resp) => resp.json()).then((data) => data).catch(Error);
			if (largeImages instanceof Error) throw largeImages;
			const ret = [];
			const total = gallery.thumbnails.entries.length;
			const digits = total.toString().length;
			const thumb_base = gallery.thumbnails.base;
			const large_base = largeImages.base;
			for (let i = 0; i < total; i++) {
				const entry = gallery.thumbnails.entries[i];
				const ext = largeImages.entries[i].path.split(".").pop() ?? "jpg";
				ret.push({
					thumb: thumb_base + entry.path,
					large: large_base + largeImages.entries[i].path,
					href: source.source + "/read/" + (i + 1),
					width: entry.dimensions[0],
					height: entry.dimensions[1],
					title: (i + 1).toString().padStart(digits, "0") + "." + ext
				});
			}
			yield Result.ok(ret);
		}
		async fetchImageData(imf) {
			const data = await window.fetch(imf.node.originSrc).then((resp) => resp.blob());
			return [data, data.size];
		}
		async parseImgNodes(images) {
			return images.map((img) => {
				return new ImageNode(img.thumb, img.href, img.title, void 0, img.large, {
					w: img.width,
					h: img.height
				});
			});
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
	};
	ADAPTER.addSetup({
		name: "hdoujin",
		workURLs: [/hdoujin.org\/g\/\d+\/\w+$/],
		match: ["hdoujin.org"],
		constructor: () => new HDoujinMatcher()
	});
	var hentainexus_exports = __exportAll({});
	var REGEXP_EXTRACT_INIT_ARGUMENTS = /initReader\("(.*?)\",\s?"(.*?)",\s?(.*?)\)/;
	var REGEXP_EXTRACT_HASH = /read\/\d+\/(\d+)$/;
	var HentaiNexusMatcher = class extends BaseMatcher {
		meta;
		baseURL;
		readerData;
		async *fetchPagesSource() {
			this.meta = this.pasrseGalleryMeta(document);
			yield Result.ok(document);
		}
		async parseImgNodes(doc) {
			const result = [];
			Array.from(doc.querySelectorAll(".section .container + .container > .box > .columns > .column a")).forEach((li, i) => {
				const img = li.querySelector("img");
				if (!img) return;
				const num = li.href.split("/").pop() || i.toString();
				const ext = img.src.split(".").pop();
				const title = num + "." + ext;
				result.push(new ImageNode(img.src, li.href, title));
			});
			return result;
		}
		async fetchOriginMeta(node) {
			if (!this.readerData) {
				const args = (await window.fetch(node.href).then((res) => res.text()).then((text) => new DOMParser().parseFromString(text, "text/html"))).querySelector("body > script")?.textContent?.match(REGEXP_EXTRACT_INIT_ARGUMENTS)?.slice(1);
				if (!args || args.length !== 3) throw new Error("cannot find reader data");
				try {
					this.initReader(args[0], args[1]);
				} catch (_error) {
					throw new Error("hentainexus updated decryption function");
				}
			}
			if (!this.readerData) throw new Error("cannot find reader data");
			const hash = node.href.match(REGEXP_EXTRACT_HASH)?.[1];
			if (!hash) throw new Error("cannot find image url_label");
			const data = this.readerData.find((d) => d.url_label === hash);
			if (!data) throw new Error("cannot find image data by url_label");
			const url = data.image_avif ?? data.image_webp ?? data.image ?? data.image_fallback;
			if (!url) throw new Error("cannot find image url");
			const ext = url.split(".").pop();
			return {
				url,
				title: hash + "." + ext
			};
		}
		galleryMeta(chapter) {
			return this.meta || super.galleryMeta(chapter);
		}
		pasrseGalleryMeta(doc) {
			const title = doc.querySelector("h1.title")?.textContent || "UNTITLED";
			const meta = new GalleryMeta(this.baseURL || window.location.href, title);
			doc.querySelectorAll(".view-page-details tr").forEach((tr) => {
				const category = tr.querySelector(".viewcolumn")?.textContent?.trim();
				if (!category) return;
				let values = Array.from(tr.querySelector(".viewcolumn + td")?.childNodes || []).map((c) => c?.textContent?.trim()).filter(Boolean);
				if (values.length === 0) return;
				if (category === "Tags") values = values.map((v) => v.replace(/\s?\([0-9,]*\)$/, ""));
				meta.tags[category] = values;
			});
			return meta;
		}
		initReader(data, originTitle) {
			if (this.meta) this.meta.originTitle = originTitle.replace(/::\s?HentaiNexus/, "");
			const hostname = window.location.hostname.split("");
			const hostnameLen = Math.min(hostname.length, 64);
			const rawSplits = window.atob(data).split("");
			for (let i = 0; i < hostnameLen; i++) rawSplits[i] = String.fromCharCode(rawSplits[i].charCodeAt(0) ^ hostname[i].charCodeAt(0));
			const decoded = rawSplits.join("");
			const poses = [];
			const list = [];
			for (let step = 2; list.length < 16; ++step) if (!poses[step]) {
				list.push(step);
				for (let j = step << 1; j <= 256; j += step) poses[j] = true;
			}
			let a = 0;
			for (let step = 0; step < 64; step++) {
				a = a ^ decoded.charCodeAt(step);
				for (let i = 0; i < 8; i++) a = a & 1 ? a >>> 1 ^ 12 : a >>> 1;
			}
			a = a & 7;
			const step = new Uint8Array(256);
			for (let i = 0; i < 256; i++) step[i] = i;
			let raw = "";
			let c = 0;
			for (let i = 0, b = 0; i < 256; i++) {
				b = (b + step[i] + decoded.charCodeAt(i % 64)) % 256;
				c = step[i];
				step[i] = step[b];
				step[b] = c;
			}
			for (let d = list[a], e = 0, f = 0, j = 0, k = 0, i = 0; i + 64 < decoded.length; i++) {
				j = (j + d) % 256;
				k = (f + step[(k + step[j]) % 256]) % 256;
				f = (f + j + step[j]) % 256;
				c = step[j];
				step[j] = step[k];
				step[k] = c;
				e = step[(k + step[(j + step[(e + f) % 256]) % 256]) % 256];
				raw += String.fromCharCode(decoded.charCodeAt(i + 64) ^ e);
			}
			this.readerData = JSON.parse(raw);
		}
	};
	ADAPTER.addSetup({
		name: "hentainexus",
		workURLs: [/hentainexus.com\/view\/\d+/],
		match: ["https://hentainexus.com/*"],
		constructor: () => new HentaiNexusMatcher()
	});
	var hentaizap_exports = __exportAll({});
	var HentaiZapMatcher = class extends BaseMatcher {
		meta;
		galleryMeta() {
			if (this.meta) return this.meta;
			const title = document.querySelector("#gallery-title")?.textContent ?? document.title;
			const originTitle = document.querySelector("p.hz-gallery-description")?.textContent;
			this.meta = new GalleryMeta(window.location.href, title);
			this.meta.originTitle = originTitle;
			Array.from(document.querySelectorAll(".hz-gallery-metadata > div.hz-gallery-entity-group")).forEach((elem) => {
				const category = elem.querySelector("span.hz-gallery-entity-label")?.textContent?.replace(":", "")?.toLowerCase();
				if (!category) return;
				const tags = Array.from(elem.querySelectorAll("a.hz-gallery-tag > span.hz-gallery-tag__name")).map((e) => e.textContent).filter(Boolean);
				this.meta.tags[category] = tags;
			});
			return this.meta;
		}
		async *fetchPagesSource() {
			const gid = window.location.href.match(/gallery\/(\d+)/)?.[1];
			if (!gid) throw new Error("cannot match gallery id from href: " + window.location.href);
			const qs = new URLSearchParams();
			qs.set("from", "1");
			qs.set("all", "1");
			const apiUrl = `${window.location.origin}/api/gallery/${gid}/thumbs?${qs.toString()}`;
			const data = await window.fetch(apiUrl).then((resp) => resp.json()).then((data) => data).catch(Error);
			if (data instanceof Error) throw data;
			if (!data.ok || data.thumbs.length === 0) throw new Error("fetch thumbs api error, response not ok");
			let firstHref = data.thumbs[0].href;
			if (!firstHref.startsWith("http")) firstHref = window.location.origin + firstHref;
			const firstDoc = await window.fetch(firstHref).then((resp) => resp.text()).catch(Error);
			if (firstDoc instanceof Error) throw firstDoc;
			const pageInfoRaw = firstDoc.match(/id="readerPagesJson"\>(\[.*?\])/)?.[1];
			if (!pageInfoRaw) throw new Error("cannot match pageInfo from " + firstHref);
			const pageInfos = JSON.parse(pageInfoRaw);
			if (pageInfos.length !== data.thumbs.length) throw new Error("thumbs length not equals page infos length");
			const ret = [];
			for (let i = 0; i < pageInfos.length; i++) {
				const info = pageInfos[i];
				const thumb = data.thumbs[i];
				ret.push({
					thumb: thumb.thumb,
					href: thumb.href,
					page: thumb.page,
					ext: info.ext,
					width: info.width,
					height: info.height
				});
			}
			yield Result.ok(ret);
		}
		async parseImgNodes(images) {
			const nodes = [];
			const digits = images.length.toString().length;
			for (let i = 0; i < images.length; i++) {
				const img = images[i];
				const title = img.page.toString().padStart(digits, "0");
				const thumb = img.thumb;
				const idx = thumb.lastIndexOf("/");
				const origin = `${thumb.substring(0, idx)}/${img.page}.${img.ext ?? "webp"}`;
				let href = img.href;
				if (!href.startsWith("http")) href = window.location.origin + href;
				const node = new ImageNode(thumb, href, `${title}.${img.ext}`, void 0, origin, {
					w: img.width,
					h: img.height
				});
				nodes.push(node);
			}
			return nodes;
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
	};
	ADAPTER.addSetup({
		name: "HentaiZap",
		workURLs: [/hentaizap.com\/gallery\/\w+\/?/],
		match: ["https://hentaizap.com/*"],
		constructor: () => new HentaiZapMatcher()
	});
	var hitomi_exports = __exportAll({});
	var CONTENT_DOMAIN = "gold-usergeneratedcontent.net";
	var HitomiGG = class {
		base = void 0;
		b;
		m;
		constructor(b, m) {
			this.b = b;
			this.m = new Function("g", m);
		}
		real_full_path_from_hash(hash) {
			return hash.replace(/^.*(..)(.)$/, "$2/$1/" + hash);
		}
		s(h) {
			const m = /(..)(.)$/.exec(h);
			return parseInt(m[2] + m[1], 16).toString(10);
		}
		subdomain_from_url(url, base, dir) {
			let retval = "";
			if (!base) {
				if (dir === "webp") retval = "w";
				else if (dir === "avif") retval = "a";
			}
			let b = 16;
			let m = /\/[0-9a-f]{61}([0-9a-f]{2})([0-9a-f])/.exec(url);
			if (!m) return retval;
			let g = parseInt(m[2] + m[1], b);
			if (!isNaN(g)) {
				if (base) retval = String.fromCharCode(97 + this.m(g)) + base;
				else retval = retval + (1 + this.m(g));
			}
			return retval;
		}
		thumbURL(hash) {
			hash = hash.replace(/^.*(..)(.)$/, "$2/$1/" + hash);
			const url = "https://a." + CONTENT_DOMAIN + "/webpsmalltn/" + hash + ".webp";
			return url.replace(/\/\/..?\.(?:gold-usergeneratedcontent\.net|hitomi\.la)\//, "//" + this.subdomain_from_url(url, "tn", "webp") + ".gold-usergeneratedcontent.net/");
		}
		originURL(hash, ext) {
			let dir = ext;
			if (dir === "webp" || dir === "avif") dir = "";
			else dir += "/";
			let url = "https://a." + CONTENT_DOMAIN + "/" + dir + this.b + this.s(hash) + "/" + hash + "." + ext;
			url = url.replace(/\/\/..?\.(?:gold-usergeneratedcontent\.net|hitomi\.la)\//, "//" + this.subdomain_from_url(url, this.base, ext) + ".gold-usergeneratedcontent.net/");
			return url;
		}
	};
	var GG_M_REGEX = /m:\sfunction\(g\)\s{(.*?return.*?;)/s;
	var GG_B_REGEX = /b:\s'(\d*\/)'/;
	var HitomiMather = class extends BaseMatcher {
		gg;
		meta = {};
		infoRecord = {};
		formats = [
			"avif",
			"jxl",
			"webp"
		];
		formatIndex = 0;
		async *fetchChapters() {
			this.formatIndex = ADAPTER.conf.hitomiFormat === "auto" ? 0 : this.formats.indexOf(ADAPTER.conf.hitomiFormat);
			if (this.formatIndex === -1) throw new Error("invalid hitomi format: " + ADAPTER.conf.hitomiFormat);
			const ggRaw = await window.fetch(`https://ltn.${CONTENT_DOMAIN}/gg.js?_=${Date.now()}`).then((resp) => resp.text());
			this.gg = new HitomiGG(GG_B_REGEX.exec(ggRaw)[1], GG_M_REGEX.exec(ggRaw)[1]);
			const ret = [];
			ret.push(new Chapter(0, document.querySelector("#gallery-brand")?.textContent || "default", window.location.href, document.querySelector(".content > .cover-column > .cover img")?.src));
			return ret;
		}
		async *fetchPagesSource(chapter) {
			const galleryID = chapter.source.match(/([0-9]+)(?:\.html)/)?.[1];
			if (!galleryID) throw new Error("cannot query hitomi gallery id");
			const infoRaw = await window.fetch(`https://ltn.${CONTENT_DOMAIN}/galleries/${galleryID}.js`).then((resp) => resp.text()).then((text) => text.replace("var galleryinfo = ", ""));
			if (!infoRaw) throw new Error("cannot query hitomi gallery info");
			const info = JSON.parse(infoRaw);
			this.setGalleryMeta(info, galleryID, chapter);
			yield Result.ok(info);
		}
		async parseImgNodes(info) {
			const files = info.files;
			const list = [];
			for (let i = 0; i < files.length; i++) {
				const file = files[i];
				let ext = this.formats.slice(this.formatIndex).find((format) => file["has" + format] === 1);
				if (!ext) {
					ext = "webp";
					evLog("error", "no format found: ", files[i]);
				}
				const title = file.name.replace(/\.\w+$/, "");
				const src = this.gg.originURL(file.hash, ext);
				const { width, height } = file;
				list.push(new ImageNode(this.gg.thumbURL(files[i].hash), src, title + "." + ext, void 0, src, width && height ? {
					w: width,
					h: height
				} : void 0));
			}
			return list;
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
		setGalleryMeta(info, galleryID, chapter) {
			this.infoRecord[chapter.id] = info;
			this.meta[chapter.id] = new GalleryMeta(chapter.source, info.title || "hitomi-" + galleryID);
			this.meta[chapter.id].originTitle = info.japanese_title || void 0;
			const excludes = ["scene_indexes", "files"];
			for (const key in info) {
				if (excludes.indexOf(key) > -1) continue;
				this.meta[chapter.id].tags[key] = info[key];
			}
		}
		galleryMeta(chapter) {
			return this.meta[chapter.id];
		}
		title() {
			const entries = Object.entries(this.infoRecord);
			if (entries.length === 0) return "hitomi-unknown";
			if (entries.length === 1) return entries[0][1].japanese_title || entries[0][1].title || "hitomi-unknown";
			else return "hitomi-multiple" + entries.map((entry) => entry[1].id).join("_");
		}
	};
	ADAPTER.addSetup({
		name: "hitomi",
		workURLs: [/hitomi.la\/(?!reader)\w+\/.*\d+\.html/],
		match: ["https://hitomi.la/*"],
		constructor: () => new HitomiMather()
	});
	function q(selector, parent) {
		const element = parent.querySelector(selector);
		if (!element) throw new Error(`Can't find element: ${selector}`);
		return element;
	}
	var im_hentai_exports = __exportAll({});
	var IMHentaiMatcher = class extends BaseMatcher {
		meta;
		async fetchOriginMeta(node, _) {
			return { url: node.originSrc };
		}
		async parseImgNodes(data) {
			const ret = [];
			const digits = data.total.toString().length;
			for (let i = 1; i <= data.total; i++) {
				const url = `https://m${data.server}.imhentai.xxx/${data.imgDir}/${data.gid}/${i}t.jpg`;
				const href = `https://imhentai.xxx/view/${data.uid}/${i}/`;
				const ext = imParseExt(data.gth[i.toString()]);
				const originSrc = `https://m${data.server}.imhentai.xxx/${data.imgDir}/${data.gid}/${i}.${ext}`;
				let wh = void 0;
				const splits = data.gth[i.toString()].split(",");
				if (splits.length === 3) wh = {
					w: parseInt(splits[1]),
					h: parseInt(splits[2])
				};
				const node = new ImageNode(url, href, `${i.toString().padStart(digits, "0")}.${ext}`, void 0, originSrc, wh);
				ret.push(node);
			}
			return ret;
		}
		async *fetchPagesSource() {
			const server = q("#load_server", document).value;
			const uid = q("#gallery_id", document).value;
			const gid = q("#load_id", document).value;
			const imgDir = q("#load_dir", document).value;
			const total = q("#load_pages", document).value;
			const gthRaw = Array.from(document.querySelectorAll("script")).find((s) => s.textContent?.trimStart().startsWith("var g_th"))?.textContent?.match(/\('(\{.*?\})'\)/)?.[1];
			if (!gthRaw) throw new Error("cannot match gallery images info");
			const gth = JSON.parse(gthRaw);
			const data = {
				server,
				uid,
				gid,
				imgDir,
				total: Number(total),
				gth
			};
			yield Result.ok(data);
		}
		title() {
			const meta = this.galleryMeta();
			let title = "";
			if (ADAPTER.conf.ehentaiTitlePrefer === "japanese") title = meta.originTitle || meta.title || "UNTITLE";
			else title = meta.title || meta.originTitle || "UNTITLE";
			return title;
		}
		galleryMeta() {
			if (this.meta) return this.meta;
			const title = document.querySelector(".right_details > h1")?.textContent || void 0;
			const originTitle = document.querySelector(".right_details > p.subtitle")?.textContent || void 0;
			const meta = new GalleryMeta(window.location.href, title || "UNTITLE");
			meta.originTitle = originTitle;
			meta.tags = {};
			const list = Array.from(document.querySelectorAll(".galleries_info > li"));
			for (const li of list) {
				let cat = li.querySelector(".tags_text")?.textContent;
				if (!cat) continue;
				cat = cat.replace(":", "").trim();
				if (!cat) continue;
				const tags = Array.from(li.querySelectorAll("a.tag")).map((a) => a.firstChild?.textContent?.trim()).filter((v) => Boolean(v));
				meta.tags[cat] = tags;
			}
			this.meta = meta;
			return this.meta;
		}
	};
	function imParseExt(str) {
		switch (str.slice(0, 1)) {
			case "j": return "jpg";
			case "g": return "gif";
			case "p": return "png";
			case "w": return "webp";
			case "a": return "avif";
			case "m": return "mp4";
			default: throw new Error("cannot parse image extension from info: " + str);
		}
	}
	ADAPTER.addSetup({
		name: "im-hentai",
		workURLs: [/imhentai.xxx\/gallery\/\d+\//],
		match: ["https://imhentai.xxx/*"],
		constructor: () => new IMHentaiMatcher()
	});
	var instagram_exports = __exportAll({});
	var InstagramMatcher = class extends BaseMatcher {
		config;
		async *fetchPagesSource() {
			this.config = parseConfig();
			let cursor = null;
			while (true) try {
				const [nodes, pageInfo] = await this.fetchPosts(cursor);
				cursor = pageInfo.end_cursor;
				yield Result.ok(nodes);
				if (!pageInfo.has_next_page) break;
			} catch (error) {
				yield Result.err(error);
			}
		}
		async parseImgNodes(nodes) {
			const ret = [];
			for (let i = 0; i < nodes.length; i++) {
				const node = nodes[i];
				const videos = node.video_versions;
				const images = !videos && node.carousel_media && node.carousel_media.length > 0 ? node.carousel_media.map((n) => n.image_versions2) : [node.image_versions2];
				const digits = images.length.toString().length;
				for (let j = 0; j < images.length; j++) {
					const img = images[j];
					const title = images.length > 1 ? `${node.pk}-${(j + 1).toString().padStart(digits, "0")}` : node.pk;
					const ext = videos ? "mp4" : "jpeg";
					const [thumb, origin] = this.getThumbAndOrigin(img.candidates, videos);
					ret.push(new ImageNode(thumb?.url ?? "", `${window.location.origin}/p/${node.code}`, `${title}.${ext}`, void 0, origin.url, {
						w: thumb.width,
						h: thumb.height
					}));
				}
			}
			return ret;
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
		async fetchPosts(cursor) {
			if (!this.config) throw new Error("instagram config null");
			const config = this.config;
			const headers = new Headers();
			headers.append("x-fb-friendly-name", config.apiName);
			headers.append("x-bloks-version-id", config.bloksVersionID);
			headers.append("x-csrftoken", config.csrfToken);
			headers.append("x-ig-app-id", config.appID);
			headers.append("x-fb-lsd", config.lsd);
			headers.append("x-asbd-id", "129477");
			let variables = {
				"username": config.username,
				"__relay_internal__pv__PolarisIsLoggedInrelayprovider": true,
				"__relay_internal__pv__PolarisFeedShareMenurelayprovider": true,
				"data": {
					"count": 12,
					"include_relationship_info": true,
					"latest_besties_reel_media": true,
					"latest_reel_media": true
				}
			};
			if (cursor) {
				variables.after = cursor;
				variables.before = null;
				variables.first = 12;
				variables.last = null;
			}
			const body = new URLSearchParams();
			body.append("av", config.userID);
			body.append("__d", "www");
			body.append("__user", "0");
			body.append("__a", "1");
			body.append("__req", "x");
			body.append("__hs", config.hasteSession);
			body.append("dpr", "1");
			body.append("__ccg", "UNKNOWN");
			body.append("__rev", config.clientVersion);
			body.append("__hsi", config.hsi);
			body.append("__dyn", config.dyn);
			body.append("__comet_req", "7");
			body.append("fb_dtsg", config.dtsg);
			body.append("lsd", config.lsd);
			body.append("__spin_r", config.spinR);
			body.append("__spin_b", config.spinB);
			body.append("__spin_t", config.spinT);
			body.append("fb_api_caller_class", "RelayModern");
			body.append("fb_api_req_friendly_name", config.apiName);
			body.append("variables", JSON.stringify(variables));
			body.append("server_timestamps", "true");
			body.append("doc_id", config.docID);
			const data = (await window.fetch("https://www.instagram.com/graphql/query", {
				headers,
				body,
				method: "POST"
			}).then((res) => res.json()))?.data?.xdt_api__v1__feed__user_timeline_graphql_connection;
			if (!data) throw new Error("failed fetch user's posts by API");
			return [data.edges.map((e) => e.node), data.page_info];
		}
		getThumbAndOrigin(candidates, videos) {
			const origin = videos?.[0] ?? candidates[0];
			let lastThumb = void 0;
			for (const ca of candidates) {
				if (!lastThumb) {
					lastThumb = ca;
					continue;
				}
				if (lastThumb.width < ca.width || ca.width <= 240) break;
				lastThumb = ca;
			}
			return [lastThumb, origin];
		}
	};
	function parseConfig() {
		const err = new Error("cannot find instagram config from script[data-sjs]");
		const raw = Array.from(document.querySelectorAll("script[data-sjs]")).find((s) => s.textContent?.trimStart().startsWith(`{"require":[["ScheduledServerJS","handle",null,[{"__bbox":{"define":`))?.textContent;
		if (!raw) throw err;
		const map = (JSON.parse(raw).require?.[0]?.[3]?.[0]?.__bbox?.define).reduce((prev, curr) => {
			prev[curr[0]] = curr[2];
			return prev;
		}, {});
		if (!map) throw err;
		let csrfToken = map["InstagramSecurityConfig"]?.csrf_token;
		let lsd = map["LSD"]?.token;
		let bloksVersionID = map["WebBloksVersioningID"]?.versioningID;
		let appID = map["CurrentUserInitialData"]?.APP_ID;
		let userID = map["CurrentUserInitialData"]?.NON_FACEBOOK_USER_ID;
		let hasteSession = map["SiteData"]?.haste_session;
		let clientVersion = map["SiteData"]?.client_revision;
		let hsi = map["SiteData"]?.hsi;
		let spinR = map["SiteData"]?.__spin_r;
		let spinB = map["SiteData"]?.__spin_b;
		let spinT = map["SiteData"]?.__spin_t;
		let dtsg = map["DTSGInitData"]?.token;
		const username = window.location.pathname.split("/")?.[1];
		if (!csrfToken || !lsd || !bloksVersionID || !appID || !userID || !hasteSession || !clientVersion || !hsi || !spinR || !spinB || !spinT || !dtsg || !username) throw err;
		return {
			csrfToken,
			lsd,
			bloksVersionID,
			appID,
			userID,
			hasteSession,
			clientVersion,
			hsi,
			spinR,
			spinB,
			spinT,
			dtsg,
			docID: "8363144743749214",
			apiName: "PolarisProfilePostsTabContentQuery_connection",
			dyn: "7xeUjG1mxu1syUbFp41twpUnwgU7SbzEdF8aUco2qwJxS0k24o0B-q1ew65xO0FE2awgo9oO0n24oaEnxO1ywOwv89k2C1Fwc60D87u3ifK0EUjwGzEaE2iwNwmE2eUlwhEe87q7U1mVEbUGdG1QwTU9UaQ0Lo6-3u2WE5B08-269wr86C1mwPwUQp1yUb9UK6V8aUuwm9EO6UaU4W",
			username
		};
	}
	ADAPTER.addSetup({
		name: "Instagram",
		workURLs: [/instagram.com\/(?!(home|explore|direct|reels|stories))\w+/],
		match: ["https://www.instagram.com/*"],
		constructor: () => new InstagramMatcher()
	});
	var jandan_exports = __exportAll({});
	var JandanPagesList = class {
		async *fetchChapters() {
			yield [new Chapter(0, "Default", window.location.href)];
		}
		async *fetchPagesSource() {
			let post = window.location.href.includes("ooxx") ? "21183" : "26402";
			let page = parseInt(window.location.href.match(/page=(\d+)/)?.[1] ?? "0");
			if (isNaN(page)) page = 0;
			let api = new URL(`${window.location.origin}/api/comment/post/${post}?order=desc&page=${page}`);
			while (page >= 0) {
				const resp = await window.fetch(api).then((res) => res.json()).catch(Error);
				if (resp instanceof Error) {
					yield Result.err(resp);
					sleep$1(1e3);
					continue;
				}
				let data = resp.data;
				if (!data) {
					yield Result.err(new Error("获取此页数据失败:" + page));
					sleep$1(1e3);
					continue;
				}
				yield Result.ok(data.list);
				page = data.current_page - 1;
				api.searchParams.set("page", page.toString());
			}
		}
	};
	var JandanTopList = class {
		async *fetchChapters() {
			yield [new Chapter(0, "4小时热门", `${window.location.origin}/api/top/4hr`)];
			yield [
				new Chapter(1, "无聊图", `${window.location.origin}/api/top/post/26402`),
				new Chapter(2, "随手拍", `${window.location.origin}/api/top/post/21183`),
				new Chapter(3, "3日最佳", `${window.location.origin}/api/top/pic3days`),
				new Chapter(4, "7日最佳", `${window.location.origin}/api/top/pic7days`)
			];
		}
		async *fetchPagesSource(chapter) {
			const data = await window.fetch(chapter.source).then((res) => res.json()).catch(Error);
			if (data instanceof Error) throw data;
			const list = data.data;
			if (!list) throw new Error("cannot find comments");
			yield Result.ok(list);
		}
	};
	var JandanMatcher = class extends BaseMatcher {
		list;
		cdnLine = "1";
		constructor() {
			super();
			if (/jandan.net\/top/.test(window.location.href)) this.list = new JandanTopList();
			else this.list = new JandanPagesList();
			const settings_raw = window.localStorage.getItem("jandan:settings");
			if (settings_raw) {
				const settings = JSON.parse(settings_raw);
				this.cdnLine = settings.cdnLine ?? "1";
			}
		}
		fetchChapters() {
			return this.list.fetchChapters();
		}
		fetchPagesSource(source) {
			return this.list.fetchPagesSource(source);
		}
		async parseImgNodes(comments) {
			const ret = [];
			for (const comment of comments) {
				const images = Array.from(comment.content.matchAll(/src="(.*?)"/gm).map((m) => m[1]));
				if (images.length === 0) continue;
				const href = `${window.location.origin}/t/${comment.id}`;
				const ooAction = new NodeAction("oo" + comment.vote_positive, "xxoo", async () => {
					await fetch(`${window.location.origin}/api/comment/vote`, {
						"headers": { "Content-Type": "application/json" },
						"referrer": window.location.origin,
						"body": `{"comment_id":${comment.id},"like_type":"pos","data_type":"comment"}`,
						"method": "POST"
					});
				});
				const xxAction = new NodeAction("xx" + comment.vote_negative, "xxoo", async () => {
					await fetch(`${window.location.origin}/api/comment/vote`, {
						"headers": { "Content-Type": "application/json" },
						"referrer": window.location.origin,
						"body": `{"comment_id":${comment.id},"like_type":"neg","data_type":"comment"}`,
						"method": "POST"
					});
				});
				for (let i = 0; i < images.length; i++) {
					const img = images[i];
					const [thumb, origin, ext, isGIF] = this.parseURL(img);
					const node = new ImageNode(thumb, href, `${comment.id}-${i + 1}.${ext}`, void 0, origin);
					node.actions.push(ooAction);
					node.actions.push(xxAction);
					if (isGIF) node.mimeType = "video/mp4";
					ret.push(node);
				}
			}
			return ret;
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
		parseURL(src) {
			if (this.cdnLine === "1") {
				src = src.replace(/img\.wangmoyu\.com/, "wangmoyuimg.cdn.dfyun.com.cn");
				src = src.replace(/img\.moyu\.im/, "moyuimg.cdn.dfyun.com.cn");
				src = src.replace(/img\.toto\.im/, "totoimg.cdn.dfyun.com.cn");
			}
			if (/gif$/.test(src)) return [
				src.replace(/(https?:\/\/[^/]+)\/\w+\/(.+?\.gif)/, "$1/thumb180/$2") + ".webp",
				src.replace(/(https?:\/\/[^/]+)\/\w+\/(.+?)\.gif/, "$1/large/$2.mp4"),
				"mp4",
				true
			];
			else {
				let origin = src.replace(/(https?:\/\/[^/]+)\/\w+\/(.+?)/, "$1/large/$2");
				if (/\.(jpg|png|jpeg)$/.test(src)) src = src + ".webp";
				const ext = origin.split(".").pop() ?? "webp";
				return [
					src,
					origin,
					ext,
					false
				];
			}
		}
	};
	ADAPTER.addSetup({
		name: "煎蛋网",
		match: ["https://jandan.net/*", "https://i.jandan.net/*"],
		workURLs: [/jandan.net\/(pic|ooxx|top)/],
		constructor: () => new JandanMatcher()
	});
	var komiic_exports = __exportAll({});
	var KomiicMatcher = class extends BaseMatcher {
		chapterType;
		meta;
		constructor() {
			super();
			this.chapterType = {
				chapter: {
					display: "话",
					sort: 1
				},
				book: {
					display: "卷",
					sort: 0
				}
			};
		}
		galleryMeta(_chapter) {
			if (this.meta) return this.meta;
			return new GalleryMeta(window.location.href, document.title);
		}
		async *fetchChapters() {
			const id = window.location.href.match(/comic\/(\d+)/)?.[1];
			if (!id) throw new Error("cannot get comic id");
			const data = await fetch(`${window.location.origin}/api/query`, {
				"headers": { "Content-Type": "application/json" },
				"body": JSON.stringify({
					operationName: "chapterByComicId",
					query: "query chapterByComicId($comicId: ID!) {\n chaptersByComicId(comicId: $comicId) {\n id\n serial\n type\n dateCreated\n dateUpdated\n size\n __typename\n }\n}",
					variables: { comicId: id }
				}),
				"method": "POST",
				"mode": "cors"
			}).then((res) => res.json());
			try {
				const cInfo = (await fetch(`${window.location.origin}/api/query`, {
					"headers": { "Content-Type": "application/json" },
					"body": JSON.stringify({
						operationName: "comicById",
						query: "query comicById($comicId: ID!) {\n comicById(comicId: $comicId) {\n id\n title\n status\n year\n imageUrl\n authors {\n id\n name\n __typename\n }\n categories {\n id\n name\n __typename\n }\n dateCreated\n dateUpdated\n views\n favoriteCount\n lastBookUpdate\n lastChapterUpdate\n __typename\n }\n}",
						variables: { comicId: id }
					}),
					"method": "POST",
					"mode": "cors"
				}).then((res) => res.json())).data.comicById;
				this.meta = new GalleryMeta(window.location.href, cInfo.title);
				this.meta.tags.authors = cInfo.authors.map((a) => a.name);
				this.meta.tags.categories = cInfo.categories.map((a) => a.name);
			} catch (err) {
				evLog("error", "fetch comic info error", err);
			}
			let chapters = data.data.chaptersByComicId;
			chapters = chapters.sort((a, b) => this.chapterType[a.type].sort - this.chapterType[b.type].sort);
			yield chapters.map((c) => new Chapter(parseInt(c.id), c.serial + this.chapterType[c.type].display, id + "/" + c.id));
		}
		async *fetchPagesSource(ch) {
			const images = await fetch(`${window.location.origin}/api/query`, {
				"headers": { "Content-Type": "application/json" },
				"body": JSON.stringify({
					operationName: "imagesByChapterId",
					query: "query imagesByChapterId($chapterId: ID!) {\n imagesByChapterId(chapterId: $chapterId) {\n id\n kid\n height\n width\n __typename\n }\n}",
					variables: { chapterId: ch.source.split("/").pop() }
				}),
				"method": "POST",
				"mode": "cors"
			}).then((res) => res.json());
			const [comicId, chapterId] = ch.source.split("/");
			const ret = images.data.imagesByChapterId.map((img) => {
				return {
					comicId,
					chapterId,
					...img
				};
			});
			yield Result.ok(ret);
		}
		async parseImgNodes(images) {
			const digits = images.length.toString().length;
			return images.map((img, i) => {
				const url = `${window.location.origin}/api/image/${img.kid}`;
				const name = (i + 1).toString().padStart(digits, "0");
				return new ImageNode("", `${window.location.origin}/comic/${img.comicId}/chapter/${img.chapterId}/page/1`, name + ".webp", void 0, url, {
					w: img.width,
					h: img.height
				});
			});
		}
		headers(node) {
			return {
				"Accept": "image/avif,image/webp,image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5",
				"Referer": node.href
			};
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
	};
	ADAPTER.addSetup({
		name: "komiic.com",
		workURLs: [/komiic.com\/comic\/\d+\/?$/],
		match: ["https://komiic.com/*"],
		constructor: () => new KomiicMatcher()
	});
	var konachan_exports = __exportAll({ KonachanMatcher: () => KonachanMatcher });
	var POST_INFO_REGEX$1 = /Post\.register\((.*)\)/g;
	var KonachanMatcher = class extends BaseMatcher {
		infos = {};
		count = 0;
		async *fetchPagesSource() {
			let doc = document;
			yield Result.ok(doc);
			let tryTimes = 0;
			while (true) {
				const url = doc.querySelector("#paginator a.next_page")?.href;
				if (!url) break;
				try {
					doc = await window.fetch(url).then((res) => res.text()).then((text) => new DOMParser().parseFromString(text, "text/html"));
				} catch (e) {
					tryTimes++;
					if (tryTimes > 3) throw new Error(`fetch next page failed, ${e}`);
					continue;
				}
				tryTimes = 0;
				yield Result.ok(doc);
			}
		}
		async parseImgNodes(doc) {
			const raw = doc.querySelector("body > script + script")?.textContent;
			if (!raw) throw new Error("cannot find post list from script");
			const matches = raw.matchAll(POST_INFO_REGEX$1);
			const ret = [];
			for (const match of matches) {
				if (!match || match.length < 2) continue;
				try {
					const info = JSON.parse(match[1]);
					this.infos[info.id.toString()] = info;
					this.count++;
					const ext = info.file_ext || info.file_url.split(".").pop();
					ret.push(new ImageNode(info.preview_url, `${window.location.origin}/post/show/${info.id}`, `${info.id}.${ext}`));
				} catch (error) {
					evLog("error", "parse post info failed", error);
					continue;
				}
			}
			return ret;
		}
		async fetchOriginMeta(node) {
			const id = node.href.split("/").pop();
			if (!id) throw new Error(`cannot find id from ${node.href}`);
			let url;
			if (ADAPTER.conf.fetchOriginal) url = this.infos[id]?.file_url;
			else url = this.infos[id]?.sample_url;
			if (!url) throw new Error(`cannot find url for id ${id}`);
			return { url };
		}
		galleryMeta() {
			const tags = new URL(window.location.href).searchParams.get("tags")?.trim();
			const meta = new GalleryMeta(window.location.href, `konachan_${tags}_${this.count}`);
			meta["infos"] = this.infos;
			return meta;
		}
	};
	ADAPTER.addSetup({
		name: "konachan",
		workURLs: [/konachan.com\/post(?!\/show\/.*)/],
		match: ["https://konachan.com/*"],
		constructor: () => new KonachanMatcher()
	});
	var kone_exports = __exportAll({});
	var KoneMatcher = class extends BaseMatcher {
		async *fetchPagesSource() {
			yield Result.ok(document);
		}
		async parseImgNodes(doc) {
			const images = Array.from(doc.querySelectorAll("#post-article img[src*=\"gimel.mittere.io\"]"));
			const digits = images.length.toString().length;
			return images.map((img, i) => {
				const src = img.src;
				const title = (i + 1).toString().padStart(digits, "0") + ".webp";
				const w = Number(img.getAttribute("width"));
				const h = Number(img.getAttribute("height"));
				return new ImageNode(src, src, title, void 0, src, w > 0 && h > 0 ? {
					w,
					h
				} : void 0);
			});
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc ?? node.href };
		}
	};
	ADAPTER.addSetup({
		name: "Kone",
		workURLs: [/kone\.gg\/s\/[\w-]+\/[\w-]+/],
		match: ["https://kone.gg/*"],
		constructor: () => new KoneMatcher()
	});
	var kuaikanmanhua_exports = __exportAll({});
	var KuaiKanMatcher = class extends BaseMatcher {
		async *fetchChapters() {
			let ele = document.querySelector(".Headers");
			if (ele) ele.style.zIndex = "1000";
			let comics = window.__NUXT__?.data?.[0].comics;
			if (!comics || (comics.length ?? 0) === 0) {
				let sc = Array.from(document.querySelectorAll("script")).find((sc) => sc.textContent.startsWith("window.__NUXT__"))?.textContent.replace("window.__NUXT__=", "");
				if (sc) try {
					comics = new Function("return " + sc)()?.data?.[0].comics;
				} catch (err) {
					throw new Error("无法解析此漫画的章节信息");
				}
			}
			if (!comics) throw new Error("无法找到此漫画的章节信息");
			yield comics.map((c, i) => {
				return new Chapter(i, c.title, `${window.location.origin}/webs/comic-next/${c.id}`, c.cover_image_url);
			});
		}
		async *fetchPagesSource(ch) {
			yield Result.ok(ch.source);
		}
		async parseImgNodes(source) {
			const doc = await window.fetch(source).then((resp) => resp.text()).then((text) => new DOMParser().parseFromString(text, "text/html")).catch(Error);
			if (doc instanceof Error) throw doc;
			let sc = Array.from(doc.querySelectorAll("script")).find((sc) => sc.textContent.startsWith("window.__NUXT__"))?.textContent.replace("window.__NUXT__=", "");
			if (!sc) throw new Error("无法找到此章节的信息");
			let images;
			try {
				images = new Function("return " + sc)().data?.[0].comicInfo?.comicImages;
			} catch (err) {
				throw new Error("无法解析此章节的信息" + err.message);
			}
			if (!images || (images.length ?? 0) === 0) throw new Error("没有找到此章节的图片列表,可能是你没有购买,请点此确认: " + source);
			const digits = images.length.toString().length;
			return images.map((img, i) => {
				return new ImageNode("", img.url, (i + 1).toString().padStart(digits, "0"), void 0, img.url, {
					w: img.baseWidth,
					h: img.baseHeight
				});
			});
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
	};
	ADAPTER.addSetup({
		name: "快看漫画",
		match: ["kuaikanmanhua.com/*"],
		workURLs: [/kuaikanmanhua.com\/web\/topic\/\d+\//],
		constructor: () => new KuaiKanMatcher()
	});
	var mangacopy_exports = __exportAll({});
	var MangaCopyMatcher = class extends BaseMatcher {
		update_date;
		chapterCount = 0;
		meta;
		jojoKey;
		galleryMeta() {
			if (this.meta) return this.meta;
			let title = document.querySelector(".comicParticulars-title-right > ul > li > h6")?.textContent ?? document.title;
			document.querySelectorAll(".comicParticulars-title-right > ul > li > span.comicParticulars-right-txt").forEach((ele) => {
				if (/^\d{4}-\d{2}-\d{2}$/.test(ele.textContent?.trim() || "")) this.update_date = ele.textContent?.trim();
			});
			title += "-c" + this.chapterCount + (this.update_date ? "-" + this.update_date : "");
			this.meta = new GalleryMeta(window.location.href, title);
			return this.meta;
		}
		async *fetchPagesSource(source) {
			yield Result.ok(source.source);
		}
		async parseImgNodes(source) {
			const raw = await window.fetch(source).then((resp) => resp.text());
			const doc = new DOMParser().parseFromString(raw, "text/html");
			const jojoKey = raw.match(/var (jojo|ccy|cct|ccz)\s?=\s?'(.*?)';/)?.[2];
			if (!jojoKey) throw new Error("cannot find jojo|ccy|cct|ccz Key for decrypt :(");
			const contentKey = doc.querySelector(".imageData[contentKey]")?.getAttribute("contentKey") ?? raw.match(/var (contentKey)\s?=\s?'(.*?)';/)?.[2];
			if (!contentKey) throw new Error("cannot find content key");
			try {
				const decryption = await decrypt(contentKey, jojoKey);
				const images = JSON.parse(decryption);
				const digits = images.length.toString().length;
				return images.map((img, i) => {
					return new ImageNode("", source, (i + 1).toString().padStart(digits, "0") + ".webp", void 0, img.url);
				});
			} catch (error) {
				throw new Error("cannot decrypt contentKey: " + error.toString() + "\n" + contentKey);
			}
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
		async *fetchChapters() {
			const thumbimg = document.querySelector(".comicParticulars-left-img > img[data-src]")?.getAttribute("data-src") || void 0;
			const pathWord = window.location.href.match(PATH_WORD_REGEX)?.[1];
			if (!pathWord) throw new Error("cannot match comic id");
			const comicInfoURL = `/comicdetail/${pathWord}/chapters`;
			const comicInfo = await window.fetch(comicInfoURL, { headers: {
				"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
				"dnts": "9",
				"Cookie": "webp=1",
				"Referer": window.location.href
			} }).then((res) => res.json()).catch((reason) => new Error(reason.toString()));
			if (comicInfo instanceof Error) throw new Error("获取漫画详情失败: " + comicInfo.toString());
			if (comicInfo.code !== 200) throw new Error("获取漫画详情失败: " + comicInfo.message);
			const detailRaw = await decrypt(comicInfo.results, getCcz());
			const detail = JSON.parse(detailRaw);
			console.log(detail);
			const chapters = [];
			const groups = detail.groups;
			if (!groups || (groups?.default?.chapters ?? []).length === 0) throw new Error("章节信息为空,可能被风控(一小时)");
			let chapterCount = 1;
			for (const group in groups) {
				const chs = groups[group].chapters;
				for (const ch of chs) chapters.push(new Chapter(chapterCount++, group === "default" ? ch.name : `${groups[group].name}-${ch.name}`, `${window.location.origin}/comic/${pathWord}/chapter/${ch.id}`, thumbimg));
			}
			this.chapterCount = chapterCount - 1;
			return chapters;
		}
	};
	function getCcz() {
		if (ccz) return ccz;
		if (ccy) return ccy;
		return "op0zzpvv.nzh.oip";
	}
	var PATH_WORD_REGEX = /\/comic\/(\w*)/;
	async function decrypt(raw, jojoKey) {
		const encoder = new TextEncoder();
		const decoder = new TextDecoder();
		const jojo = encoder.encode(jojoKey);
		const header = raw.substring(0, 16);
		const body = raw.substring(16);
		const iv = encoder.encode(header);
		const bodyBytes = new Uint8Array(body.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));
		const cryptoKey = await crypto.subtle.importKey("raw", jojo, { name: "AES-CBC" }, false, ["decrypt"]);
		const decryptedBytes = await crypto.subtle.decrypt({
			name: "AES-CBC",
			iv
		}, cryptoKey, bodyBytes);
		return decoder.decode(decryptedBytes);
	}
	ADAPTER.addSetup({
		name: "拷贝漫画",
		workURLs: [/(mangacopy|copymanga|copy4000).*?\/comic\/[^\/]*\/?$/],
		match: ["https://www.mangacopy.com/*"],
		constructor: () => new MangaCopyMatcher()
	});
	var mangadex_exports = __exportAll({});
	var MangaDexMatcher = class extends BaseMatcher {
		async *fetchChapters() {
			const galleryId = window.location.href.match(/title\/([^\/]+)\//)?.[1];
			if (!galleryId) throw new Error("cannot match gallery id from href");
			const data = await window.fetch(`https://api.mangadex.org/manga/${galleryId}/feed?limit=96&includes[]=scanlation_group&includes[]=user&order[volume]=desc&order[chapter]=desc&offset=0&contentRating[]=safe&contentRating[]=suggestive&contentRating[]=erotica&contentRating[]=pornographic&includeUnavailable=0`).then((resp) => resp.json()).catch(Error);
			if (data instanceof Error) throw data;
			if (data.result !== "ok") throw new Error(`query chapters error: ${data.response}`);
			const chapters = [];
			let chId = 1;
			for (const ch of data.data) {
				if (ch.attributes.externalUrl) continue;
				const vol = ch.attributes.volume ? "vol." + ch.attributes.volume : "";
				const chNo = ch.attributes.chapter ? "ch." + ch.attributes.chapter : "";
				const title = ch.attributes.title ?? ch.id;
				const lang = ch.attributes.translatedLanguage ?? "";
				chapters.push(new Chapter(chId, [
					lang,
					vol,
					chNo,
					title
				], ch.id));
				chId++;
			}
			yield chapters;
		}
		async *fetchPagesSource(ch) {
			yield Result.ok(ch.source);
		}
		async parseImgNodes(id) {
			const data = await window.fetch(`https://api.mangadex.org/at-home/server/${id}`).then((resp) => resp.json()).catch(Error);
			if (data instanceof Error) throw data;
			const baseUrl = data.baseUrl;
			const hash = data.chapter.hash;
			const digits = data.chapter.data.length.toString().length;
			return data.chapter.data.map((url, i) => {
				const href = `https://mangadex.org/chapter/${id}/${i + 1}`;
				const ext = url.split(".").pop() ?? "jpg";
				const title = (i + 1).toString().padStart(digits, "0");
				const src = `${baseUrl}/data/${hash}/${url}`;
				return new ImageNode("", href, title + "." + ext, void 0, src);
			});
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
		headers(_node) {
			return {
				"Origin": "https://mangadex.org",
				"Referer": "https://mangadex.org"
			};
		}
	};
	ADAPTER.addSetup({
		name: "MangaDex",
		workURLs: [/mangadex.org\/title\/[^\/]+\//],
		match: ["https://mangadex.org/*"],
		constructor: () => new MangaDexMatcher()
	});
	var mangapark_exports = __exportAll({});
	var mangatoto_exports = __exportAll({});
	var manhuagui_exports = __exportAll({});
	var MHGMatcher = class extends BaseMatcher {
		meta;
		chapterCount = 0;
		galleryMeta() {
			if (this.meta) return this.meta;
			let title = document.querySelector(".book-title > h1")?.textContent ?? document.title;
			title += "-c" + this.chapterCount;
			const matches = document.querySelector(".detail-list .status")?.textContent?.match(STATUS_REGEX);
			const date = matches?.[1];
			title += date ? "-" + date : "";
			const last = matches?.[2];
			title += last ? "-" + last.trim() : "";
			this.meta = new GalleryMeta(window.location.href, title);
			return this.meta;
		}
		async *fetchPagesSource(source) {
			yield Result.ok(source.source);
		}
		async parseImgNodes(source) {
			const matches = (await window.fetch(source).then((res) => res.text())).match(IMG_DATA_PARAM_REGEX);
			if (!matches || matches.length < 5) throw new Error("cannot match image data");
			let data;
			try {
				data = parseImgData(matches[1], parseInt(matches[2]), parseInt(matches[3]), matches[4]);
			} catch (error) {
				throw new Error("cannot parse image data: " + error.toString());
			}
			const server = getServer();
			return data.files.map((f, i) => {
				const src = `${server}/${data.path}/${f}?e=${data.sl.e}&m=${data.sl.m}}`;
				return new ImageNode("", `https://www.manhuagui.com/comic/${data.bid}/${data.cid}.html#p=${i + 1}`, f, void 0, src);
			});
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
		async *fetchChapters() {
			const thumbimg = document.querySelector(".book-cover img")?.src;
			const chapters = [];
			document.querySelectorAll(".chapter-list").forEach((element) => {
				let prefix = findSibling(element, "prev", (e) => e.tagName.toLowerCase() === "h4")?.firstElementChild?.textContent ?? void 0;
				prefix = prefix ? prefix + "-" : "";
				element.querySelectorAll("ul").forEach((ul) => {
					const ret = Array.from(ul.querySelectorAll("li > a")).reverse().map((element) => new Chapter(0, prefix + element.title, element.href, thumbimg));
					chapters.push(...ret);
				});
			});
			chapters.forEach((ch, i) => ch.id = i + 1);
			return chapters;
		}
	};
	function findSibling(element, dir, eq) {
		const sibling = (e) => dir === "prev" ? e.previousElementSibling : e.nextElementSibling;
		let e = element;
		while (e = sibling(e)) if (eq(e)) return e;
		return null;
	}
	var MHG_SERVERS = [
		{
			name: "自动",
			hosts: [
				{
					h: "i",
					w: .1
				},
				{
					h: "eu",
					w: 5
				},
				{
					h: "eu1",
					w: 5
				},
				{
					h: "us",
					w: 1
				},
				{
					h: "us1",
					w: 1
				},
				{
					h: "us2",
					w: 1
				},
				{
					h: "us3",
					w: 1
				}
			]
		},
		{
			name: "电信",
			hosts: [{
				h: "eu",
				w: 1
			}, {
				h: "eu1",
				w: 1
			}]
		},
		{
			name: "联通",
			hosts: [
				{
					h: "us",
					w: 1
				},
				{
					h: "us1",
					w: 1
				},
				{
					h: "us2",
					w: 1
				},
				{
					h: "us3",
					w: 1
				}
			]
		}
	];
	function getServer() {
		const serv = parseInt(window.localStorage.getItem("") ?? "0");
		const host = parseInt(window.localStorage.getItem("") ?? "0");
		return `https://${MHG_SERVERS[serv]?.hosts[host]?.h ?? "us1"}.hamreus.com`;
	}
	var STATUS_REGEX = /\[(\d{4}-\d{2}-\d{2})\].*?\[(.*?)\]/;
	var IMG_DATA_PARAM_REGEX = /\('\w+\.\w+\((.*?)\).*?,(\d+),(\d+),'(.*?)'\[/;
	function decompressFromBase64(input) {
		return LZString.decompressFromBase64(input);
	}
	function parseImgData(tamplate, a, c, raw) {
		const keys = decompressFromBase64(raw).split("|");
		const d = {};
		function e(n) {
			return (n < a ? "" : e(Math.floor(n / a)).toString()) + ((n = n % a) > 35 ? String.fromCharCode(n + 29) : n.toString(36));
		}
		while (c--) d[e(c)] = keys[c] || e(c);
		const dataStr = tamplate.replace(new RegExp("\\b\\w+\\b", "g"), (key) => d[key]);
		return JSON.parse(dataStr);
	}
	ADAPTER.addSetup({
		name: "漫画柜",
		workURLs: [/manhuagui.com\/comic\/\d+\/?$/],
		match: ["https://www.manhuagui.com/*"],
		constructor: () => new MHGMatcher()
	});
	var mh160_exports = __exportAll({});
	var MH160Matcher = class extends BaseMatcher {
		hosts;
		constructor() {
			super();
			let hosts = [
				"xwdf.tgmhfc.uk",
				"mhreswhm.tgmhfc.uk",
				"qwe123.tgmhfc.uk",
				"resmhpic.tgmhfc.uk",
				"reszxc.tgmhfc.uk"
			];
			this.hosts = hosts.map((h) => ({
				h: "https://" + h,
				sort: Math.random()
			})).sort((a, b) => a.sort - b.sort).map((h) => h.h);
		}
		title() {
			return document.querySelector(".Introduct .h1")?.textContent ?? document.title;
		}
		async *fetchChapters() {
			yield Array.from(document.querySelectorAll("#chapterList_ul_1 > li > a")).map((elem, i) => {
				return new Chapter(i, elem.textContent, elem.href);
			});
		}
		async *fetchPagesSource(ch) {
			yield Result.ok(ch.source);
		}
		async parseImgNodes(source) {
			const raw = await window.fetch(source).then((resp) => resp.text()).catch(Error);
			if (raw instanceof Error) throw raw;
			const data = raw.match(/var qTcms_S_m_murl_e=\"([^"]*?)\"/)?.[1];
			if (!data) throw new Error("no images url matched, regexp: var qTcms_S_m_murl_e=\\\"([^\"]*?)\\\"");
			const spID = raw.match(/var qTcms_S_p_id=\"([^"]*?)\"/)?.[1];
			if (!spID) throw new Error("no qTcms_S_p_id matched, regexp: var qTcms_S_p_id=\\\"([^\"]*?)\\\"");
			const imgPaths = b64DecodeUnicode(data).split("$qingtiandy$");
			const digits = imgPaths.length.toString().length;
			return imgPaths.map((path, i) => {
				return new ImageNode("", source, path.split("/").pop() ?? (i + 1).toString().padStart(digits, "0") + ".jpg", void 0, this.getImgUrl(path, spID));
			});
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
		getImgUrl(path, spID) {
			if (path.startsWith("/")) {
				if (parseInt(spID || "0") > 542724) return this.hosts[0] + path;
				else return "https://mhpic6.tgmhfc.uk" + path;
			} else throw new Error("还未支持此图片url解析: " + path);
		}
		headers() {
			return {
				"Accept": "image/avif,image/webp,image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5",
				"Referer": "https://m.mh160mh.com/"
			};
		}
	};
	ADAPTER.addSetup({
		name: "漫画160",
		workURLs: [/mh160mh.com\/kanmanhua\/\w+\/$/],
		match: ["https://m.mh160mh.com/kanmanhua/*"],
		constructor: () => new MH160Matcher()
	});
	var PICTURE_EXTENSION = [
		"jpeg",
		"jpg",
		"png",
		"gif",
		"webp",
		"bmp",
		"avif",
		"jxl"
	];
	var VIDEO_EXTENSION = [
		"mp4",
		"webm",
		"ogg",
		"ogv",
		"mov",
		"avi",
		"mkv",
		"av1"
	];
	function isImage(ext) {
		return PICTURE_EXTENSION.includes(ext);
	}
	function isVideo(ext) {
		return VIDEO_EXTENSION.includes(ext);
	}
	var miniserve_exports = __exportAll({});
	var MiniServeMatcher = class extends BaseMatcher {
		map = new Map();
		currentDirectorMedias = [];
		async *fetchChapters() {
			const list = Array.from(document.querySelectorAll("table tbody a.file"));
			const chapters = [];
			let id = 1;
			for (const a of list) {
				const href = a.href;
				const ext = href.split(".").pop()?.toLowerCase();
				if (ext === "zip") {
					chapters.push(new Chapter(id, a.textContent ?? "unknown-" + id, href));
					id++;
				} else if (isImage(ext ?? "") || isVideo(ext ?? "")) {
					const node = new ImageNode(a.href, a.href, a.textContent ?? "", void 0, a.href);
					if (isImage(ext)) node.mimeType = "image/" + ext;
					else if (isVideo(ext)) node.mimeType = "video/" + ext;
					this.currentDirectorMedias.push(node);
				}
			}
			if (this.currentDirectorMedias.length > 0) chapters.unshift(new Chapter(0, "Current Directory", ""));
			if (chapters.length === 0) throw new Error("can not found zip files or current directory has empty image list");
			return chapters;
		}
		async *fetchPagesSource(source) {
			yield Result.ok(source.source);
		}
		async parseImgNodes(href, chapterID) {
			if (!href && this.currentDirectorMedias.length > 0) return this.currentDirectorMedias;
			const blob = await window.fetch(href).then((res) => res.blob());
			const entries = await new _zip_js_zip_js.ZipReader(new _zip_js_zip_js.BlobReader(blob)).getEntries();
			const map = new Map();
			this.map.set(chapterID, map);
			return entries.filter((e) => {
				const ext = (e.filename.split(".").pop() ?? "jpg").toLowerCase();
				return isImage(ext) || isVideo(ext);
			}).map((e) => {
				const promise = e.getData(new _zip_js_zip_js.BlobWriter());
				map.set(e.filename, promise);
				const ext = (e.filename.split(".").pop() ?? "jpg").toLowerCase();
				const node = new ImageNode("", e.filename, e.filename, void 0);
				if (isImage(ext)) node.mimeType = "image/" + ext;
				else if (isVideo(ext)) node.mimeType = "video/" + ext;
				return node;
			});
		}
		async fetchOriginMeta(node, _retry, chapterID) {
			if (node.originSrc) return { url: node.originSrc };
			const dataPromise = this.map.get(chapterID)?.get(node.href);
			if (!dataPromise) throw new Error("cannot read image from zip");
			const data = await dataPromise;
			return { url: URL.createObjectURL(data) };
		}
		async processData(data, _contentType, node) {
			return [data, node.mimeType];
		}
	};
	ADAPTER.addSetup({
		name: "Mini Serve",
		workURLs: [/.*:41021/],
		constructor: () => new MiniServeMatcher()
	});
	var mycomic_exports = __exportAll({});
	var MyComicMatcher = class extends BaseMatcher {
		meta;
		galleryMeta(chapter) {
			return this.meta ?? super.galleryMeta(chapter);
		}
		initGalleryMeta() {
			const title = document.querySelector(".grow > div[data-flux-heading]")?.textContent ?? document.title;
			this.meta = new GalleryMeta(window.location.href, title);
		}
		async *fetchChapters() {
			this.initGalleryMeta();
			const volumes = Array.from(document.querySelectorAll(".mt-8.mb-12 > div[x-data]"));
			const result = [];
			for (const vol of volumes) {
				let raw = vol.getAttribute("x-data");
				if (raw) {
					raw = raw.replace(/,\n\s*toggleSorting\(\) \{.*?\},/gms, "");
					raw = raw.replaceAll(/(chapters|decending)/g, "\"$1\"");
				}
				const data = JSON.parse(raw ?? "{}");
				let volName = vol.querySelector(".text-lg > div")?.textContent ?? "";
				volName = volName ? volName + "-" : "";
				if (!data.chapters) continue;
				const chs = data.chapters.map((ch) => new Chapter(ch.id, volName + ch.title, `https://mycomic.com/cn/chapters/${ch.id}`));
				result.push(...chs);
			}
			return result;
		}
		async *fetchPagesSource(ch) {
			while (true) {
				const doc = await window.fetch(ch.source).then((res) => res.text()).then((text) => new DOMParser().parseFromString(text, "text/html"));
				if (doc.title === "Just a moment...") yield Result.err(new Error("页面需要人机验证,请打开此地址进行验证,然后再次选择此章节: " + ch.source));
				else {
					yield Result.ok(doc);
					break;
				}
			}
		}
		async parseImgNodes(doc) {
			const imgs = Array.from(doc.querySelectorAll(".\\-mx-6 > img[x-ref]"));
			if (imgs.length === 0) throw new Error("无法找到图片信息, CSS选择器: .\\-mx-6 > img[x-ref]");
			const imgNodes = [];
			const digits = imgs.length.toString().length;
			for (let i = 0; i < imgs.length; i++) {
				const img = imgs[i];
				const src = img.getAttribute("src") || img.getAttribute("data-src");
				if (!src) {
					evLog("error", `cannot found image src, `, img);
					continue;
				}
				const ext = src.split(".").pop();
				const title = (i + 1).toString().padStart(digits, "0") + "." + ext;
				imgNodes.push(new ImageNode("", src, title, void 0, src, {
					w: img.width,
					h: img.height
				}));
			}
			return imgNodes;
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
		headers() {
			return {
				"Referer": "https://mycomic.com/",
				"Accept": "image/avif,image/webp,image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5",
				"Sec-Fetch-Dest": "image",
				"Sec-Fetch-Mode": "no-cors",
				"Sec-Fetch-Site": "cross-site"
			};
		}
	};
	ADAPTER.addSetup({
		name: "My Comic",
		workURLs: [/mycomic.com\/(\w+\/)?comics\/\d+(#.*)?$/],
		match: ["https://mycomic.com/*"],
		constructor: () => new MyComicMatcher()
	});
	var nhentai_exports = __exportAll({});
	function nhParseExt(str) {
		switch (str.slice(0, 1)) {
			case "j": return "jpg";
			case "g": return "gif";
			case "p": return "png";
			case "w": return "webp";
			case "a": return "avif";
			case "m": return "mp4";
			default: throw new Error("cannot parse image extension from info: " + str);
		}
	}
	var NHMatcher = class extends BaseMatcher {
		meta;
		imageCDNUrls = [
			"https://i1.nhentai.net",
			"https://i2.nhentai.net",
			"https://i3.nhentai.net",
			"https://i4.nhentai.net"
		];
		thumbCDNUrls = [
			"https://t1.nhentai.net",
			"https://t2.nhentai.net",
			"https://t3.nhentai.net",
			"https://t4.nhentai.net"
		];
		galleryMeta() {
			return this.meta;
		}
		createMeta(info) {
			const meta = new GalleryMeta(window.location.href, info.title?.english || document.title);
			meta.originTitle = info.title?.japanese;
			if (info.tags && info.tags.length > 0) meta.tags = info.tags.reduce((prev, curr) => {
				if (!prev[curr.type]) prev[curr.type] = [];
				prev[curr.type].push(curr.name);
				return prev;
			}, {});
			this.meta = meta;
		}
		async getImageServers() {
			const config = await window.fetch(`${window.origin}/api/v2/config`).then((res) => res.json()).catch(Error);
			if (config instanceof Error) throw config;
			this.imageCDNUrls = config.image_servers;
			this.thumbCDNUrls = config.thumb_servers;
		}
		async fetchOriginMeta(node, retry) {
			if (retry) {
				const regex = /https:\/\/(.*?)\//;
				const cdn = node.originSrc?.match(regex)?.[1];
				const index = this.imageCDNUrls?.indexOf(cdn ?? "") ?? -1;
				if (index > -1) return { url: node.originSrc.replace(regex, `https://${this.imageCDNUrls[(index + 1) % this.imageCDNUrls.length]}/`) };
			}
			return { url: node.originSrc };
		}
		async parseImgNodes() {
			await this.getImageServers();
			const galleryID = window.location.href.match(/g\/(\d+)/)?.[1];
			if (!galleryID) throw new Error("cannot match gallery id from url");
			const resp = await window.fetch(`${window.location.origin}/api/v2/galleries/${galleryID}`).then((res) => res.json()).catch(Error);
			if (resp instanceof Error) throw resp;
			const data = resp;
			this.createMeta(data);
			const digits = data.pages.length.toString().length;
			const ret = [];
			for (let i = 0; i < data.pages.length; i++) {
				const node = data.pages[i];
				const title = (i + 1).toString().padStart(digits, "0");
				const ext = node.path.split(".").pop() ?? ".guess.webp";
				const href = `${window.location.origin}/g/${galleryID}/${node.number}/`;
				const originSrc = `${this.imageCDNUrls[i % this.imageCDNUrls.length]}/${node.path}`;
				const thumbnail = `${this.thumbCDNUrls[i % this.thumbCDNUrls.length]}/${node.thumbnail}`;
				const wh = {
					w: node.thumbnail_width,
					h: node.thumbnail_height
				};
				ret.push(new ImageNode(thumbnail, href, title + "." + ext, void 0, originSrc, wh));
			}
			return ret;
		}
		async *fetchPagesSource() {
			yield Result.ok(document);
		}
	};
	var NHxxxMatcher = class extends BaseMatcher {
		meta;
		galleryMeta() {
			return this.meta;
		}
		parseMeta() {
			const title = document.querySelector(".info h1")?.textContent;
			const originTItle = document.querySelector(".info h2")?.textContent;
			const meta = new GalleryMeta(window.location.href, title ?? document.title);
			meta.originTitle = originTItle ?? void 0;
			Array.from(document.querySelectorAll(".info > ul > li.tags")).forEach((ele) => {
				let cat = ele.querySelector("span.text")?.textContent ?? "misc";
				cat = cat.trim().replace(":", "");
				const tags = Array.from(ele.querySelectorAll("a.tag_btn > .tag_name")).map((t) => t.textContent?.trim()).filter(Boolean);
				meta.tags[cat] = tags;
			});
			this.meta = meta;
		}
		async *fetchPagesSource() {
			this.parseMeta();
			yield Result.ok(document);
		}
		async parseImgNodes(page) {
			const doc = page;
			await sleep$1(200);
			const [files, thumbs] = this.parseInfo(doc);
			if (files.length !== thumbs.length) throw new Error("thumbs length not eq images length");
			const cover = doc.querySelector(".cover img")?.src;
			if (!cover) throw new Error("cannot find cover src");
			const base = cover.slice(0, cover.lastIndexOf("/") + 1);
			const ret = [];
			const digits = files.length.toString().length;
			let href = window.location.href;
			if (href.endsWith("/")) href = href.slice(0, -1);
			for (let i = 0; i < files.length; i++) {
				const title = (i + 1).toString().padStart(digits, "0");
				const thumb = thumbs[i];
				const thumbSrc = base + thumb[0] + "." + nhParseExt(thumb[1]);
				const file = files[i];
				const originSrc = base + file[0] + "." + nhParseExt(file[1]);
				const splits = file[1].split(",");
				let wh = void 0;
				if (splits.length === 3) wh = {
					w: parseInt(splits[1].trim()),
					h: parseInt(splits[2].trim())
				};
				ret.push(new ImageNode(thumbSrc, href + "/" + (i + 1), title + "." + nhParseExt(file[1]), void 0, originSrc, wh));
			}
			return ret;
		}
		parseInfo(doc) {
			const matches = Array.from(doc.querySelectorAll("script[type]")).find((ele) => ele.textContent?.trimStart().startsWith("var g_th"))?.textContent?.match(/\('(.*)'\);/);
			if (!matches || matches.length !== 2) throw new Error("cannot find images info from script");
			const info = JSON.parse(matches[1]);
			return [Object.entries(info.fl), Object.entries(info.th)];
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
	};
	ADAPTER.addSetup({
		name: "nhentai",
		workURLs: [/nhentai.net\/g\/\d+\/?$/],
		match: ["https://nhentai.net/*"],
		constructor: () => new NHMatcher()
	});
	ADAPTER.addSetup({
		name: "nhentai.xxx",
		workURLs: [/nhentai.xxx\/g\/\d+\/?$/],
		match: ["https://nhentai.xxx/*"],
		constructor: () => new NHxxxMatcher()
	});
	var niyaniya_exports = __exportAll({});
	var REGEXP_EXTRACT_GALLERY_ID = /niyaniya.moe\/\w+\/(\d+\/\w+)/;
	var NIYANIYA_API_HOST = "api.schale.network";
	var NAMESPACE_MAP = {
		0: "misc",
		1: "artist",
		2: "circle",
		7: "uploader",
		8: "male",
		9: "female",
		10: "mixed",
		11: "language"
	};
	var NiyaniyaMatcher = class extends BaseMatcher {
		meta;
		galleryMeta() {
			return this.meta || new GalleryMeta(window.location.href, "koharu-unknows");
		}
		async *fetchPagesSource(source) {
			yield Result.ok(source.source);
		}
		createMeta(detail) {
			const tags = detail.tags.reduce((map, tag) => {
				const category = NAMESPACE_MAP[tag.namespace || 0] || "misc";
				if (!map[category]) map[category] = [];
				map[category].push(tag.name);
				return map;
			}, {});
			this.meta = new GalleryMeta(window.location.href, detail.title);
			this.meta.tags = tags;
		}
		async parseImgNodes(source) {
			const matches = source.match(REGEXP_EXTRACT_GALLERY_ID);
			const crt = window.localStorage.getItem("clearance");
			if (!crt) throw new Error("cannot get clearance from localStorage");
			if (!matches || matches.length < 2) throw new Error("invaild url: " + source);
			const galleryID = matches[1];
			const detailAPI = `https://${NIYANIYA_API_HOST}/books/detail/${galleryID}`;
			const detailDataAPI = `https://${NIYANIYA_API_HOST}/books/detail/${galleryID}?crt=${crt}`;
			const [detail, detailData] = await Promise.all([window.fetch(detailAPI).then((res) => res.json()).then((j) => j).catch(Error), window.fetch(detailDataAPI, { method: "POST" }).then((res) => res.json()).then((j) => j).catch(Error)]);
			if (detail instanceof Error || detailData instanceof Error) throw new Error("failed to obtain data, perhaps the API of this site has changed");
			detail.data = detailData.data;
			this.createMeta(detail);
			const [w, data] = Object.entries(detail.data).sort((a, b) => b[1].size - a[1].size).find(([_, v]) => v.id !== void 0 && v.key !== void 0) ?? [void 0, void 0];
			if (w === void 0 && data === void 0) throw new Error("cannot find resolution from gallery detail");
			const dataAPI = `https://${NIYANIYA_API_HOST}/books/data/${galleryID}/${data.id}/${data.key}/${w}?crt=${crt}`;
			const items = await window.fetch(dataAPI).then((res) => res.json()).then((j) => j).catch(Error);
			if (items instanceof Error) throw new Error("failed to obtain data, perhaps the API of this site has changed");
			if (items.entries.length !== detail.thumbnails.entries.length) throw new Error("thumbnails length not match");
			const thumbs = detail.thumbnails.entries;
			const thumbBase = detail.thumbnails.base;
			const itemBase = items.base;
			const pad = items.entries.length.toString().length;
			return items.entries.map((item, i) => {
				const href = `${window.location.origin}/reader/${galleryID}/${i + 1}`;
				const title = (i + 1).toString().padStart(pad, "0") + "." + item.path.split(".").pop();
				const src = itemBase + item.path;
				return new ImageNode(thumbBase + thumbs[i].path, href, title, void 0, src, {
					w: item.dimensions[0],
					h: item.dimensions[1]
				});
			});
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
		headers() {
			return {
				"Referer": "https://niyaniya.moe/",
				"Origin": window.location.origin
			};
		}
	};
	ADAPTER.addSetup({
		name: "niyaniya.moe",
		workURLs: [/(niyaniya.moe|shupogaki.moe|hoshino.one)\/(g|reader)\/\d+\/\w+/],
		match: ["https://niyaniya.moe/*"],
		constructor: () => new NiyaniyaMatcher()
	});
	var pawchive_exports = __exportAll({});
	var PawchiveListAbstract = class {
		async *next() {
			const url = new URL(window.location.href);
			let page = parseInt(url.searchParams.get("o") ?? "0");
			page = isNaN(page) ? 0 : page;
			const query = url.searchParams.get("q");
			while (true) {
				const ret = await window.fetch(this.getURL(page, query), { headers: { "Accept": "text/css" } }).then((res) => res.json()).catch(Error);
				if (ret instanceof Error) {
					yield Result.err(ret);
					continue;
				}
				if (ret.error) {
					yield Result.err(new Error(ret.error));
					continue;
				}
				const results = this.getPosts(ret);
				if (!results || results.length === 0) break;
				page += results.length;
				const resultLen = results.length;
				while (results.length > 0) yield Result.ok(results.splice(0, 10));
				if (resultLen < 50) break;
			}
		}
	};
	var PawchiveListArtist = class extends PawchiveListAbstract {
		getURL(pages, query) {
			const u = new URL(`${window.location.origin}/api/v1${window.location.pathname}/posts`);
			if (pages > 0) u.searchParams.set("o", pages.toString());
			if (query) u.searchParams.set("q", query);
			return u.href;
		}
		getPosts(res) {
			return res;
		}
		getList(_response) {
			return [];
		}
	};
	var PawchiveListSinglePost = class extends PawchiveListAbstract {
		getPosts(res) {
			if (res?.post) return [res.post];
			if (res?.attachments) return [res];
			throw new Error("single post cannot find post attachments");
		}
		getURL() {
			return `${window.location.origin}/api/v1${window.location.pathname}`;
		}
		getList(response) {
			return [...response.previews ?? [], ...response.attachments ?? []];
		}
	};
	var PawchiveMatcher = class extends BaseMatcher {
		list;
		constructor() {
			super();
			if (/user\/\w+/.test(window.location.href)) {
				if (/post\/\w+/.test(window.location.href)) this.list = new PawchiveListSinglePost();
				else this.list = new PawchiveListArtist();
			}
		}
		fetchPagesSource() {
			if (!this.list) throw new Error("Current path is not supported");
			return this.list.next();
		}
		async parseImgNodes(results) {
			const nodes = [];
			const newImageNode = (id, user, service, path, name, server) => {
				const node = new ImageNode(`https://img.${window.location.hostname}/thumbnail/data/${path}`, `${window.location.origin}/${service}/user/${user}/post/${id}`, name, void 0, server ? `${server}/data/${path}?f=${name}` : `https://file.${window.location.hostname}/data/${path}?f=${name}`);
				if (path.indexOf(".mp4") > 1) {
					node.mimeType = "video/mp4";
					node.thumbnailSrc = "";
				}
				const ext = path.split(".").pop() ?? "";
				if (!isImage(ext)) {
					if (ADAPTER.conf.excludeVideo || !isVideo(ext)) return;
				}
				return node;
			};
			const chunks = [];
			for (const res of results) {
				const list = [];
				if (res.file?.path) list.push(res.file);
				list.push(...res.attachments ?? []);
				chunks.push({
					res,
					list,
					needFetchPost: !list[0]?.server && list.length > 0
				});
			}
			const originSrcMap = new Map();
			for (const chunk of chunks) for (const file of chunk.list) {
				if (!file.path) throw new Error("cannot find image file path");
				if (!file.name) throw new Error("cannot find image file name");
				const node = newImageNode(chunk.res.id, chunk.res.user, chunk.res.service, file.path, file.name);
				if (node) {
					if (originSrcMap.has(node.originSrc)) continue;
					originSrcMap.set(node.originSrc, true);
					nodes.push(node);
				}
			}
			return nodes;
		}
		async fetchOriginMeta(node) {
			if (!node.originSrc) throw new Error("cannot find pawchive image file: " + node.href);
			return { url: node.originSrc };
		}
	};
	ADAPTER.addSetup({
		name: "pawchive",
		workURLs: [/pawchive.pw\/\w+\/user\/\w+(\/post\/\w+)?(\?\w=.*)?$/],
		match: ["https://pawchive.pw/*"],
		constructor: () => new PawchiveMatcher()
	});
	var pinterest_exports = __exportAll({});
	var RESOURCE_NAME = "BaseSearchResource";
	var PIN_ID_REGEXP = /\/pin\/([^/]+)/;
	var PIN_IMG_SELECTOR = "a[href*='/pin/'] img[src*='pinimg.com']";
	var DOM_PIN_BATCH_SIZE = 16;
	var PinterestMatcher = class extends BaseMatcher {
		resourceOptions;
		nextBookmark;
		seenPinIDs = new Set();
		pinCount = 0;
		async *fetchPagesSource() {
			try {
				if (isHomePage()) {
					for await (const page of this.fetchDomPinPages()) yield Result.ok(page);
					return;
				}
				if (isPinPage()) {
					const initial = tryParseInitialProps();
					if (initial) {
						const pins = extractPinPagePins(initial);
						pins.forEach((pin) => this.seenPinIDs.add(pin.id));
						yield Result.ok({ pins });
					}
					for await (const page of this.fetchDomPinPages()) yield Result.ok(page);
					return;
				}
				const initial = tryParseInitialProps();
				const resource = initial ? tryExtractSearchResource(initial) : void 0;
				if (!resource) {
					for await (const page of this.fetchDomPinPages()) yield Result.ok(page);
					return;
				}
				this.resourceOptions = resource.options;
				this.nextBookmark = resource.nextBookmark;
				resource.pins.forEach((pin) => this.seenPinIDs.add(pin.id));
				yield Result.ok({
					pins: resource.pins,
					nextBookmark: resource.nextBookmark
				});
				while (this.nextBookmark && this.nextBookmark !== "-end-") try {
					const next = await this.fetchSearchPage(this.nextBookmark);
					this.nextBookmark = next.nextBookmark;
					next.pins?.forEach((pin) => this.seenPinIDs.add(pin.id));
					yield Result.ok(next);
				} catch {
					this.nextBookmark = void 0;
					for await (const page of this.fetchDomPinPages()) yield Result.ok(page);
				}
			} catch (error) {
				yield Result.err(error);
			}
		}
		async parseImgNodes(page) {
			const list = [];
			for (const pin of page.pins ?? []) {
				if (pin.type !== "pin" || !pin.images) continue;
				const thumb = pickImage(pin.images, [
					"236x",
					"474x",
					"736x",
					"1200x",
					"orig"
				]);
				const origin = pickImage(pin.images, [
					"orig",
					"1200x",
					"736x",
					"564x",
					"474x",
					"236x"
				]);
				if (!thumb?.url || !origin?.url) continue;
				const title = buildTitle(pin, origin.url);
				list.push(new ImageNode(thumb.url, `${window.location.origin}/pin/${pin.id}/`, title, void 0, origin.url, {
					w: origin.width || thumb.width,
					h: origin.height || thumb.height
				}));
				this.pinCount++;
			}
			for (const pin of page.domPins ?? []) {
				list.push(new ImageNode(pin.thumbnailSrc, pin.href, buildTitleFromText(pin.title, pin.id, pin.thumbnailSrc), void 0, pin.originSrc, pin.rect));
				this.pinCount++;
			}
			return list;
		}
		async fetchOriginMeta(node) {
			if (node.originSrc) return { url: node.originSrc };
			const initial = parseInitialProps(await window.fetch(node.href, { credentials: "include" }).then((res) => {
				if (!res.ok) throw new Error(`Pinterest pin request failed: ${res.status} ${res.statusText}`);
				return res.text();
			}).then((text) => new DOMParser().parseFromString(text, "text/html")));
			const pinID = node.href.match(PIN_ID_REGEXP)?.[1];
			const pin = extractPinPagePins(initial, pinID)[0];
			if (!pin?.images) throw new Error("cannot find Pinterest pin origin image");
			const origin = pickImage(pin.images, [
				"orig",
				"1200x",
				"736x",
				"564x",
				"474x",
				"236x"
			]);
			if (!origin?.url) throw new Error("cannot find Pinterest pin origin image url");
			return { url: origin.url };
		}
		galleryMeta() {
			const pageTitle = document.title && document.title !== "Pinterest" ? document.title : "pinterest";
			return new GalleryMeta(window.location.href, `${pageTitle}-${this.pinCount}`);
		}
		async fetchSearchPage(bookmark) {
			if (!this.resourceOptions) throw new Error("Pinterest search resource options are missing");
			const params = new URLSearchParams();
			params.set("source_url", window.location.pathname + window.location.search);
			params.set("data", JSON.stringify({
				options: {
					...this.resourceOptions,
					bookmarks: [bookmark]
				},
				context: {}
			}));
			params.set("_", Date.now().toString());
			const json = await window.fetch(`/resource/${RESOURCE_NAME}/get/?${params.toString()}`, {
				credentials: "include",
				headers: {
					"Accept": "application/json, text/javascript, */*, q=0.01",
					"X-Requested-With": "XMLHttpRequest"
				}
			}).then((res) => {
				if (!res.ok) throw new Error(`Pinterest resource request failed: ${res.status} ${res.statusText}`);
				return res.json();
			});
			const data = json?.resource_response?.data;
			return {
				pins: Array.isArray(data?.results) ? data.results.filter(isPin) : [],
				nextBookmark: json?.resource?.options?.bookmarks?.[0] ?? json?.resource_response?.bookmark ?? json?.resource_response?.nextBookmark
			};
		}
		async *fetchDomPinPages() {
			let idleTimes = 0;
			while (idleTimes < 4) {
				const domPins = this.collectRelatedPins();
				if (domPins.length > 0) {
					idleTimes = 0;
					for (let i = 0; i < domPins.length; i += DOM_PIN_BATCH_SIZE) yield { domPins: domPins.slice(i, i + DOM_PIN_BATCH_SIZE) };
					continue;
				} else idleTimes++;
				window.scrollBy(0, Math.max(window.innerHeight, 900));
				await sleep(1200);
			}
		}
		collectRelatedPins() {
			const currentID = window.location.pathname.match(PIN_ID_REGEXP)?.[1];
			const pins = [];
			const imgs = Array.from(document.querySelectorAll(PIN_IMG_SELECTOR));
			for (const img of imgs) {
				const href = img.closest("a[href*='/pin/']")?.href;
				const id = href?.match(PIN_ID_REGEXP)?.[1];
				const srcs = pickDomImageSrcs(img);
				if (!href || !id || !srcs.thumbnail || id === currentID || this.seenPinIDs.has(id)) continue;
				this.seenPinIDs.add(id);
				pins.push({
					id,
					href,
					title: img.alt || `pinterest-${id}`,
					thumbnailSrc: srcs.thumbnail,
					originSrc: srcs.origin,
					rect: {
						w: img.naturalWidth || img.width || 236,
						h: img.naturalHeight || img.height || 236
					}
				});
			}
			return pins;
		}
	};
	function isPinPage() {
		return PIN_ID_REGEXP.test(window.location.pathname);
	}
	function isHomePage() {
		return /^\/?$/.test(window.location.pathname);
	}
	function sleep(ms) {
		return new Promise((resolve) => window.setTimeout(resolve, ms));
	}
	function parseInitialProps(doc = document) {
		const raw = doc.querySelector("#__PWS_INITIAL_PROPS__")?.textContent;
		if (!raw) throw new Error("cannot find Pinterest initial props");
		return JSON.parse(raw);
	}
	function tryParseInitialProps(doc = document) {
		try {
			return parseInitialProps(doc);
		} catch {
			return;
		}
	}
	function extractSearchResource(initial) {
		const resources = initial.initialReduxState?.resources?.[RESOURCE_NAME];
		const entry = resources ? Object.entries(resources)[0] : void 0;
		if (!entry) throw new Error("cannot find Pinterest search resource");
		const [optionsRaw, resource] = entry;
		return {
			options: Object.fromEntries(JSON.parse(optionsRaw)),
			pins: Array.isArray(resource.data?.results) ? resource.data.results.filter(isPin) : [],
			nextBookmark: resource.nextBookmark
		};
	}
	function tryExtractSearchResource(initial) {
		try {
			return extractSearchResource(initial);
		} catch {
			return;
		}
	}
	function extractPinPagePins(initial, expectedID) {
		const pathID = expectedID ?? window.location.pathname.match(PIN_ID_REGEXP)?.[1];
		const pins = Object.values(initial.initialReduxState?.pins ?? {}).filter(isPin);
		if (!pathID) return pins;
		const current = pins.find((pin) => pin.id === pathID);
		return current ? [current] : pins;
	}
	function isPin(value) {
		const pin = value;
		return !!pin && pin.type === "pin" && !!pin.id && !!pin.images;
	}
	function pickImage(images, keys) {
		for (const key of keys) {
			const image = images[key];
			if (Array.isArray(image)) {
				const found = image.find((img) => img?.url);
				if (found) return found;
			} else if (image?.url) return image;
		}
		return Object.values(images).flat().find((img) => img?.url);
	}
	function pickDomImageSrcs(img) {
		const srcset = (img.getAttribute("srcset") ?? "").split(",").map((src) => src.trim().split(/\s+/)[0]).filter(Boolean);
		const current = img.currentSrc || img.src;
		const sources = [...srcset, current].filter(Boolean);
		const origin = sources.find((src) => src.includes("/originals/")) ?? sources.find((src) => src.includes("/736x/")) ?? current;
		return {
			thumbnail: current || sources.find((src) => src.includes("/474x/")) || sources.find((src) => src.includes("/236x/")) || origin,
			origin
		};
	}
	function buildTitle(pin, src) {
		return buildTitleFromText(pin.title || pin.grid_title || pin.description || `pinterest-${pin.id}`, pin.id, src);
	}
	function buildTitleFromText(rawTitle, id, src) {
		const ext = src.match(/\.(\w+)(?:\?|$)/)?.[1] ?? "jpg";
		return `${rawTitle.trim().replaceAll(/\s+/g, " ").replaceAll(/[\\/:*?"<>|]/g, "_") || `pinterest-${id}`}-${id}.${ext}`;
	}
	ADAPTER.addSetup({
		name: "Pinterest",
		workURLs: [
			/pinterest\.[^/]+\/?([?#].*)?$/,
			/pinterest\.[^/]+\/search\/pins\/.*[?&]q=/,
			/pinterest\.[^/]+\/pin\/\d+/
		],
		match: ["https://*.pinterest.com/*"],
		constructor: () => new PinterestMatcher()
	});
	var HTMLUgoiraElement = class extends HTMLElement {
		_shadow;
		canvas;
		resizeObserver = null;
		player;
		_frames;
		connected = false;
		constructor() {
			super();
			this._shadow = this.attachShadow({ mode: "open" });
			this.canvas = document.createElement("canvas");
			this.player = new UgoiraPlayer();
			this.initShadowDOM();
		}
		set frames(fs) {
			this._frames = fs;
			if (this._frames) this.player.mount(this.canvas, this._frames);
			else this.player.unmount();
			if (this.connected) this.play();
		}
		get frames() {
			return this._frames;
		}
		connectedCallback() {
			this.connected = true;
			this.setupResizeObserver();
			if (this._frames) this.play();
		}
		disconnectedCallback() {
			this.pause();
			this.connected = false;
			if (this.resizeObserver) this.resizeObserver.disconnect();
		}
		setupResizeObserver() {
			this.resizeObserver = new ResizeObserver(() => this.updateCanvasSize());
			const parent = this.parentElement;
			if (parent) this.resizeObserver.observe(parent);
		}
		updateCanvasSize() {
			if (!this.parentElement) return;
			this.player.frame0WHPromise.then((wh) => {
				this.canvas.width = wh.width;
				this.canvas.height = wh.height;
			});
		}
		play() {
			this.player.play();
		}
		pause() {
			this.player.pause();
		}
		initShadowDOM() {
			const style = document.createElement("style");
			style.textContent = `
            canvas {
                display: block;
                width: 100%;
                height: 100%;
            }
        `;
			this._shadow.appendChild(style);
			this._shadow.appendChild(this.canvas);
		}
	};
	var UgoiraPlayer = class {
		ctx;
		data = [];
		paused = true;
		index = 0;
		wh;
		animationFrameID;
		frame0WHPromise;
		frame0WHResolvce;
		constructor() {
			let tResolve;
			this.frame0WHPromise = new Promise((resolve, _reject) => tResolve = resolve);
			this.frame0WHResolvce = tResolve;
		}
		mount(canvas, frames) {
			const data = [];
			for (let i = 0; i < frames.length; i++) {
				const frame = frames[i];
				const b = new Blob([frame.data], { type: frame.mimeType });
				const src = URL.createObjectURL(b);
				const img = new Image();
				img.addEventListener("load", () => {
					URL.revokeObjectURL(src);
				});
				if (i == 0) img.addEventListener("load", () => {
					this.wh = {
						width: img.naturalWidth,
						height: img.naturalHeight
					};
					this.frame0WHResolvce(this.wh);
				});
				img.src = src;
				data.push({
					img,
					delay: frame.delay
				});
			}
			this.ctx = canvas.getContext("2d");
			this.data = data;
		}
		unmount() {
			this.ctx = void 0;
			this.data = [];
			this.paused = true;
			this.index = 0;
		}
		play() {
			if (!this.paused) return;
			this.paused = false;
			this.frame0WHPromise.then(() => {
				if (this.animationFrameID) {
					window.cancelAnimationFrame(this.animationFrameID);
					this.animationFrameID = void 0;
				}
				const animate = this.createAnimate();
				this.animationFrameID = window.requestAnimationFrame(animate);
			});
		}
		pause() {
			this.paused = true;
			if (this.animationFrameID) {
				window.cancelAnimationFrame(this.animationFrameID);
				this.animationFrameID = void 0;
			}
		}
		createAnimate() {
			let start;
			const animate = (timestamp) => {
				if (start === void 0) start = timestamp;
				const frame = this.data[this.index];
				if (timestamp - start >= frame.delay) {
					this.index++;
					start = timestamp;
					if (this.index >= this.data.length) this.index = 0;
					this.ctx.clearRect(0, 0, this.wh?.width ?? 100, this.wh?.height ?? 100);
					this.ctx.drawImage(frame.img, 0, 0);
				}
				if (!this.paused) this.animationFrameID = window.requestAnimationFrame(animate);
			};
			return animate;
		}
	};
	var pixiv_exports = __exportAll({});
	var PixivHomeAPI = class {
		homeData;
		thumbnails = {};
		pids = {};
		async *fetchChapters() {
			const { error, body } = await window.fetch("https://www.pixiv.net/ajax/top/illust?mode=all&lang=en").then((res) => res.json());
			if (error) throw new Error("fetch your home data error, check you have already logged in");
			this.homeData = body;
			this.thumbnails = body.thumbnails.illust.reduce((prev, curr) => {
				prev[curr.id] = curr;
				return prev;
			}, {});
			const chapters = [];
			const byTag = body.page.recommendByTag.reduce((prev, curr) => {
				prev[curr.tag] = curr.ids;
				return prev;
			}, {});
			this.pids = {
				"follow": body.page.follow.map((id) => id.toString()),
				"for you": body.page.recommend.ids,
				...byTag
			};
			let id = 0;
			for (const [t, pids] of Object.entries(this.pids)) {
				chapters.push(new Chapter(id, t === "follow" ? "Your Following" : "Recommend " + t, t, this.thumbnails[pids[0] ?? ""]?.url));
				id++;
			}
			return chapters;
		}
		async *next(chapter) {
			const pidList = this.pids[chapter.source];
			if (pidList.length === 0) {
				yield Result.ok([]);
				return;
			}
			while (pidList.length > 0) {
				const grouped = pidList.splice(0, 20).reduce((prev, curr) => {
					const userId = this.thumbnails[curr]?.userId ?? "unk";
					if (!prev[userId]) prev[userId] = [];
					prev[userId].push(curr);
					return prev;
				}, {});
				const ret = Object.entries(grouped).map(([userID, pids]) => ({
					id: userID === "unk" ? void 0 : userID,
					pids
				}));
				yield Result.ok(ret);
			}
		}
		title() {
			return "home";
		}
	};
	var PixivArtistWorksAPI = class {
		artist;
		chapterPids = new Map();
		title() {
			return this.artist ?? "artist-unknown";
		}
		constructor() {
			if (ADAPTER.conf.pixivRecordReading) EBUS.subscribe("ifq-do", (_index, imf) => window.localStorage.setItem(`cl-${this.artist}-last-read`, imf.node.href));
		}
		async *fetchChapters() {
			this.artist = await this.findArtistID();
			if (!this.artist) throw new Error("Cannot find artist id!");
			const currArtWork = window.location.href.match(/artworks\/(\d+)$/)?.[1];
			if (currArtWork) {
				const chapter = new Chapter(1, i18n.currentArtWorks.get(), "");
				this.chapterPids.set(chapter.id, [currArtWork]);
				yield [chapter];
			}
			const res = await window.fetch(`https://www.pixiv.net/ajax/user/${this.artist}/profile/all`).then((resp) => resp.json()).catch(Error);
			if (res instanceof Error) throw res;
			if (res.error) throw new Error(`Fetch illust list error: ${res.message}`);
			let pidList = [...Object.keys(res.body.illusts), ...Object.keys(res.body.manga)];
			pidList = pidList.sort((a, b) => parseInt(b) - parseInt(a));
			const latest = window.localStorage.getItem(`cl-${this.artist}-latest`);
			window.localStorage.setItem(`cl-${this.artist}-latest`, pidList[0]);
			const chapters = [];
			const latestIndex = latest ? pidList.indexOf(latest) : -1;
			if (latestIndex > 0) {
				const chapter = new Chapter(chapters.length + 2, i18n.latestArtWorks, "");
				const sliced = [...pidList.slice(0, latestIndex)];
				this.chapterPids.set(chapter.id, sliced);
				chapters.push(chapter);
			}
			if (ADAPTER.conf.pixivRecordReading) {
				const lastRead = window.localStorage.getItem(`cl-${this.artist}-last-read`)?.match(/artworks\/(\d+)$/)?.[1];
				const lastReadIndex = lastRead ? pidList.indexOf(lastRead) : -1;
				if (lastReadIndex > 0 && lastReadIndex < pidList.length - 1) {
					const chapterAfterRead = new Chapter(chapters.length + 2, ADAPTER.conf.pixivAscendWorks ? i18n.beforeLastReading.get() : i18n.afterLastReading.get(), "");
					const slicedAfter = [...pidList.slice(lastReadIndex)];
					this.chapterPids.set(chapterAfterRead.id, slicedAfter);
					chapters.push(chapterAfterRead);
					const chapterBeforeRead = new Chapter(chapters.length + 2, ADAPTER.conf.pixivAscendWorks ? i18n.afterLastReading.get() : i18n.beforeLastReading.get(), "");
					const slicedBefore = [...pidList.slice(0, lastReadIndex + 1)];
					this.chapterPids.set(chapterBeforeRead.id, slicedBefore);
					chapters.push(chapterBeforeRead);
				}
			}
			const chapter = new Chapter(chapters.length + 2, i18n.allArtWorks.get(), "");
			this.chapterPids.set(chapter.id, pidList);
			chapters.push(chapter);
			return chapters;
		}
		async *next(chapter) {
			let pidList = this.chapterPids.get(chapter.id);
			if (!pidList) throw new Error("cannot get pid list of " + chapter.title);
			if (ADAPTER.conf.pixivAscendWorks) pidList = pidList.reverse();
			while (pidList.length > 0) {
				const pids = pidList.splice(0, 20);
				yield Result.ok([{
					id: this.artist,
					pids
				}]);
			}
		}
		async findArtistID() {
			let href = window.location.href;
			const artistID = /users\/(\d+)/.exec(href)?.[1];
			if (artistID) return artistID;
			const pid = /artworks\/(\d+)/.exec(href)?.[1];
			if (!pid) return;
			href = document.querySelector("a[data-gtm-value][href*='/users/']")?.href || document.querySelector("a.user-details-icon[href*='/users/']")?.href;
			if (href) {
				const artistID = /users\/(\d+)/.exec(href)?.[1];
				if (artistID) return artistID;
			}
			return await window.fetch(`${window.location.origin}/ajax/illust/${pid}?lang=en`).then((res) => res.json()).then((data) => data.body?.userId);
		}
	};
	var PID_EXTRACT = /\/(\d+)[-_\w]*\.\w+$/;
	var PixivMatcher = class extends BaseMatcher {
		api;
		meta;
		pageCount = 0;
		works = {};
		ugoiraMetas = {};
		csrfToken;
		pidDatas = new Map();
		constructor() {
			super();
			this.meta = new GalleryMeta(window.location.href, "UNTITLE");
			if (/pixiv.net(\/(en\/?|\/illustration)|\/)?$/.test(window.location.href)) this.api = new PixivHomeAPI();
			else this.api = new PixivArtistWorksAPI();
		}
		async processData(data, contentType, node) {
			const meta = this.ugoiraMetas[node.originSrc];
			if (!meta) return [data, contentType];
			const promises = await new _zip_js_zip_js.ZipReader(new _zip_js_zip_js.Uint8ArrayReader(data)).getEntries().then((entries) => {
				const ret = [];
				for (const entry of entries) {
					if (entry.directory) continue;
					ret.push(entry.getData(new _zip_js_zip_js.Uint8ArrayWriter()).then((data) => ({
						name: entry.filename,
						data
					})));
				}
				return ret;
			});
			const files = await Promise.all(promises).then(((entries) => entries.filter((f) => f && f.data.length > 0).map((f) => f)));
			if (files.length !== meta.body.frames.length) throw new Error("unpack ugoira file error: file count not equal to meta");
			const mimeType = meta.body.mime_type;
			const list = files.map((f) => ({
				name: f.name,
				data: f.data,
				contentType: mimeType
			}));
			const metaStr = meta.body.frames.map((m) => `file '${m.file}'\nduration ${m.delay / 1e3}`).join("\n");
			const metaStrRaw = new TextEncoder().encode(metaStr);
			list.unshift({
				name: "frames.txt",
				contentType: "text/plain",
				data: metaStrRaw
			});
			return [new SubData(node.title, list, meta.body.frames), "ugoira/ugoira"];
		}
		galleryMeta() {
			this.meta.title = `pixiv_${this.api.title()}_w${Object.keys(this.works).length}_p${this.pageCount}` || "UNTITLE";
			this.meta.tags = Object.entries(this.works).reduce((tags, work) => {
				tags[work[0]] = work[1].tags;
				return tags;
			}, {});
			return this.meta;
		}
		async fetchTagsByPids(artistID, pids) {
			try {
				const data = await window.fetch(`https://www.pixiv.net/ajax/user/${artistID}/profile/illusts?ids[]=${pids.join("&ids[]=")}&work_category=illustManga&is_first_page=0&lang=en`).then((resp) => resp.json());
				if (!data.error) {
					const works = {};
					Object.entries(data.body.works).forEach(([k, w]) => {
						works[k] = {
							id: w.id,
							title: w.title,
							alt: w.alt,
							illustType: w.illustType,
							description: w.description,
							tags: w.tags,
							pageCount: w.pageCount
						};
					});
					this.works = {
						...this.works,
						...works
					};
				} else evLog("error", "WARN: fetch tags by pids error: ", data.message);
			} catch (error) {
				evLog("error", "ERROR: fetch tags by pids error: ", error);
			}
		}
		fetchChapters() {
			this.csrfToken = document.querySelector("#__NEXT_DATA__")?.textContent?.match(/\\"api\\":\{\\"token\\":\\"(\w+)\\"/)?.[1];
			return this.api.fetchChapters();
		}
		fetchPagesSource(chapter) {
			return this.api.next(chapter);
		}
		async fetchPidAndData(pids) {
			const needFetched = pids.filter((p) => !this.pidDatas.has(p));
			const dataList = await batchFetch(needFetched.map((p) => `https://www.pixiv.net/ajax/illust/${p}/pages?lang=en`), 5, "json");
			for (let i = 0; i < needFetched.length; i++) this.pidDatas.set(needFetched[i], dataList[i]);
			return pids.map((p) => [p, this.pidDatas.get(p)]);
		}
		async parseImgNodes(aps) {
			const list = [];
			if (aps.length === 0) return list;
			const pids = [];
			for (const ap of aps) {
				if (ap.id) this.fetchTagsByPids(ap.id, ap.pids);
				pids.push(...ap.pids);
			}
			if (pids.length === 0) return list;
			if (ADAPTER.conf.pixivAscendWorks) pids.sort((a, b) => parseInt(a) - parseInt(b));
			else pids.sort((a, b) => parseInt(b) - parseInt(a));
			const pidDatas = await this.fetchPidAndData(pids);
			for (let i = 0; i < pidDatas.length; i++) {
				const [pid, data] = pidDatas[i];
				if (!data || data instanceof Error || data.error) {
					const reason = `pid:[${pid}], ${data?.message}`;
					evLog("error", reason);
					EBUS.emit("notify-message", "error", reason, 8e3);
					continue;
				}
				const actionLike = new NodeAction("☺", "like this illust", async () => {
					if (this.csrfToken) await fetch("https://www.pixiv.net/ajax/illusts/like", {
						"headers": {
							"content-type": "application/json; charset=utf-8",
							"x-csrf-token": this.csrfToken
						},
						"body": "{\"illust_id\":\"" + pid + "\"}",
						"method": "POST",
						"mode": "cors"
					});
					else EBUS.emit("notify-message", "error", "cannot find csrf_token from this page");
				});
				const actionBookmark = new NodeAction("♥", "bookmark this illust", async () => {
					if (this.csrfToken) await fetch("https://www.pixiv.net/ajax/illusts/bookmarks/add", {
						"credentials": "include",
						"headers": {
							"content-type": "application/json; charset=utf-8",
							"x-csrf-token": this.csrfToken
						},
						"body": "{\"illust_id\":\"" + pid + "\",\"restrict\":0,\"comment\":\"\",\"tags\":[]}",
						"method": "POST",
						"mode": "cors"
					});
					else EBUS.emit("notify-message", "error", "cannot find csrf_token from this page");
				});
				this.pageCount += data.body.length;
				const digits = data.body.length.toString().length;
				let j = -1;
				for (const p of data.body) {
					let title = p.urls.original.split("/").pop() || `${pid}_p${j.toString().padStart(digits)}.jpg`;
					const matches = p.urls.original.match(PID_EXTRACT);
					if (matches && matches.length > 2 && matches[2] && matches[2] === "ugoira") title = title.replace(/\.\w+$/, ".gif");
					j++;
					const node = new ImageNode(replaceHost(p.urls.small, ADAPTER.conf.pixivMirrorHost), `${window.location.origin}/artworks/${pid}`, title, void 0, replaceHost(p.urls.original, ADAPTER.conf.pixivMirrorHost), {
						w: p.width,
						h: p.height
					});
					node.actions.push(actionLike);
					node.actions.push(actionBookmark);
					list.push(node);
				}
			}
			return list;
		}
		async fetchOriginMeta(node) {
			const matches = node.originSrc.match(PID_EXTRACT);
			if (!matches || matches.length < 2) throw new Error("cannot match pid from img src: " + node.originSrc);
			const pid = matches[1];
			const p = matches[2];
			if (this.works[pid]?.illustType === 2 || p === "ugoira") {
				const meta = await window.fetch(`https://www.pixiv.net/ajax/illust/${pid}/ugoira_meta?lang=en`).then((resp) => resp.json());
				const original = replaceHost(meta.body.src, ADAPTER.conf.pixivMirrorHost);
				this.ugoiraMetas[original] = meta;
				return { url: original };
			} else return { url: node.originSrc };
		}
	};
	ADAPTER.addSetup({
		name: "Pixiv",
		workURLs: [/pixiv.net\/(\w*\/|illustration)?(artworks\/.*|users\/.*|$)/],
		match: ["https://www.pixiv.net/*"],
		constructor: () => {
			if (!customElements.get("ugoira-element")) customElements.define("ugoira-element", HTMLUgoiraElement);
			return new PixivMatcher();
		}
	});
	var redgifs_exports = __exportAll({ RedGifsMatcher: () => RedGifsMatcher });
	var RedGifsMatcher = class extends BaseMatcher {
		pageURL = window.location.href;
		pending = new Set();
		media = new Map();
		token;
		tokenUntil = 0;
		tokenPromise;
		disposed = false;
		author;
		order;
		constructor() {
			super();
			const url = new URL(this.pageURL);
			const match = url.pathname.match(/^\/users\/([a-z0-9_.-]+)\/?$/i);
			if (!match) throw new Error("RedGIFs: open an author profile first.");
			this.author = match[1].toLowerCase();
			const order = url.searchParams.get("order");
			this.order = [
				"new",
				"recent",
				"best"
			].includes(order || "") ? order : "new";
		}
		checkActive() {
			if (this.disposed || window.location.href !== this.pageURL) throw new Error("RedGIFs: request cancelled after leaving the profile.");
		}
		dispose() {
			this.disposed = true;
			for (const cancel of Array.from(this.pending)) cancel();
			this.media.clear();
			this.token = void 0;
		}
		request(url, responseType, headers = {}, imf) {
			return new Promise((resolve, reject) => {
				let handle;
				let idleTimer;
				let settled = false;
				const idleMs = Math.max(1, Number(ADAPTER.conf.timeout) || 30) * 1e3;
				const finish = (error, response) => {
					if (settled) return;
					settled = true;
					clearTimeout(idleTimer);
					this.pending.delete(cancel);
					if (imf?.abortSignal === cancel) imf.abortSignal = void 0;
					if (error) reject(error);
					else resolve(response);
				};
				const cancel = () => {
					finish(new Error("RedGIFs: request cancelled."));
					handle?.abort?.();
				};
				const resetIdleTimer = () => {
					if (!imf || settled) return;
					clearTimeout(idleTimer);
					idleTimer = setTimeout(() => {
						finish(new Error("RedGIFs: video download timed out without progress."));
						handle?.abort?.();
					}, idleMs);
				};
				try {
					this.checkActive();
					this.pending.add(cancel);
					if (imf) imf.abortSignal = cancel;
					resetIdleTimer();
					handle = GM_XHR({
						method: "GET",
						url,
						responseType,
						timeout: imf ? 6e5 : Math.max(1e4, idleMs),
						headers: {
							"Referer": "https://www.redgifs.com/",
							...headers
						},
						onload: (response) => {
							try {
								this.checkActive();
								if (response.status < 200 || response.status >= 300) {
									const hint = response.status === 429 ? " Too many requests; wait before retrying." : response.status === 403 ? " Access denied; check that the original page is accessible." : "";
									throw Object.assign(new Error(`RedGIFs: HTTP ${response.status}.${hint}`), { status: response.status });
								}
								if (imf) imf.setDownloadState({ readyState: 4 });
								finish(null, response.response);
							} catch (error) {
								finish(error);
							}
						},
						onerror: () => finish(new Error("RedGIFs: network request failed. Check userscript network permissions.")),
						ontimeout: () => finish(new Error("RedGIFs: request timed out; retry when the connection recovers.")),
						onabort: () => finish(new Error("RedGIFs: request cancelled.")),
						onprogress: (event) => {
							if (!settled && imf) {
								resetIdleTimer();
								imf.setDownloadState({
									total: event.total,
									loaded: event.loaded,
									readyState: event.readyState
								});
							}
						}
					});
					handle?.catch?.(() => finish(new Error("RedGIFs: network request failed.")));
				} catch (error) {
					finish(error);
				}
			});
		}
		async json(path, token) {
			const headers = {
				"Accept": "application/json",
				"Origin": "https://www.redgifs.com"
			};
			if (token) headers.Authorization = "Bearer " + token;
			const response = await this.request("https://api.redgifs.com/v2/" + path, "json", headers);
			let data;
			try {
				data = typeof response === "string" ? JSON.parse(response) : response;
			} catch {
				throw new Error("RedGIFs: invalid JSON response; open the original page and retry.");
			}
			if (!data || typeof data !== "object" || data.error) throw new Error("RedGIFs: unexpected API response.");
			return data;
		}
		async authorization() {
			this.checkActive();
			if (this.token && Date.now() < this.tokenUntil) return this.token;
			if (!this.tokenPromise) this.tokenPromise = this.json("auth/temporary").then((data) => {
				if (typeof data.token !== "string" || !data.token) throw new Error("RedGIFs: temporary authorization unavailable.");
				this.token = data.token;
				this.tokenUntil = Date.now() + 3e5;
				return data.token;
			}).finally(() => {
				this.tokenPromise = void 0;
			});
			return this.tokenPromise;
		}
		async api(path) {
			for (let attempt = 0; attempt < 2; attempt++) {
				const token = await this.authorization();
				try {
					return await this.json(path, token);
				} catch (error) {
					if (!(error instanceof Error) || !("status" in error) || error.status !== 401 || attempt !== 0) throw error;
					if (this.token === token) {
						this.token = void 0;
						this.tokenUntil = 0;
					}
				}
			}
			throw new Error("RedGIFs: authorization failed.");
		}
		mediaURL(value) {
			if (typeof value !== "string") return "";
			try {
				const url = new URL(value);
				if (url.protocol === "https:" && !url.username && !url.password && (url.hostname === "redgifs.com" || url.hostname.endsWith(".redgifs.com"))) return url.href;
			} catch {}
			return "";
		}
		isVideo(gif) {
			return !!gif && /^[a-z0-9]+$/i.test(gif.id || "") && Number(gif.type) === 1;
		}
		async *fetchChapters() {
			yield [new Chapter(0, this.author, this.pageURL)];
		}
		async *fetchPagesSource() {
			const seen = new Set();
			let page = 1;
			while (!this.disposed) try {
				const query = new URLSearchParams({
					page: String(page),
					count: "40",
					order: this.order,
					type: "g"
				});
				const data = await this.api(`users/${encodeURIComponent(this.author)}/search?${query}`);
				if (!Array.isArray(data.gifs) || !Number.isInteger(Number(data.pages)) || Number(data.pages) < 0) throw new Error("RedGIFs: author list format changed.");
				if (data.page != null && Number(data.page) !== page) throw new Error("RedGIFs: unexpected page number; retry the author list.");
				const fresh = [];
				for (const gif of data.gifs) {
					if (!this.isVideo(gif)) continue;
					const id = gif.id.toLowerCase();
					if (seen.has(id)) continue;
					seen.add(id);
					fresh.push(gif);
				}
				if (fresh.length) yield Result.ok(fresh);
				if (page >= Number(data.pages) || data.gifs.length === 0) return;
				page++;
			} catch (error) {
				yield Result.err(error instanceof Error ? error : new Error(String(error)));
				if (this.disposed || window.location.href !== this.pageURL) return;
			}
		}
		async parseImgNodes(gifs) {
			this.checkActive();
			return gifs.filter((gif) => this.isVideo(gif)).map((gif) => {
				const id = gif.id.toLowerCase();
				this.media.set(id, {
					gif,
					fetchedAt: Date.now()
				});
				const size = Number(gif.width) > 0 && Number(gif.height) > 0 ? {
					w: Number(gif.width),
					h: Number(gif.height)
				} : void 0;
				const poster = this.mediaURL(gif.urls?.poster) || this.mediaURL(gif.urls?.thumbnail);
				const video = this.mediaURL(gif.urls?.hd) || this.mediaURL(gif.urls?.sd);
				const node = new ImageNode(poster, `https://www.redgifs.com/watch/${id}`, `${this.author}_${id}.mp4`, void 0, video || void 0, size);
				node.mimeType = "video/mp4";
				return node;
			});
		}
		async fetchOriginMeta(node, retry) {
			this.checkActive();
			const id = new URL(node.href).pathname.match(/^\/watch\/([a-z0-9]+)$/i)?.[1]?.toLowerCase();
			if (!id) throw new Error("RedGIFs: invalid video ID.");
			let cached = this.media.get(id);
			if (retry || !cached || Date.now() - cached.fetchedAt > 6e4 || !(cached.gif.urls?.hd || cached.gif.urls?.sd)) {
				const data = await this.api("gifs/" + id);
				if (!this.isVideo(data.gif)) throw new Error("RedGIFs: this video is unavailable.");
				cached = {
					gif: data.gif,
					fetchedAt: Date.now()
				};
				this.media.set(id, cached);
			}
			const urls = cached.gif.urls || {};
			const url = this.mediaURL(urls.hd) || this.mediaURL(urls.sd);
			if (!url) throw new Error("RedGIFs: no downloadable MP4 URL is available for this video.");
			const poster = this.mediaURL(urls.poster) || this.mediaURL(urls.thumbnail);
			if (poster) node.thumbnailSrc = poster;
			return { url };
		}
		async fetchImageData(imf) {
			const url = this.mediaURL(imf.node.originSrc);
			if (!url) throw new Error("RedGIFs: invalid media address.");
			const blob = await this.request(url, "blob", {}, imf);
			if (!blob || typeof blob.arrayBuffer !== "function" || !blob.size) throw new Error("RedGIFs: empty video response.");
			return [blob, 200];
		}
		async processData(data, contentType) {
			if (contentType?.startsWith("video/")) return [data, contentType];
			if ((!contentType || /^(application\/octet-stream|binary\/)/i.test(contentType)) && data.length >= 12 && data[4] === 102 && data[5] === 116 && data[6] === 121 && data[7] === 112) return [data, "video/mp4"];
			throw new Error("RedGIFs: response is not a video/MP4 file; refresh and retry.");
		}
		galleryMeta() {
			return new GalleryMeta(this.pageURL, "RedGIFs - " + this.author);
		}
	};
	ADAPTER.addSetup({
		name: "redgifs",
		workURLs: [/^https:\/\/(?:www\.)?redgifs\.com\/users\/[a-z0-9_.-]+\/?(?:[?#].*)?$/i],
		match: ["https://www.redgifs.com/users/*", "https://redgifs.com/users/*"],
		constructor: () => new RedGifsMatcher()
	});
	var rokuhentai_exports = __exportAll({ RokuHentaiMatcher: () => RokuHentaiMatcher });
	var RokuHentaiMatcher = class extends BaseMatcher {
		sprites = [];
		fetchedThumbnail = [];
		galleryId = "";
		imgCount = 0;
		galleryMeta() {
			const title = document.querySelector(".site-manga-info__title-text")?.textContent || "UNTITLE";
			const meta = new GalleryMeta(window.location.href, title);
			meta.originTitle = title;
			const tagTrList = document.querySelectorAll("div.mdc-chip .site-tag-count");
			const tags = {};
			tagTrList.forEach((tr) => {
				const splits = tr.getAttribute("data-tag")?.trim().split(":");
				if (splits === void 0 || splits.length === 0) return;
				const cat = splits[0];
				if (tags[cat] === void 0) tags[cat] = [];
				tags[cat].push(splits[1].replaceAll("\"", ""));
			});
			meta.tags = tags;
			return meta;
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
		async parseImgNodes(range) {
			const list = [];
			const digits = this.imgCount.toString().length;
			for (let i = range[0]; i < range[1]; i++) {
				let thumbnail = "";
				let thumbnailAsync = void 0;
				if (this.sprites[i]) thumbnailAsync = this.fetchThumbnail(i);
				else thumbnail = `https://rokuhentai.com/_images/page-thumbnails/${this.galleryId}/${i}.jpg`;
				const src = `https://rokuhentai.com/_images/pages/${this.galleryId}/${i}.jpg`;
				list.push(new ImageNode(thumbnail, src, i.toString().padStart(digits, "0") + ".jpg", thumbnailAsync, src));
			}
			return list;
		}
		async *fetchPagesSource() {
			const doc = document;
			const imgCount = parseInt(doc.querySelector(".mdc-typography--caption")?.textContent || "");
			if (isNaN(imgCount)) throw new Error("error: failed query image count!");
			this.imgCount = imgCount;
			this.galleryId = window.location.href.split("/").pop();
			const images = Array.from(doc.querySelectorAll(".mdc-layout-grid__cell .site-page-card__media"));
			for (const img of images) {
				this.fetchedThumbnail.push(void 0);
				const x = parseInt(img.getAttribute("data-offset-x") || "");
				const y = parseInt(img.getAttribute("data-offset-y") || "");
				const width = parseInt(img.getAttribute("data-width") || "");
				const height = parseInt(img.getAttribute("data-height") || "");
				if (isNaN(x) || isNaN(y) || isNaN(width) || isNaN(height)) {
					this.sprites.push(void 0);
					continue;
				}
				const src = img.getAttribute("data-src");
				this.sprites.push({
					src,
					pos: {
						x,
						y,
						width,
						height
					}
				});
			}
			for (let i = 0; i < this.imgCount; i += 20) yield Result.ok([i, Math.min(i + 20, this.imgCount)]);
		}
		async fetchThumbnail(index) {
			if (this.fetchedThumbnail[index]) return this.fetchedThumbnail[index];
			const src = this.sprites[index].src;
			const positions = [];
			for (let i = index; i < this.imgCount; i++) if (src === this.sprites[i]?.src) positions.push(this.sprites[i].pos);
			else break;
			const urls = await splitImagesFromUrl(src, positions);
			for (let i = index; i < index + urls.length; i++) this.fetchedThumbnail[i] = urls[i - index];
			return this.fetchedThumbnail[index];
		}
		async processData(data) {
			return [data, "image/jpeg"];
		}
	};
	ADAPTER.addSetup({
		name: "rokuhentai",
		workURLs: [/rokuhentai.com\/\w+$/],
		match: ["https://rokuhentai.com/*"],
		constructor: () => new RokuHentaiMatcher()
	});
	var se8_exports = __exportAll({});
	var Se8Matcher = class extends BaseMatcher {
		async *fetchChapters() {
			yield Array.from(document.querySelectorAll(".catalog-list li.chapter-item > a")).map((elem, i) => new Chapter(i, elem.textContent ?? "", elem.href));
		}
		async *fetchPagesSource(source) {
			yield Result.ok(source.source);
		}
		async parseImgNodes(href) {
			const doc = await window.fetch(href).then((resp) => resp.text()).then((text) => new DOMParser().parseFromString(text, "text/html")).catch(Error);
			if (doc instanceof Error) throw doc;
			return Array.from(doc.querySelectorAll("#mainView > .comic-list > .comic-page > img")).map((elem) => new ImageNode("", href, elem.alt, void 0, elem.src));
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
	};
	ADAPTER.addSetup({
		name: "韩漫库",
		workURLs: [/se8.us\/index.php\/comic\/[^/]*$/],
		match: ["https://se8.us/*"],
		constructor: () => new Se8Matcher()
	});
	var seqingman_exports = __exportAll({});
	var SeqingmanMatcher = class extends BaseMatcher {
		async *fetchChapters() {
			const elements = Array.from(document.querySelectorAll("#chapterlist > ul > li"));
			const ret = [];
			for (const elem of elements) {
				const a = elem.querySelector("a");
				const href = a.href;
				const title = a.textContent;
				const num = parseInt(elem.getAttribute("data-num") ?? "0");
				ret.push(new Chapter(num, title, href));
			}
			yield ret;
		}
		async *fetchPagesSource(source) {
			yield Result.ok(source.source);
		}
		async parseImgNodes(source) {
			const doc = await window.fetch(source).then((resp) => resp.text()).then((text) => new DOMParser().parseFromString(text, "text/html")).catch(Error);
			if (doc instanceof Error) throw doc;
			const images = Array.from(doc.querySelectorAll("#ch_img_container > img"));
			const digits = images.length.toString().length;
			return images.map((img, i) => {
				const src = img.src;
				const ext = src.split(".").pop() ?? "jpg";
				return new ImageNode("", source, (i + 1).toString().padStart(digits, "0") + "." + ext, void 0, src);
			});
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
	};
	ADAPTER.addSetup({
		name: "色情漫",
		workURLs: [/seqingman.com\/series\/[^/]*$/],
		match: ["seqingman.com"],
		constructor: () => new SeqingmanMatcher()
	});
	var steam_exports = __exportAll({});
	var STEAM_THUMB_IMG_URL_REGEX = /background-image:\surl\(.*?(h.*\/).*?\)/;
	var SteamMatcher = class extends BaseMatcher {
		async fetchOriginMeta(node) {
			let raw = "";
			try {
				raw = await window.fetch(node.href).then((resp) => resp.text());
				if (!raw) throw new Error("[text] is empty");
			} catch (error) {
				throw new Error(`Fetch source page error, expected [text]! ${error}`);
			}
			const imgURL = new DOMParser().parseFromString(raw, "text/html").querySelector(".actualmediactn > a")?.getAttribute("href");
			if (!imgURL) throw new Error("Cannot Query Steam original Image URL");
			return { url: imgURL };
		}
		async parseImgNodes(source) {
			const list = [];
			const doc = await window.fetch(source).then((resp) => resp.text()).then((raw) => new DOMParser().parseFromString(raw, "text/html"));
			if (!doc) throw new Error("warn: steam matcher failed to get document from source page!");
			const nodes = doc.querySelectorAll(".profile_media_item");
			if (!nodes || nodes.length == 0) throw new Error("warn: failed query image nodes!");
			for (const node of Array.from(nodes)) {
				const src = STEAM_THUMB_IMG_URL_REGEX.exec(node.innerHTML)?.[1];
				if (!src) throw new Error(`Cannot Match Steam Image URL, Content: ${node.innerHTML}`);
				const newNode = new ImageNode(src, node.getAttribute("href"), node.getAttribute("data-publishedfileid") + ".jpg");
				list.push(newNode);
			}
			return list;
		}
		async *fetchPagesSource() {
			let totalPages = -1;
			document.querySelectorAll(".pagingPageLink").forEach((ele) => {
				totalPages = Number(ele.textContent);
			});
			const url = new URL(window.location.href);
			url.searchParams.set("view", "grid");
			if (totalPages === -1) {
				const doc = await window.fetch(url.href).then((response) => response.text()).then((text) => new DOMParser().parseFromString(text, "text/html")).catch(() => null);
				if (!doc) throw new Error("warn: steam matcher failed to get document from source page!");
				doc.querySelectorAll(".pagingPageLink").forEach((ele) => totalPages = Number(ele.textContent));
			}
			if (totalPages > 0) for (let p = 1; p <= totalPages; p++) {
				url.searchParams.set("p", p.toString());
				yield Result.ok(url.href);
			}
			else yield Result.ok(url.href);
		}
		parseGalleryMeta() {
			const appid = new URL(window.location.href).searchParams.get("appid");
			return new GalleryMeta(window.location.href, "steam-" + appid || "all");
		}
	};
	ADAPTER.addSetup({
		name: "Steam Screenshots",
		workURLs: [/steamcommunity.com\/id\/[^/]+\/screenshots.*/],
		match: ["https://steamcommunity.com/*"],
		constructor: () => new SteamMatcher()
	});
	var twitter_exports = __exportAll({
		performTweetAction: () => performTweetAction,
		refreshActionsQueryId: () => refreshActionsQueryId
	});
	var TwitterUserMediasAPI = class {
		uuid = uuid();
		userID;
		async *fetchChapters() {
			if (window.location.href.includes("/media")) return [new Chapter(1, "User Medias", window.location.href, "https://pbs.twimg.com/profile_images/1683899100922511378/5lY42eHs_bigger.jpg")];
			else return [new Chapter(0, "User Posts", window.location.href, "https://pbs.twimg.com/profile_images/1683899100922511378/5lY42eHs_bigger.jpg"), new Chapter(1, "User Media", window.location.href, "https://pbs.twimg.com/profile_images/1683899100922511378/5lY42eHs_bigger.jpg")];
		}
		async next(chapter, cursor) {
			if (!this.userID) this.userID = getUserID();
			if (!this.userID) throw new Error("Cannot obatained User ID");
			let url = "";
			if (chapter.id === 0) {
				const variables = `{"userId":"${this.userID}","count":20,${cursor ? "\"cursor\":\"" + cursor + "\"," : ""}"includePromotedContent":true,"withQuickPromoteEligibilityTweetFields":true,"withVoice":true}`;
				url = `${window.location.origin}/i/api/graphql/ehYmFq6d3xwc49yqt52MIg/UserTweets?variables=${encodeURIComponent(variables)}&features=%7B%22rweb_video_screen_enabled%22%3Afalse%2C%22profile_label_improvements_pcf_label_in_post_enabled%22%3Atrue%2C%22responsive_web_profile_redirect_enabled%22%3Afalse%2C%22rweb_tipjar_consumption_enabled%22%3Atrue%2C%22verified_phone_label_enabled%22%3Afalse%2C%22creator_subscriptions_tweet_preview_api_enabled%22%3Atrue%2C%22responsive_web_graphql_timeline_navigation_enabled%22%3Atrue%2C%22responsive_web_graphql_skip_user_profile_image_extensions_enabled%22%3Afalse%2C%22premium_content_api_read_enabled%22%3Afalse%2C%22communities_web_enable_tweet_community_results_fetch%22%3Atrue%2C%22c9s_tweet_anatomy_moderator_badge_enabled%22%3Atrue%2C%22responsive_web_grok_analyze_button_fetch_trends_enabled%22%3Afalse%2C%22responsive_web_grok_analyze_post_followups_enabled%22%3Atrue%2C%22responsive_web_jetfuel_frame%22%3Atrue%2C%22responsive_web_grok_share_attachment_enabled%22%3Atrue%2C%22responsive_web_grok_annotations_enabled%22%3Afalse%2C%22articles_preview_enabled%22%3Atrue%2C%22responsive_web_edit_tweet_api_enabled%22%3Atrue%2C%22graphql_is_translatable_rweb_tweet_is_translatable_enabled%22%3Atrue%2C%22view_counts_everywhere_api_enabled%22%3Atrue%2C%22longform_notetweets_consumption_enabled%22%3Atrue%2C%22responsive_web_twitter_article_tweet_consumption_enabled%22%3Atrue%2C%22tweet_awards_web_tipping_enabled%22%3Afalse%2C%22responsive_web_grok_show_grok_translated_post%22%3Afalse%2C%22responsive_web_grok_analysis_button_from_backend%22%3Atrue%2C%22post_ctas_fetch_enabled%22%3Atrue%2C%22creator_subscriptions_quote_tweet_preview_enabled%22%3Afalse%2C%22freedom_of_speech_not_reach_fetch_enabled%22%3Atrue%2C%22standardized_nudges_misinfo%22%3Atrue%2C%22tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled%22%3Atrue%2C%22longform_notetweets_rich_text_read_enabled%22%3Atrue%2C%22longform_notetweets_inline_media_enabled%22%3Atrue%2C%22responsive_web_grok_image_annotation_enabled%22%3Atrue%2C%22responsive_web_grok_imagine_annotation_enabled%22%3Atrue%2C%22responsive_web_grok_community_note_auto_translation_is_enabled%22%3Afalse%2C%22responsive_web_enhance_cards_enabled%22%3Afalse%7D&fieldToggles=%7B%22withArticlePlainText%22%3Afalse%7D`;
			} else {
				const variables = `{"userId":"${this.userID}","count":20,${cursor ? "\"cursor\":\"" + cursor + "\"," : ""}"includePromotedContent":false,"withClientEventToken":false,"withBirdwatchNotes":false,"withVoice":true,"withV2Timeline":true}`;
				url = `${window.location.origin}/i/api/graphql/MjGtmDI0wpveHq8k2zIlUQ/UserMedia?variables=${encodeURIComponent(variables)}&features=%7B%22rweb_video_screen_enabled%22%3Afalse%2C%22profile_label_improvements_pcf_label_in_post_enabled%22%3Atrue%2C%22responsive_web_profile_redirect_enabled%22%3Afalse%2C%22rweb_tipjar_consumption_enabled%22%3Atrue%2C%22verified_phone_label_enabled%22%3Afalse%2C%22creator_subscriptions_tweet_preview_api_enabled%22%3Atrue%2C%22responsive_web_graphql_timeline_navigation_enabled%22%3Atrue%2C%22responsive_web_graphql_skip_user_profile_image_extensions_enabled%22%3Afalse%2C%22premium_content_api_read_enabled%22%3Afalse%2C%22communities_web_enable_tweet_community_results_fetch%22%3Atrue%2C%22c9s_tweet_anatomy_moderator_badge_enabled%22%3Atrue%2C%22responsive_web_grok_analyze_button_fetch_trends_enabled%22%3Afalse%2C%22responsive_web_grok_analyze_post_followups_enabled%22%3Atrue%2C%22responsive_web_jetfuel_frame%22%3Atrue%2C%22responsive_web_grok_share_attachment_enabled%22%3Atrue%2C%22responsive_web_grok_annotations_enabled%22%3Afalse%2C%22articles_preview_enabled%22%3Atrue%2C%22responsive_web_edit_tweet_api_enabled%22%3Atrue%2C%22graphql_is_translatable_rweb_tweet_is_translatable_enabled%22%3Atrue%2C%22view_counts_everywhere_api_enabled%22%3Atrue%2C%22longform_notetweets_consumption_enabled%22%3Atrue%2C%22responsive_web_twitter_article_tweet_consumption_enabled%22%3Atrue%2C%22tweet_awards_web_tipping_enabled%22%3Afalse%2C%22responsive_web_grok_show_grok_translated_post%22%3Afalse%2C%22responsive_web_grok_analysis_button_from_backend%22%3Atrue%2C%22post_ctas_fetch_enabled%22%3Atrue%2C%22creator_subscriptions_quote_tweet_preview_enabled%22%3Afalse%2C%22freedom_of_speech_not_reach_fetch_enabled%22%3Atrue%2C%22standardized_nudges_misinfo%22%3Atrue%2C%22tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled%22%3Atrue%2C%22longform_notetweets_rich_text_read_enabled%22%3Atrue%2C%22longform_notetweets_inline_media_enabled%22%3Atrue%2C%22responsive_web_grok_image_annotation_enabled%22%3Atrue%2C%22responsive_web_grok_imagine_annotation_enabled%22%3Atrue%2C%22responsive_web_grok_community_note_auto_translation_is_enabled%22%3Afalse%2C%22responsive_web_enhance_cards_enabled%22%3Afalse%7D&fieldToggles=%7B%22withArticlePlainText%22%3Afalse%7D`;
			}
			try {
				const res = await window.fetch(url, {
					headers: createHeader(this.uuid),
					signal: AbortSignal.timeout(1e4)
				});
				const json = await res.json();
				if (res.status !== 200 && json?.errors?.[0].message) throw new Error(json?.errors?.[0].message);
				if (chapter.id === 0) {
					const entries = json.data.user.result.timeline.timeline.instructions.find((ins) => ins.type === "TimelineAddEntries");
					if (!entries) throw new Error("Not found TimelineAddEntries");
					const { items, cursor } = homeForYouEntriesToItems(entries);
					return [items, cursor];
				} else {
					const instructions = json.data.user.result.timeline.timeline.instructions;
					const items = [];
					const addToModule = instructions.find((ins) => ins.type === "TimelineAddToModule");
					const entries = instructions.find((ins) => ins.type === "TimelineAddEntries");
					if (!entries) throw new Error("Not found TimelineAddEntries");
					if (addToModule) addToModule.moduleItems.forEach((i) => items.push(i.item));
					if (items.length === 0) (entries.entries.find((entry) => entry.content.entryType === "TimelineTimelineModule")?.content)?.items.forEach((i) => items.push(i.item));
					return [items, (entries.entries.find((entry) => entry.content.entryType === "TimelineTimelineCursor" && entry.entryId.startsWith("cursor-bottom"))?.content)?.value];
				}
			} catch (error) {
				throw new Error(`twitter api query error: ${error}`);
			}
		}
	};
	var TwitterListsAPI = class {
		uuid = uuid();
		listID;
		async *fetchChapters() {
			return [new Chapter(1, "User Medias", window.location.href)];
		}
		getListID() {
			return window.location.href.match(/i\/lists\/(\d+)$/)?.[1];
		}
		async next(_chapter, cursor) {
			if (!this.listID) this.listID = this.getListID();
			if (!this.listID) throw new Error("Cannot obatained list ID");
			const variables = `{"listId":"${this.listID}","count":20${cursor ? ",\"cursor\":\"" + cursor + "\"" : ""}}`;
			const url = `${window.location.origin}/i/api/graphql/LSefrrxhpeX8HITbKfWz9g/ListLatestTweetsTimeline?variables=${encodeURIComponent(variables)}&features=%7B%22rweb_video_screen_enabled%22%3Afalse%2C%22profile_label_improvements_pcf_label_in_post_enabled%22%3Atrue%2C%22rweb_tipjar_consumption_enabled%22%3Atrue%2C%22responsive_web_graphql_exclude_directive_enabled%22%3Atrue%2C%22verified_phone_label_enabled%22%3Afalse%2C%22creator_subscriptions_tweet_preview_api_enabled%22%3Atrue%2C%22responsive_web_graphql_timeline_navigation_enabled%22%3Atrue%2C%22responsive_web_graphql_skip_user_profile_image_extensions_enabled%22%3Afalse%2C%22premium_content_api_read_enabled%22%3Afalse%2C%22communities_web_enable_tweet_community_results_fetch%22%3Atrue%2C%22c9s_tweet_anatomy_moderator_badge_enabled%22%3Atrue%2C%22responsive_web_grok_analyze_button_fetch_trends_enabled%22%3Afalse%2C%22responsive_web_grok_analyze_post_followups_enabled%22%3Atrue%2C%22responsive_web_jetfuel_frame%22%3Afalse%2C%22responsive_web_grok_share_attachment_enabled%22%3Atrue%2C%22articles_preview_enabled%22%3Atrue%2C%22responsive_web_edit_tweet_api_enabled%22%3Atrue%2C%22graphql_is_translatable_rweb_tweet_is_translatable_enabled%22%3Atrue%2C%22view_counts_everywhere_api_enabled%22%3Atrue%2C%22longform_notetweets_consumption_enabled%22%3Atrue%2C%22responsive_web_twitter_article_tweet_consumption_enabled%22%3Atrue%2C%22tweet_awards_web_tipping_enabled%22%3Afalse%2C%22responsive_web_grok_show_grok_translated_post%22%3Afalse%2C%22responsive_web_grok_analysis_button_from_backend%22%3Atrue%2C%22creator_subscriptions_quote_tweet_preview_enabled%22%3Afalse%2C%22freedom_of_speech_not_reach_fetch_enabled%22%3Atrue%2C%22standardized_nudges_misinfo%22%3Atrue%2C%22tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled%22%3Atrue%2C%22longform_notetweets_rich_text_read_enabled%22%3Atrue%2C%22longform_notetweets_inline_media_enabled%22%3Atrue%2C%22responsive_web_grok_image_annotation_enabled%22%3Atrue%2C%22responsive_web_enhance_cards_enabled%22%3Afalse%7D`;
			try {
				const res = await window.fetch(url, {
					headers: createHeader(this.uuid),
					signal: AbortSignal.timeout(1e4)
				});
				const json = await res.json();
				if (res.status !== 200 && json?.errors?.[0].message) throw new Error(json?.errors?.[0].message);
				const entries = json.data.list.tweets_timeline.timeline.instructions.find((ins) => ins.type === "TimelineAddEntries");
				if (!entries) throw new Error("Not found TimelineAddEntries");
				const { items, cursor } = homeForYouEntriesToItems(entries);
				return [items, cursor];
			} catch (error) {
				throw new Error(`twitter api query error: ${error}`);
			}
		}
	};
	var TwitterHomeForYouAPI = class {
		listAPIs = new Map();
		uuid = uuid();
		seenTweetIds = {
			1: [],
			2: [],
			3: []
		};
		chapterCursors = {
			1: void 0,
			2: void 0,
			3: void 0
		};
		myID;
		async *fetchChapters() {
			yield [
				new Chapter(1, "For you", window.location.href),
				new Chapter(2, "Following", window.location.href),
				new Chapter(3, "Your Likes", window.location.href)
			];
			const listChapters = await this.fetchListChapters();
			if (listChapters.length > 0) yield listChapters;
		}
		async fetchListChapters() {
			let nextID = 100;
			this.listAPIs.clear();
			const h = {};
			createHeader(this.uuid).forEach((v, k) => {
				h[k] = v;
			});
			const resp = await simpleFetch(`${window.location.origin}/i/api/graphql/HeY9oqJxWKHSTCoBXaWnHg/ListsManagementPageTimeline?variables=%7B%22count%22%3A100%7D&features=%7B%22rweb_video_screen_enabled%22%3Afalse%2C%22rweb_cashtags_enabled%22%3Atrue%2C%22profile_label_improvements_pcf_label_in_post_enabled%22%3Atrue%2C%22responsive_web_profile_redirect_enabled%22%3Atrue%2C%22rweb_tipjar_consumption_enabled%22%3Afalse%2C%22verified_phone_label_enabled%22%3Afalse%2C%22creator_subscriptions_tweet_preview_api_enabled%22%3Atrue%2C%22responsive_web_graphql_timeline_navigation_enabled%22%3Atrue%2C%22premium_content_api_read_enabled%22%3Afalse%2C%22communities_web_enable_tweet_community_results_fetch%22%3Atrue%2C%22c9s_tweet_anatomy_moderator_badge_enabled%22%3Atrue%2C%22responsive_web_grok_analyze_button_fetch_trends_enabled%22%3Afalse%2C%22responsive_web_grok_analyze_post_followups_enabled%22%3Atrue%2C%22rweb_cashtags_composer_attachment_enabled%22%3Atrue%2C%22responsive_web_jetfuel_frame%22%3Atrue%2C%22rweb_sports_post_context_enabled%22%3Atrue%2C%22x_elections_post_context_enabled%22%3Atrue%2C%22responsive_web_grok_share_attachment_enabled%22%3Atrue%2C%22responsive_web_grok_annotations_enabled%22%3Atrue%2C%22articles_preview_enabled%22%3Atrue%2C%22responsive_web_edit_tweet_api_enabled%22%3Atrue%2C%22rweb_conversational_replies_downvote_enabled%22%3Afalse%2C%22graphql_is_translatable_rweb_tweet_is_translatable_enabled%22%3Atrue%2C%22view_counts_everywhere_api_enabled%22%3Atrue%2C%22longform_notetweets_consumption_enabled%22%3Atrue%2C%22responsive_web_twitter_article_tweet_consumption_enabled%22%3Atrue%2C%22content_disclosure_indicator_enabled%22%3Atrue%2C%22content_disclosure_ai_generated_indicator_enabled%22%3Atrue%2C%22responsive_web_grok_show_grok_translated_post%22%3Atrue%2C%22responsive_web_grok_analysis_button_from_backend%22%3Atrue%2C%22post_ctas_fetch_enabled%22%3Atrue%2C%22freedom_of_speech_not_reach_fetch_enabled%22%3Atrue%2C%22standardized_nudges_misinfo%22%3Atrue%2C%22tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled%22%3Atrue%2C%22longform_notetweets_rich_text_read_enabled%22%3Atrue%2C%22longform_notetweets_inline_media_enabled%22%3Afalse%2C%22responsive_web_nested_quote_preview_enabled%22%3Atrue%2C%22responsive_web_grok_image_annotation_enabled%22%3Atrue%2C%22responsive_web_grok_imagine_annotation_enabled%22%3Atrue%2C%22responsive_web_made_on_x_label_enabled%22%3Afalse%2C%22responsive_web_grok_community_note_auto_translation_is_enabled%22%3Atrue%2C%22responsive_web_enhance_cards_enabled%22%3Afalse%7D`, "json", h).catch(Error);
			if (resp instanceof Error) {
				evLog("error", "fetch lists failed: " + resp.message);
				return [];
			}
			const instructions = resp.data?.viewer?.list_management_timeline?.timeline?.instructions;
			if (!instructions || instructions.length === 0) return [];
			const entries = instructions.find((inst) => inst.type === "TimelineAddEntries")?.entries;
			if (!entries || entries.length === 0) return [];
			const items = entries.find((entry) => entry.entryId === "owned-subscribed-list-module-0")?.content?.items;
			if (!items || items.length === 0) return [];
			let lists = [];
			let pinningLists = [];
			for (const item of items) {
				const list = item.item?.itemContent?.list;
				const data = {
					id: list.id,
					id_str: list.id_str,
					name: list.name,
					mode: list.mode,
					pinning: list.pinning,
					cover: list.custom_banner_media?.media_info?.original_img_url ?? list.default_banner_media?.media_info?.original_img_url
				};
				if (data.pinning) pinningLists.push(data);
				else lists.push(data);
			}
			lists.unshift(...pinningLists);
			return lists.map((list) => {
				const id = nextID++;
				const api = new TwitterListsAPI();
				api.listID = list.id_str;
				this.listAPIs.set(id, api);
				return new Chapter(id, `${list.pinning ? "📌 " : ""}${list.name}${list.mode === "Private" ? " 🔒" : ""}`, `${location.origin}/i/lists/${list.id_str}`, list.cover);
			});
		}
		async next(chapter, listCursor) {
			const listAPI = this.listAPIs.get(chapter.id);
			if (listAPI) return listAPI.next(chapter, listCursor);
			const cursor = this.chapterCursors[chapter.id];
			const seenTweetIds = this.seenTweetIds[chapter.id].slice(-30).map((e) => "\"" + e + "\"").join(",");
			const headers = createHeader(this.uuid);
			const [url, body] = (() => {
				if (chapter.id === 1) return [`${window.location.origin}/i/api/graphql/ci_OQZ2k0rG0Ax_lXRiWVA/HomeTimeline`, `{"variables":{"count":20,${cursor ? `"cursor":"${cursor}",` : ""}"includePromotedContent":true,"latestControlAvailable":true,"requestContext":"launch","withCommunity":true,"seenTweetIds":[${seenTweetIds}]},"features":{"rweb_video_screen_enabled":false,"profile_label_improvements_pcf_label_in_post_enabled":true,"rweb_tipjar_consumption_enabled":true,"responsive_web_graphql_exclude_directive_enabled":true,"verified_phone_label_enabled":false,"creator_subscriptions_tweet_preview_api_enabled":true,"responsive_web_graphql_timeline_navigation_enabled":true,"responsive_web_graphql_skip_user_profile_image_extensions_enabled":false,"premium_content_api_read_enabled":false,"communities_web_enable_tweet_community_results_fetch":true,"c9s_tweet_anatomy_moderator_badge_enabled":true,"responsive_web_grok_analyze_button_fetch_trends_enabled":false,"responsive_web_grok_analyze_post_followups_enabled":true,"responsive_web_jetfuel_frame":false,"responsive_web_grok_share_attachment_enabled":true,"articles_preview_enabled":true,"responsive_web_edit_tweet_api_enabled":true,"graphql_is_translatable_rweb_tweet_is_translatable_enabled":true,"view_counts_everywhere_api_enabled":true,"longform_notetweets_consumption_enabled":true,"responsive_web_twitter_article_tweet_consumption_enabled":true,"tweet_awards_web_tipping_enabled":false,"responsive_web_grok_show_grok_translated_post":false,"responsive_web_grok_analysis_button_from_backend":true,"creator_subscriptions_quote_tweet_preview_enabled":false,"freedom_of_speech_not_reach_fetch_enabled":true,"standardized_nudges_misinfo":true,"tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled":true,"longform_notetweets_rich_text_read_enabled":true,"longform_notetweets_inline_media_enabled":true,"responsive_web_grok_image_annotation_enabled":true,"responsive_web_enhance_cards_enabled":false},"queryId":"ci_OQZ2k0rG0Ax_lXRiWVA"}`];
				else if (chapter.id === 2) return [`${window.location.origin}/i/api/graphql/HN6oP_7h7HayqyYimz97Iw/HomeLatestTimeline`, `{"variables":{"count":20,${cursor ? `"cursor":"${cursor}",` : ""}"includePromotedContent":true,"enableRanking":false,"seenTweetIds":[${seenTweetIds}]},"features":{"rweb_video_screen_enabled":false,"profile_label_improvements_pcf_label_in_post_enabled":true,"responsive_web_profile_redirect_enabled":false,"rweb_tipjar_consumption_enabled":true,"verified_phone_label_enabled":false,"creator_subscriptions_tweet_preview_api_enabled":true,"responsive_web_graphql_timeline_navigation_enabled":true,"responsive_web_graphql_skip_user_profile_image_extensions_enabled":false,"premium_content_api_read_enabled":false,"communities_web_enable_tweet_community_results_fetch":true,"c9s_tweet_anatomy_moderator_badge_enabled":true,"responsive_web_grok_analyze_button_fetch_trends_enabled":false,"responsive_web_grok_analyze_post_followups_enabled":true,"responsive_web_jetfuel_frame":true,"responsive_web_grok_share_attachment_enabled":true,"responsive_web_grok_annotations_enabled":false,"articles_preview_enabled":true,"responsive_web_edit_tweet_api_enabled":true,"graphql_is_translatable_rweb_tweet_is_translatable_enabled":true,"view_counts_everywhere_api_enabled":true,"longform_notetweets_consumption_enabled":true,"responsive_web_twitter_article_tweet_consumption_enabled":true,"tweet_awards_web_tipping_enabled":false,"responsive_web_grok_show_grok_translated_post":false,"responsive_web_grok_analysis_button_from_backend":true,"post_ctas_fetch_enabled":true,"creator_subscriptions_quote_tweet_preview_enabled":false,"freedom_of_speech_not_reach_fetch_enabled":true,"standardized_nudges_misinfo":true,"tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled":true,"longform_notetweets_rich_text_read_enabled":true,"longform_notetweets_inline_media_enabled":true,"responsive_web_grok_image_annotation_enabled":true,"responsive_web_grok_imagine_annotation_enabled":true,"responsive_web_grok_community_note_auto_translation_is_enabled":false,"responsive_web_enhance_cards_enabled":false},"queryId":"HN6oP_7h7HayqyYimz97Iw"}`];
				else {
					if (!this.myID) this.myID = getMyID();
					if (!this.myID) throw new Error("cannot find my id from current page");
					const cursorStr = cursor ? `"cursor":"${cursor}",` : "";
					const variables = `{"userId":"${this.myID}","count":20,${cursorStr}"includePromotedContent":false,"withClientEventToken":false,"withBirdwatchNotes":false,"withVoice":true}`;
					return [`${window.location.origin}/i/api/graphql/uxjTlmrTI61zreSIV1urbw/Likes?variables=${encodeURIComponent(variables)}&features=%7B%22rweb_video_screen_enabled%22%3Afalse%2C%22profile_label_improvements_pcf_label_in_post_enabled%22%3Atrue%2C%22rweb_tipjar_consumption_enabled%22%3Atrue%2C%22responsive_web_graphql_exclude_directive_enabled%22%3Atrue%2C%22verified_phone_label_enabled%22%3Afalse%2C%22creator_subscriptions_tweet_preview_api_enabled%22%3Atrue%2C%22responsive_web_graphql_timeline_navigation_enabled%22%3Atrue%2C%22responsive_web_graphql_skip_user_profile_image_extensions_enabled%22%3Afalse%2C%22premium_content_api_read_enabled%22%3Afalse%2C%22communities_web_enable_tweet_community_results_fetch%22%3Atrue%2C%22c9s_tweet_anatomy_moderator_badge_enabled%22%3Atrue%2C%22responsive_web_grok_analyze_button_fetch_trends_enabled%22%3Afalse%2C%22responsive_web_grok_analyze_post_followups_enabled%22%3Atrue%2C%22responsive_web_jetfuel_frame%22%3Afalse%2C%22responsive_web_grok_share_attachment_enabled%22%3Atrue%2C%22articles_preview_enabled%22%3Atrue%2C%22responsive_web_edit_tweet_api_enabled%22%3Atrue%2C%22graphql_is_translatable_rweb_tweet_is_translatable_enabled%22%3Atrue%2C%22view_counts_everywhere_api_enabled%22%3Atrue%2C%22longform_notetweets_consumption_enabled%22%3Atrue%2C%22responsive_web_twitter_article_tweet_consumption_enabled%22%3Atrue%2C%22tweet_awards_web_tipping_enabled%22%3Afalse%2C%22responsive_web_grok_show_grok_translated_post%22%3Afalse%2C%22responsive_web_grok_analysis_button_from_backend%22%3Atrue%2C%22creator_subscriptions_quote_tweet_preview_enabled%22%3Afalse%2C%22freedom_of_speech_not_reach_fetch_enabled%22%3Atrue%2C%22standardized_nudges_misinfo%22%3Atrue%2C%22tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled%22%3Atrue%2C%22longform_notetweets_rich_text_read_enabled%22%3Atrue%2C%22longform_notetweets_inline_media_enabled%22%3Atrue%2C%22responsive_web_grok_image_annotation_enabled%22%3Atrue%2C%22responsive_web_enhance_cards_enabled%22%3Afalse%7D&fieldToggles=%7B%22withArticlePlainText%22%3Afalse%7D`, ""];
				}
			})();
			try {
				const h = {};
				headers.forEach((v, k) => {
					h[k] = v;
				});
				const text = await new Promise((resolve, reject) => {
					GM_XHR({
						method: body ? "POST" : "GET",
						url,
						headers: h,
						data: body ? body : void 0,
						timeout: 2e4,
						onload: (event) => resolve(event.response),
						ontimeout: () => reject("timeout"),
						onerror: (reason) => reject(reason)
					});
				});
				const json = JSON.parse(text);
				if (json?.errors?.[0].message) throw new Error(json?.errors?.[0].message);
				const entries = (() => {
					if (chapter.id === 3) {
						if (json?.data?.user?.result?.timeline_v2?.timeline?.instructions) return json.data.user.result.timeline_v2.timeline.instructions;
						else if (json?.data?.user?.result?.timeline?.timeline?.instructions) return json.data.user.result.timeline.timeline.instructions;
						else throw new Error("cannot found: json?.data?.user?.result?.timeline_v2?.timeline?.instructions");
					} else {
						if (!json?.data?.home?.home_timeline_urt?.instructions) throw new Error("cannot found: json?.data?.home?.home_timeline_urt?.instructions");
						return json.data.home.home_timeline_urt.instructions;
					}
				})().find((ins) => ins.type === "TimelineAddEntries");
				if (!entries) throw new Error("Not found TimelineAddEntries");
				const { items, ids, cursor } = homeForYouEntriesToItems(entries);
				this.seenTweetIds[chapter.id] = ids;
				this.chapterCursors[chapter.id] = cursor;
				return [items, cursor];
			} catch (error) {
				throw new Error(`twitter api query error: ${error}`);
			}
		}
	};
	var TwitterMatcher = class extends BaseMatcher {
		postCount = 0;
		mediaCount = 0;
		api;
		uuid = uuid();
		constructor() {
			super();
			if (/\/home$/.test(window.location.href)) this.api = new TwitterHomeForYouAPI();
			else if (/i\/lists\/\d+$/.test(window.location.href)) this.api = new TwitterListsAPI();
			else this.api = new TwitterUserMediasAPI();
		}
		fetchChapters() {
			return this.api.fetchChapters();
		}
		async *fetchPagesSource(chapter) {
			let cursor;
			while (true) try {
				const [mediaPage, nextCursor] = await this.api.next(chapter, cursor);
				cursor = nextCursor || "last";
				if (!mediaPage || mediaPage.length === 0) break;
				yield Result.ok(mediaPage);
				if (!nextCursor) break;
			} catch (error) {
				yield Result.err(error);
			}
		}
		async parseImgNodes(items) {
			if (!items) throw new Error("warn: cannot find items");
			const list = [];
			for (const item of items) {
				const [mediaList, tweetID, bookmarked, favorited] = checkoutMedias(item);
				if (mediaList.length === 0) {
					const user = item.itemContent?.tweet_results?.result?.core?.user_results?.result?.legacy?.screen_name ?? item.itemContent?.tweet_results?.result?.core?.user_results?.result?.core?.screen_name;
					const rest_id = item.itemContent.tweet_results.result.rest_id;
					evLog("error", `cannot found mediaList: ${window.location.origin}/${user}/status/${rest_id}`, item);
					continue;
				}
				const actions = this.tweetActions(tweetID, bookmarked, favorited);
				this.postCount++;
				if (ADAPTER.conf.reverseMultipleImagesPost) mediaList.reverse();
				for (let i = 0; i < mediaList.length; i++) {
					const media = mediaList[i];
					if (ADAPTER.conf.excludeVideo && media.type === "video") continue;
					if (media.type !== "video" && media.type !== "photo" && media.type !== "animated_gif") {
						evLog("error", `Not supported media type: ${media.type}`);
						continue;
					}
					const node = this.mediaNode(media, i, actions);
					list.push(node);
					this.mediaCount++;
				}
			}
			return list;
		}
		tweetActions(tweetID, bookmarked, favorited) {
			if (!tweetID) return [];
			const actionLike = new NodeAction("❤", "like this tweet", async (self, _node, trigger) => {
				let operation = self.data === "liked" ? "UnfavoriteTweet" : "FavoriteTweet";
				await performTweetAction(operation, tweetID, this.uuid);
				self.data = operation === "FavoriteTweet" ? "liked" : "unknown";
				self.icon = operation === "FavoriteTweet" ? "Cancel ❤" : "❤";
				trigger.textContent = self.icon;
			}, true);
			actionLike.data = favorited ? "liked" : void 0;
			actionLike.icon = favorited ? "Cancel ❤" : "❤";
			const actionBookmark = new NodeAction("🔖", "bookmark this tweet", async (self, _node, trigger) => {
				let operation = self.data === "bookmarked" ? "DeleteBookmark" : "CreateBookmark";
				await performTweetAction(operation, tweetID, this.uuid);
				self.data = operation === "CreateBookmark" ? "bookmarked" : "unknown";
				self.icon = operation === "CreateBookmark" ? "Del 🔖" : "🔖";
				trigger.textContent = self.icon;
			}, true);
			actionBookmark.data = bookmarked ? "bookmarked" : void 0;
			actionBookmark.icon = bookmarked ? "Del 🔖" : "🔖";
			return [actionLike, actionBookmark];
		}
		mediaNode(media, index, actions) {
			const ext = media.media_url_https.split(".").pop();
			const baseSrc = media.media_url_https.replace(`.${ext}`, "");
			const src = `${baseSrc}?format=${ext}&name=${media.sizes.small ? "small" : "thumb"}`;
			let href = media.expanded_url.replace(/\/(photo|video)\/\d+/, "");
			href = `${href}/${media.type === "video" ? "video" : "photo"}/${index + 1}`;
			let largeSrc = "";
			if (ADAPTER.conf.fetchOriginal && media.original_info) largeSrc = `${baseSrc}?format=${ext}&name=orig`;
			else largeSrc = `${baseSrc}?format=${ext}&name=${media.sizes.large ? "large" : media.sizes.medium ? "medium" : "small"}`;
			const title = `${media.id_str}-${baseSrc.split("/").pop()}.${ext}`;
			const wh = {
				w: media.sizes.small.w,
				h: media.sizes.small.h
			};
			const node = new ImageNode(src, href, title, void 0, largeSrc, wh);
			node.actions.push(...actions);
			this.selectVideoVariant(node, media.video_info);
			return node;
		}
		selectVideoVariant(node, info) {
			if (info) {
				let bitrate = 0;
				for (const variant of info.variants) if (variant.bitrate !== void 0 && variant.bitrate >= bitrate) {
					bitrate = variant.bitrate;
					node.originSrc = variant.url;
					node.mimeType = variant.content_type;
					node.title = node.title.replace(/\.\w+$/, `.${variant.content_type.split("/")[1]}`);
				}
			}
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
		galleryMeta() {
			const userName = window.location.href.match(/(twitter|x).com\/(\w+)\/?/)?.[2];
			return new GalleryMeta(window.location.href, `twitter-${userName || document.title}-${this.postCount}-${this.mediaCount}`);
		}
	};
	function getMyID() {
		return Array.from(document.querySelectorAll("script")).find((sc) => sc.innerText.startsWith("window.__INITIAL_STATE__"))?.innerText.match(/"id_str":\s?"(\d+)"/)?.[1];
	}
	function getUserID() {
		const userName = window.location.href.match(/(twitter|x).com\/(\w+)\/?/)?.[2] || "lililjiliijili";
		const followBTNs = Array.from(document.querySelectorAll("button[data-testid][aria-label]"));
		if (followBTNs.length === 0) return void 0;
		return (followBTNs.find((btn) => (btn.getAttribute("aria-label") ?? "").toLowerCase().includes(`@${userName.toLowerCase()}`)) || followBTNs[0]).getAttribute("data-testid").match(/(\d+)/)?.[1];
	}
	function createHeader(uuid) {
		const headers = new Headers();
		headers.set("authorization", "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA");
		headers.set("Pragma", "no-cache");
		headers.set("Cache-Control", "no-cache");
		headers.set("content-type", "application/json");
		headers.set("x-client-uuid", uuid);
		headers.set("x-twitter-auth-type", "OAuth2Session");
		headers.set("x-twitter-client-language", "en");
		headers.set("x-twitter-active-user", "yes");
		headers.set("x-client-transaction-id", transactionId());
		headers.set("Sec-Fetch-Dest", "empty");
		headers.set("Sec-Fetch-Mode", "cors");
		headers.set("Sec-Fetch-Site", "same-origin");
		const csrfToken = document.cookie.match(/ct0=(\w+)/)?.[1];
		if (!csrfToken) throw new Error("Not found csrfToken");
		headers.set("x-csrf-token", csrfToken);
		return headers;
	}
	function homeForYouEntriesToItems(entries) {
		const items = [];
		const ids = [];
		let cursor;
		for (const entry of entries.entries) if (entry.content.entryType === "TimelineTimelineItem" && !entry.entryId.startsWith("promoted-")) {
			if (!entry.content.itemContent.tweet_results?.result) continue;
			items.push(entry.content);
			if (entry.content.itemContent.tweet_results.result.legacy?.id_str) ids.push(entry.content.itemContent.tweet_results.result.legacy.id_str);
			if (entry.content.itemContent.tweet_results.result.legacy?.retweeted_status_result?.result?.legacy?.id_str) ids.push(entry.content.itemContent.tweet_results.result.legacy?.retweeted_status_result?.result?.legacy?.id_str);
		} else if (entry.content.entryType === "TimelineTimelineModule" && entry.content.displayType === "VerticalConversation") entry.content.items.forEach((i) => {
			if (i.item.itemContent.tweet_results?.result) {
				items.push(i.item);
				if (i.item.itemContent.tweet_results.result.legacy?.id_str) ids.push(i.item.itemContent.tweet_results.result.legacy?.id_str);
				if (i.item.itemContent.tweet_results.result.legacy?.retweeted_status_result?.result?.legacy?.id_str) ids.push(i.item.itemContent.tweet_results.result.legacy?.retweeted_status_result?.result?.legacy?.id_str);
			}
		});
		else if (entry.content.entryType === "TimelineTimelineCursor" && entry.entryId.startsWith("cursor-bottom")) cursor = entry.content.value;
		return {
			items,
			ids,
			cursor
		};
	}
	function tweetLegacies(item) {
		const result = item.itemContent?.tweet_results?.result;
		return [result?.legacy, result?.tweet?.legacy].flatMap((outer) => [
			outer,
			outer?.retweeted_status_result?.result?.tweet?.legacy,
			outer?.retweeted_status_result?.result?.legacy
		]).filter((legacy) => !!legacy);
	}
	function checkoutMedias(item) {
		const legacies = tweetLegacies(item);
		const medias = [];
		const mediaIDs = new Set();
		for (const media of legacies.flatMap((legacy) => legacy.entities?.media ?? [])) {
			if (mediaIDs.has(media.id_str)) continue;
			mediaIDs.add(media.id_str);
			medias.push(media);
		}
		return [
			medias,
			legacies.findLast((legacy) => legacy.id_str != null)?.id_str,
			legacies.some((legacy) => legacy.bookmarked),
			legacies.some((legacy) => legacy.favorited)
		];
	}
	async function refreshActionsQueryId() {
		const url = [...Array.from(document.scripts).map((script) => script.src), ...performance.getEntriesByType("resource").map((entry) => entry.name)].find((url) => /^https:\/\/abs\.twimg\.com\/responsive-web\/client-web[^/]*\/main\.[\w]+\.js$/.test(url));
		if (!url) throw new Error("can not find responsive-web/client-web/main.js url");
		const definitions = (await simpleFetch(url, "text")).matchAll(/queryId\s*:\s*["']([\w-]+)["']\s*,\s*operationName\s*:\s*["'](FavoriteTweet|UnfavoriteTweet|CreateBookmark|DeleteBookmark)["']/g);
		const queryIdMap = {};
		for (const definition of definitions) {
			const operation = definition[2];
			queryIdMap[operation] = definition[1];
		}
		if (Object.keys(queryIdMap).length === 0) throw new Error("can not match queryId and operationName from main.js");
		window.localStorage.setItem("x-operation-queryIds", JSON.stringify(queryIdMap));
		return queryIdMap;
	}
	var xOperationQueryIds = void 0;
	function getQueryIdsByLocalStorage() {
		const raw = window.localStorage.getItem("x-operation-queryIds");
		if (raw) try {
			return JSON.parse(raw);
		} catch (_err) {
			evLog("error", "parse [x-operation-queryIds] error, got raw from localstorage: " + raw);
		}
		return {
			"FavoriteTweet": "lI07N6Otwv1PhnEgXILM7A",
			"UnfavoriteTweet": "ZYKSe-w7KEslx3JhSIk5LA",
			"CreateBookmark": "aoDbu3RHznuiSkQ9aNM67Q",
			"DeleteBookmark": "Wlmlj2-xzyS1GN3a6cj-mQ"
		};
	}
	async function getQueryId(operation, refresh = false) {
		if (xOperationQueryIds === void 0) xOperationQueryIds = getQueryIdsByLocalStorage();
		if (refresh) xOperationQueryIds = await refreshActionsQueryId();
		if (!xOperationQueryIds[operation]) throw new Error(`cannot get queryId for operation [${operation}]`);
		return xOperationQueryIds[operation];
	}
	async function performTweetAction(operation, tweetID, uuid) {
		let queryId = await getQueryId(operation);
		try {
			await sendAction(queryId, operation, tweetID, uuid);
		} catch (error) {
			if (!(error instanceof Error) || error.message !== "X action HTTP 404") throw error;
			queryId = await getQueryId(operation, true);
			await sendAction(queryId, operation, tweetID, uuid);
		}
	}
	async function sendAction(queryId, operation, tweetID, uuid) {
		await window.fetch(`https://x.com/i/api/graphql/${queryId}/${operation}`, {
			"headers": createHeader(uuid),
			"body": "{\"variables\":{\"tweet_id\":\"" + tweetID + "\"},\"queryId\":\"" + queryId + "\"}",
			"method": "POST",
			"mode": "cors"
		});
	}
	ADAPTER.addSetup({
		name: "Twitter | X",
		workURLs: [/(\/x|twitter).com\/(?!(explore|notifications|messages|jobs|lists)$|i\/(?!list)|search\?)\w+/],
		match: ["https://x.com/*"],
		constructor: () => new TwitterMatcher()
	});
	var wnacg_exports = __exportAll({});
	var PAGES_PER_INDEX_PAGE = 12;
	var WnacgMatcher = class extends BaseMatcher {
		meta;
		baseURL;
		galleryURL;
		async *fetchChapters() {
			const id = document.querySelector("#sr_pub") ? this.extractIDFromHref(window.location.href) : window.location.href.match(/-sid-(\d+)/)?.[1];
			if (!id) return [new Chapter(0, "Default", window.location.href)];
			const chapters = [];
			const seen = new Set();
			let cover;
			for (let page = 1;; page++) {
				const doc = await this.requestDocument(`${window.location.origin}/photos-index-aid-${id}-page-${page}.html?order=asc&mode=list`);
				if (page === 1) {
					this.meta = this.pasrseGalleryMeta(doc);
					const coverSrc = doc.querySelector(".asTBcell.uwthumb img")?.getAttribute("src");
					if (coverSrc) cover = this.toAbsoluteURL(coverSrc);
				}
				let added = 0;
				doc.querySelectorAll(".sr_compact a[data-chid]").forEach((ele) => {
					const chid = ele.getAttribute("data-chid");
					if (seen.has(chid)) return;
					seen.add(chid);
					added++;
					const title = ele.textContent?.trim() || chid;
					chapters.push(new Chapter(chapters.length, title, `${window.location.origin}/photos-index-aid-${chid}.html`, cover));
				});
				if (added === 0 || !doc.querySelector(".bot_toolbar .paginator .next")) break;
			}
			if (chapters.length === 0) throw new Error("Cannot find any chapter in this series");
			yield chapters;
		}
		async *fetchPagesSource(chapter) {
			const id = this.extractIDFromHref(chapter.source);
			if (!id) throw new Error("Cannot find gallery ID");
			this.baseURL = `${window.location.origin}/photos-index-page-1-aid-${id}.html`;
			this.galleryURL = `${window.location.origin}/photos-gallery-aid-${id}.html`;
			let indexDoc = await this.requestDocument(this.baseURL);
			chapter.meta = this.pasrseGalleryMeta(indexDoc);
			const imageList = await this.requestGalleryImages(this.galleryURL);
			if (imageList.length === 0) throw new Error("Cannot find any image in this gallery");
			const indexPageCount = this.extractIndexPageCount(indexDoc, imageList.length);
			let position = 0;
			for (let page = 1; page <= indexPageCount; page++) {
				let thumbnails = [];
				if (page === 1) thumbnails = this.extractThumbnails(indexDoc, position);
				else {
					const thumbnailPage = `${window.location.origin}/photos-index-page-${page}-aid-${id}.html`;
					const doc = await this.requestDocument(thumbnailPage).catch((error) => {
						evLog("error", `wnacg: cannot fetch album index page ${page}, thumbnails are skipped:`, error);
					});
					if (doc) thumbnails = this.extractThumbnails(doc, position);
				}
				thumbnails.forEach((thumbnail) => {
					const img = imageList[thumbnail.pageNumber - 1];
					if (img) img.thumbnail = thumbnail.url;
				});
				const count = thumbnails.length || PAGES_PER_INDEX_PAGE;
				const chunk = imageList.slice(position, position + count);
				position += chunk.length;
				if (chunk.length > 0) yield Result.ok(chunk);
			}
			if (position < imageList.length) yield Result.ok(imageList.slice(position));
		}
		async parseImgNodes(list) {
			return list.map((img) => new ImageNode(img.thumbnail || "", img.url, img.caption, void 0, img.url));
		}
		async fetchOriginMeta(node) {
			const url = node.originSrc ?? node.thumbnailSrc;
			const realext = (url.includes(".") ? url.split(".").pop() : "jpg")?.split("?verify")[0];
			return {
				url,
				title: node.title.replace("[", "").replace("]", "") + "." + realext
			};
		}
		galleryMeta(chapter) {
			return chapter.meta || this.meta || super.galleryMeta(chapter);
		}
		title(chapters) {
			return this.meta?.title || super.title(chapters);
		}
		extractIDFromHref(href) {
			const match = href.match(/aid-(\d+)/);
			if (!match) return void 0;
			return match[1];
		}
		pasrseGalleryMeta(doc) {
			const title = doc.querySelector("#bodywrap > h2")?.textContent || "unknown";
			const meta = new GalleryMeta(this.baseURL || window.location.href, title);
			meta.tags = {
				"tags": Array.from(doc.querySelectorAll(".asTB .tagshow")).map((ele) => ele.textContent).filter(Boolean),
				"description": Array.from(doc.querySelector(".asTB > .asTBcell.uwconn > p")?.childNodes || []).map((e) => e.textContent).filter(Boolean)
			};
			return meta;
		}
		async requestDocument(url) {
			return window.fetch(url).then((res) => res.text()).then((text) => new DOMParser().parseFromString(text, "text/html"));
		}
		extractIndexPageCount(doc, imageCount) {
			let lastPage = 1;
			doc.querySelectorAll(".paginator a").forEach((ele) => {
				const page = ele.getAttribute("href")?.match(/photos-index-page-(\d+)-aid-/)?.[1];
				if (page) lastPage = Math.max(lastPage, parseInt(page, 10));
			});
			const perPage = doc.querySelectorAll(".gallary_wrap li.gallary_item").length || PAGES_PER_INDEX_PAGE;
			return Math.max(lastPage, Math.ceil(imageCount / perPage));
		}
		extractThumbnails(doc, offset) {
			const thumbnails = [];
			doc.querySelectorAll(".gallary_wrap li.gallary_item").forEach((ele, indexInPage) => {
				const src = ele.querySelector(".pic_box img")?.getAttribute("src");
				if (!src) return;
				thumbnails.push({
					pageNumber: offset + indexInPage + 1,
					url: this.toAbsoluteURL(src)
				});
			});
			return thumbnails;
		}
		toAbsoluteURL(src) {
			try {
				return new URL(src, this.baseURL || window.location.href).href;
			} catch (error) {
				evLog("error", "wnacg: invalid thumbnail url:", src, error);
				return src;
			}
		}
		async requestGalleryImages(galleryURL) {
			const text = await window.fetch(galleryURL).then((res) => res.text());
			let js = "";
			for (let line of text.split("\n")) {
				line = line.replace("document.writeln(\"", "");
				line = line.replace("\");", "");
				if (line.includes("var imglist")) {
					line = line.replace("var imglist = ", "");
					line = line.replaceAll("fast_img_host+\\", "");
					line = line.replaceAll("\\", "");
					js += line;
				}
			}
			return this.extractUrlsAndCaptions(js);
		}
		extractUrlsAndCaptions(inputStr) {
			const regex = /url:\s*"(.*?)",\s*caption:\s*"(.*?)"/gs;
			let match;
			const results = [];
			while ((match = regex.exec(inputStr)) !== null) results.push({
				url: match[1],
				caption: match[2]
			});
			if (results.length > 0) {
				if (results[results.length - 1].caption.includes("加入收藏")) results.pop();
			}
			return results;
		}
	};
	ADAPTER.addSetup({
		name: "绅士漫画",
		workURLs: [/(wnacg.(com|ru)|wn\d{2}.(cc|ru))\/photos-(index|slide)/],
		match: ["https://www.wnacg.com/*"],
		preloadAllPages: true,
		constructor: () => new WnacgMatcher()
	});
	var yabai_exports = __exportAll({});
	var YabaiMatcher = class extends BaseMatcher {
		meta;
		title() {
			return this.meta?.title ?? document.title;
		}
		galleryMeta() {
			return this.meta;
		}
		async *fetchPagesSource() {
			const data = await this.query(window.location.href + "/read", `{"page":1}`);
			if (data.props?.pages?.data?.list) {
				const list = data.props?.pages?.data;
				yield Result.ok(list);
			} else throw new Error("cannot fetch pages " + (data?.message ?? ""));
		}
		async parseImgNodes(raw) {
			const items = this.buildList(raw);
			if (items.length === 0) throw new Error("cannot build list from gallery data");
			const page = Math.ceil(raw.count / 20);
			const data = await this.query(window.location.href, `{"page":${page}}`);
			const thumbnails = data.props?.post?.data?.page_list;
			if (!thumbnails) throw new Error("cannot fetch thumbnails");
			const meta = data.props?.post?.data;
			if (meta) this.meta = this.buildGalleryMeta(meta);
			const ret = [];
			for (let i = 0; i < items.length; i++) {
				const item = items[i];
				const thumb = thumbnails[i];
				ret.push(new ImageNode(thumb, item.url, `${item.name}.${item.ext}`, void 0, item.url));
			}
			return ret;
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
		buildGalleryMeta(data) {
			const meta = new GalleryMeta(data.url, data.name);
			meta.originTitle = data.alt_name;
			meta.tags = {
				flag: [data.flag],
				category: [data.category],
				date: [data.date],
				...data.tags
			};
			return meta;
		}
		buildList(data) {
			const list = data.list;
			const urls = [];
			for (let r = 0; r < data.count; r++) {
				const index = parseInt(list.head[r]) - 1;
				const name = list.head[r].padStart(4, "0");
				urls[index] = {
					url: "".concat(list.root, "/").concat(list.code.toString(), "/").concat(name, "-").concat(list.hash[r], "-").concat(list.rand[r], ".").concat(list.type[r]),
					name,
					ext: list.type[r]
				};
			}
			return urls;
		}
		async query(url, body) {
			const csrf = document.cookie.match(/XSRF-TOKEN=([^;]+);?/)?.[1];
			if (!csrf) throw new Error("cannot get csrf token form cookie");
			return await (await window.fetch(url, {
				"headers": {
					"Content-Type": "application/json",
					"X-Requested-With": "XMLHttpRequest",
					"X-Inertia": "true",
					"X-Inertia-Version": transactionId(),
					"X-XSRF-TOKEN": decodeURIComponent(csrf)
				},
				"body": body,
				"method": "POST"
			})).json();
		}
	};
	ADAPTER.addSetup({
		name: "Yabai.si",
		workURLs: [/yabai.si\/g\/\w+\/?$/],
		match: ["https://yabai.si/*"],
		constructor: () => new YabaiMatcher()
	});
	var yandere_exports = __exportAll({});
	var POST_INFO_REGEX = /Post\.register\((.*)\)/g;
	var YandereMatcher = class extends BaseMatcher {
		infos = {};
		count = 0;
		async *fetchPagesSource() {
			let doc = document;
			yield Result.ok(doc);
			let tryTimes = 0;
			while (true) {
				const url = doc.querySelector("#paginator a.next_page")?.href;
				if (!url) break;
				try {
					doc = await window.fetch(url).then((res) => res.text()).then((text) => new DOMParser().parseFromString(text, "text/html"));
				} catch (e) {
					tryTimes++;
					if (tryTimes > 3) throw new Error(`fetch next page failed, ${e}`);
					continue;
				}
				tryTimes = 0;
				yield Result.ok(doc);
			}
		}
		async parseImgNodes(doc) {
			const raw = doc.querySelector("body > form + script")?.textContent;
			if (!raw) throw new Error("cannot find post list from script");
			const matches = raw.matchAll(POST_INFO_REGEX);
			const ret = [];
			for (const match of matches) {
				if (!match || match.length < 2) continue;
				try {
					const info = JSON.parse(match[1]);
					this.infos[info.id.toString()] = info;
					this.count++;
					ret.push(new ImageNode(info.preview_url, `${window.location.origin}/post/show/${info.id}`, `${info.id}.${info.file_ext}`, void 0, void 0, {
						w: info.width,
						h: info.height
					}));
				} catch (error) {
					evLog("error", "parse post info failed", error);
					continue;
				}
			}
			return ret;
		}
		async fetchOriginMeta(node) {
			const id = node.href.split("/").pop();
			if (!id) throw new Error(`cannot find id from ${node.href}`);
			let url;
			if (ADAPTER.conf.fetchOriginal) url = this.infos[id]?.file_url;
			else url = this.infos[id]?.sample_url;
			if (!url) throw new Error(`cannot find url for id ${id}`);
			return { url };
		}
		galleryMeta() {
			const tags = new URL(window.location.href).searchParams.get("tags")?.trim();
			const meta = new GalleryMeta(window.location.href, `yande_${tags || "post"}_${this.count}`);
			meta["infos"] = this.infos;
			return meta;
		}
	};
	ADAPTER.addSetup({
		name: "yande.re",
		workURLs: [/yande.re\/post(?!\/show\/.*)/],
		match: ["https://yande.re/*"],
		constructor: () => new YandereMatcher()
	});
	var ykmh_exports = __exportAll({});
	var YKMHMatcher = class extends BaseMatcher {
		meta;
		galleryMeta() {
			if (this.meta) return this.meta;
			const title = document.querySelector(".comic_deCon h1")?.textContent ?? document.title;
			this.meta = new GalleryMeta(window.location.href, title);
			return this.meta;
		}
		async *fetchChapters() {
			yield Array.from(document.querySelectorAll("ul[id*=chapter-list] > li")).map((elem) => {
				let title = elem.querySelector(".list_con_zj")?.textContent;
				const url = elem.querySelector("a")?.href;
				if (!title) title = elem.querySelector("a")?.textContent?.trim();
				return {
					title,
					url
				};
			}).filter((e) => e.title && e.url).map((e, i) => new Chapter(i, e.title, e.url));
		}
		async *fetchPagesSource(ch) {
			yield Result.ok(ch.source);
		}
		async parseImgNodes(source) {
			const raw = await window.fetch(source).then((resp) => resp.text()).catch(Error);
			if (raw instanceof Error) throw raw;
			const imageUrls = raw.match(/var chapterImages = \[(.*?)\]/)?.[1];
			if (!imageUrls) throw new Error("no images url matched, regexp: var chapterImages = \\[(.*?)\\]");
			const urls = imageUrls.split(",").map((url) => url.replaceAll("\"", "").trim());
			const digits = urls.length.toString().length;
			return urls.map((url, i) => {
				const ext = url.split(".").pop() ?? "jpg";
				return new ImageNode("", source, (i + 1).toString().padStart(digits, "0") + "." + ext, void 0, url);
			});
		}
		async fetchOriginMeta(node) {
			return { url: node.originSrc };
		}
	};
	ADAPTER.addSetup({
		name: "优酷漫画",
		workURLs: [/ykmh.net\/manhua\/\w+\/?$/],
		match: ["https://www.ykmh.net/manhua/*"],
		constructor: () => new YKMHMatcher()
	});
	var GestureController = class {
		viewport;
		zoomTarget;
		cb;
		scale = 1;
		panX = 0;
		panY = 0;
		trackingSingle = false;
		startX = 0;
		startY = 0;
		lastX = 0;
		lastY = 0;
		startTime = 0;
		moved = false;
		gestureAxis = "undecided";
		pinching = false;
		initialPinchDist = 0;
		initialPinchScale = 1;
		initialPinchMidX = 0;
		initialPinchMidY = 0;
		initialPanX = 0;
		initialPanY = 0;
		lastTapTime = 0;
		lastTapX = 0;
		lastTapY = 0;
		singleTapTimer;
		keyHandler;
		constructor(viewport, zoomTarget, callbacks) {
			this.viewport = viewport;
			this.zoomTarget = zoomTarget;
			this.cb = callbacks;
			this.viewport.addEventListener("touchstart", this.onTouchStart, { passive: false });
			this.viewport.addEventListener("touchmove", this.onTouchMove, { passive: false });
			this.viewport.addEventListener("touchend", this.onTouchEnd, { passive: false });
			this.viewport.addEventListener("touchcancel", this.onTouchEnd, { passive: false });
			this.viewport.addEventListener("click", this.onMouseClick);
			this.keyHandler = (ev) => {
				if (ev.target instanceof HTMLInputElement || ev.target instanceof HTMLSelectElement) return;
				if (ev.key === "Escape") this.cb.onClose();
				else if (ev.key === "ArrowLeft") this.cb.onTapZone("left");
				else if (ev.key === "ArrowRight" || ev.key === " ") this.cb.onTapZone("right");
			};
			window.addEventListener("keydown", this.keyHandler);
		}
		destroy() {
			window.removeEventListener("keydown", this.keyHandler);
			window.clearTimeout(this.singleTapTimer);
		}
		get isZoomed() {
			return this.scale > 1.02;
		}
		resetZoom(animate = true) {
			this.scale = 1;
			this.panX = 0;
			this.panY = 0;
			this.applyTransform(animate);
		}
		applyTransform(animate = false) {
			const el = this.zoomTarget();
			if (!el) return;
			this.clampPan();
			el.style.transition = animate ? "transform 0.2s cubic-bezier(0.2, 0.8, 0.2, 1)" : "none";
			if (this.scale <= 1.001) el.style.transform = "";
			else el.style.transform = `translate3d(${this.panX}px, ${this.panY}px, 0) scale(${this.scale})`;
		}
		clampPan() {
			if (this.scale <= 1) {
				this.panX = 0;
				this.panY = 0;
				return;
			}
			const rect = this.viewport.getBoundingClientRect();
			const maxX = (this.scale - 1) * rect.width / 2;
			const maxY = (this.scale - 1) * rect.height / 2;
			this.panX = Math.max(-maxX, Math.min(maxX, this.panX));
			this.panY = Math.max(-maxY, Math.min(maxY, this.panY));
		}
		isInteractiveElement(target) {
			if (!(target instanceof HTMLElement)) return false;
			return Boolean(target.closest("button, a, select, input, [data-clm-interactive]"));
		}
		onTouchStart = (ev) => {
			if (this.isInteractiveElement(ev.target)) return;
			if (ev.touches.length === 2) {
				ev.preventDefault();
				this.trackingSingle = false;
				this.pinching = true;
				const [t1, t2] = [ev.touches[0], ev.touches[1]];
				this.initialPinchDist = Math.hypot(t2.clientX - t1.clientX, t2.clientY - t1.clientY);
				this.initialPinchScale = this.scale;
				const rect = this.viewport.getBoundingClientRect();
				this.initialPinchMidX = (t1.clientX + t2.clientX) / 2 - (rect.left + rect.width / 2);
				this.initialPinchMidY = (t1.clientY + t2.clientY) / 2 - (rect.top + rect.height / 2);
				this.initialPanX = this.panX;
				this.initialPanY = this.panY;
				return;
			}
			if (ev.touches.length === 1 && !this.pinching) {
				const t = ev.touches[0];
				this.trackingSingle = true;
				this.startX = this.lastX = t.clientX;
				this.startY = this.lastY = t.clientY;
				this.startTime = performance.now();
				this.moved = false;
				this.gestureAxis = "undecided";
			}
		};
		onTouchMove = (ev) => {
			if (this.pinching && ev.touches.length === 2) {
				ev.preventDefault();
				const [t1, t2] = [ev.touches[0], ev.touches[1]];
				const dist = Math.hypot(t2.clientX - t1.clientX, t2.clientY - t1.clientY);
				if (this.initialPinchDist > 0) {
					const nextScale = Math.max(1, Math.min(4, this.initialPinchScale * (dist / this.initialPinchDist)));
					const ratio = nextScale / this.initialPinchScale;
					this.scale = nextScale;
					this.panX = this.initialPinchMidX * (1 - ratio) + this.initialPanX * ratio;
					this.panY = this.initialPinchMidY * (1 - ratio) + this.initialPanY * ratio;
					this.applyTransform(false);
				}
				return;
			}
			if (!this.trackingSingle || ev.touches.length !== 1) return;
			const t = ev.touches[0];
			const dx = t.clientX - this.startX;
			const dy = t.clientY - this.startY;
			const stepX = t.clientX - this.lastX;
			const stepY = t.clientY - this.lastY;
			this.lastX = t.clientX;
			this.lastY = t.clientY;
			if (!this.moved && Math.hypot(dx, dy) > 8) {
				this.moved = true;
				this.gestureAxis = Math.abs(dx) >= Math.abs(dy) ? "x" : "y";
			}
			if (!this.moved) return;
			if (this.isZoomed) {
				ev.preventDefault();
				this.panX += stepX;
				this.panY += stepY;
				this.applyTransform(false);
				return;
			}
			if (this.cb.getMode() === "horizontal") {
				ev.preventDefault();
				this.cb.onHorizontalDragMove(dx);
			}
		};
		onTouchEnd = (ev) => {
			if (this.pinching) {
				if (ev.touches.length === 0) {
					this.pinching = false;
					if (this.scale < 1.05) this.resetZoom(true);
					else this.applyTransform(true);
				}
				return;
			}
			if (!this.trackingSingle) return;
			this.trackingSingle = false;
			const dt = Math.max(1, performance.now() - this.startTime);
			const totalDx = this.lastX - this.startX;
			if (this.moved) {
				if (!this.isZoomed && this.cb.getMode() === "horizontal") {
					const velocity = totalDx / dt;
					this.cb.onHorizontalDragEnd(totalDx, velocity);
				}
				return;
			}
			if (this.isInteractiveElement(ev.target)) return;
			ev.preventDefault();
			this.handleTap(this.startX, this.startY);
		};
		onMouseClick = (ev) => {
			if (this.isInteractiveElement(ev.target)) return;
			this.handleTap(ev.clientX, ev.clientY);
		};
		handleTap(clientX, clientY) {
			const now = performance.now();
			const distFromLast = Math.hypot(clientX - this.lastTapX, clientY - this.lastTapY);
			if (now - this.lastTapTime < 280 && distFromLast < 36) {
				window.clearTimeout(this.singleTapTimer);
				this.lastTapTime = 0;
				if (this.isZoomed) this.resetZoom(true);
				else {
					const rect = this.viewport.getBoundingClientRect();
					const offsetX = clientX - (rect.left + rect.width / 2);
					const offsetY = clientY - (rect.top + rect.height / 2);
					this.scale = 2.2;
					this.panX = -offsetX * 1.2;
					this.panY = -offsetY * 1.2;
					this.applyTransform(true);
				}
				return;
			}
			this.lastTapTime = now;
			this.lastTapX = clientX;
			this.lastTapY = clientY;
			window.clearTimeout(this.singleTapTimer);
			this.singleTapTimer = window.setTimeout(() => {
				if (this.isZoomed) {
					this.cb.onTapZone("center");
					return;
				}
				const rect = this.viewport.getBoundingClientRect();
				const ratio = (clientX - rect.left) / Math.max(1, rect.width);
				if (ratio < .3) this.cb.onTapZone("left");
				else if (ratio > .7) this.cb.onTapZone("right");
				else this.cb.onTapZone("center");
			}, 220);
		}
	};
	var READER_STYLE = `
:host {
  all: initial;
  font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
  color: #f4f4f5;
  -webkit-tap-highlight-color: transparent;
  user-select: none;
  -webkit-user-select: none;
}

* {
  box-sizing: border-box;
}

/* 右下角微缩启动入口(阅读器关闭时可见,图标化不啰嗦) */
.clm-fab {
  position: fixed;
  right: 16px;
  bottom: calc(22px + env(safe-area-inset-bottom, 0px));
  z-index: 2147483645;
  width: 46px;
  height: 46px;
  padding: 0;
  border-radius: 23px;
  border: 1px solid rgba(255, 255, 255, 0.16);
  background: rgba(18, 18, 22, 0.88);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5);
  cursor: pointer;
  touch-action: manipulation;
  transition: transform 0.15s ease;
}
.clm-fab:active {
  transform: scale(0.92);
}
.clm-fab.hidden {
  display: none;
}

/* 全屏阅读器根容器(直接锚定 inset: 0 真实铺满区域,避免全屏态下 100dvh 计算溢出视口底部) */
.clm-overlay {
  position: fixed;
  inset: 0;
  z-index: 2147483646;
  background: #09090b;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  overscroll-behavior: none;
}
.clm-overlay.hidden {
  display: none;
}

/* 视口区域 */
.clm-viewport {
  position: relative;
  flex: 1;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

/* 模式 1:横向翻页舞台 */
.clm-viewport.mode-horizontal {
  touch-action: none;
}
.clm-h-track {
  position: relative;
  width: 100%;
  height: 100%;
  will-change: transform;
}
.clm-h-slot {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

/* 模式 2:纵向卷轴容器 */
.clm-viewport.mode-vertical {
  overflow-y: auto;
  overflow-x: hidden;
  -webkit-overflow-scrolling: touch;
  overscroll-behavior-y: contain;
  touch-action: pan-y;
}
.clm-v-list {
  width: 100%;
  max-width: 900px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  transform-origin: center center;
}

/* 模式 3:横向卷轴容器(高度撑满,左右自由连续滚动) */
.clm-viewport.mode-horizontal-scroll {
  overflow-x: auto;
  overflow-y: hidden;
  -webkit-overflow-scrolling: touch;
  overscroll-behavior-x: contain;
  touch-action: pan-x;
}
.clm-viewport.mode-horizontal-scroll.rtl-scroll {
  direction: rtl;
}
.clm-hs-list {
  height: 100%;
  width: max-content;
  display: flex;
  flex-direction: row;
  align-items: stretch;
  transform-origin: center center;
}

.clm-v-chapter-banner {
  padding: 20px 16px 12px;
  text-align: center;
  font-size: 12px;
  color: #71717a;
  background: #09090b;
  border-top: 1px solid rgba(255, 255, 255, 0.06);
}
.clm-hs-chapter-banner {
  height: 100%;
  padding: 16px 10px;
  writing-mode: vertical-rl;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #71717a;
  background: #09090b;
  border-inline-start: 1px solid rgba(255, 255, 255, 0.06);
  direction: ltr;
  flex-shrink: 0;
}

/* 单页图片卡片 */
.clm-page-item {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #09090b;
  flex-shrink: 0;
}
.clm-viewport.mode-horizontal .clm-page-item {
  width: 100%;
  height: 100%;
}
.clm-viewport.mode-vertical .clm-page-item {
  width: 100%;
  min-height: 220px;
}
.clm-viewport.mode-horizontal-scroll .clm-page-item {
  height: 100%;
  width: auto;
  min-width: 160px;
  direction: ltr;
}

.clm-page-media {
  display: block;
  user-select: none;
  -webkit-user-drag: none;
}
.clm-viewport.mode-horizontal .clm-page-media {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}
.clm-viewport.mode-vertical .clm-page-media {
  width: 100%;
  height: auto;
}
.clm-viewport.mode-horizontal-scroll .clm-page-media {
  height: 100%;
  width: auto;
  max-width: none;
}

/* 加载占位与错误重试层(极简数字 + 环形微光) */
.clm-page-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 24px 16px;
  color: #71717a;
  text-align: center;
  min-height: 200px;
  min-width: 160px;
  width: 100%;
  height: 100%;
}
.clm-page-index-badge {
  font-size: 28px;
  font-weight: 600;
  color: rgba(255, 255, 255, 0.2);
  font-variant-numeric: tabular-nums;
}
.clm-progress-text {
  font-size: 12px;
  color: #52525b;
  font-variant-numeric: tabular-nums;
}
.clm-retry-btn {
  margin-top: 4px;
  width: 38px;
  height: 38px;
  border-radius: 19px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  background: rgba(255, 255, 255, 0.08);
  color: #f4f4f5;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
.clm-retry-btn:active {
  background: rgba(255, 255, 255, 0.2);
}

/* 右下角微缩阅读胶囊(HUD 收起时仅显示干净页码) */
.clm-mini-pill {
  position: absolute;
  right: 12px;
  bottom: calc(16px + env(safe-area-inset-bottom, 0px));
  z-index: 10;
  padding: 2px 8px;
  border-radius: 8px;
  background: rgba(0, 0, 0, 0.45);
  color: rgba(255, 255, 255, 0.68);
  font-size: 11px;
  font-variant-numeric: tabular-nums;
  pointer-events: none;
  transition: opacity 0.18s ease;
}
.clm-hud-open .clm-mini-pill {
  opacity: 0;
}

/* ==================== 两块极简设计系统:悬浮顶栏 & 单行悬浮底栏 ==================== */
.clm-topbar,
.clm-bottombar {
  position: absolute;
  left: 12px;
  right: 12px;
  z-index: 20;
  background: rgba(18, 18, 22, 0.84);
  backdrop-filter: blur(16px);
  -webkit-backdrop-filter: blur(16px);
  border: 1px solid rgba(255, 255, 255, 0.09);
  box-shadow: 0 8px 28px rgba(0, 0, 0, 0.45);
  transition: transform 0.22s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.18s ease;
}

.clm-topbar {
  top: calc(14px + env(safe-area-inset-top, 0px));
  height: 46px;
  padding: 0 6px;
  border-radius: 23px;
  display: flex;
  align-items: center;
  gap: 6px;
  transform: translateY(-20px);
  opacity: 0;
  pointer-events: none;
}
.clm-hud-open .clm-topbar {
  transform: translateY(0);
  opacity: 1;
  pointer-events: auto;
}

/* 严格单行悬浮胶囊底栏:额外抬高避开手机底部系统手势防误触区与全屏边栏 */
.clm-bottombar {
  bottom: calc(36px + env(safe-area-inset-bottom, 0px));
  height: 48px;
  padding: 0 8px;
  border-radius: 24px;
  display: flex;
  align-items: center;
  gap: 8px;
  transform: translateY(20px);
  opacity: 0;
  pointer-events: none;
}
.clm-hud-open .clm-bottombar {
  transform: translateY(0);
  opacity: 1;
  pointer-events: auto;
}

/* 纯图标圆形按钮 */
.clm-icon-btn {
  width: 34px;
  height: 34px;
  padding: 0;
  border-radius: 17px;
  border: none;
  background: transparent;
  color: #e4e4e7;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  flex-shrink: 0;
  transition: background 0.15s ease, color 0.15s ease;
}
.clm-icon-btn:active {
  background: rgba(255, 255, 255, 0.16);
}
.clm-icon-btn.active {
  background: rgba(59, 130, 246, 0.22);
  color: #60a5fa;
}
.clm-icon-btn:disabled {
  opacity: 0.28;
  pointer-events: none;
}
.clm-icon-btn svg {
  width: 18px;
  height: 18px;
  stroke: currentColor;
  fill: none;
  stroke-width: 1.9;
  stroke-linecap: round;
  stroke-linejoin: round;
}

.clm-title-wrap {
  flex: 1;
  min-width: 0;
  padding: 0 4px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.clm-comic-title {
  font-size: 13px;
  font-weight: 600;
  color: #fafafa;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.clm-chapter-sub {
  font-size: 10.5px;
  color: #a1a1aa;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.clm-chapter-sub:empty {
  display: none;
}

/* 单行进度滑条与页码 */
.clm-page-counter {
  font-size: 11.5px;
  color: #a1a1aa;
  min-width: 44px;
  text-align: right;
  font-variant-numeric: tabular-nums;
  flex-shrink: 0;
}
.clm-slider {
  flex: 1;
  min-width: 0;
  height: 28px;
  margin: 0;
  accent-color: #60a5fa;
  cursor: pointer;
}
.clm-slider.rtl {
  direction: rtl;
}

.clm-node-actions {
  display: flex;
  align-items: center;
  gap: 2px;
}
.clm-node-actions:empty {
  display: none;
}

/* ==================== 二级弹出面板(阅读设置 Sheet & 章节目录 Sheet) ==================== */
.clm-sheet-backdrop {
  position: absolute;
  inset: 0;
  z-index: 30;
  background: rgba(0, 0, 0, 0.55);
  display: flex;
  align-items: flex-end;
  justify-content: center;
}
.clm-sheet-backdrop.hidden {
  display: none;
}

.clm-sheet {
  width: 100%;
  max-width: 520px;
  background: rgba(24, 24, 28, 0.96);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border-radius: 20px 20px 0 0;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  padding: 10px 16px calc(32px + env(safe-area-inset-bottom, 0px));
  display: flex;
  flex-direction: column;
  gap: 14px;
}
.clm-sheet-handle {
  width: 36px;
  height: 4px;
  border-radius: 2px;
  background: rgba(255, 255, 255, 0.2);
  align-self: center;
  margin-bottom: 2px;
}

/* 设置面板内的分段选择器 */
.clm-seg-group {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 6px;
  padding: 4px;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.06);
}
.clm-seg-btn {
  height: 36px;
  border: none;
  border-radius: 9px;
  background: transparent;
  color: #a1a1aa;
  font-size: 13px;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  cursor: pointer;
  transition: background 0.15s ease, color 0.15s ease;
}
.clm-seg-btn.active {
  background: rgba(255, 255, 255, 0.14);
  color: #fff;
  font-weight: 600;
}

/* 设置面板内的紧凑芯片行 */
.clm-chip-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 8px;
}
.clm-chip-btn {
  height: 48px;
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.08);
  background: rgba(255, 255, 255, 0.04);
  color: #d4d4d8;
  font-size: 11.5px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4px;
  cursor: pointer;
}
.clm-chip-btn svg {
  width: 17px;
  height: 17px;
  stroke: currentColor;
  fill: none;
  stroke-width: 1.8;
  stroke-linecap: round;
  stroke-linejoin: round;
}
.clm-chip-btn:active {
  background: rgba(255, 255, 255, 0.14);
}
.clm-chip-btn.active {
  border-color: rgba(96, 165, 250, 0.55);
  background: rgba(59, 130, 246, 0.18);
  color: #93c5fd;
}
.clm-chip-btn.disabled {
  opacity: 0.32;
  pointer-events: none;
}

/* ==================== 章节目录抽屉(支持搜索、正倒序、百章分段锚点) ==================== */
.clm-drawer {
  max-height: 76dvh;
  gap: 10px;
}
.clm-drawer-toolbar {
  display: flex;
  align-items: center;
  gap: 8px;
}
.clm-search-input {
  flex: 1;
  min-width: 0;
  height: 34px;
  padding: 0 12px;
  border-radius: 17px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  background: rgba(255, 255, 255, 0.06);
  color: #fafafa;
  font-size: 13px;
  outline: none;
}
.clm-search-input::placeholder {
  color: #71717a;
}
.clm-search-input:focus {
  border-color: rgba(96, 165, 250, 0.6);
}

/* 章节分段快速跳转条(超过 40 话自动出现,不截断列表,仅作瞬间电梯定位) */
.clm-range-bar {
  display: flex;
  align-items: center;
  gap: 6px;
  overflow-x: auto;
  padding-bottom: 2px;
  scrollbar-width: none;
}
.clm-range-bar::-webkit-scrollbar {
  display: none;
}
.clm-range-bar.hidden {
  display: none;
}
.clm-range-pill {
  height: 26px;
  padding: 0 10px;
  border-radius: 13px;
  border: 1px solid rgba(255, 255, 255, 0.09);
  background: rgba(255, 255, 255, 0.04);
  color: #a1a1aa;
  font-size: 11.5px;
  font-variant-numeric: tabular-nums;
  white-space: nowrap;
  flex-shrink: 0;
  cursor: pointer;
}
.clm-range-pill.active {
  background: rgba(59, 130, 246, 0.22);
  border-color: rgba(96, 165, 250, 0.5);
  color: #93c5fd;
}

/* 单列清爽章节列表:带序号与最多两行完整标题,百章千章不叠字 */
.clm-chapter-list {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding-right: 2px;
}
.clm-chapter-item {
  width: 100%;
  padding: 10px 12px;
  border-radius: 10px;
  border: none;
  background: rgba(255, 255, 255, 0.03);
  color: #e4e4e7;
  font-size: 13px;
  line-height: 1.35;
  text-align: left;
  display: flex;
  align-items: baseline;
  gap: 10px;
  cursor: pointer;
  flex-shrink: 0;
}
.clm-chapter-item:active {
  background: rgba(255, 255, 255, 0.1);
}
.clm-chapter-item.current {
  background: rgba(59, 130, 246, 0.2);
  color: #93c5fd;
  font-weight: 600;
}
.clm-chap-num {
  font-size: 11.5px;
  color: #71717a;
  font-variant-numeric: tabular-nums;
  min-width: 28px;
  flex-shrink: 0;
}
.clm-chapter-item.current .clm-chap-num {
  color: #60a5fa;
}
.clm-chap-title {
  flex: 1;
  min-width: 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  word-break: break-word;
}
.clm-chapter-empty {
  padding: 28px 0;
  text-align: center;
  font-size: 13px;
  color: #71717a;
}

/* 全局轻加载指示与 Toast */
.clm-loading-banner {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 25;
  padding: 10px 18px;
  border-radius: 20px;
  background: rgba(20, 20, 24, 0.9);
  border: 1px solid rgba(255, 255, 255, 0.1);
  font-size: 12.5px;
  color: #d4d4d8;
  pointer-events: none;
}
.clm-loading-banner.hidden {
  display: none;
}

.clm-toast {
  position: absolute;
  top: calc(62px + env(safe-area-inset-top, 0px));
  left: 50%;
  transform: translateX(-50%);
  z-index: 40;
  max-width: 84vw;
  padding: 6px 14px;
  border-radius: 16px;
  background: rgba(24, 24, 28, 0.92);
  border: 1px solid rgba(255, 255, 255, 0.12);
  color: #f4f4f5;
  font-size: 12.5px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4);
  pointer-events: none;
  transition: opacity 0.18s ease;
}
.clm-toast.error {
  border-color: rgba(239, 68, 68, 0.55);
  color: #fca5a5;
}
.clm-toast.hidden {
  opacity: 0;
  display: none;
}
`;
	var ICONS = {
		book: `<svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" fill="none" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M2 4h7a3 3 0 0 1 3 3v13a2.5 2.5 0 0 0-2.5-2.5H2z"/><path d="M22 4h-7a3 3 0 0 0-3 3v13a2.5 2.5 0 0 1 2.5-2.5H22z"/></svg>`,
		close: `<svg viewBox="0 0 24 24"><path d="M18 6 6 18M6 6l12 12"/></svg>`,
		fullscreenEnter: `<svg viewBox="0 0 24 24"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/></svg>`,
		fullscreenExit: `<svg viewBox="0 0 24 24"><path d="M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 1 2-2h3M3 16h3a2 2 0 0 1 2 2v3"/></svg>`,
		chapters: `<svg viewBox="0 0 24 24"><path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/></svg>`,
		settings: `<svg viewBox="0 0 24 24"><line x1="4" y1="6" x2="20" y2="6"/><line x1="4" y1="12" x2="20" y2="12"/><line x1="4" y1="18" x2="20" y2="18"/><circle cx="9" cy="6" r="2" fill="#18181b"/><circle cx="15" cy="12" r="2" fill="#18181b"/><circle cx="10" cy="18" r="2" fill="#18181b"/></svg>`,
		prevChap: `<svg viewBox="0 0 24 24"><polygon points="19 20 9 12 19 4 19 20"/><line x1="5" y1="19" x2="5" y2="5"/></svg>`,
		nextChap: `<svg viewBox="0 0 24 24"><polygon points="5 4 15 12 5 20 5 4"/><line x1="19" y1="5" x2="19" y2="19"/></svg>`,
		rtl: `<svg viewBox="0 0 24 24"><path d="M20 12H4m0 0 5-5m-5 5 5 5"/></svg>`,
		ltr: `<svg viewBox="0 0 24 24"><path d="M4 12h16m0 0-5-5m5 5-5 5"/></svg>`,
		auto: `<svg viewBox="0 0 24 24"><path d="m12 3 1.9 4.6L18.5 9l-4.6 1.9L12 15.5l-1.9-4.6L5.5 9l4.6-1.4Z"/><path d="M19 16v4m-2-2h4"/></svg>`,
		hd: `<svg viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="14" rx="2.5"/><path d="M7 9v6m4-6v6M7 12h4m3-3v6h2a2 2 0 0 0 2-2v-2a2 2 0 0 0-2-2h-2z"/></svg>`,
		reload: `<svg viewBox="0 0 24 24"><path d="M21 12a9 9 0 1 1-2.64-6.36L21 8"/><path d="M21 3v5h-5"/></svg>`,
		sort: `<svg viewBox="0 0 24 24"><path d="m3 16 4 4 4-4M7 20V4M21 8l-4-4-4 4m4-4v16"/></svg>`,
		locate: `<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="7"/><circle cx="12" cy="12" r="2"/><path d="M12 2v3m0 14v3M2 12h3m14 0h3"/></svg>`
	};
	var WEBTOON_RATIO_THRESHOLD = 2.8;
	var CHAPTER_RANGE_CHUNK = 50;
	var MobileReader = class {
		host;
		shadow;
		matcher;
		fetcher;
		gesture;
		opened = false;
		initialized = false;
		hudOpen = false;
		curChapter = 0;
		curPage = 0;
		prevBodyOverflow = "";
		autoDecided = false;
		ratioSamples = new Map();
		mountedContinuousChapters = new Set();
		continuousItems = new Map();
		intersectionObserver;
		appendingNextChapter = false;
		chapterReversed = false;
		chapterQuery = "";
		fabBtn;
		overlayEl;
		viewportEl;
		hTrackEl;
		hSlots;
		vListEl;
		hsListEl;
		comicTitleEl;
		chapterSubEl;
		miniPillEl;
		pageCounterEl;
		sliderEl;
		fsBtn;
		chaptersBtn;
		settingsBtn;
		prevChapBtn;
		nextChapBtn;
		nodeActionsWrap;
		settingsBackdropEl;
		modeSegBtns;
		dirChipEl;
		autoChipEl;
		origChipEl;
		reloadChipEl;
		drawerBackdropEl;
		chapterSearchEl;
		chapterRangeBarEl;
		chapterListEl;
		loadingBannerEl;
		toastEl;
		toastTimer;
		fsChangeHandler = () => this.syncFullscreenBtn();
		constructor(matcher) {
			this.matcher = matcher;
			this.fetcher = new PageFetcher(matcher, {
				onChaptersUpdated: () => {
					if (!this.drawerBackdropEl.classList.contains("hidden")) this.renderChapterDrawer();
					this.refreshHUD();
				},
				onChapterChanged: (idx) => {
					this.curChapter = idx;
					this.curPage = 0;
					this.refreshHUD();
				},
				onPagesAppended: (chapterIndex, newItems, _done) => {
					this.trySampleFromNodes(chapterIndex, newItems);
					this.onPagesAppended(chapterIndex, newItems);
				},
				onLoadingState: (loading, text) => {
					this.setLoading(loading, text);
				}
			});
			this.host = document.createElement("div");
			this.host.id = "cloomobile-root";
			this.shadow = this.host.attachShadow({ mode: "open" });
			this.buildDOM();
			document.documentElement.appendChild(this.host);
			document.addEventListener("fullscreenchange", this.fsChangeHandler);
			document.addEventListener("webkitfullscreenchange", this.fsChangeHandler);
			EBUS.subscribe("notify-message", (level, msg, duration) => {
				this.showToast(msg, level === "error", duration ?? 2400);
			});
		}
		destroy() {
			this.close();
			document.removeEventListener("fullscreenchange", this.fsChangeHandler);
			document.removeEventListener("webkitfullscreenchange", this.fsChangeHandler);
			this.gesture?.destroy();
			this.intersectionObserver?.disconnect();
			this.fetcher.abort();
			this.matcher.dispose?.();
			this.host.remove();
		}
		async open() {
			if (this.opened) return;
			this.opened = true;
			this.prevBodyOverflow = document.body.style.overflow;
			document.body.style.overflow = "hidden";
			this.fabBtn.classList.add("hidden");
			this.overlayEl.classList.remove("hidden");
			if (ADAPTER.conf.autoFullscreen) this.enterFullscreen();
			this.syncFullscreenBtn();
			this.applyModeClass();
			this.refreshHUD();
			if (!this.initialized) {
				this.initialized = true;
				await this.fetcher.init();
				this.curChapter = this.fetcher.chapterIndex;
				this.curPage = 0;
				this.comicTitleEl.textContent = this.matcher.title(this.fetcher.chapters);
				this.trySampleFromNodes(this.curChapter, this.getCurrentChapter()?.queue ?? []);
				this.rebuildViewportForCurrentMode();
				this.notifyActivePage();
			}
		}
		close() {
			if (!this.opened) return;
			this.opened = false;
			document.body.style.overflow = this.prevBodyOverflow;
			this.overlayEl.classList.add("hidden");
			this.fabBtn.classList.remove("hidden");
			this.setHudOpen(false);
			this.settingsBackdropEl.classList.add("hidden");
			this.drawerBackdropEl.classList.add("hidden");
			this.gesture.resetZoom(false);
			this.exitFullscreenIfActive();
		}
		isFullscreenActive() {
			const doc = document;
			return Boolean(doc.fullscreenElement || doc.webkitFullscreenElement);
		}
		enterFullscreen() {
			if (this.isFullscreenActive()) return;
			const target = document.documentElement;
			try {
				if (target.requestFullscreen) target.requestFullscreen({ navigationUI: "hide" }).catch(() => {});
				else if (target.webkitRequestFullscreen) target.webkitRequestFullscreen();
			} catch {}
		}
		exitFullscreenIfActive() {
			if (!this.isFullscreenActive()) return;
			const doc = document;
			try {
				if (doc.exitFullscreen) doc.exitFullscreen().catch(() => {});
				else if (doc.webkitExitFullscreen) doc.webkitExitFullscreen();
			} catch {}
		}
		toggleFullscreen() {
			if (this.isFullscreenActive()) {
				ADAPTER.updateConf({ autoFullscreen: false });
				this.exitFullscreenIfActive();
			} else {
				ADAPTER.updateConf({ autoFullscreen: true });
				this.enterFullscreen();
			}
			this.syncFullscreenBtn();
		}
		syncFullscreenBtn() {
			if (!this.fsBtn) return;
			const active = this.isFullscreenActive();
			this.fsBtn.innerHTML = active ? ICONS.fullscreenExit : ICONS.fullscreenEnter;
			this.fsBtn.classList.toggle("active", active);
		}
		trySampleFromNodes(chapterIndex, items) {
			if (this.autoDecided || !ADAPTER.conf.autoDetectMode || chapterIndex !== this.curChapter) return;
			for (const imf of items) {
				if (imf.index > 4) break;
				const rect = imf.node.rect;
				if (rect && rect.w > 10 && rect.h > 10) this.recordDimensionSample(imf.index, rect.w, rect.h);
			}
		}
		recordDimensionSample(pageIndex, w, h) {
			if (this.autoDecided || !ADAPTER.conf.autoDetectMode || pageIndex > 4 || w <= 0 || h <= 0) return;
			this.ratioSamples.set(pageIndex, h / w);
			const values = Array.from(this.ratioSamples.values());
			const hasSuperStrip = values.some((r) => r >= 3.2);
			if (!hasSuperStrip && values.length < 2) return;
			this.autoDecided = true;
			const isWebtoon = hasSuperStrip || values.filter((r) => r >= WEBTOON_RATIO_THRESHOLD).length >= Math.ceil(values.length / 2);
			const desired = isWebtoon ? "vertical" : ADAPTER.conf.lastHorizontalMode || "horizontal";
			if (desired !== ADAPTER.conf.readMode) {
				ADAPTER.updateConf({ readMode: desired });
				if (this.opened) {
					this.gesture.resetZoom(false);
					this.applyModeClass();
					this.rebuildViewportForCurrentMode();
					this.refreshHUD();
					this.showToast(isWebtoon ? "自动识别:条漫纵向" : "自动识别:横向模式", false, 1400);
				}
			}
		}
		buildDOM() {
			const styleEl = document.createElement("style");
			styleEl.textContent = READER_STYLE;
			this.fabBtn = document.createElement("button");
			this.fabBtn.className = "clm-fab";
			this.fabBtn.title = "阅读";
			this.fabBtn.innerHTML = ICONS.book;
			this.fabBtn.addEventListener("click", () => void this.open());
			this.overlayEl = document.createElement("div");
			this.overlayEl.className = "clm-overlay hidden";
			this.overlayEl.innerHTML = `
      <header class="clm-topbar" data-clm-interactive="1">
        <button class="clm-icon-btn" data-act="close" title="退出">${ICONS.close}</button>
        <div class="clm-title-wrap">
          <div class="clm-comic-title">…</div>
          <div class="clm-chapter-sub"></div>
        </div>
        <div class="clm-node-actions"></div>
        <button class="clm-icon-btn" data-act="fullscreen" title="全屏">${ICONS.fullscreenEnter}</button>
        <button class="clm-icon-btn" data-act="chapters" title="目录">${ICONS.chapters}</button>
      </header>

      <main class="clm-viewport mode-horizontal">
        <div class="clm-h-track">
          <div class="clm-h-slot" data-slot="left" style="transform: translateX(-100%)"></div>
          <div class="clm-h-slot" data-slot="center" style="transform: translateX(0)"></div>
          <div class="clm-h-slot" data-slot="right" style="transform: translateX(100%)"></div>
        </div>
        <div class="clm-v-list" style="display: none"></div>
        <div class="clm-hs-list" style="display: none"></div>
      </main>

      <div class="clm-mini-pill">0 / 0</div>
      <div class="clm-loading-banner hidden">加载中…</div>
      <div class="clm-toast hidden"></div>

      <footer class="clm-bottombar" data-clm-interactive="1">
        <button class="clm-icon-btn" data-act="prev-chap" title="上一话">${ICONS.prevChap}</button>
        <input class="clm-slider" type="range" min="1" max="1" value="1" />
        <span class="clm-page-counter">0/0</span>
        <button class="clm-icon-btn" data-act="next-chap" title="下一话">${ICONS.nextChap}</button>
        <button class="clm-icon-btn" data-act="open-settings" title="设置">${ICONS.settings}</button>
      </footer>

      <div class="clm-sheet-backdrop hidden" data-sheet="settings" data-clm-interactive="1">
        <div class="clm-sheet">
          <div class="clm-sheet-handle"></div>
          <div class="clm-seg-group">
            <button class="clm-seg-btn" data-mode="horizontal">翻页</button>
            <button class="clm-seg-btn" data-mode="horizontal-scroll">横卷</button>
            <button class="clm-seg-btn" data-mode="vertical">纵卷</button>
          </div>
          <div class="clm-chip-grid">
            <button class="clm-chip-btn" data-act="toggle-dir">
              <span class="clm-chip-icon">${ICONS.rtl}</span>
              <span class="clm-chip-label">右→左</span>
            </button>
            <button class="clm-chip-btn" data-act="toggle-auto">
              <span class="clm-chip-icon">${ICONS.auto}</span>
              <span class="clm-chip-label">自动纵横</span>
            </button>
            <button class="clm-chip-btn" data-act="toggle-orig">
              <span class="clm-chip-icon">${ICONS.hd}</span>
              <span class="clm-chip-label">原图</span>
            </button>
            <button class="clm-chip-btn" data-act="retry-cur">
              <span class="clm-chip-icon">${ICONS.reload}</span>
              <span class="clm-chip-label">重载</span>
            </button>
          </div>
        </div>
      </div>

      <div class="clm-sheet-backdrop hidden" data-sheet="chapters" data-clm-interactive="1">
        <div class="clm-sheet clm-drawer">
          <div class="clm-sheet-handle"></div>
          <div class="clm-drawer-toolbar">
            <input class="clm-search-input" type="search" placeholder="搜索章节…" />
            <button class="clm-icon-btn" data-act="locate-chap" title="定位当前">${ICONS.locate}</button>
            <button class="clm-icon-btn" data-act="sort-chap" title="正倒序">${ICONS.sort}</button>
          </div>
          <div class="clm-range-bar hidden"></div>
          <div class="clm-chapter-list"></div>
        </div>
      </div>
    `;
			this.shadow.append(styleEl, this.fabBtn, this.overlayEl);
			const q = (sel) => this.overlayEl.querySelector(sel);
			this.viewportEl = q(".clm-viewport");
			this.hTrackEl = q(".clm-h-track");
			const slots = Array.from(this.hTrackEl.querySelectorAll(".clm-h-slot"));
			this.hSlots = [
				slots[0],
				slots[1],
				slots[2]
			];
			this.vListEl = q(".clm-v-list");
			this.hsListEl = q(".clm-hs-list");
			this.comicTitleEl = q(".clm-comic-title");
			this.chapterSubEl = q(".clm-chapter-sub");
			this.miniPillEl = q(".clm-mini-pill");
			this.pageCounterEl = q(".clm-page-counter");
			this.sliderEl = q(".clm-slider");
			this.fsBtn = q("[data-act=\"fullscreen\"]");
			this.chaptersBtn = q("[data-act=\"chapters\"]");
			this.settingsBtn = q("[data-act=\"open-settings\"]");
			this.prevChapBtn = q("[data-act=\"prev-chap\"]");
			this.nextChapBtn = q("[data-act=\"next-chap\"]");
			this.nodeActionsWrap = q(".clm-node-actions");
			this.settingsBackdropEl = q("[data-sheet=\"settings\"]");
			this.modeSegBtns = this.settingsBackdropEl.querySelectorAll(".clm-seg-btn");
			this.dirChipEl = q("[data-act=\"toggle-dir\"]");
			this.autoChipEl = q("[data-act=\"toggle-auto\"]");
			this.origChipEl = q("[data-act=\"toggle-orig\"]");
			this.reloadChipEl = q("[data-act=\"retry-cur\"]");
			this.drawerBackdropEl = q("[data-sheet=\"chapters\"]");
			this.chapterSearchEl = q(".clm-search-input");
			this.chapterRangeBarEl = q(".clm-range-bar");
			this.chapterListEl = q(".clm-chapter-list");
			this.loadingBannerEl = q(".clm-loading-banner");
			this.toastEl = q(".clm-toast");
			q("[data-act=\"close\"]").addEventListener("click", () => this.close());
			this.fsBtn.addEventListener("click", () => this.toggleFullscreen());
			this.chaptersBtn.addEventListener("click", () => {
				this.openChapterDrawer();
			});
			this.drawerBackdropEl.addEventListener("click", (e) => {
				if (e.target === this.drawerBackdropEl) this.drawerBackdropEl.classList.add("hidden");
			});
			this.settingsBtn.addEventListener("click", () => {
				this.refreshHUD();
				this.settingsBackdropEl.classList.remove("hidden");
			});
			this.settingsBackdropEl.addEventListener("click", (e) => {
				if (e.target === this.settingsBackdropEl) this.settingsBackdropEl.classList.add("hidden");
			});
			this.modeSegBtns.forEach((btn) => {
				btn.addEventListener("click", () => {
					const mode = btn.dataset.mode;
					this.switchReadMode(mode);
				});
			});
			this.dirChipEl.addEventListener("click", () => this.toggleDirection());
			this.autoChipEl.addEventListener("click", () => {
				const next = !ADAPTER.conf.autoDetectMode;
				ADAPTER.updateConf({ autoDetectMode: next });
				if (next) {
					this.autoDecided = false;
					this.trySampleFromNodes(this.curChapter, this.getCurrentChapter()?.queue ?? []);
				}
				this.refreshHUD();
				this.showToast(next ? "自动纵横识别:开" : "自动纵横识别:关", false, 1300);
			});
			this.origChipEl.addEventListener("click", () => {
				const next = !ADAPTER.conf.fetchOriginal;
				ADAPTER.updateConf({ fetchOriginal: next });
				this.refreshHUD();
				this.showToast(next ? "原图:开" : "原图:关", false, 1300);
			});
			this.reloadChipEl.addEventListener("click", () => {
				const imf = this.getCurrentFetcher();
				if (imf) imf.start(true);
				this.settingsBackdropEl.classList.add("hidden");
			});
			this.chapterSearchEl.addEventListener("input", () => {
				this.chapterQuery = this.chapterSearchEl.value.trim();
				this.renderChapterDrawer();
			});
			q("[data-act=\"sort-chap\"]").addEventListener("click", () => {
				this.chapterReversed = !this.chapterReversed;
				this.renderChapterDrawer();
			});
			q("[data-act=\"locate-chap\"]").addEventListener("click", () => {
				this.scrollCurrentChapterIntoView(true);
			});
			this.prevChapBtn.addEventListener("click", () => void this.jumpChapter(this.curChapter - 1));
			this.nextChapBtn.addEventListener("click", () => void this.jumpChapter(this.curChapter + 1));
			this.sliderEl.addEventListener("input", () => {
				const targetIdx = Math.max(0, Number(this.sliderEl.value) - 1);
				this.jumpToPageInCurrentChapter(targetIdx);
			});
			this.viewportEl.addEventListener("scroll", () => {
				if (ADAPTER.conf.readMode === "horizontal" || !this.opened) return;
				this.onContinuousScroll();
			}, { passive: true });
			this.gesture = new GestureController(this.viewportEl, () => {
				const mode = ADAPTER.conf.readMode;
				if (mode === "horizontal") return this.hSlots[1];
				if (mode === "horizontal-scroll") return this.hsListEl;
				return this.vListEl;
			}, {
				getMode: () => ADAPTER.conf.readMode,
				onHorizontalDragMove: (dx) => this.onHorizontalDragMove(dx),
				onHorizontalDragEnd: (dx, vel) => void this.onHorizontalDragEnd(dx, vel),
				onTapZone: (zone) => void this.onTapZone(zone),
				onStepPage: (delta) => void this.stepPage(delta),
				onClose: () => this.close()
			});
		}
		setHudOpen(open) {
			this.hudOpen = open;
			this.overlayEl.classList.toggle("clm-hud-open", open);
			if (!open) this.settingsBackdropEl.classList.add("hidden");
		}
		setLoading(loading, text) {
			if (text) this.loadingBannerEl.textContent = text;
			this.loadingBannerEl.classList.toggle("hidden", !loading);
		}
		showToast(msg, isError = false, duration = 2e3) {
			window.clearTimeout(this.toastTimer);
			this.toastEl.textContent = msg;
			this.toastEl.classList.toggle("error", isError);
			this.toastEl.classList.remove("hidden");
			this.toastTimer = window.setTimeout(() => {
				this.toastEl.classList.add("hidden");
			}, duration);
		}
		getCurrentChapter() {
			return this.fetcher.chapters[this.curChapter];
		}
		getCurrentFetcher() {
			return this.getCurrentChapter()?.queue[this.curPage];
		}
		switchReadMode(mode) {
			if (mode === ADAPTER.conf.readMode) return;
			this.autoDecided = true;
			const patch = { readMode: mode };
			if (mode === "horizontal" || mode === "horizontal-scroll") patch.lastHorizontalMode = mode;
			ADAPTER.updateConf(patch);
			this.gesture.resetZoom(false);
			this.applyModeClass();
			this.rebuildViewportForCurrentMode();
			this.refreshHUD();
		}
		toggleDirection() {
			const nextRtl = !ADAPTER.conf.rtl;
			ADAPTER.updateConf({ rtl: nextRtl });
			this.applyModeClass();
			if (ADAPTER.conf.readMode === "horizontal") this.renderHorizontalSlots();
			else if (ADAPTER.conf.readMode === "horizontal-scroll") this.mountContinuousFromCurrent();
			this.refreshHUD();
		}
		applyModeClass() {
			const mode = ADAPTER.conf.readMode;
			this.viewportEl.classList.toggle("mode-horizontal", mode === "horizontal");
			this.viewportEl.classList.toggle("mode-horizontal-scroll", mode === "horizontal-scroll");
			this.viewportEl.classList.toggle("mode-vertical", mode === "vertical");
			this.viewportEl.classList.toggle("rtl-scroll", mode === "horizontal-scroll" && ADAPTER.conf.rtl);
			this.hTrackEl.style.display = mode === "horizontal" ? "block" : "none";
			this.vListEl.style.display = mode === "vertical" ? "flex" : "none";
			this.hsListEl.style.display = mode === "horizontal-scroll" ? "flex" : "none";
		}
		rebuildViewportForCurrentMode() {
			if (ADAPTER.conf.readMode === "horizontal") {
				this.clearContinuousDOM();
				this.renderHorizontalSlots();
			} else {
				this.hSlots.forEach((s) => s.innerHTML = "");
				this.mountContinuousFromCurrent();
			}
			this.refreshHUD();
		}
		peekAdjacentCursor(delta) {
			const ch = this.fetcher.chapters[this.curChapter];
			if (!ch) return null;
			const nextPage = this.curPage + delta;
			if (nextPage >= 0 && nextPage < ch.queue.length) return {
				chapterIndex: this.curChapter,
				pageIndex: nextPage
			};
			if (delta === -1 && this.curChapter > 0) {
				const prevCh = this.fetcher.chapters[this.curChapter - 1];
				if (prevCh && prevCh.queue.length > 0) return {
					chapterIndex: this.curChapter - 1,
					pageIndex: prevCh.queue.length - 1
				};
			}
			if (delta === 1 && ch.done && this.curChapter + 1 < this.fetcher.chapters.length) {
				const nextCh = this.fetcher.chapters[this.curChapter + 1];
				if (nextCh && nextCh.queue.length > 0) return {
					chapterIndex: this.curChapter + 1,
					pageIndex: 0
				};
			}
			return null;
		}
		renderHorizontalSlots() {
			if (ADAPTER.conf.readMode !== "horizontal") return;
			const rtl = ADAPTER.conf.rtl;
			const leftDelta = rtl ? 1 : -1;
			const rightDelta = rtl ? -1 : 1;
			const leftCursor = this.peekAdjacentCursor(leftDelta);
			const centerCursor = {
				chapterIndex: this.curChapter,
				pageIndex: this.curPage
			};
			const rightCursor = this.peekAdjacentCursor(rightDelta);
			this.hTrackEl.style.transition = "none";
			this.hTrackEl.style.transform = "translate3d(0, 0, 0)";
			this.fillSlot(this.hSlots[0], leftCursor);
			this.fillSlot(this.hSlots[1], centerCursor);
			this.fillSlot(this.hSlots[2], rightCursor);
		}
		fillSlot(slot, cursor) {
			slot.innerHTML = "";
			if (!cursor) return;
			const imf = this.fetcher.chapters[cursor.chapterIndex]?.queue[cursor.pageIndex];
			if (!imf) return;
			slot.appendChild(this.createPageElement(imf));
		}
		onHorizontalDragMove(dx) {
			const rtl = ADAPTER.conf.rtl;
			const targetDelta = dx > 0 ? rtl ? 1 : -1 : rtl ? -1 : 1;
			const effectiveDx = this.peekAdjacentCursor(targetDelta) !== null ? dx : dx * .28;
			this.hTrackEl.style.transition = "none";
			this.hTrackEl.style.transform = `translate3d(${effectiveDx}px, 0, 0)`;
		}
		async onHorizontalDragEnd(dx, velocity) {
			const width = Math.max(1, this.viewportEl.clientWidth);
			if (!(Math.abs(dx) > width * .18 || Math.abs(velocity) > .35)) {
				await this.animateTrackTo(0);
				return;
			}
			const rtl = ADAPTER.conf.rtl;
			const stepDelta = dx > 0 ? rtl ? 1 : -1 : rtl ? -1 : 1;
			if (this.peekAdjacentCursor(stepDelta) !== null) {
				const targetX = dx > 0 ? width : -width;
				await this.animateTrackTo(targetX);
			} else await this.animateTrackTo(0);
			await this.stepPage(stepDelta);
		}
		animateTrackTo(x) {
			return new Promise((resolve) => {
				this.hTrackEl.style.transition = "transform 0.18s cubic-bezier(0.22, 1, 0.36, 1)";
				this.hTrackEl.style.transform = `translate3d(${x}px, 0, 0)`;
				const timer = window.setTimeout(resolve, 190);
				this.hTrackEl.addEventListener("transitionend", () => {
					window.clearTimeout(timer);
					resolve();
				}, { once: true });
			});
		}
		async onTapZone(zone) {
			if (zone === "center") {
				this.setHudOpen(!this.hudOpen);
				return;
			}
			if (this.hudOpen) {
				this.setHudOpen(false);
				return;
			}
			const mode = ADAPTER.conf.readMode;
			if (mode === "vertical") {
				const h = this.viewportEl.clientHeight * .82;
				const dir = zone === "right" ? 1 : -1;
				this.viewportEl.scrollBy({
					top: dir * h,
					behavior: "smooth"
				});
				return;
			}
			if (mode === "horizontal-scroll") {
				const w = this.viewportEl.clientWidth * .82;
				const dir = zone === "left" ? -1 : 1;
				this.viewportEl.scrollBy({
					left: dir * w,
					behavior: "smooth"
				});
				return;
			}
			const rtl = ADAPTER.conf.rtl;
			if (zone === "left") await this.stepPage(rtl ? 1 : -1);
			else await this.stepPage(rtl ? -1 : 1);
		}
		async stepPage(delta) {
			const ch = this.getCurrentChapter();
			if (!ch) return;
			this.gesture.resetZoom(false);
			const targetPage = this.curPage + delta;
			if (targetPage >= 0 && targetPage < ch.queue.length) {
				this.curPage = targetPage;
				this.renderHorizontalSlots();
				this.notifyActivePage();
				return;
			}
			if (delta === 1) {
				if (!ch.done) {
					this.setLoading(true, "加载中…");
					const gotMore = await this.fetcher.appendNextPage(this.curChapter);
					this.setLoading(false);
					if (gotMore && targetPage < ch.queue.length) {
						this.curPage = targetPage;
						this.renderHorizontalSlots();
						this.notifyActivePage();
						return;
					}
				}
				if (this.curChapter + 1 < this.fetcher.chapters.length) {
					const nextChapIdx = this.curChapter + 1;
					const nextChap = this.fetcher.chapters[nextChapIdx];
					this.setLoading(true, nextChap.displayTitle);
					const ok = await this.fetcher.ensureChapterStarted(nextChapIdx);
					this.setLoading(false);
					if (ok && nextChap.queue.length > 0) {
						this.curChapter = nextChapIdx;
						this.curPage = 0;
						this.renderHorizontalSlots();
						this.notifyActivePage();
						this.showToast(nextChap.displayTitle, false, 1500);
						return;
					}
				}
				this.showToast("已到末页", false, 1300);
				return;
			}
			if (delta === -1) {
				if (this.curChapter > 0) {
					const prevChapIdx = this.curChapter - 1;
					const prevChap = this.fetcher.chapters[prevChapIdx];
					this.setLoading(true, prevChap.displayTitle);
					const ok = await this.fetcher.ensureChapterStarted(prevChapIdx);
					this.setLoading(false);
					if (ok && prevChap.queue.length > 0) {
						this.curChapter = prevChapIdx;
						this.curPage = prevChap.queue.length - 1;
						this.renderHorizontalSlots();
						this.notifyActivePage();
						this.showToast(prevChap.displayTitle, false, 1500);
						return;
					}
				}
				this.showToast("已到首页", false, 1300);
			}
		}
		getActiveContinuousContainer() {
			return ADAPTER.conf.readMode === "horizontal-scroll" ? this.hsListEl : this.vListEl;
		}
		clearContinuousDOM() {
			this.intersectionObserver?.disconnect();
			this.mountedContinuousChapters.clear();
			this.continuousItems.clear();
			this.vListEl.innerHTML = "";
			this.hsListEl.innerHTML = "";
		}
		mountContinuousFromCurrent() {
			this.clearContinuousDOM();
			const isHScroll = ADAPTER.conf.readMode === "horizontal-scroll";
			this.intersectionObserver = new IntersectionObserver((entries) => {
				for (const entry of entries) {
					if (!entry.isIntersecting) continue;
					const el = entry.target;
					const cIdx = Number(el.dataset.chapter);
					const pIdx = Number(el.dataset.page);
					if (!Number.isNaN(cIdx) && !Number.isNaN(pIdx)) {
						this.curChapter = cIdx;
						this.curPage = pIdx;
						this.notifyActivePage();
					}
				}
			}, {
				root: this.viewportEl,
				rootMargin: isHScroll ? "0px -38% 0px -38%" : "-35% 0px -45% 0px",
				threshold: 0
			});
			const ch = this.getCurrentChapter();
			if (!ch) return;
			this.appendChapterToContinuousDOM(this.curChapter, ch.queue, true);
			const key = `${this.curChapter}:${this.curPage}`;
			const targetEl = this.continuousItems.get(key);
			if (targetEl) requestAnimationFrame(() => {
				targetEl.scrollIntoView({
					block: isHScroll ? "nearest" : "start",
					inline: isHScroll ? "start" : "nearest"
				});
			});
		}
		appendChapterToContinuousDOM(chapterIndex, items, isFirstBanner = false) {
			const ch = this.fetcher.chapters[chapterIndex];
			if (!ch) return;
			const isHScroll = ADAPTER.conf.readMode === "horizontal-scroll";
			const container = this.getActiveContinuousContainer();
			if (!this.mountedContinuousChapters.has(chapterIndex)) {
				this.mountedContinuousChapters.add(chapterIndex);
				if (!isFirstBanner || this.fetcher.chapters.length > 1) {
					const banner = document.createElement("div");
					banner.className = isHScroll ? "clm-hs-chapter-banner" : "clm-v-chapter-banner";
					banner.textContent = ch.displayTitle;
					container.appendChild(banner);
				}
			}
			const frag = document.createDocumentFragment();
			for (const imf of items) {
				const key = `${chapterIndex}:${imf.index}`;
				if (this.continuousItems.has(key)) continue;
				const el = this.createPageElement(imf);
				el.dataset.chapter = String(chapterIndex);
				el.dataset.page = String(imf.index);
				this.continuousItems.set(key, el);
				this.intersectionObserver?.observe(el);
				frag.appendChild(el);
			}
			container.appendChild(frag);
		}
		onContinuousScroll() {
			const mode = ADAPTER.conf.readMode;
			let remainPx = Infinity;
			let thresholdPx = 0;
			if (mode === "vertical") {
				const { scrollTop, scrollHeight, clientHeight } = this.viewportEl;
				remainPx = scrollHeight - (scrollTop + clientHeight);
				thresholdPx = clientHeight * 1.5;
			} else if (mode === "horizontal-scroll") {
				const { scrollLeft, scrollWidth, clientWidth } = this.viewportEl;
				remainPx = scrollWidth - (Math.abs(scrollLeft) + clientWidth);
				thresholdPx = clientWidth * 1.5;
			}
			if (remainPx > thresholdPx) return;
			const mountedList = Array.from(this.mountedContinuousChapters).sort((a, b) => a - b);
			const tailChapIdx = mountedList[mountedList.length - 1] ?? this.curChapter;
			const tailChap = this.fetcher.chapters[tailChapIdx];
			if (!tailChap) return;
			if (!tailChap.done) this.fetcher.appendNextPage(tailChapIdx);
			else if (tailChapIdx + 1 < this.fetcher.chapters.length && !this.appendingNextChapter) {
				const nextIdx = tailChapIdx + 1;
				this.appendingNextChapter = true;
				this.fetcher.ensureChapterStarted(nextIdx).then((ok) => {
					if (ok && ADAPTER.conf.readMode !== "horizontal") {
						const nextCh = this.fetcher.chapters[nextIdx];
						this.appendChapterToContinuousDOM(nextIdx, nextCh.queue);
					}
				}).finally(() => {
					this.appendingNextChapter = false;
				});
			}
		}
		onPagesAppended(chapterIndex, newItems) {
			if (!this.opened) return;
			if (ADAPTER.conf.readMode === "horizontal") {
				if (chapterIndex === this.curChapter || Math.abs(chapterIndex - this.curChapter) <= 1) this.renderHorizontalSlots();
			} else if (this.mountedContinuousChapters.has(chapterIndex) && newItems.length > 0) this.appendChapterToContinuousDOM(chapterIndex, newItems);
			else if (this.mountedContinuousChapters.size === 0 && chapterIndex === this.curChapter) this.mountContinuousFromCurrent();
			this.refreshHUD();
		}
		createPageElement(imf) {
			const wrap = document.createElement("div");
			wrap.className = "clm-page-item";
			if (ADAPTER.conf.readMode !== "horizontal" && imf.node.rect?.w && imf.node.rect?.h) wrap.style.aspectRatio = `${imf.node.rect.w} / ${imf.node.rect.h}`;
			const syncUI = () => {
				wrap.innerHTML = "";
				if (imf.stage === FetchState.DONE) {
					wrap.style.aspectRatio = "";
					const mediaEl = this.buildMediaNode(imf);
					wrap.appendChild(mediaEl);
					return;
				}
				const stateBox = document.createElement("div");
				stateBox.className = "clm-page-state";
				const badge = document.createElement("div");
				badge.className = "clm-page-index-badge";
				badge.textContent = `${imf.index + 1}`;
				stateBox.appendChild(badge);
				if (imf.stage === FetchState.FAILED) {
					const retryBtn = document.createElement("button");
					retryBtn.className = "clm-retry-btn";
					retryBtn.dataset.clmInteractive = "1";
					retryBtn.title = imf.failedReason || "重试";
					retryBtn.innerHTML = ICONS.reload;
					retryBtn.addEventListener("click", (ev) => {
						ev.stopPropagation();
						imf.start(true);
					});
					stateBox.appendChild(retryBtn);
				} else if (imf.downloadState.total > 0 && imf.downloadState.loaded > 0) {
					const pct = Math.min(99, Math.round(imf.downloadState.loaded / imf.downloadState.total * 100));
					const prog = document.createElement("div");
					prog.className = "clm-progress-text";
					prog.textContent = `${pct}%`;
					stateBox.appendChild(prog);
				}
				wrap.appendChild(stateBox);
			};
			imf.onStateChange = () => {
				if (wrap.isConnected) syncUI();
			};
			syncUI();
			return wrap;
		}
		buildMediaNode(imf) {
			if (imf.contentType === "ugoira/ugoira" && imf.data instanceof SubData) {
				if (!customElements.get("ugoira-element")) customElements.define("ugoira-element", HTMLUgoiraElement);
				const ugoira = document.createElement("ugoira-element");
				ugoira.className = "clm-page-media";
				const frameDelays = imf.data.extra ?? [];
				const delayMap = new Map(frameDelays.map((f) => [f.file, f.delay]));
				ugoira.frames = imf.data.list.filter((item) => item.contentType.startsWith("image")).map((item) => ({
					name: item.name,
					delay: delayMap.get(item.name) ?? 60,
					mimeType: item.contentType,
					data: item.data
				}));
				return ugoira;
			}
			const src = imf.node.blobSrc || imf.node.originSrc || imf.node.thumbnailSrc;
			const ext = imf.node.mimeType?.split("/")[1] || src.split(".").pop()?.split("?")[0] || "";
			if (imf.node.mimeType?.startsWith("video/") || isVideo(ext.toLowerCase())) {
				const video = document.createElement("video");
				video.className = "clm-page-media";
				video.src = src;
				video.controls = true;
				video.playsInline = true;
				video.loop = true;
				video.dataset.clmInteractive = "1";
				return video;
			}
			const img = document.createElement("img");
			img.className = "clm-page-media";
			img.decoding = "async";
			img.src = src;
			img.alt = imf.node.title || `${imf.index + 1}`;
			img.addEventListener("load", () => {
				if (imf.chapterIndex === this.curChapter && img.naturalWidth > 0 && img.naturalHeight > 0) {
					if (!imf.node.rect) imf.node.rect = {
						w: img.naturalWidth,
						h: img.naturalHeight
					};
					this.recordDimensionSample(imf.index, img.naturalWidth, img.naturalHeight);
				}
			}, { once: true });
			return img;
		}
		async jumpChapter(targetChapIdx) {
			if (targetChapIdx < 0 || targetChapIdx >= this.fetcher.chapters.length) return;
			this.drawerBackdropEl.classList.add("hidden");
			this.gesture.resetZoom(false);
			await this.fetcher.switchToChapter(targetChapIdx);
			this.curChapter = targetChapIdx;
			this.curPage = 0;
			this.rebuildViewportForCurrentMode();
			this.notifyActivePage();
		}
		jumpToPageInCurrentChapter(pageIdx) {
			const ch = this.getCurrentChapter();
			if (!ch || pageIdx < 0 || pageIdx >= ch.queue.length) return;
			this.curPage = pageIdx;
			this.gesture.resetZoom(false);
			const mode = ADAPTER.conf.readMode;
			if (mode === "horizontal") this.renderHorizontalSlots();
			else this.continuousItems.get(`${this.curChapter}:${pageIdx}`)?.scrollIntoView({
				block: mode === "horizontal-scroll" ? "nearest" : "start",
				inline: mode === "horizontal-scroll" ? "start" : "nearest"
			});
			this.notifyActivePage();
		}
		notifyActivePage() {
			this.fetcher.onActivePage(this.curChapter, this.curPage);
			this.refreshHUD();
		}
		refreshHUD() {
			const ch = this.getCurrentChapter();
			const totalLoaded = ch?.queue.length ?? 0;
			const pageNum = totalLoaded > 0 ? this.curPage + 1 : 0;
			const counterText = `${pageNum}/${totalLoaded}${ch && !ch.done ? "+" : ""}`;
			this.chapterSubEl.textContent = this.fetcher.chapters.length > 1 && ch ? ch.displayTitle : "";
			this.miniPillEl.textContent = counterText;
			this.pageCounterEl.textContent = counterText;
			this.sliderEl.max = String(Math.max(1, totalLoaded));
			this.sliderEl.value = String(Math.max(1, pageNum));
			const mode = ADAPTER.conf.readMode;
			const isHorizontalAny = mode === "horizontal" || mode === "horizontal-scroll";
			this.sliderEl.classList.toggle("rtl", isHorizontalAny && ADAPTER.conf.rtl);
			const hasMultiChapters = this.fetcher.chapters.length > 1;
			this.chaptersBtn.style.display = hasMultiChapters ? "inline-flex" : "none";
			this.prevChapBtn.style.display = hasMultiChapters ? "inline-flex" : "none";
			this.nextChapBtn.style.display = hasMultiChapters ? "inline-flex" : "none";
			this.prevChapBtn.disabled = this.curChapter <= 0;
			this.nextChapBtn.disabled = this.curChapter >= this.fetcher.chapters.length - 1;
			this.modeSegBtns.forEach((btn) => {
				btn.classList.toggle("active", btn.dataset.mode === mode);
			});
			this.dirChipEl.classList.toggle("disabled", !isHorizontalAny);
			this.dirChipEl.classList.toggle("active", isHorizontalAny && ADAPTER.conf.rtl);
			const dirIconEl = this.dirChipEl.querySelector(".clm-chip-icon");
			const dirLabelEl = this.dirChipEl.querySelector(".clm-chip-label");
			if (dirIconEl) dirIconEl.innerHTML = ADAPTER.conf.rtl ? ICONS.rtl : ICONS.ltr;
			if (dirLabelEl) dirLabelEl.textContent = ADAPTER.conf.rtl ? "右→左" : "左→右";
			this.autoChipEl.classList.toggle("active", ADAPTER.conf.autoDetectMode);
			this.origChipEl.classList.toggle("active", ADAPTER.conf.fetchOriginal);
			this.nodeActionsWrap.innerHTML = "";
			const curImf = this.getCurrentFetcher();
			if (curImf && curImf.node.actions.length > 0) for (const act of curImf.node.actions) {
				const btn = document.createElement("button");
				btn.className = "clm-icon-btn";
				btn.textContent = act.icon;
				btn.title = act.description;
				btn.addEventListener("click", () => void act.run(curImf.node, btn));
				this.nodeActionsWrap.appendChild(btn);
			}
		}
		openChapterDrawer() {
			this.renderChapterDrawer();
			this.drawerBackdropEl.classList.remove("hidden");
			requestAnimationFrame(() => {
				this.scrollCurrentChapterIntoView(false);
			});
		}
		scrollCurrentChapterIntoView(smooth) {
			this.chapterListEl.querySelector(".clm-chapter-item.current")?.scrollIntoView({
				block: "center",
				behavior: smooth ? "smooth" : "instant"
			});
		}
		renderChapterDrawer() {
			const total = this.fetcher.chapters.length;
			const queryLower = this.chapterQuery.toLowerCase();
			let entries = this.fetcher.chapters.map((ch, idx) => ({
				ch,
				idx
			}));
			if (this.chapterReversed) entries.reverse();
			if (queryLower) entries = entries.filter(({ ch, idx }) => ch.displayTitle.toLowerCase().includes(queryLower) || String(idx + 1).includes(queryLower));
			this.chapterRangeBarEl.innerHTML = "";
			if (total > 40 && !queryLower) {
				this.chapterRangeBarEl.classList.remove("hidden");
				const groupCount = Math.ceil(total / CHAPTER_RANGE_CHUNK);
				const groupIndices = Array.from({ length: groupCount }, (_, g) => g);
				if (this.chapterReversed) groupIndices.reverse();
				for (const g of groupIndices) {
					const startIdx = g * CHAPTER_RANGE_CHUNK;
					const endIdx = Math.min(total - 1, startIdx + CHAPTER_RANGE_CHUNK - 1);
					const targetIdx = this.chapterReversed ? endIdx : startIdx;
					const pill = document.createElement("button");
					pill.className = "clm-range-pill" + (this.curChapter >= startIdx && this.curChapter <= endIdx ? " active" : "");
					pill.textContent = this.chapterReversed ? `${endIdx + 1}-${startIdx + 1}` : `${startIdx + 1}-${endIdx + 1}`;
					pill.addEventListener("click", () => {
						this.chapterRangeBarEl.querySelectorAll(".clm-range-pill").forEach((p) => p.classList.remove("active"));
						pill.classList.add("active");
						this.chapterListEl.querySelector(`[data-chap-idx="${targetIdx}"]`)?.scrollIntoView({
							block: "start",
							behavior: "smooth"
						});
					});
					this.chapterRangeBarEl.appendChild(pill);
				}
			} else this.chapterRangeBarEl.classList.add("hidden");
			this.chapterListEl.innerHTML = "";
			if (entries.length === 0) {
				const empty = document.createElement("div");
				empty.className = "clm-chapter-empty";
				empty.textContent = "无匹配章节";
				this.chapterListEl.appendChild(empty);
				return;
			}
			const frag = document.createDocumentFragment();
			for (const { ch, idx } of entries) {
				const btn = document.createElement("button");
				btn.className = "clm-chapter-item" + (idx === this.curChapter ? " current" : "");
				btn.dataset.chapIdx = String(idx);
				const numSpan = document.createElement("span");
				numSpan.className = "clm-chap-num";
				numSpan.textContent = `#${idx + 1}`;
				const titleSpan = document.createElement("span");
				titleSpan.className = "clm-chap-title";
				titleSpan.textContent = ch.displayTitle;
				btn.append(numSpan, titleSpan);
				btn.addEventListener("click", () => void this.jumpChapter(idx));
				frag.appendChild(btn);
			}
			this.chapterListEl.appendChild(frag);
		}
	};
	var modules = Object.assign({
		"./platform/matchers/18comic.ts": _18comic_exports,
		"./platform/matchers/3hentai.ts": _3hentai_exports,
		"./platform/matchers/akuma.ts": akuma_exports,
		"./platform/matchers/arca.ts": arca_exports,
		"./platform/matchers/artstation.ts": artstation_exports,
		"./platform/matchers/asmhentai.ts": asmhentai_exports,
		"./platform/matchers/bilibili.ts": bilibili_exports,
		"./platform/matchers/colamanga.ts": colamanga_exports,
		"./platform/matchers/cosplaytele-parser.ts": cosplaytele_parser_exports,
		"./platform/matchers/cosplaytele.ts": cosplaytele_exports,
		"./platform/matchers/danbooru.ts": danbooru_exports,
		"./platform/matchers/douban.ts": douban_exports,
		"./platform/matchers/eahentai.ts": eahentai_exports,
		"./platform/matchers/ehentai.ts": ehentai_exports,
		"./platform/matchers/github.ts": github_exports,
		"./platform/matchers/hanime1.ts": hanime1_exports,
		"./platform/matchers/hdoujin.ts": hdoujin_exports,
		"./platform/matchers/hentainexus.ts": hentainexus_exports,
		"./platform/matchers/hentaizap.ts": hentaizap_exports,
		"./platform/matchers/hitomi.ts": hitomi_exports,
		"./platform/matchers/im-hentai.ts": im_hentai_exports,
		"./platform/matchers/instagram.ts": instagram_exports,
		"./platform/matchers/jandan.ts": jandan_exports,
		"./platform/matchers/komiic.ts": komiic_exports,
		"./platform/matchers/konachan.ts": konachan_exports,
		"./platform/matchers/kone.ts": kone_exports,
		"./platform/matchers/kuaikanmanhua.ts": kuaikanmanhua_exports,
		"./platform/matchers/mangacopy.ts": mangacopy_exports,
		"./platform/matchers/mangadex.ts": mangadex_exports,
		"./platform/matchers/mangapark.ts": mangapark_exports,
		"./platform/matchers/mangatoto.ts": mangatoto_exports,
		"./platform/matchers/manhuagui.ts": manhuagui_exports,
		"./platform/matchers/mh160.ts": mh160_exports,
		"./platform/matchers/miniserve.ts": miniserve_exports,
		"./platform/matchers/mycomic.ts": mycomic_exports,
		"./platform/matchers/nhentai.ts": nhentai_exports,
		"./platform/matchers/niyaniya.ts": niyaniya_exports,
		"./platform/matchers/pawchive.ts": pawchive_exports,
		"./platform/matchers/pinterest.ts": pinterest_exports,
		"./platform/matchers/pixiv.ts": pixiv_exports,
		"./platform/matchers/redgifs.ts": redgifs_exports,
		"./platform/matchers/rokuhentai.ts": rokuhentai_exports,
		"./platform/matchers/se8.ts": se8_exports,
		"./platform/matchers/seqingman.ts": seqingman_exports,
		"./platform/matchers/steam.ts": steam_exports,
		"./platform/matchers/twitter.ts": twitter_exports,
		"./platform/matchers/wnacg.ts": wnacg_exports,
		"./platform/matchers/yabai.ts": yabai_exports,
		"./platform/matchers/yandere.ts": yandere_exports,
		"./platform/matchers/ykmh.ts": ykmh_exports
	});
	for (const path in modules) modules[path];
	var activeReader;
	var debouncer = new Debouncer();
	function teardown() {
		if (activeReader) {
			activeReader.destroy();
			activeReader = void 0;
		}
		EBUS.reset();
	}
	function bootstrap() {
		if (window.self !== window.top) return;
		debouncer.addEvent("URL_BOOT", () => {
			teardown();
			const setup = ADAPTER.findMatcher(window.location.href);
			if (!setup) return;
			activeReader = new MobileReader(setup.constructor());
			if (ADAPTER.conf.autoOpen) activeReader.open();
		}, 120);
	}
	_GM_registerMenuCommand?.("打开阅读器", () => {
		if (!activeReader) bootstrap();
		setTimeout(() => void activeReader?.open(), 150);
	});
	_GM_registerMenuCommand?.("切换进入页面自动打开阅读器", () => {
		const next = !ADAPTER.conf.autoOpen;
		ADAPTER.updateConf({ autoOpen: next });
		alert(`cloomobile:自动打开阅读器已${next ? "开启" : "关闭"}`);
	});
	var lastHref = window.location.href;
	new MutationObserver(() => {
		if (window.location.href !== lastHref) {
			lastHref = window.location.href;
			bootstrap();
		}
	}).observe(document.documentElement, {
		subtree: true,
		childList: true
	});
	bootstrap();
})(zip);