import { s as DEFAULT_BROWSER_VERSIONS, y as LANGUAGES } from "./constants-DgZl8nng.js";
import upath from "upath";
import childProcess from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import util from "node:util";
import { codeFrameColumns } from "@babel/code-frame";
import { evaluate, parse } from "@humanwhocodes/momoa";
import { Ajv } from "ajv";
import formatsPlugin from "ajv-formats";
import { XMLParser } from "fast-xml-parser";
import StreamZip from "node-stream-zip";
import osLocale from "os-locale";
import resolvePkg from "resolve-pkg";
import { titleCase } from "title-case";
import tmp from "tmp";
import { blueBright, gray, greenBright, red, redBright, yellowBright } from "yoctocolors";
import { Console } from "node:console";
import debug from "debug";
import yoctoSpinner from "yocto-spinner";
//#region src/logger.ts
const isUnicodeSupported = process.platform !== "win32" || Boolean(process.env.WT_SESSION);
const randomBookSymbol = [
	"📕",
	"📗",
	"📘",
	"📙"
][Math.floor(Math.random() * 4)];
const spinnerFrames = isUnicodeSupported ? [
	"▁▁╱ ",
	"▁║▁ ",
	"╲▁▁ ",
	"▁▁▁ ",
	"▁▁▁ ",
	"▁▁▁ "
] : [
	"-   ",
	"\\   ",
	"|   ",
	"/   "
];
const infoSymbol = blueBright("INFO");
const successSymbol = greenBright("SUCCESS");
const warnSymbol = yellowBright("WARN");
const errorSymbol = redBright("ERROR");
var Logger = class Logger {
	/**
	* 0: silent 1: info 2: verbose 3: debug
	*/
	static #logLevel = 0;
	static #loggerInstance;
	static #nonBlockingLogPrinted = false;
	static #customLogger;
	static #logPrefix;
	static #stdin = process.stdin;
	static #stdout = process.stdout;
	static #stderr = process.stderr;
	static #signal;
	/**
	* True in the forked build subprocess (renderMode: docker),
	* which logs non-interactively.
	*/
	static #containerForkMode = false;
	static {
		this.debug = debug("vs-cli");
	}
	static get #console() {
		if (this.#customLogger) return {
			...this.#customLogger,
			log: () => {}
		};
		return new Console({
			stdout: this.#stdout,
			stderr: this.#stderr
		});
	}
	static get #spinner() {
		return this.#loggerInstance && this.#loggerInstance.#spinnerInstance;
	}
	static get stdin() {
		return this.#stdin;
	}
	static get stdout() {
		return this.#stdout;
	}
	static get stderr() {
		return this.#stderr;
	}
	static get signal() {
		return this.#signal;
	}
	static get isInteractive() {
		return !this.#customLogger && this.#stderr.isTTY && process.env.TERM !== "dumb" && !("CI" in process.env) && !import.meta.env?.VITEST && !debug.enabled("vs-cli") && !this.#containerForkMode;
	}
	static startLogging(text) {
		if (this.#logLevel === 0) return;
		if (!this.isInteractive) {
			this.logInfo(text);
			return;
		}
		if (this.#loggerInstance) {
			this.#loggerInstance.#spinnerInstance.text = text;
			return this.#loggerInstance;
		}
		this.#loggerInstance = new Logger(this.#stderr);
		this.#loggerInstance.#start(text);
		return this.#loggerInstance;
	}
	static suspendLogging(text) {
		if (this.#logLevel === 0) return;
		if (!this.#spinner || !this.isInteractive) {
			this.logInfo(text);
			return;
		}
		const currentMsg = this.#spinner?.text;
		this.logUpdate(currentMsg);
		this.#spinner.stop(`${infoSymbol} ${text}\n`);
		return { [Symbol.dispose]() {
			if (Logger.isInteractive) {
				Logger.#console.log("");
				Logger.#spinner?.start(currentMsg);
				Logger.#nonBlockingLogPrinted = true;
			}
		} };
	}
	static log(...messages) {
		if (this.#logLevel < 1) return;
		Logger.#console.log(...messages);
	}
	static logUpdate(...messages) {
		if (!this.#spinner || !this.isInteractive) {
			this.logInfo(...messages);
			return;
		}
		this.#spinner.stop(this.#nonBlockingLogPrinted ? void 0 : `${infoSymbol} ${this.#spinner.text}`);
		this.#spinner.start(messages.join(" "));
		this.#nonBlockingLogPrinted = false;
	}
	/**
	* Update the text of the running spinner in place without printing a
	* checkpoint line. Unlike `logUpdate`, this method does nothing when the
	* output is not interactive, so it is safe to call at a high frequency.
	*/
	static logUpdateProgress(...messages) {
		if (this.#logLevel < 1 || !this.#spinner || !this.isInteractive) return;
		this.#spinner.text = messages.join(" ");
		this.#nonBlockingLogPrinted = true;
	}
	static getMessage(message, symbol) {
		return !this.#customLogger && symbol ? `${symbol} ${message}` : message;
	}
	static #nonBlockingLog(logMethod, message) {
		if (!this.#spinner || !this.isInteractive) {
			const line = this.#logPrefix ? `${this.#logPrefix} ${message}` : message;
			if (this.#logLevel >= 3) this.debug(line);
			else this.#console[logMethod](line);
			return;
		}
		this.logUpdate(this.#spinner.text);
		this.#nonBlockingLogPrinted = true;
		this.#spinner.stop(message);
		this.#spinner.start();
	}
	static logSuccess(...messages) {
		if (this.#logLevel < 1) return;
		this.#nonBlockingLog("info", this.getMessage(messages.join(" "), successSymbol));
	}
	static logError(...messages) {
		if (this.#logLevel < 1) return;
		this.#nonBlockingLog("error", this.getMessage(messages.join(" "), errorSymbol));
	}
	static logWarn(...messages) {
		if (this.#logLevel < 1) return;
		this.#nonBlockingLog("warn", this.getMessage(messages.join(" "), warnSymbol));
	}
	static logInfo(...messages) {
		if (this.#logLevel < 1) return;
		this.#nonBlockingLog("info", this.getMessage(messages.join(" "), infoSymbol));
	}
	static logVerbose(...messages) {
		if (this.#logLevel < 2) return;
		this.#nonBlockingLog("info", this.getMessage(messages.join(" ")));
	}
	static setLogOptions({ logLevel, logger, stdin, stdout, stderr, signal, containerForkMode }) {
		if (logLevel) {
			this.#logLevel = {
				silent: 0,
				info: 1,
				verbose: 2,
				debug: 3
			}[logLevel];
			if (this.#logLevel >= 3) debug.enable("vs-cli");
		}
		if (logger) this.#customLogger = logger;
		if (stdin) this.#stdin = stdin;
		if (stdout) this.#stdout = stdout;
		if (stderr) this.#stderr = stderr;
		if (signal) this.#signal = signal;
		if (containerForkMode !== void 0) this.#containerForkMode = containerForkMode;
	}
	static setLogPrefix(prefix) {
		this.#logPrefix = prefix;
	}
	#spinnerInstance;
	#disposeSpinnerCleanupHandler;
	constructor(stream) {
		this.#spinnerInstance = yoctoSpinner({
			handleSignals: false,
			spinner: {
				frames: spinnerFrames,
				interval: 80
			},
			color: "gray",
			stream
		});
	}
	#start(text) {
		this.#spinnerInstance.start(text);
		this.#disposeSpinnerCleanupHandler = registerCleanupHandler("Stopping spinner", () => {
			this.#spinnerInstance.stop();
		});
	}
	[Symbol.dispose]() {
		this.#disposeSpinnerCleanupHandler?.();
		this.#spinnerInstance.stop(Logger.#nonBlockingLogPrinted ? void 0 : `${infoSymbol} ${this.#spinnerInstance.text}`);
		Logger.#loggerInstance = void 0;
	}
};
//#endregion
//#region schemas/pub-manifest/module/bcp.schema.json
var bcp_schema_default = {
	$schema: "http://json-schema.org/draft-07/schema#",
	$id: "https://www.w3.org/ns/pub-schema/manifest/module/bcp.schema.json",
	title: "BCP47 Language tag",
	type: "string",
	pattern: "^((?:(en-GB-oed|i-ami|i-bnn|i-default|i-enochian|i-hak|i-klingon|i-lux|i-mingo|i-navajo|i-pwn|i-tao|i-tay|i-tsu|sgn-BE-FR|sgn-BE-NL|sgn-CH-DE)|(art-lojban|cel-gaulish|no-bok|no-nyn|zh-guoyu|zh-hakka|zh-min|zh-min-nan|zh-xiang))|((?:([A-Za-z]{2,3}(-(?:[A-Za-z]{3}(-[A-Za-z]{3}){0,2}))?)|[A-Za-z]{4}|[A-Za-z]{5,8})(-(?:[A-Za-z]{4}))?(-(?:[A-Za-z]{2}|[0-9]{3}))?(-(?:[A-Za-z0-9]{5,8}|[0-9][A-Za-z0-9]{3}))*(-(?:[0-9A-WY-Za-wy-z](-[A-Za-z0-9]{2,8})+))*(-(?:x(-[A-Za-z0-9]{1,8})+))?)|(?:x(-[A-Za-z0-9]{1,8})+))$"
};
//#endregion
//#region schemas/pub-manifest/module/context.schema.json
var context_schema_default = {
	$schema: "http://json-schema.org/draft-07/schema#",
	$id: "https://www.w3.org/ns/pub-schema/manifest/module/context.schema.json",
	title: "Publication Contexts",
	type: "array",
	items: [{ "const": "https://schema.org" }, { "const": "https://www.w3.org/ns/pub-context" }],
	additionalItems: { "anyOf": [
		{ "type": "string" },
		{
			"type": "object",
			"properties": {
				"language": { "$ref": "bcp.schema.json" },
				"direction": false
			},
			"required": ["language"]
		},
		{
			"type": "object",
			"properties": {
				"direction": {
					"type": "string",
					"enum": ["ltr", "rtl"]
				},
				"language": false
			},
			"required": ["direction"]
		},
		{
			"type": "object",
			"properties": {
				"language": { "$ref": "bcp.schema.json" },
				"direction": {
					"type": "string",
					"enum": ["ltr", "rtl"]
				}
			},
			"required": ["language", "direction"]
		},
		{
			"type": "object",
			"properties": {
				"language": false,
				"direction": false
			}
		}
	] }
};
//#endregion
//#region schemas/pub-manifest/module/contributor-object.schema.json
var contributor_object_schema_default = {
	$schema: "http://json-schema.org/draft-07/schema#",
	$id: "https://www.w3.org/ns/pub-schema/manifest/module/contributor-object.schema.json",
	title: "Contributor Object",
	type: "object",
	properties: {
		"name": { "$ref": "localizable.schema.json" },
		"id": { "$ref": "url.schema.json" },
		"type": { "oneOf": [{
			"type": "string",
			"enum": ["Person", "Organization"],
			"default": "Person"
		}, {
			"type": "array",
			"items": { "type": "string" },
			"contains": { "enum": ["Person", "Organization"] }
		}] },
		"url": { "$ref": "url.schema.json" },
		"identifier": {
			"type": "array",
			"items": { "type": "string" }
		}
	},
	required: ["name"]
};
//#endregion
//#region schemas/pub-manifest/module/contributor.schema.json
var contributor_schema_default = {
	$schema: "http://json-schema.org/draft-07/schema#",
	$id: "https://www.w3.org/ns/pub-schema/manifest/module/contributor.schema.json",
	title: "Contributor",
	anyOf: [
		{ "type": "string" },
		{
			"type": "array",
			"items": { "anyOf": [{ "type": "string" }, { "$ref": "contributor-object.schema.json" }] }
		},
		{ "$ref": "contributor-object.schema.json" }
	]
};
//#endregion
//#region schemas/pub-manifest/module/date.schema.json
var date_schema_default = {
	$schema: "http://json-schema.org/draft-07/schema#",
	$id: "https://www.w3.org/ns/pub-schema/manifest/module/date.schema.json",
	title: "Dates",
	type: "string",
	format: "date-time"
};
//#endregion
//#region schemas/pub-manifest/module/duration.schema.json
var duration_schema_default = {
	$schema: "http://json-schema.org/draft-07/schema#",
	$id: "https://www.w3.org/ns/pub-schema/manifest/module/duration.schema.json",
	title: "Duration",
	type: "string",
	pattern: "^P(?!$)((\\d+Y)|(\\d+\\.\\d+Y$))?((\\d+M)|(\\d+\\.\\d+M$))?((\\d+W)|(\\d+\\.\\d+W$))?((\\d+D)|(\\d+\\.\\d+D$))?(T(?=\\d)((\\d+H)|(\\d+\\.\\d+H$))?((\\d+M)|(\\d+\\.\\d+M$))?(\\d+(\\.\\d+)?S)?)??$"
};
//#endregion
//#region schemas/pub-manifest/module/item-lists.schema.json
var item_lists_schema_default = {
	$schema: "http://json-schema.org/draft-07/schema#",
	$id: "https://www.w3.org/ns/pub-schema/manifest/module/item-lists.schema.json",
	title: "Lists of ItemList",
	oneOf: [{ "$ref": "ItemList.schema.json" }, {
		"type": "array",
		"items": { "$ref": "ItemList.schema.json" }
	}]
};
//#endregion
//#region schemas/pub-manifest/module/ItemList.schema.json
var ItemList_schema_default = {
	$schema: "http://json-schema.org/draft-07/schema#",
	$id: "https://www.w3.org/ns/pub-schema/manifest/module/ItemList.schema.json",
	title: "schema.org ItemList object",
	type: "object",
	properties: {
		"type": { "oneOf": [{
			"type": "string",
			"const": "ItemList"
		}, {
			"type": "array",
			"items": { "type": "string" },
			"contains": { "const": "ItemList" }
		}] },
		"itemListElement": {
			"type": ["array"],
			"items": { "type": "string" }
		}
	},
	required: ["type", "itemListElement"]
};
//#endregion
//#region schemas/pub-manifest/module/language.schema.json
var language_schema_default = {
	$schema: "http://json-schema.org/draft-07/schema#",
	$id: "https://www.w3.org/ns/pub-schema/manifest/module/language.schema.json",
	title: "Languages",
	oneOf: [{ "$ref": "bcp.schema.json" }, {
		"type": "array",
		"items": { "$ref": "bcp.schema.json" }
	}]
};
//#endregion
//#region schemas/pub-manifest/module/link.schema.json
var link_schema_default = {
	$schema: "http://json-schema.org/draft-07/schema#",
	$id: "https://www.w3.org/ns/pub-schema/manifest/module/link.schema.json",
	title: "Publication Links",
	type: "object",
	properties: {
		"type": { "oneOf": [{
			"type": "string",
			"const": "LinkedResource"
		}, {
			"type": "array",
			"items": { "type": "string" },
			"contains": { "const": "LinkedResource" }
		}] },
		"url": { "$ref": "url.schema.json" },
		"encodingFormat": { "type": "string" },
		"name": { "$ref": "localizable.schema.json" },
		"description": { "anyOf": [{ "type": "string" }, { "$ref": "localizable-object.schema.json" }] },
		"rel": {
			"type": ["string", "array"],
			"items": { "type": "string" }
		},
		"integrity": { "type": "string" },
		"duration": { "$ref": "duration.schema.json" },
		"alternate": { "$ref": "resource.categorization.schema.json" }
	},
	required: ["url"]
};
//#endregion
//#region schemas/pub-manifest/module/localizable-object.schema.json
var localizable_object_schema_default = {
	$schema: "http://json-schema.org/draft-07/schema#",
	$id: "https://www.w3.org/ns/pub-schema/manifest/module/localizable-object.schema.json",
	title: "Localizable String Object",
	type: "object",
	properties: {
		"value": { "type": "string" },
		"language": { "$ref": "bcp.schema.json" }
	},
	required: ["value"]
};
//#endregion
//#region schemas/pub-manifest/module/localizable.schema.json
var localizable_schema_default = {
	$schema: "http://json-schema.org/draft-07/schema#",
	$id: "https://www.w3.org/ns/pub-schema/manifest/module/localizable.schema.json",
	title: "Localizable String or Object",
	anyOf: [
		{ "type": "string" },
		{
			"type": "array",
			"items": { "anyOf": [{ "type": "string" }, { "$ref": "localizable-object.schema.json" }] }
		},
		{ "$ref": "localizable-object.schema.json" }
	]
};
//#endregion
//#region schemas/pub-manifest/module/resource.categorization.schema.json
var resource_categorization_schema_default = {
	$schema: "http://json-schema.org/draft-07/schema#",
	$id: "https://www.w3.org/ns/pub-schema/manifest/module/resource.categorization.schema.json",
	title: "Resource Categorization",
	oneOf: [{ "oneOf": [{ "$ref": "url.schema.json" }, { "$ref": "link.schema.json" }] }, {
		"type": "array",
		"items": { "anyOf": [{ "$ref": "url.schema.json" }, { "$ref": "link.schema.json" }] },
		"uniqueItems": true
	}]
};
//#endregion
//#region schemas/pub-manifest/module/strings.schema.json
var strings_schema_default = {
	$schema: "http://json-schema.org/draft-07/schema#",
	$id: "https://www.w3.org/ns/pub-schema/manifest/module/strings.schema.json",
	title: "Unique strings",
	type: ["string", "array"],
	items: { "type": "string" }
};
//#endregion
//#region schemas/pub-manifest/module/url.schema.json
var url_schema_default = {
	$schema: "http://json-schema.org/draft-07/schema#",
	$id: "https://www.w3.org/ns/pub-schema/manifest/module/url.schema.json",
	title: "URL",
	type: "string",
	format: "uri-reference"
};
//#endregion
//#region schemas/pub-manifest/module/urls.schema.json
var urls_schema_default = {
	$schema: "http://json-schema.org/draft-07/schema#",
	$id: "https://www.w3.org/ns/pub-schema/manifest/module/urls.schema.json",
	title: "URLs",
	oneOf: [{
		"type": "string",
		"format": "uri-reference"
	}, {
		"type": "array",
		"items": {
			"type": "string",
			"format": "uri-reference"
		}
	}]
};
//#endregion
//#region schemas/pub-manifest/publication.schema.json
var publication_schema_default = {
	$schema: "http://json-schema.org/draft-07/schema#",
	$id: "https://www.w3.org/ns/pub-schema/manifest/publication.schema.json",
	title: "Publication Manifest",
	type: "object",
	properties: {
		"@context": { "$ref": "module/context.schema.json" },
		"type": {
			"type": ["string", "array"],
			"items": { "type": "string" }
		},
		"conformsTo": { "oneOf": [{ "$ref": "module/url.schema.json" }, {
			"type": "array",
			"items": { "$ref": "module/url.schema.json" }
		}] },
		"id": { "type": "string" },
		"abridged": { "type": "boolean" },
		"accessMode": { "$ref": "module/strings.schema.json" },
		"accessModeSufficient": { "$ref": "module/item-lists.schema.json" },
		"accessibilityFeature": { "$ref": "module/strings.schema.json" },
		"accessibilityHazard": { "$ref": "module/strings.schema.json" },
		"accessibilitySummary": { "$ref": "module/localizable.schema.json" },
		"artist": { "$ref": "module/contributor.schema.json" },
		"author": { "$ref": "module/contributor.schema.json" },
		"colorist": { "$ref": "module/contributor.schema.json" },
		"contributor": { "$ref": "module/contributor.schema.json" },
		"creator": { "$ref": "module/contributor.schema.json" },
		"editor": { "$ref": "module/contributor.schema.json" },
		"illustrator": { "$ref": "module/contributor.schema.json" },
		"inker": { "$ref": "module/contributor.schema.json" },
		"letterer": { "$ref": "module/contributor.schema.json" },
		"penciler": { "$ref": "module/contributor.schema.json" },
		"publisher": { "$ref": "module/contributor.schema.json" },
		"readBy": { "$ref": "module/contributor.schema.json" },
		"translator": { "$ref": "module/contributor.schema.json" },
		"url": { "$ref": "module/urls.schema.json" },
		"duration": { "$ref": "module/duration.schema.json" },
		"inLanguage": { "$ref": "module/language.schema.json" },
		"dateModified": { "$ref": "module/date.schema.json" },
		"datePublished": { "$ref": "module/date.schema.json" },
		"name": { "$ref": "module/localizable.schema.json" },
		"readingOrder": { "$ref": "module/resource.categorization.schema.json" },
		"resources": { "$ref": "module/resource.categorization.schema.json" },
		"links": { "$ref": "module/resource.categorization.schema.json" },
		"readingProgression": {
			"type": "string",
			"enum": ["ltr", "rtl"],
			"default": "ltr"
		}
	},
	required: ["@context", "conformsTo"]
};
//#endregion
//#region src/schema/pub-manifest.ts
const publicationSchemas = [
	bcp_schema_default,
	context_schema_default,
	contributor_object_schema_default,
	contributor_schema_default,
	date_schema_default,
	duration_schema_default,
	item_lists_schema_default,
	ItemList_schema_default,
	language_schema_default,
	link_schema_default,
	localizable_object_schema_default,
	localizable_schema_default,
	resource_categorization_schema_default,
	strings_schema_default,
	url_schema_default,
	urls_schema_default,
	publication_schema_default
];
//#endregion
//#region src/util.ts
const cwd = upath.normalize(process.cwd());
const execFile = util.promisify(childProcess.execFile);
async function exec(command, args = [], options = {}) {
	const subprocess = await execFile(command, args, {
		...options,
		encoding: "utf8"
	});
	subprocess.stdout = subprocess.stdout.trim();
	return subprocess;
}
const cleanupHandlers = [];
const terminationHooks = /* @__PURE__ */ new Set();
let cleanupPromise;
let processTerminationInstalled = false;
let handlingProcessTermination = false;
const registerCleanupHandler = (debugMessage, handler, { prepend = false } = {}) => {
	const callback = () => {
		Logger.debug(debugMessage);
		return handler();
	};
	if (prepend) cleanupHandlers.unshift(callback);
	else cleanupHandlers.push(callback);
	return () => {
		const index = cleanupHandlers.indexOf(callback);
		if (index !== -1) cleanupHandlers.splice(index, 1);
	};
};
const executeWithCleanupOnInterrupt = (debugMessage, tryTask, finallyTask) => {
	let thrownError;
	const runPromise = (async () => {
		try {
			return await tryTask();
		} catch (error) {
			thrownError = error;
			throw error;
		} finally {
			await finallyTask?.(thrownError);
		}
	})();
	const unregister = registerCleanupHandler(debugMessage, async () => {
		try {
			await runPromise;
		} catch {}
	}, { prepend: true });
	return runPromise.finally(unregister);
};
function registerTerminationHook(hook) {
	terminationHooks.add(hook);
	return () => {
		terminationHooks.delete(hook);
	};
}
function runCleanupHandlers() {
	if (cleanupPromise) return cleanupPromise;
	let resolveCleanup;
	const currentCleanupPromise = new Promise((resolve) => {
		resolveCleanup = resolve;
	});
	cleanupPromise = currentCleanupPromise;
	(async () => {
		try {
			while (cleanupHandlers.length > 0) try {
				await cleanupHandlers.shift()?.();
			} catch (e) {}
		} finally {
			cleanupPromise = void 0;
			resolveCleanup?.();
		}
	})();
	return currentCleanupPromise;
}
async function handleProcessTermination(exitCode) {
	if (handlingProcessTermination) return;
	handlingProcessTermination = true;
	for (const hook of terminationHooks) try {
		hook(exitCode);
	} catch (e) {}
	try {
		await runCleanupHandlers();
	} finally {
		process.exit(exitCode);
	}
}
function setupProcessTermination() {
	if (processTerminationInstalled) return;
	processTerminationInstalled = true;
	process.on("SIGINT", () => void handleProcessTermination(130));
	process.on("SIGTERM", () => void handleProcessTermination(143));
	process.on("SIGHUP", () => void handleProcessTermination(129));
	process.once("exit", () => {
		runCleanupHandlers();
	});
}
var DetailError = class extends Error {
	constructor(message, detail) {
		super(message);
		this.detail = detail;
	}
};
function getFormattedError(err) {
	return err instanceof DetailError ? `${err.message}\n${err.detail}` : err.stack || err.message;
}
function toError(value) {
	return value instanceof Error ? value : new Error(String(value));
}
async function gracefulError(err) {
	console.log(`${redBright("ERROR")} ${getFormattedError(err)}

${gray("If you think this is a bug, please report at https://github.com/vivliostyle/vivliostyle-cli/issues")}`);
	process.exitCode = 1;
	await runCleanupHandlers();
}
function readPackageJson(path) {
	return JSON.parse(fs.readFileSync(path, "utf8"));
}
function statFileSync(filePath, { errorMessage = "Specified input does not exist" } = {}) {
	try {
		return fs.statSync(filePath);
	} catch (err) {
		if (err.code === "ENOENT") throw new Error(`${errorMessage}: ${filePath}`, { cause: err });
		throw err;
	}
}
function inflateZip(filePath, dest) {
	return new Promise((res, rej) => {
		try {
			const zip = new StreamZip({
				file: filePath,
				storeEntries: true
			});
			zip.on("error", rej);
			zip.on("ready", () => {
				(async () => {
					try {
						await util.promisify(zip.extract.bind(zip))(null, dest);
						await util.promisify(zip.close.bind(zip))();
						Logger.debug(`Unzipped ${filePath} to ${dest}`);
						res();
					} catch (err) {
						rej(toError(err));
					}
				})();
			});
		} catch (err) {
			rej(toError(err));
		}
	});
}
function useTmpDirectory() {
	const directory = new Promise((res, rej) => {
		tmp.dir({ unsafeCleanup: true }, (err, path) => {
			if (err) {
				rej(err);
				return;
			}
			Logger.debug(`Created the temporary directory: ${path}`);
			res(path);
		});
	});
	if (import.meta.env?.VITEST) return directory.then((path) => [path, () => {}]);
	let path;
	const callback = () => {
		if (path) fs.rmSync(path, {
			force: true,
			recursive: true
		});
	};
	registerCleanupHandler("Removing the temporary directory", async () => {
		try {
			path = await directory;
		} catch {
			return;
		}
		callback();
	});
	return directory.then((createdPath) => {
		path = createdPath;
		return [createdPath, callback];
	});
}
function touchTmpFile(path) {
	fs.mkdirSync(upath.dirname(path), { recursive: true });
	fs.closeSync(fs.openSync(path, "a"));
	Logger.debug(`Created the temporary file: ${path}`);
	const callback = () => {
		fs.rmSync(path, {
			force: true,
			recursive: true
		});
	};
	registerCleanupHandler(`Removing the temporary file: ${path}`, callback);
	return callback;
}
function pathEquals(path1, path2) {
	return upath.relative(path1, path2) === "";
}
function pathContains(parentPath, childPath) {
	const rel = upath.relative(parentPath, childPath);
	return rel !== "" && !rel.startsWith("..");
}
function isValidUri(str) {
	return /^(https?|file|data):/iv.test(str);
}
function cachedFn(fn) {
	let cache = null;
	return () => cache ?? (cache = fn());
}
const isInContainer = cachedFn(function isInContainer() {
	return fs.existsSync("/opt/vivliostyle-cli/.vs-cli-version");
});
const isRunningOnWSL = cachedFn(function isRunningOnWSL() {
	return fs.existsSync("/proc/version") && fs.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft");
});
async function openEpub(epubPath, tmpDir) {
	const inflation = inflateZip(epubPath, tmpDir);
	const deleteEpub = async () => {
		try {
			await inflation;
		} catch {}
		fs.rmSync(tmpDir, {
			force: true,
			recursive: true
		});
	};
	registerCleanupHandler(`Removing the temporary EPUB directory: ${tmpDir}`, deleteEpub);
	await inflation;
	Logger.debug(`Created the temporary EPUB directory: ${tmpDir}`);
	return deleteEpub;
}
function getDefaultEpubOpfPath(epubDir) {
	const containerXmlPath = upath.join(epubDir, "META-INF/container.xml");
	const { container } = new XMLParser({ ignoreAttributes: false }).parse(fs.readFileSync(containerXmlPath, "utf8"));
	const rootfile = [container.rootfiles.rootfile].flat()[0];
	return upath.join(epubDir, rootfile["@_full-path"]);
}
function getEpubRootDir(epubOpfPath) {
	function traverse(dir) {
		if (fs.readdirSync(dir).includes("META-INF") && pathEquals(epubOpfPath, getDefaultEpubOpfPath(dir))) return dir;
		const next = upath.dirname(dir);
		if (pathEquals(dir, next)) return;
		return traverse(next);
	}
	return traverse(upath.dirname(epubOpfPath));
}
const getAjvValidatorFunction = (schema, refSchemas) => (obj) => {
	const ajv = new Ajv({ strict: false });
	formatsPlugin(ajv);
	if (refSchemas) ajv.addSchema(refSchemas);
	const validate = ajv.compile(schema);
	if (!validate(obj)) {
		const [validationError] = validate.errors ?? [];
		throw new Error(validationError?.message, { cause: validationError });
	}
	return true;
};
const assertPubManifestSchema = getAjvValidatorFunction(publication_schema_default, publicationSchemas);
function parseJsonc(rawJsonc) {
	return evaluate(parse(rawJsonc, {
		mode: "jsonc",
		ranges: false,
		tokens: false
	}));
}
function prettifySchemaError(rawJsonc, issues) {
	const parsed = parse(rawJsonc, {
		mode: "jsonc",
		ranges: false,
		tokens: false
	});
	function traverse(nodes, depth) {
		return nodes.flatMap((issue) => {
			const p = issue.path?.length ?? 0;
			if (!issue.issues) return [[[issue], depth + p]];
			return traverse(issue.issues, depth + p).map(([i, d]) => [[issue, ...i], d]);
		});
	}
	const all = traverse(issues, 0);
	const maxDepth = Math.max(...all.map(([, d]) => d));
	const deepest = all.find(([, d]) => d === maxDepth);
	/* v8 ignore next 3 */
	if (!deepest) throw new Error("Failed to locate the deepest schema issue");
	const issuesTraversed = deepest[0];
	let jsonValue = parsed.body;
	for (const p of issuesTraversed.flatMap((v) => v.path ?? [])) {
		let childValue;
		if (p.type === "object" && jsonValue.type === "Object") childValue = jsonValue.members.find((m) => m.name.type === "Identifier" && m.name.name === p.key || m.name.type === "String" && m.name.value === p.key)?.value;
		if (p.type === "array" && jsonValue.type === "Array") childValue = jsonValue.elements[p.key]?.value;
		if (childValue) jsonValue = childValue;
		else break;
	}
	const deepestIssue = issuesTraversed.at(-1);
	/* v8 ignore next 3 */
	if (!deepestIssue) throw new Error("Failed to locate the deepest schema issue");
	let message = red(deepestIssue.message);
	if (jsonValue) message += `\n${codeFrameColumns(rawJsonc, jsonValue.loc, { highlightCode: true })}`;
	return message;
}
function writeFileIfChanged(filePath, content) {
	if (!fs.existsSync(filePath) || !fs.readFileSync(filePath).equals(content)) {
		fs.mkdirSync(upath.dirname(filePath), { recursive: true });
		fs.writeFileSync(filePath, content);
	}
}
let cachedLocale;
function getOsLocale() {
	if (import.meta.env?.VITEST) return process.env.TEST_LOCALE || "en";
	if (cachedLocale) return cachedLocale;
	const locale = osLocale();
	const langs = Object.keys(LANGUAGES);
	cachedLocale = langs.includes(locale) ? locale : langs.includes(locale.split("-")[0]) ? locale.split("-")[0] : "en";
	return cachedLocale;
}
function toTitleCase(input) {
	return titleCase(input.replaceAll(/[\W_]/gv, " ").replaceAll(/\s+/gv, " ").trim());
}
function debounce(func, wait, options = {}) {
	const leading = options.leading ?? false;
	const trailing = options.trailing ?? !leading;
	let timer = null;
	let pending = false;
	const invoke = (...args) => {
		pending = false;
		func(...args);
	};
	return (...args) => {
		pending = true;
		if (timer) clearTimeout(timer);
		const callNow = leading && !timer;
		timer = setTimeout(() => {
			const shouldCall = trailing && pending && !(leading && callNow);
			timer = null;
			if (shouldCall) invoke(...args);
			else pending = false;
		}, wait);
		if (callNow) invoke(...args);
	};
}
const getCacheDir = cachedFn(function getCacheDir() {
	let osCacheDir;
	if (process.platform === "linux") osCacheDir = process.env.XDG_CACHE_HOME || upath.join(os.homedir(), ".cache");
	else if (process.platform === "darwin") osCacheDir = upath.join(os.homedir(), "Library", "Caches");
	else if (process.platform === "win32") osCacheDir = process.env.LOCALAPPDATA || upath.join(os.homedir(), "AppData", "Local");
	else throw new Error(`Unsupported platform: ${process.platform}`);
	return upath.join(osCacheDir, "vivliostyle");
});
const detectBrowserPlatform = cachedFn(function detectBrowserPlatform() {
	const platform = process.platform;
	const arch = process.arch;
	switch (platform) {
		case "darwin": return arch === "arm64" ? "mac_arm" : "mac";
		case "linux": return arch === "arm64" ? "linux_arm" : "linux";
		case "win32": return arch === "x64" || arch === "arm64" && isWindows11(os.release()) ? "win64" : "win32";
		default: return;
	}
});
function isWindows11(version) {
	const parts = version.split(".");
	if (parts.length > 2) {
		const major = Number.parseInt(parts[0], 10);
		const minor = Number.parseInt(parts[1], 10);
		const patch = Number.parseInt(parts[2], 10);
		return major > 10 || major === 10 && minor > 0 || major === 10 && minor === 0 && patch >= 22e3;
	}
	return false;
}
const getDefaultBrowserTag = (browserType) => {
	if (import.meta.env?.VITEST) return "100.0";
	const platform = detectBrowserPlatform();
	return platform && DEFAULT_BROWSER_VERSIONS[browserType][platform];
};
function whichPm() {
	if (!process.env.npm_config_user_agent) return "npm";
	const pmSpec = process.env.npm_config_user_agent.split(" ")[0];
	const separatorPos = pmSpec.lastIndexOf("/");
	return pmSpec.slice(0, separatorPos);
}
const cliRoot = upath.join(import.meta.filename, "../..");
const cliVersion = (() => {
	if (import.meta.env?.VITEST) return "0.0.1";
	return readPackageJson(upath.join(cliRoot, "package.json")).version;
})();
const viewerRoot = resolvePkg("@vivliostyle/viewer", { cwd: cliRoot });
const coreVersion = (() => {
	if (import.meta.env?.VITEST) return "0.0.1";
	if (!viewerRoot) return "Unknown";
	return readPackageJson(upath.join(viewerRoot, "package.json")).version;
})();
const versionForDisplay = `cli: ${cliVersion}
core: ${coreVersion}`;
//#endregion
export { statFileSync as A, isUnicodeSupported as B, pathEquals as C, registerTerminationHook as D, registerCleanupHandler as E, versionForDisplay as F, viewerRoot as I, whichPm as L, toTitleCase as M, touchTmpFile as N, runCleanupHandlers as O, useTmpDirectory as P, writeFileIfChanged as R, pathContains as S, readPackageJson as T, randomBookSymbol as V, isInContainer as _, cwd as a, openEpub as b, exec as c, getDefaultBrowserTag as d, getDefaultEpubOpfPath as f, gracefulError as g, getOsLocale as h, coreVersion as i, toError as j, setupProcessTermination as k, executeWithCleanupOnInterrupt as l, getFormattedError as m, assertPubManifestSchema as n, debounce as o, getEpubRootDir as p, cliVersion as r, detectBrowserPlatform as s, DetailError as t, getCacheDir as u, isRunningOnWSL as v, prettifySchemaError as w, parseJsonc as x, isValidUri as y, Logger as z };

//# sourceMappingURL=util-CsmUMRtR.js.map