(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.svelte = {}));
})(this, (function (exports) { 'use strict';

const now = () => performance.now();

/** @param {any} timings */
function collapse_timings(timings) {
	const result = {};
	timings.forEach(
		/** @param {any} timing */ (timing) => {
			result[timing.label] = Object.assign(
				{
					total: timing.end - timing.start
				},
				timing.children && collapse_timings(timing.children)
			);
		}
	);
	return result;
}

class Stats {
	/**
	 * @typedef {Object} Timing
	 * @property {string} label
	 * @property {number} start
	 * @property {number} end
	 * @property {Timing[]} children
	 */

	/** @type {number} */
	start_time;

	/** @type {Timing} */
	current_timing;

	/** @type {Timing[]} */
	current_children;

	/** @type {Timing[]} */
	timings;

	/** @type {Timing[]} */
	stack;
	constructor() {
		this.start_time = now();
		this.stack = [];
		this.current_children = this.timings = [];
	}

	/** @param {any} label */
	start(label) {
		const timing = {
			label,
			start: now(),
			end: null,
			children: []
		};
		this.current_children.push(timing);
		this.stack.push(timing);
		this.current_timing = timing;
		this.current_children = timing.children;
	}

	/** @param {any} label */
	stop(label) {
		if (label !== this.current_timing.label) {
			throw new Error(
				`Mismatched timing labels (expected ${this.current_timing.label}, got ${label})`
			);
		}
		this.current_timing.end = now();
		this.stack.pop();
		this.current_timing = this.stack[this.stack.length - 1];
		this.current_children = this.current_timing ? this.current_timing.children : this.timings;
	}
	render() {
		const timings = Object.assign(
			{
				total: now() - this.start_time
			},
			collapse_timings(this.timings)
		);
		return {
			timings
		};
	}
}

// This file was generated. Do not modify manually!
var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 81, 2, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];

// This file was generated. Do not modify manually!
var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938, 6, 4191];

// This file was generated. Do not modify manually!
var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";

// This file was generated. Do not modify manually!
var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";

// These are a run-length and offset encoded representation of the
// >0xffff code points that are a valid part of identifiers. The
// offset starts at 0x10000, and each pair of numbers represents an
// offset to the next range, and then a size of the range.

// Reserved word lists for various dialects of the language

var reservedWords = {
  3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
  5: "class enum extends super const export import",
  6: "enum",
  strict: "implements interface let package private protected public static yield",
  strictBind: "eval arguments"
};

// And the keywords

var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";

var keywords$1 = {
  5: ecma5AndLessKeywords,
  "5module": ecma5AndLessKeywords + " export import",
  6: ecma5AndLessKeywords + " const class extends export import super"
};

var keywordRelationalOperator = /^in(stanceof)?$/;

// ## Character categories

var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");

// This has a complexity linear to the value of the code. The
// assumption is that looking up astral identifier characters is
// rare.
function isInAstralSet(code, set) {
  var pos = 0x10000;
  for (var i = 0; i < set.length; i += 2) {
    pos += set[i];
    if (pos > code) { return false }
    pos += set[i + 1];
    if (pos >= code) { return true }
  }
  return false
}

// Test whether a given character code starts an identifier.

function isIdentifierStart(code, astral) {
  if (code < 65) { return code === 36 }
  if (code < 91) { return true }
  if (code < 97) { return code === 95 }
  if (code < 123) { return true }
  if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  if (astral === false) { return false }
  return isInAstralSet(code, astralIdentifierStartCodes)
}

// Test whether a given character is part of an identifier.

function isIdentifierChar(code, astral) {
  if (code < 48) { return code === 36 }
  if (code < 58) { return true }
  if (code < 65) { return false }
  if (code < 91) { return true }
  if (code < 97) { return code === 95 }
  if (code < 123) { return true }
  if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
  if (astral === false) { return false }
  return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
}

// ## Token types

// The assignment of fine-grained, information-carrying type objects
// allows the tokenizer to store the information it has about a
// token in a way that is very cheap for the parser to look up.

// All token type variables start with an underscore, to make them
// easy to recognize.

// The `beforeExpr` property is used to disambiguate between regular
// expressions and divisions. It is set on all token types that can
// be followed by an expression (thus, a slash after them would be a
// regular expression).
//
// The `startsExpr` property is used to check if the token ends a
// `yield` expression. It is set on all token types that either can
// directly start an expression (like a quotation mark) or can
// continue an expression (like the body of a string).
//
// `isLoop` marks a keyword as starting a loop, which is important
// to know when parsing a label, in order to allow or disallow
// continue jumps to that label.

var TokenType = function TokenType(label, conf) {
  if ( conf === void 0 ) conf = {};

  this.label = label;
  this.keyword = conf.keyword;
  this.beforeExpr = !!conf.beforeExpr;
  this.startsExpr = !!conf.startsExpr;
  this.isLoop = !!conf.isLoop;
  this.isAssign = !!conf.isAssign;
  this.prefix = !!conf.prefix;
  this.postfix = !!conf.postfix;
  this.binop = conf.binop || null;
  this.updateContext = null;
};

function binop(name, prec) {
  return new TokenType(name, {beforeExpr: true, binop: prec})
}
var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};

// Map keyword names to token types.

var keywords = {};

// Succinct definitions of keyword token types
function kw(name, options) {
  if ( options === void 0 ) options = {};

  options.keyword = name;
  return keywords[name] = new TokenType(name, options)
}

var types$1 = {
  num: new TokenType("num", startsExpr),
  regexp: new TokenType("regexp", startsExpr),
  string: new TokenType("string", startsExpr),
  name: new TokenType("name", startsExpr),
  privateId: new TokenType("privateId", startsExpr),
  eof: new TokenType("eof"),

  // Punctuation token types.
  bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
  bracketR: new TokenType("]"),
  braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
  braceR: new TokenType("}"),
  parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
  parenR: new TokenType(")"),
  comma: new TokenType(",", beforeExpr),
  semi: new TokenType(";", beforeExpr),
  colon: new TokenType(":", beforeExpr),
  dot: new TokenType("."),
  question: new TokenType("?", beforeExpr),
  questionDot: new TokenType("?."),
  arrow: new TokenType("=>", beforeExpr),
  template: new TokenType("template"),
  invalidTemplate: new TokenType("invalidTemplate"),
  ellipsis: new TokenType("...", beforeExpr),
  backQuote: new TokenType("`", startsExpr),
  dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),

  // Operators. These carry several kinds of properties to help the
  // parser use them properly (the presence of these properties is
  // what categorizes them as operators).
  //
  // `binop`, when present, specifies that this operator is a binary
  // operator, and will refer to its precedence.
  //
  // `prefix` and `postfix` mark the operator as a prefix or postfix
  // unary operator.
  //
  // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  // binary operators with a very low precedence, that should result
  // in AssignmentExpression nodes.

  eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
  assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
  incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  logicalOR: binop("||", 1),
  logicalAND: binop("&&", 2),
  bitwiseOR: binop("|", 3),
  bitwiseXOR: binop("^", 4),
  bitwiseAND: binop("&", 5),
  equality: binop("==/!=/===/!==", 6),
  relational: binop("</>/<=/>=", 7),
  bitShift: binop("<</>>/>>>", 8),
  plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  modulo: binop("%", 10),
  star: binop("*", 10),
  slash: binop("/", 10),
  starstar: new TokenType("**", {beforeExpr: true}),
  coalesce: binop("??", 1),

  // Keyword token types.
  _break: kw("break"),
  _case: kw("case", beforeExpr),
  _catch: kw("catch"),
  _continue: kw("continue"),
  _debugger: kw("debugger"),
  _default: kw("default", beforeExpr),
  _do: kw("do", {isLoop: true, beforeExpr: true}),
  _else: kw("else", beforeExpr),
  _finally: kw("finally"),
  _for: kw("for", {isLoop: true}),
  _function: kw("function", startsExpr),
  _if: kw("if"),
  _return: kw("return", beforeExpr),
  _switch: kw("switch"),
  _throw: kw("throw", beforeExpr),
  _try: kw("try"),
  _var: kw("var"),
  _const: kw("const"),
  _while: kw("while", {isLoop: true}),
  _with: kw("with"),
  _new: kw("new", {beforeExpr: true, startsExpr: true}),
  _this: kw("this", startsExpr),
  _super: kw("super", startsExpr),
  _class: kw("class", startsExpr),
  _extends: kw("extends", beforeExpr),
  _export: kw("export"),
  _import: kw("import", startsExpr),
  _null: kw("null", startsExpr),
  _true: kw("true", startsExpr),
  _false: kw("false", startsExpr),
  _in: kw("in", {beforeExpr: true, binop: 7}),
  _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
  _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
};

// Matches a whole line break (where CRLF is considered a single
// line break). Used to count lines.

var lineBreak = /\r\n?|\n|\u2028|\u2029/;
var lineBreakG = new RegExp(lineBreak.source, "g");

function isNewLine(code) {
  return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
}

function nextLineBreak(code, from, end) {
  if ( end === void 0 ) end = code.length;

  for (var i = from; i < end; i++) {
    var next = code.charCodeAt(i);
    if (isNewLine(next))
      { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 }
  }
  return -1
}

var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;

var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;

var ref = Object.prototype;
var hasOwnProperty$1 = ref.hasOwnProperty;
var toString$1 = ref.toString;

var hasOwn = Object.hasOwn || (function (obj, propName) { return (
  hasOwnProperty$1.call(obj, propName)
); });

var isArray = Array.isArray || (function (obj) { return (
  toString$1.call(obj) === "[object Array]"
); });

function wordsRegexp(words) {
  return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
}

function codePointToString(code) {
  // UTF-16 Decoding
  if (code <= 0xFFFF) { return String.fromCharCode(code) }
  code -= 0x10000;
  return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
}

var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;

// These are used when `options.locations` is on, for the
// `startLoc` and `endLoc` properties.

var Position = function Position(line, col) {
  this.line = line;
  this.column = col;
};

Position.prototype.offset = function offset (n) {
  return new Position(this.line, this.column + n)
};

var SourceLocation = function SourceLocation(p, start, end) {
  this.start = start;
  this.end = end;
  if (p.sourceFile !== null) { this.source = p.sourceFile; }
};

// The `getLineInfo` function is mostly useful when the
// `locations` option is off (for performance reasons) and you
// want to find the line/column position for a given character
// offset. `input` should be the code string that the offset refers
// into.

function getLineInfo(input, offset) {
  for (var line = 1, cur = 0;;) {
    var nextBreak = nextLineBreak(input, cur, offset);
    if (nextBreak < 0) { return new Position(line, offset - cur) }
    ++line;
    cur = nextBreak;
  }
}

// A second argument must be given to configure the parser process.
// These options are recognized (only `ecmaVersion` is required):

var defaultOptions = {
  // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"`
  // (the latest version the library supports). This influences
  // support for strict mode, the set of reserved words, and support
  // for new syntax features.
  ecmaVersion: null,
  // `sourceType` indicates the mode the code should be parsed in.
  // Can be either `"script"` or `"module"`. This influences global
  // strict mode and parsing of `import` and `export` declarations.
  sourceType: "script",
  // `onInsertedSemicolon` can be a callback that will be called
  // when a semicolon is automatically inserted. It will be passed
  // the position of the comma as an offset, and if `locations` is
  // enabled, it is given the location as a `{line, column}` object
  // as second argument.
  onInsertedSemicolon: null,
  // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  // trailing commas.
  onTrailingComma: null,
  // By default, reserved words are only enforced if ecmaVersion >= 5.
  // Set `allowReserved` to a boolean value to explicitly turn this on
  // an off. When this option has the value "never", reserved words
  // and keywords can also not be used as property names.
  allowReserved: null,
  // When enabled, a return at the top level is not considered an
  // error.
  allowReturnOutsideFunction: false,
  // When enabled, import/export statements are not constrained to
  // appearing at the top of the program, and an import.meta expression
  // in a script isn't considered an error.
  allowImportExportEverywhere: false,
  // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
  // When enabled, await identifiers are allowed to appear at the top-level scope,
  // but they are still not allowed in non-async functions.
  allowAwaitOutsideFunction: null,
  // When enabled, super identifiers are not constrained to
  // appearing in methods and do not raise an error when they appear elsewhere.
  allowSuperOutsideMethod: null,
  // When enabled, hashbang directive in the beginning of file is
  // allowed and treated as a line comment. Enabled by default when
  // `ecmaVersion` >= 2023.
  allowHashBang: false,
  // When `locations` is on, `loc` properties holding objects with
  // `start` and `end` properties in `{line, column}` form (with
  // line being 1-based and column 0-based) will be attached to the
  // nodes.
  locations: false,
  // A function can be passed as `onToken` option, which will
  // cause Acorn to call that function with object in the same
  // format as tokens returned from `tokenizer().getToken()`. Note
  // that you are not allowed to call the parser from the
  // callback—that will corrupt its internal state.
  onToken: null,
  // A function can be passed as `onComment` option, which will
  // cause Acorn to call that function with `(block, text, start,
  // end)` parameters whenever a comment is skipped. `block` is a
  // boolean indicating whether this is a block (`/* */`) comment,
  // `text` is the content of the comment, and `start` and `end` are
  // character offsets that denote the start and end of the comment.
  // When the `locations` option is on, two more parameters are
  // passed, the full `{line, column}` locations of the start and
  // end of the comments. Note that you are not allowed to call the
  // parser from the callback—that will corrupt its internal state.
  onComment: null,
  // Nodes have their start and end characters offsets recorded in
  // `start` and `end` properties (directly on the node, rather than
  // the `loc` object, which holds line/column data. To also add a
  // [semi-standardized][range] `range` property holding a `[start,
  // end]` array with the same numbers, set the `ranges` option to
  // `true`.
  //
  // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  ranges: false,
  // It is possible to parse multiple files into a single AST by
  // passing the tree produced by parsing the first file as
  // `program` option in subsequent parses. This will add the
  // toplevel forms of the parsed file to the `Program` (top) node
  // of an existing parse tree.
  program: null,
  // When `locations` is on, you can pass this to record the source
  // file in every node's `loc` object.
  sourceFile: null,
  // This value, if given, is stored in every node, whether
  // `locations` is on or off.
  directSourceFile: null,
  // When enabled, parenthesized expressions are represented by
  // (non-standard) ParenthesizedExpression nodes
  preserveParens: false
};

// Interpret and default an options object

var warnedAboutEcmaVersion = false;

function getOptions(opts) {
  var options = {};

  for (var opt in defaultOptions)
    { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; }

  if (options.ecmaVersion === "latest") {
    options.ecmaVersion = 1e8;
  } else if (options.ecmaVersion == null) {
    if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
      warnedAboutEcmaVersion = true;
      console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
    }
    options.ecmaVersion = 11;
  } else if (options.ecmaVersion >= 2015) {
    options.ecmaVersion -= 2009;
  }

  if (options.allowReserved == null)
    { options.allowReserved = options.ecmaVersion < 5; }

  if (!opts || opts.allowHashBang == null)
    { options.allowHashBang = options.ecmaVersion >= 14; }

  if (isArray(options.onToken)) {
    var tokens = options.onToken;
    options.onToken = function (token) { return tokens.push(token); };
  }
  if (isArray(options.onComment))
    { options.onComment = pushComment(options, options.onComment); }

  return options
}

function pushComment(options, array) {
  return function(block, text, start, end, startLoc, endLoc) {
    var comment = {
      type: block ? "Block" : "Line",
      value: text,
      start: start,
      end: end
    };
    if (options.locations)
      { comment.loc = new SourceLocation(this, startLoc, endLoc); }
    if (options.ranges)
      { comment.range = [start, end]; }
    array.push(comment);
  }
}

// Each scope gets a bitset that may contain these flags
var
    SCOPE_TOP = 1,
    SCOPE_FUNCTION = 2,
    SCOPE_ASYNC = 4,
    SCOPE_GENERATOR = 8,
    SCOPE_ARROW = 16,
    SCOPE_SIMPLE_CATCH = 32,
    SCOPE_SUPER = 64,
    SCOPE_DIRECT_SUPER = 128,
    SCOPE_CLASS_STATIC_BLOCK = 256,
    SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;

function functionFlags(async, generator) {
  return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
}

// Used in checkLVal* and declareName to determine the type of a binding
var
    BIND_NONE = 0, // Not a binding
    BIND_VAR = 1, // Var-style binding
    BIND_LEXICAL = 2, // Let- or const-style binding
    BIND_FUNCTION = 3, // Function declaration
    BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
    BIND_OUTSIDE = 5; // Special case for function names as bound inside the function

var Parser$1 = function Parser(options, input, startPos) {
  this.options = options = getOptions(options);
  this.sourceFile = options.sourceFile;
  this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  var reserved = "";
  if (options.allowReserved !== true) {
    reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
    if (options.sourceType === "module") { reserved += " await"; }
  }
  this.reservedWords = wordsRegexp(reserved);
  var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  this.reservedWordsStrict = wordsRegexp(reservedStrict);
  this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  this.input = String(input);

  // Used to signal to callers of `readWord1` whether the word
  // contained any escape sequences. This is needed because words with
  // escape sequences must not be interpreted as keywords.
  this.containsEsc = false;

  // Set up token state

  // The current position of the tokenizer in the input.
  if (startPos) {
    this.pos = startPos;
    this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
    this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  } else {
    this.pos = this.lineStart = 0;
    this.curLine = 1;
  }

  // Properties of the current token:
  // Its type
  this.type = types$1.eof;
  // For tokens that include more information than their type, the value
  this.value = null;
  // Its start and end offset
  this.start = this.end = this.pos;
  // And, if locations are used, the {line, column} object
  // corresponding to those offsets
  this.startLoc = this.endLoc = this.curPosition();

  // Position information for the previous token
  this.lastTokEndLoc = this.lastTokStartLoc = null;
  this.lastTokStart = this.lastTokEnd = this.pos;

  // The context stack is used to superficially track syntactic
  // context to predict whether a regular expression is allowed in a
  // given position.
  this.context = this.initialContext();
  this.exprAllowed = true;

  // Figure out if it's a module code.
  this.inModule = options.sourceType === "module";
  this.strict = this.inModule || this.strictDirective(this.pos);

  // Used to signify the start of a potential arrow function
  this.potentialArrowAt = -1;
  this.potentialArrowInForAwait = false;

  // Positions to delayed-check that yield/await does not exist in default parameters.
  this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  // Labels in scope.
  this.labels = [];
  // Thus-far undefined exports.
  this.undefinedExports = Object.create(null);

  // If enabled, skip leading hashbang line.
  if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
    { this.skipLineComment(2); }

  // Scope tracking for duplicate variable names (see scope.js)
  this.scopeStack = [];
  this.enterScope(SCOPE_TOP);

  // For RegExp validation
  this.regexpState = null;

  // The stack of private names.
  // Each element has two properties: 'declared' and 'used'.
  // When it exited from the outermost class definition, all used private names must be declared.
  this.privateNameStack = [];
};

var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } };

Parser$1.prototype.parse = function parse () {
  var node = this.options.program || this.startNode();
  this.nextToken();
  return this.parseTopLevel(node)
};

prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };

prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };

prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };

prototypeAccessors.canAwait.get = function () {
  for (var i = this.scopeStack.length - 1; i >= 0; i--) {
    var scope = this.scopeStack[i];
    if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false }
    if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }
  }
  return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
};

prototypeAccessors.allowSuper.get = function () {
  var ref = this.currentThisScope();
    var flags = ref.flags;
    var inClassFieldInit = ref.inClassFieldInit;
  return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
};

prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };

prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };

prototypeAccessors.allowNewDotTarget.get = function () {
  var ref = this.currentThisScope();
    var flags = ref.flags;
    var inClassFieldInit = ref.inClassFieldInit;
  return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit
};

prototypeAccessors.inClassStaticBlock.get = function () {
  return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0
};

Parser$1.extend = function extend () {
    var plugins = [], len = arguments.length;
    while ( len-- ) plugins[ len ] = arguments[ len ];

  var cls = this;
  for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
  return cls
};

Parser$1.parse = function parse (input, options) {
  return new this(options, input).parse()
};

Parser$1.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  var parser = new this(options, input, pos);
  parser.nextToken();
  return parser.parseExpression()
};

Parser$1.tokenizer = function tokenizer (input, options) {
  return new this(options, input)
};

Object.defineProperties( Parser$1.prototype, prototypeAccessors );

var pp$9 = Parser$1.prototype;

// ## Parser utilities

var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
pp$9.strictDirective = function(start) {
  if (this.options.ecmaVersion < 5) { return false }
  for (;;) {
    // Try to find string literal.
    skipWhiteSpace.lastIndex = start;
    start += skipWhiteSpace.exec(this.input)[0].length;
    var match = literal.exec(this.input.slice(start));
    if (!match) { return false }
    if ((match[1] || match[2]) === "use strict") {
      skipWhiteSpace.lastIndex = start + match[0].length;
      var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
      var next = this.input.charAt(end);
      return next === ";" || next === "}" ||
        (lineBreak.test(spaceAfter[0]) &&
         !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
    }
    start += match[0].length;

    // Skip semicolon, if any.
    skipWhiteSpace.lastIndex = start;
    start += skipWhiteSpace.exec(this.input)[0].length;
    if (this.input[start] === ";")
      { start++; }
  }
};

// Predicate that tests whether the next token is of the given
// type, and if yes, consumes it as a side effect.

pp$9.eat = function(type) {
  if (this.type === type) {
    this.next();
    return true
  } else {
    return false
  }
};

// Tests whether parsed token is a contextual keyword.

pp$9.isContextual = function(name) {
  return this.type === types$1.name && this.value === name && !this.containsEsc
};

// Consumes contextual keyword if possible.

pp$9.eatContextual = function(name) {
  if (!this.isContextual(name)) { return false }
  this.next();
  return true
};

// Asserts that following token is given contextual keyword.

pp$9.expectContextual = function(name) {
  if (!this.eatContextual(name)) { this.unexpected(); }
};

// Test whether a semicolon can be inserted at the current position.

pp$9.canInsertSemicolon = function() {
  return this.type === types$1.eof ||
    this.type === types$1.braceR ||
    lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
};

pp$9.insertSemicolon = function() {
  if (this.canInsertSemicolon()) {
    if (this.options.onInsertedSemicolon)
      { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
    return true
  }
};

// Consume a semicolon, or, failing that, see if we are allowed to
// pretend that there is a semicolon at this position.

pp$9.semicolon = function() {
  if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); }
};

pp$9.afterTrailingComma = function(tokType, notNext) {
  if (this.type === tokType) {
    if (this.options.onTrailingComma)
      { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
    if (!notNext)
      { this.next(); }
    return true
  }
};

// Expect a token of a given type. If found, consume it, otherwise,
// raise an unexpected token error.

pp$9.expect = function(type) {
  this.eat(type) || this.unexpected();
};

// Raise an unexpected token error.

pp$9.unexpected = function(pos) {
  this.raise(pos != null ? pos : this.start, "Unexpected token");
};

var DestructuringErrors = function DestructuringErrors() {
  this.shorthandAssign =
  this.trailingComma =
  this.parenthesizedAssign =
  this.parenthesizedBind =
  this.doubleProto =
    -1;
};

pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  if (!refDestructuringErrors) { return }
  if (refDestructuringErrors.trailingComma > -1)
    { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  if (parens > -1) { this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); }
};

pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  if (!refDestructuringErrors) { return false }
  var shorthandAssign = refDestructuringErrors.shorthandAssign;
  var doubleProto = refDestructuringErrors.doubleProto;
  if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
  if (shorthandAssign >= 0)
    { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
  if (doubleProto >= 0)
    { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
};

pp$9.checkYieldAwaitInDefaultParams = function() {
  if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
    { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  if (this.awaitPos)
    { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
};

pp$9.isSimpleAssignTarget = function(expr) {
  if (expr.type === "ParenthesizedExpression")
    { return this.isSimpleAssignTarget(expr.expression) }
  return expr.type === "Identifier" || expr.type === "MemberExpression"
};

var pp$8 = Parser$1.prototype;

// ### Statement parsing

// Parse a program. Initializes the parser, reads any number of
// statements, and wraps them in a Program node.  Optionally takes a
// `program` argument.  If present, the statements will be appended
// to its body instead of creating a new node.

pp$8.parseTopLevel = function(node) {
  var exports = Object.create(null);
  if (!node.body) { node.body = []; }
  while (this.type !== types$1.eof) {
    var stmt = this.parseStatement(null, true, exports);
    node.body.push(stmt);
  }
  if (this.inModule)
    { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
      {
        var name = list[i];

        this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
      } }
  this.adaptDirectivePrologue(node.body);
  this.next();
  node.sourceType = this.options.sourceType;
  return this.finishNode(node, "Program")
};

var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};

pp$8.isLet = function(context) {
  if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  skipWhiteSpace.lastIndex = this.pos;
  var skip = skipWhiteSpace.exec(this.input);
  var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  // For ambiguous cases, determine if a LexicalDeclaration (or only a
  // Statement) is allowed here. If context is not empty then only a Statement
  // is allowed. However, `let [` is an explicit negative lookahead for
  // ExpressionStatement, so special-case it first.
  if (nextCh === 91 || nextCh === 92) { return true } // '[', '/'
  if (context) { return false }

  if (nextCh === 123 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '{', astral
  if (isIdentifierStart(nextCh, true)) {
    var pos = next + 1;
    while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
    if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
    var ident = this.input.slice(next, pos);
    if (!keywordRelationalOperator.test(ident)) { return true }
  }
  return false
};

// check 'async [no LineTerminator here] function'
// - 'async /*foo*/ function' is OK.
// - 'async /*\n*/ function' is invalid.
pp$8.isAsyncFunction = function() {
  if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
    { return false }

  skipWhiteSpace.lastIndex = this.pos;
  var skip = skipWhiteSpace.exec(this.input);
  var next = this.pos + skip[0].length, after;
  return !lineBreak.test(this.input.slice(this.pos, next)) &&
    this.input.slice(next, next + 8) === "function" &&
    (next + 8 === this.input.length ||
     !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
};

// Parse a single statement.
//
// If expecting a statement and finding a slash operator, parse a
// regular expression literal. This is to handle cases like
// `if (foo) /blah/.exec(foo)`, where looking at the previous token
// does not help.

pp$8.parseStatement = function(context, topLevel, exports) {
  var starttype = this.type, node = this.startNode(), kind;

  if (this.isLet(context)) {
    starttype = types$1._var;
    kind = "let";
  }

  // Most types of statements are recognized by the keyword they
  // start with. Many are trivial to parse, some require a bit of
  // complexity.

  switch (starttype) {
  case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  case types$1._debugger: return this.parseDebuggerStatement(node)
  case types$1._do: return this.parseDoStatement(node)
  case types$1._for: return this.parseForStatement(node)
  case types$1._function:
    // Function as sole body of either an if statement or a labeled statement
    // works, but not when it is part of a labeled statement that is the sole
    // body of an if statement.
    if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
    return this.parseFunctionStatement(node, false, !context)
  case types$1._class:
    if (context) { this.unexpected(); }
    return this.parseClass(node, true)
  case types$1._if: return this.parseIfStatement(node)
  case types$1._return: return this.parseReturnStatement(node)
  case types$1._switch: return this.parseSwitchStatement(node)
  case types$1._throw: return this.parseThrowStatement(node)
  case types$1._try: return this.parseTryStatement(node)
  case types$1._const: case types$1._var:
    kind = kind || this.value;
    if (context && kind !== "var") { this.unexpected(); }
    return this.parseVarStatement(node, kind)
  case types$1._while: return this.parseWhileStatement(node)
  case types$1._with: return this.parseWithStatement(node)
  case types$1.braceL: return this.parseBlock(true, node)
  case types$1.semi: return this.parseEmptyStatement(node)
  case types$1._export:
  case types$1._import:
    if (this.options.ecmaVersion > 10 && starttype === types$1._import) {
      skipWhiteSpace.lastIndex = this.pos;
      var skip = skipWhiteSpace.exec(this.input);
      var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
      if (nextCh === 40 || nextCh === 46) // '(' or '.'
        { return this.parseExpressionStatement(node, this.parseExpression()) }
    }

    if (!this.options.allowImportExportEverywhere) {
      if (!topLevel)
        { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
      if (!this.inModule)
        { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
    }
    return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports)

    // If the statement does not start with a statement keyword or a
    // brace, it's an ExpressionStatement or LabeledStatement. We
    // simply start parsing an expression, and afterwards, if the
    // next token is a colon and the expression was a simple
    // Identifier node, we switch to interpreting it as a label.
  default:
    if (this.isAsyncFunction()) {
      if (context) { this.unexpected(); }
      this.next();
      return this.parseFunctionStatement(node, true, !context)
    }

    var maybeName = this.value, expr = this.parseExpression();
    if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon))
      { return this.parseLabeledStatement(node, maybeName, expr, context) }
    else { return this.parseExpressionStatement(node, expr) }
  }
};

pp$8.parseBreakContinueStatement = function(node, keyword) {
  var isBreak = keyword === "break";
  this.next();
  if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; }
  else if (this.type !== types$1.name) { this.unexpected(); }
  else {
    node.label = this.parseIdent();
    this.semicolon();
  }

  // Verify that there is an actual destination to break or
  // continue to.
  var i = 0;
  for (; i < this.labels.length; ++i) {
    var lab = this.labels[i];
    if (node.label == null || lab.name === node.label.name) {
      if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
      if (node.label && isBreak) { break }
    }
  }
  if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
};

pp$8.parseDebuggerStatement = function(node) {
  this.next();
  this.semicolon();
  return this.finishNode(node, "DebuggerStatement")
};

pp$8.parseDoStatement = function(node) {
  this.next();
  this.labels.push(loopLabel);
  node.body = this.parseStatement("do");
  this.labels.pop();
  this.expect(types$1._while);
  node.test = this.parseParenExpression();
  if (this.options.ecmaVersion >= 6)
    { this.eat(types$1.semi); }
  else
    { this.semicolon(); }
  return this.finishNode(node, "DoWhileStatement")
};

// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
// loop is non-trivial. Basically, we have to parse the init `var`
// statement or expression, disallowing the `in` operator (see
// the second parameter to `parseExpression`), and then check
// whether the next token is `in` or `of`. When there is no init
// part (semicolon immediately after the opening parenthesis), it
// is a regular `for` loop.

pp$8.parseForStatement = function(node) {
  this.next();
  var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
  this.labels.push(loopLabel);
  this.enterScope(0);
  this.expect(types$1.parenL);
  if (this.type === types$1.semi) {
    if (awaitAt > -1) { this.unexpected(awaitAt); }
    return this.parseFor(node, null)
  }
  var isLet = this.isLet();
  if (this.type === types$1._var || this.type === types$1._const || isLet) {
    var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
    this.next();
    this.parseVar(init$1, true, kind);
    this.finishNode(init$1, "VariableDeclaration");
    if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
      if (this.options.ecmaVersion >= 9) {
        if (this.type === types$1._in) {
          if (awaitAt > -1) { this.unexpected(awaitAt); }
        } else { node.await = awaitAt > -1; }
      }
      return this.parseForIn(node, init$1)
    }
    if (awaitAt > -1) { this.unexpected(awaitAt); }
    return this.parseFor(node, init$1)
  }
  var startsWithLet = this.isContextual("let"), isForOf = false;
  var refDestructuringErrors = new DestructuringErrors;
  var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
  if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
    if (this.options.ecmaVersion >= 9) {
      if (this.type === types$1._in) {
        if (awaitAt > -1) { this.unexpected(awaitAt); }
      } else { node.await = awaitAt > -1; }
    }
    if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); }
    this.toAssignable(init, false, refDestructuringErrors);
    this.checkLValPattern(init);
    return this.parseForIn(node, init)
  } else {
    this.checkExpressionErrors(refDestructuringErrors, true);
  }
  if (awaitAt > -1) { this.unexpected(awaitAt); }
  return this.parseFor(node, init)
};

pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  this.next();
  return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
};

pp$8.parseIfStatement = function(node) {
  this.next();
  node.test = this.parseParenExpression();
  // allow function declarations in branches, but only in non-strict mode
  node.consequent = this.parseStatement("if");
  node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;
  return this.finishNode(node, "IfStatement")
};

pp$8.parseReturnStatement = function(node) {
  if (!this.inFunction && !this.options.allowReturnOutsideFunction)
    { this.raise(this.start, "'return' outside of function"); }
  this.next();

  // In `return` (and `break`/`continue`), the keywords with
  // optional arguments, we eagerly look for a semicolon or the
  // possibility to insert one.

  if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; }
  else { node.argument = this.parseExpression(); this.semicolon(); }
  return this.finishNode(node, "ReturnStatement")
};

pp$8.parseSwitchStatement = function(node) {
  this.next();
  node.discriminant = this.parseParenExpression();
  node.cases = [];
  this.expect(types$1.braceL);
  this.labels.push(switchLabel);
  this.enterScope(0);

  // Statements under must be grouped (by label) in SwitchCase
  // nodes. `cur` is used to keep the node that we are currently
  // adding statements to.

  var cur;
  for (var sawDefault = false; this.type !== types$1.braceR;) {
    if (this.type === types$1._case || this.type === types$1._default) {
      var isCase = this.type === types$1._case;
      if (cur) { this.finishNode(cur, "SwitchCase"); }
      node.cases.push(cur = this.startNode());
      cur.consequent = [];
      this.next();
      if (isCase) {
        cur.test = this.parseExpression();
      } else {
        if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
        sawDefault = true;
        cur.test = null;
      }
      this.expect(types$1.colon);
    } else {
      if (!cur) { this.unexpected(); }
      cur.consequent.push(this.parseStatement(null));
    }
  }
  this.exitScope();
  if (cur) { this.finishNode(cur, "SwitchCase"); }
  this.next(); // Closing brace
  this.labels.pop();
  return this.finishNode(node, "SwitchStatement")
};

pp$8.parseThrowStatement = function(node) {
  this.next();
  if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
    { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  node.argument = this.parseExpression();
  this.semicolon();
  return this.finishNode(node, "ThrowStatement")
};

// Reused empty array added for node fields that are always empty.

var empty$1 = [];

pp$8.parseCatchClauseParam = function() {
  var param = this.parseBindingAtom();
  var simple = param.type === "Identifier";
  this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
  this.checkLValPattern(param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  this.expect(types$1.parenR);

  return param
};

pp$8.parseTryStatement = function(node) {
  this.next();
  node.block = this.parseBlock();
  node.handler = null;
  if (this.type === types$1._catch) {
    var clause = this.startNode();
    this.next();
    if (this.eat(types$1.parenL)) {
      clause.param = this.parseCatchClauseParam();
    } else {
      if (this.options.ecmaVersion < 10) { this.unexpected(); }
      clause.param = null;
      this.enterScope(0);
    }
    clause.body = this.parseBlock(false);
    this.exitScope();
    node.handler = this.finishNode(clause, "CatchClause");
  }
  node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;
  if (!node.handler && !node.finalizer)
    { this.raise(node.start, "Missing catch or finally clause"); }
  return this.finishNode(node, "TryStatement")
};

pp$8.parseVarStatement = function(node, kind, allowMissingInitializer) {
  this.next();
  this.parseVar(node, false, kind, allowMissingInitializer);
  this.semicolon();
  return this.finishNode(node, "VariableDeclaration")
};

pp$8.parseWhileStatement = function(node) {
  this.next();
  node.test = this.parseParenExpression();
  this.labels.push(loopLabel);
  node.body = this.parseStatement("while");
  this.labels.pop();
  return this.finishNode(node, "WhileStatement")
};

pp$8.parseWithStatement = function(node) {
  if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  this.next();
  node.object = this.parseParenExpression();
  node.body = this.parseStatement("with");
  return this.finishNode(node, "WithStatement")
};

pp$8.parseEmptyStatement = function(node) {
  this.next();
  return this.finishNode(node, "EmptyStatement")
};

pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
  for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
    {
    var label = list[i$1];

    if (label.name === maybeName)
      { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  } }
  var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;
  for (var i = this.labels.length - 1; i >= 0; i--) {
    var label$1 = this.labels[i];
    if (label$1.statementStart === node.start) {
      // Update information about previous labels on this node
      label$1.statementStart = this.start;
      label$1.kind = kind;
    } else { break }
  }
  this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  this.labels.pop();
  node.label = expr;
  return this.finishNode(node, "LabeledStatement")
};

pp$8.parseExpressionStatement = function(node, expr) {
  node.expression = expr;
  this.semicolon();
  return this.finishNode(node, "ExpressionStatement")
};

// Parse a semicolon-enclosed block of statements, handling `"use
// strict"` declarations when `allowStrict` is true (used for
// function bodies).

pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  if ( node === void 0 ) node = this.startNode();

  node.body = [];
  this.expect(types$1.braceL);
  if (createNewLexicalScope) { this.enterScope(0); }
  while (this.type !== types$1.braceR) {
    var stmt = this.parseStatement(null);
    node.body.push(stmt);
  }
  if (exitStrict) { this.strict = false; }
  this.next();
  if (createNewLexicalScope) { this.exitScope(); }
  return this.finishNode(node, "BlockStatement")
};

// Parse a regular `for` loop. The disambiguation code in
// `parseStatement` will already have parsed the init statement or
// expression.

pp$8.parseFor = function(node, init) {
  node.init = init;
  this.expect(types$1.semi);
  node.test = this.type === types$1.semi ? null : this.parseExpression();
  this.expect(types$1.semi);
  node.update = this.type === types$1.parenR ? null : this.parseExpression();
  this.expect(types$1.parenR);
  node.body = this.parseStatement("for");
  this.exitScope();
  this.labels.pop();
  return this.finishNode(node, "ForStatement")
};

// Parse a `for`/`in` and `for`/`of` loop, which are almost
// same from parser's perspective.

pp$8.parseForIn = function(node, init) {
  var isForIn = this.type === types$1._in;
  this.next();

  if (
    init.type === "VariableDeclaration" &&
    init.declarations[0].init != null &&
    (
      !isForIn ||
      this.options.ecmaVersion < 8 ||
      this.strict ||
      init.kind !== "var" ||
      init.declarations[0].id.type !== "Identifier"
    )
  ) {
    this.raise(
      init.start,
      ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
    );
  }
  node.left = init;
  node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  this.expect(types$1.parenR);
  node.body = this.parseStatement("for");
  this.exitScope();
  this.labels.pop();
  return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
};

// Parse a list of variable declarations.

pp$8.parseVar = function(node, isFor, kind, allowMissingInitializer) {
  node.declarations = [];
  node.kind = kind;
  for (;;) {
    var decl = this.startNode();
    this.parseVarId(decl, kind);
    if (this.eat(types$1.eq)) {
      decl.init = this.parseMaybeAssign(isFor);
    } else if (!allowMissingInitializer && kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
      this.unexpected();
    } else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {
      this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
    } else {
      decl.init = null;
    }
    node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
    if (!this.eat(types$1.comma)) { break }
  }
  return node
};

pp$8.parseVarId = function(decl, kind) {
  decl.id = this.parseBindingAtom();
  this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
};

var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;

// Parse a function declaration or literal (depending on the
// `statement & FUNC_STATEMENT`).

// Remove `allowExpressionBody` for 7.0.0, as it is only called with false
pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {
  this.initFunction(node);
  if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
    if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT))
      { this.unexpected(); }
    node.generator = this.eat(types$1.star);
  }
  if (this.options.ecmaVersion >= 8)
    { node.async = !!isAsync; }

  if (statement & FUNC_STATEMENT) {
    node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent();
    if (node.id && !(statement & FUNC_HANGING_STATEMENT))
      // If it is a regular function declaration in sloppy mode, then it is
      // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
      // mode depends on properties of the current scope (see
      // treatFunctionsAsVar).
      { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
  }

  var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  this.yieldPos = 0;
  this.awaitPos = 0;
  this.awaitIdentPos = 0;
  this.enterScope(functionFlags(node.async, node.generator));

  if (!(statement & FUNC_STATEMENT))
    { node.id = this.type === types$1.name ? this.parseIdent() : null; }

  this.parseFunctionParams(node);
  this.parseFunctionBody(node, allowExpressionBody, false, forInit);

  this.yieldPos = oldYieldPos;
  this.awaitPos = oldAwaitPos;
  this.awaitIdentPos = oldAwaitIdentPos;
  return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
};

pp$8.parseFunctionParams = function(node) {
  this.expect(types$1.parenL);
  node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  this.checkYieldAwaitInDefaultParams();
};

// Parse a class declaration or literal (depending on the
// `isStatement` parameter).

pp$8.parseClass = function(node, isStatement) {
  this.next();

  // ecma-262 14.6 Class Definitions
  // A class definition is always strict mode code.
  var oldStrict = this.strict;
  this.strict = true;

  this.parseClassId(node, isStatement);
  this.parseClassSuper(node);
  var privateNameMap = this.enterClassBody();
  var classBody = this.startNode();
  var hadConstructor = false;
  classBody.body = [];
  this.expect(types$1.braceL);
  while (this.type !== types$1.braceR) {
    var element = this.parseClassElement(node.superClass !== null);
    if (element) {
      classBody.body.push(element);
      if (element.type === "MethodDefinition" && element.kind === "constructor") {
        if (hadConstructor) { this.raiseRecoverable(element.start, "Duplicate constructor in the same class"); }
        hadConstructor = true;
      } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
        this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
      }
    }
  }
  this.strict = oldStrict;
  this.next();
  node.body = this.finishNode(classBody, "ClassBody");
  this.exitClassBody();
  return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
};

pp$8.parseClassElement = function(constructorAllowsSuper) {
  if (this.eat(types$1.semi)) { return null }

  var ecmaVersion = this.options.ecmaVersion;
  var node = this.startNode();
  var keyName = "";
  var isGenerator = false;
  var isAsync = false;
  var kind = "method";
  var isStatic = false;

  if (this.eatContextual("static")) {
    // Parse static init block
    if (ecmaVersion >= 13 && this.eat(types$1.braceL)) {
      this.parseClassStaticBlock(node);
      return node
    }
    if (this.isClassElementNameStart() || this.type === types$1.star) {
      isStatic = true;
    } else {
      keyName = "static";
    }
  }
  node.static = isStatic;
  if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
    if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
      isAsync = true;
    } else {
      keyName = "async";
    }
  }
  if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) {
    isGenerator = true;
  }
  if (!keyName && !isAsync && !isGenerator) {
    var lastValue = this.value;
    if (this.eatContextual("get") || this.eatContextual("set")) {
      if (this.isClassElementNameStart()) {
        kind = lastValue;
      } else {
        keyName = lastValue;
      }
    }
  }

  // Parse element name
  if (keyName) {
    // 'async', 'get', 'set', or 'static' were not a keyword contextually.
    // The last token is any of those. Make it the element name.
    node.computed = false;
    node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
    node.key.name = keyName;
    this.finishNode(node.key, "Identifier");
  } else {
    this.parseClassElementName(node);
  }

  // Parse element value
  if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) {
    var isConstructor = !node.static && checkKeyName(node, "constructor");
    var allowsDirectSuper = isConstructor && constructorAllowsSuper;
    // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
    if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
    node.kind = isConstructor ? "constructor" : kind;
    this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
  } else {
    this.parseClassField(node);
  }

  return node
};

pp$8.isClassElementNameStart = function() {
  return (
    this.type === types$1.name ||
    this.type === types$1.privateId ||
    this.type === types$1.num ||
    this.type === types$1.string ||
    this.type === types$1.bracketL ||
    this.type.keyword
  )
};

pp$8.parseClassElementName = function(element) {
  if (this.type === types$1.privateId) {
    if (this.value === "constructor") {
      this.raise(this.start, "Classes can't have an element named '#constructor'");
    }
    element.computed = false;
    element.key = this.parsePrivateIdent();
  } else {
    this.parsePropertyName(element);
  }
};

pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  // Check key and flags
  var key = method.key;
  if (method.kind === "constructor") {
    if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
    if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
  } else if (method.static && checkKeyName(method, "prototype")) {
    this.raise(key.start, "Classes may not have a static property named prototype");
  }

  // Parse value
  var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);

  // Check value
  if (method.kind === "get" && value.params.length !== 0)
    { this.raiseRecoverable(value.start, "getter should have no params"); }
  if (method.kind === "set" && value.params.length !== 1)
    { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
  if (method.kind === "set" && value.params[0].type === "RestElement")
    { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }

  return this.finishNode(method, "MethodDefinition")
};

pp$8.parseClassField = function(field) {
  if (checkKeyName(field, "constructor")) {
    this.raise(field.key.start, "Classes can't have a field named 'constructor'");
  } else if (field.static && checkKeyName(field, "prototype")) {
    this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
  }

  if (this.eat(types$1.eq)) {
    // To raise SyntaxError if 'arguments' exists in the initializer.
    var scope = this.currentThisScope();
    var inClassFieldInit = scope.inClassFieldInit;
    scope.inClassFieldInit = true;
    field.value = this.parseMaybeAssign();
    scope.inClassFieldInit = inClassFieldInit;
  } else {
    field.value = null;
  }
  this.semicolon();

  return this.finishNode(field, "PropertyDefinition")
};

pp$8.parseClassStaticBlock = function(node) {
  node.body = [];

  var oldLabels = this.labels;
  this.labels = [];
  this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);
  while (this.type !== types$1.braceR) {
    var stmt = this.parseStatement(null);
    node.body.push(stmt);
  }
  this.next();
  this.exitScope();
  this.labels = oldLabels;

  return this.finishNode(node, "StaticBlock")
};

pp$8.parseClassId = function(node, isStatement) {
  if (this.type === types$1.name) {
    node.id = this.parseIdent();
    if (isStatement)
      { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
  } else {
    if (isStatement === true)
      { this.unexpected(); }
    node.id = null;
  }
};

pp$8.parseClassSuper = function(node) {
  node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null;
};

pp$8.enterClassBody = function() {
  var element = {declared: Object.create(null), used: []};
  this.privateNameStack.push(element);
  return element.declared
};

pp$8.exitClassBody = function() {
  var ref = this.privateNameStack.pop();
  var declared = ref.declared;
  var used = ref.used;
  var len = this.privateNameStack.length;
  var parent = len === 0 ? null : this.privateNameStack[len - 1];
  for (var i = 0; i < used.length; ++i) {
    var id = used[i];
    if (!hasOwn(declared, id.name)) {
      if (parent) {
        parent.used.push(id);
      } else {
        this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
      }
    }
  }
};

function isPrivateNameConflicted(privateNameMap, element) {
  var name = element.key.name;
  var curr = privateNameMap[name];

  var next = "true";
  if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
    next = (element.static ? "s" : "i") + element.kind;
  }

  // `class { get #a(){}; static set #a(_){} }` is also conflict.
  if (
    curr === "iget" && next === "iset" ||
    curr === "iset" && next === "iget" ||
    curr === "sget" && next === "sset" ||
    curr === "sset" && next === "sget"
  ) {
    privateNameMap[name] = "true";
    return false
  } else if (!curr) {
    privateNameMap[name] = next;
    return false
  } else {
    return true
  }
}

function checkKeyName(node, name) {
  var computed = node.computed;
  var key = node.key;
  return !computed && (
    key.type === "Identifier" && key.name === name ||
    key.type === "Literal" && key.value === name
  )
}

// Parses module export declaration.

pp$8.parseExportAllDeclaration = function(node, exports) {
  if (this.options.ecmaVersion >= 11) {
    if (this.eatContextual("as")) {
      node.exported = this.parseModuleExportName();
      this.checkExport(exports, node.exported, this.lastTokStart);
    } else {
      node.exported = null;
    }
  }
  this.expectContextual("from");
  if (this.type !== types$1.string) { this.unexpected(); }
  node.source = this.parseExprAtom();
  this.semicolon();
  return this.finishNode(node, "ExportAllDeclaration")
};

pp$8.parseExport = function(node, exports) {
  this.next();
  // export * from '...'
  if (this.eat(types$1.star)) {
    return this.parseExportAllDeclaration(node, exports)
  }
  if (this.eat(types$1._default)) { // export default ...
    this.checkExport(exports, "default", this.lastTokStart);
    node.declaration = this.parseExportDefaultDeclaration();
    return this.finishNode(node, "ExportDefaultDeclaration")
  }
  // export var|const|let|function|class ...
  if (this.shouldParseExportStatement()) {
    node.declaration = this.parseExportDeclaration(node);
    if (node.declaration.type === "VariableDeclaration")
      { this.checkVariableExport(exports, node.declaration.declarations); }
    else
      { this.checkExport(exports, node.declaration.id, node.declaration.id.start); }
    node.specifiers = [];
    node.source = null;
  } else { // export { x, y as z } [from '...']
    node.declaration = null;
    node.specifiers = this.parseExportSpecifiers(exports);
    if (this.eatContextual("from")) {
      if (this.type !== types$1.string) { this.unexpected(); }
      node.source = this.parseExprAtom();
    } else {
      for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
        // check for keywords used as local names
        var spec = list[i];

        this.checkUnreserved(spec.local);
        // check if export is defined
        this.checkLocalExport(spec.local);

        if (spec.local.type === "Literal") {
          this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
        }
      }

      node.source = null;
    }
    this.semicolon();
  }
  return this.finishNode(node, "ExportNamedDeclaration")
};

pp$8.parseExportDeclaration = function(node) {
  return this.parseStatement(null)
};

pp$8.parseExportDefaultDeclaration = function() {
  var isAsync;
  if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {
    var fNode = this.startNode();
    this.next();
    if (isAsync) { this.next(); }
    return this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync)
  } else if (this.type === types$1._class) {
    var cNode = this.startNode();
    return this.parseClass(cNode, "nullableID")
  } else {
    var declaration = this.parseMaybeAssign();
    this.semicolon();
    return declaration
  }
};

pp$8.checkExport = function(exports, name, pos) {
  if (!exports) { return }
  if (typeof name !== "string")
    { name = name.type === "Identifier" ? name.name : name.value; }
  if (hasOwn(exports, name))
    { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  exports[name] = true;
};

pp$8.checkPatternExport = function(exports, pat) {
  var type = pat.type;
  if (type === "Identifier")
    { this.checkExport(exports, pat, pat.start); }
  else if (type === "ObjectPattern")
    { for (var i = 0, list = pat.properties; i < list.length; i += 1)
      {
        var prop = list[i];

        this.checkPatternExport(exports, prop);
      } }
  else if (type === "ArrayPattern")
    { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
      var elt = list$1[i$1];

        if (elt) { this.checkPatternExport(exports, elt); }
    } }
  else if (type === "Property")
    { this.checkPatternExport(exports, pat.value); }
  else if (type === "AssignmentPattern")
    { this.checkPatternExport(exports, pat.left); }
  else if (type === "RestElement")
    { this.checkPatternExport(exports, pat.argument); }
  else if (type === "ParenthesizedExpression")
    { this.checkPatternExport(exports, pat.expression); }
};

pp$8.checkVariableExport = function(exports, decls) {
  if (!exports) { return }
  for (var i = 0, list = decls; i < list.length; i += 1)
    {
    var decl = list[i];

    this.checkPatternExport(exports, decl.id);
  }
};

pp$8.shouldParseExportStatement = function() {
  return this.type.keyword === "var" ||
    this.type.keyword === "const" ||
    this.type.keyword === "class" ||
    this.type.keyword === "function" ||
    this.isLet() ||
    this.isAsyncFunction()
};

// Parses a comma-separated list of module exports.

pp$8.parseExportSpecifier = function(exports) {
  var node = this.startNode();
  node.local = this.parseModuleExportName();

  node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
  this.checkExport(
    exports,
    node.exported,
    node.exported.start
  );

  return this.finishNode(node, "ExportSpecifier")
};

pp$8.parseExportSpecifiers = function(exports) {
  var nodes = [], first = true;
  // export { x, y as z } [from '...']
  this.expect(types$1.braceL);
  while (!this.eat(types$1.braceR)) {
    if (!first) {
      this.expect(types$1.comma);
      if (this.afterTrailingComma(types$1.braceR)) { break }
    } else { first = false; }

    nodes.push(this.parseExportSpecifier(exports));
  }
  return nodes
};

// Parses import declaration.

pp$8.parseImport = function(node) {
  this.next();

  // import '...'
  if (this.type === types$1.string) {
    node.specifiers = empty$1;
    node.source = this.parseExprAtom();
  } else {
    node.specifiers = this.parseImportSpecifiers();
    this.expectContextual("from");
    node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();
  }
  this.semicolon();
  return this.finishNode(node, "ImportDeclaration")
};

// Parses a comma-separated list of module imports.

pp$8.parseImportSpecifier = function() {
  var node = this.startNode();
  node.imported = this.parseModuleExportName();

  if (this.eatContextual("as")) {
    node.local = this.parseIdent();
  } else {
    this.checkUnreserved(node.imported);
    node.local = node.imported;
  }
  this.checkLValSimple(node.local, BIND_LEXICAL);

  return this.finishNode(node, "ImportSpecifier")
};

pp$8.parseImportDefaultSpecifier = function() {
  // import defaultObj, { x, y as z } from '...'
  var node = this.startNode();
  node.local = this.parseIdent();
  this.checkLValSimple(node.local, BIND_LEXICAL);
  return this.finishNode(node, "ImportDefaultSpecifier")
};

pp$8.parseImportNamespaceSpecifier = function() {
  var node = this.startNode();
  this.next();
  this.expectContextual("as");
  node.local = this.parseIdent();
  this.checkLValSimple(node.local, BIND_LEXICAL);
  return this.finishNode(node, "ImportNamespaceSpecifier")
};

pp$8.parseImportSpecifiers = function() {
  var nodes = [], first = true;
  if (this.type === types$1.name) {
    nodes.push(this.parseImportDefaultSpecifier());
    if (!this.eat(types$1.comma)) { return nodes }
  }
  if (this.type === types$1.star) {
    nodes.push(this.parseImportNamespaceSpecifier());
    return nodes
  }
  this.expect(types$1.braceL);
  while (!this.eat(types$1.braceR)) {
    if (!first) {
      this.expect(types$1.comma);
      if (this.afterTrailingComma(types$1.braceR)) { break }
    } else { first = false; }

    nodes.push(this.parseImportSpecifier());
  }
  return nodes
};

pp$8.parseModuleExportName = function() {
  if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {
    var stringLiteral = this.parseLiteral(this.value);
    if (loneSurrogate.test(stringLiteral.value)) {
      this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
    }
    return stringLiteral
  }
  return this.parseIdent(true)
};

// Set `ExpressionStatement#directive` property for directive prologues.
pp$8.adaptDirectivePrologue = function(statements) {
  for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
    statements[i].directive = statements[i].expression.raw.slice(1, -1);
  }
};
pp$8.isDirectiveCandidate = function(statement) {
  return (
    this.options.ecmaVersion >= 5 &&
    statement.type === "ExpressionStatement" &&
    statement.expression.type === "Literal" &&
    typeof statement.expression.value === "string" &&
    // Reject parenthesized strings.
    (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  )
};

var pp$7 = Parser$1.prototype;

// Convert existing expression atom to assignable pattern
// if possible.

pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {
  if (this.options.ecmaVersion >= 6 && node) {
    switch (node.type) {
    case "Identifier":
      if (this.inAsync && node.name === "await")
        { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
      break

    case "ObjectPattern":
    case "ArrayPattern":
    case "AssignmentPattern":
    case "RestElement":
      break

    case "ObjectExpression":
      node.type = "ObjectPattern";
      if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
      for (var i = 0, list = node.properties; i < list.length; i += 1) {
        var prop = list[i];

      this.toAssignable(prop, isBinding);
        // Early error:
        //   AssignmentRestProperty[Yield, Await] :
        //     `...` DestructuringAssignmentTarget[Yield, Await]
        //
        //   It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
        if (
          prop.type === "RestElement" &&
          (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
        ) {
          this.raise(prop.argument.start, "Unexpected token");
        }
      }
      break

    case "Property":
      // AssignmentProperty has type === "Property"
      if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
      this.toAssignable(node.value, isBinding);
      break

    case "ArrayExpression":
      node.type = "ArrayPattern";
      if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
      this.toAssignableList(node.elements, isBinding);
      break

    case "SpreadElement":
      node.type = "RestElement";
      this.toAssignable(node.argument, isBinding);
      if (node.argument.type === "AssignmentPattern")
        { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
      break

    case "AssignmentExpression":
      if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
      node.type = "AssignmentPattern";
      delete node.operator;
      this.toAssignable(node.left, isBinding);
      break

    case "ParenthesizedExpression":
      this.toAssignable(node.expression, isBinding, refDestructuringErrors);
      break

    case "ChainExpression":
      this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
      break

    case "MemberExpression":
      if (!isBinding) { break }

    default:
      this.raise(node.start, "Assigning to rvalue");
    }
  } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  return node
};

// Convert list of expression atoms to binding list.

pp$7.toAssignableList = function(exprList, isBinding) {
  var end = exprList.length;
  for (var i = 0; i < end; i++) {
    var elt = exprList[i];
    if (elt) { this.toAssignable(elt, isBinding); }
  }
  if (end) {
    var last = exprList[end - 1];
    if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
      { this.unexpected(last.argument.start); }
  }
  return exprList
};

// Parses spread element.

pp$7.parseSpread = function(refDestructuringErrors) {
  var node = this.startNode();
  this.next();
  node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  return this.finishNode(node, "SpreadElement")
};

pp$7.parseRestBinding = function() {
  var node = this.startNode();
  this.next();

  // RestElement inside of a function parameter must be an identifier
  if (this.options.ecmaVersion === 6 && this.type !== types$1.name)
    { this.unexpected(); }

  node.argument = this.parseBindingAtom();

  return this.finishNode(node, "RestElement")
};

// Parses lvalue (assignable) atom.

pp$7.parseBindingAtom = function() {
  if (this.options.ecmaVersion >= 6) {
    switch (this.type) {
    case types$1.bracketL:
      var node = this.startNode();
      this.next();
      node.elements = this.parseBindingList(types$1.bracketR, true, true);
      return this.finishNode(node, "ArrayPattern")

    case types$1.braceL:
      return this.parseObj(true)
    }
  }
  return this.parseIdent()
};

pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) {
  var elts = [], first = true;
  while (!this.eat(close)) {
    if (first) { first = false; }
    else { this.expect(types$1.comma); }
    if (allowEmpty && this.type === types$1.comma) {
      elts.push(null);
    } else if (allowTrailingComma && this.afterTrailingComma(close)) {
      break
    } else if (this.type === types$1.ellipsis) {
      var rest = this.parseRestBinding();
      this.parseBindingListItem(rest);
      elts.push(rest);
      if (this.type === types$1.comma) { this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); }
      this.expect(close);
      break
    } else {
      elts.push(this.parseAssignableListItem(allowModifiers));
    }
  }
  return elts
};

pp$7.parseAssignableListItem = function(allowModifiers) {
  var elem = this.parseMaybeDefault(this.start, this.startLoc);
  this.parseBindingListItem(elem);
  return elem
};

pp$7.parseBindingListItem = function(param) {
  return param
};

// Parses assignment pattern around given atom if possible.

pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
  left = left || this.parseBindingAtom();
  if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left }
  var node = this.startNodeAt(startPos, startLoc);
  node.left = left;
  node.right = this.parseMaybeAssign();
  return this.finishNode(node, "AssignmentPattern")
};

// The following three functions all verify that a node is an lvalue —
// something that can be bound, or assigned to. In order to do so, they perform
// a variety of checks:
//
// - Check that none of the bound/assigned-to identifiers are reserved words.
// - Record name declarations for bindings in the appropriate scope.
// - Check duplicate argument names, if checkClashes is set.
//
// If a complex binding pattern is encountered (e.g., object and array
// destructuring), the entire pattern is recursively checked.
//
// There are three versions of checkLVal*() appropriate for different
// circumstances:
//
// - checkLValSimple() shall be used if the syntactic construct supports
//   nothing other than identifiers and member expressions. Parenthesized
//   expressions are also correctly handled. This is generally appropriate for
//   constructs for which the spec says
//
//   > It is a Syntax Error if AssignmentTargetType of [the production] is not
//   > simple.
//
//   It is also appropriate for checking if an identifier is valid and not
//   defined elsewhere, like import declarations or function/class identifiers.
//
//   Examples where this is used include:
//     a += …;
//     import a from '…';
//   where a is the node to be checked.
//
// - checkLValPattern() shall be used if the syntactic construct supports
//   anything checkLValSimple() supports, as well as object and array
//   destructuring patterns. This is generally appropriate for constructs for
//   which the spec says
//
//   > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
//   > an ArrayLiteral and AssignmentTargetType of [the production] is not
//   > simple.
//
//   Examples where this is used include:
//     (a = …);
//     const a = …;
//     try { … } catch (a) { … }
//   where a is the node to be checked.
//
// - checkLValInnerPattern() shall be used if the syntactic construct supports
//   anything checkLValPattern() supports, as well as default assignment
//   patterns, rest elements, and other constructs that may appear within an
//   object or array destructuring pattern.
//
//   As a special case, function parameters also use checkLValInnerPattern(),
//   as they also support defaults and rest constructs.
//
// These functions deliberately support both assignment and binding constructs,
// as the logic for both is exceedingly similar. If the node is the target of
// an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
// should be set to the appropriate BIND_* constant, like BIND_VAR or
// BIND_LEXICAL.
//
// If the function is called with a non-BIND_NONE bindingType, then
// additionally a checkClashes object may be specified to allow checking for
// duplicate argument names. checkClashes is ignored if the provided construct
// is an assignment (i.e., bindingType is BIND_NONE).

pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
  if ( bindingType === void 0 ) bindingType = BIND_NONE;

  var isBind = bindingType !== BIND_NONE;

  switch (expr.type) {
  case "Identifier":
    if (this.strict && this.reservedWordsStrictBind.test(expr.name))
      { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
    if (isBind) {
      if (bindingType === BIND_LEXICAL && expr.name === "let")
        { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
      if (checkClashes) {
        if (hasOwn(checkClashes, expr.name))
          { this.raiseRecoverable(expr.start, "Argument name clash"); }
        checkClashes[expr.name] = true;
      }
      if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
    }
    break

  case "ChainExpression":
    this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
    break

  case "MemberExpression":
    if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
    break

  case "ParenthesizedExpression":
    if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
    return this.checkLValSimple(expr.expression, bindingType, checkClashes)

  default:
    this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  }
};

pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
  if ( bindingType === void 0 ) bindingType = BIND_NONE;

  switch (expr.type) {
  case "ObjectPattern":
    for (var i = 0, list = expr.properties; i < list.length; i += 1) {
      var prop = list[i];

    this.checkLValInnerPattern(prop, bindingType, checkClashes);
    }
    break

  case "ArrayPattern":
    for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
      var elem = list$1[i$1];

    if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
    }
    break

  default:
    this.checkLValSimple(expr, bindingType, checkClashes);
  }
};

pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  if ( bindingType === void 0 ) bindingType = BIND_NONE;

  switch (expr.type) {
  case "Property":
    // AssignmentProperty has type === "Property"
    this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
    break

  case "AssignmentPattern":
    this.checkLValPattern(expr.left, bindingType, checkClashes);
    break

  case "RestElement":
    this.checkLValPattern(expr.argument, bindingType, checkClashes);
    break

  default:
    this.checkLValPattern(expr, bindingType, checkClashes);
  }
};

// The algorithm used to determine whether a regexp can appear at a
// given point in the program is loosely based on sweet.js' approach.
// See https://github.com/mozilla/sweet.js/wiki/design


var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  this.token = token;
  this.isExpr = !!isExpr;
  this.preserveSpace = !!preserveSpace;
  this.override = override;
  this.generator = !!generator;
};

var types = {
  b_stat: new TokContext("{", false),
  b_expr: new TokContext("{", true),
  b_tmpl: new TokContext("${", false),
  p_stat: new TokContext("(", false),
  p_expr: new TokContext("(", true),
  q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  f_stat: new TokContext("function", false),
  f_expr: new TokContext("function", true),
  f_expr_gen: new TokContext("function", true, false, null, true),
  f_gen: new TokContext("function", false, false, null, true)
};

var pp$6 = Parser$1.prototype;

pp$6.initialContext = function() {
  return [types.b_stat]
};

pp$6.curContext = function() {
  return this.context[this.context.length - 1]
};

pp$6.braceIsBlock = function(prevType) {
  var parent = this.curContext();
  if (parent === types.f_expr || parent === types.f_stat)
    { return true }
  if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr))
    { return !parent.isExpr }

  // The check for `tt.name && exprAllowed` detects whether we are
  // after a `yield` or `of` construct. See the `updateContext` for
  // `tt.name`.
  if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed)
    { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow)
    { return true }
  if (prevType === types$1.braceL)
    { return parent === types.b_stat }
  if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name)
    { return false }
  return !this.exprAllowed
};

pp$6.inGeneratorContext = function() {
  for (var i = this.context.length - 1; i >= 1; i--) {
    var context = this.context[i];
    if (context.token === "function")
      { return context.generator }
  }
  return false
};

pp$6.updateContext = function(prevType) {
  var update, type = this.type;
  if (type.keyword && prevType === types$1.dot)
    { this.exprAllowed = false; }
  else if (update = type.updateContext)
    { update.call(this, prevType); }
  else
    { this.exprAllowed = type.beforeExpr; }
};

// Used to handle egde cases when token context could not be inferred correctly during tokenization phase

pp$6.overrideContext = function(tokenCtx) {
  if (this.curContext() !== tokenCtx) {
    this.context[this.context.length - 1] = tokenCtx;
  }
};

// Token-specific context update code

types$1.parenR.updateContext = types$1.braceR.updateContext = function() {
  if (this.context.length === 1) {
    this.exprAllowed = true;
    return
  }
  var out = this.context.pop();
  if (out === types.b_stat && this.curContext().token === "function") {
    out = this.context.pop();
  }
  this.exprAllowed = !out.isExpr;
};

types$1.braceL.updateContext = function(prevType) {
  this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
  this.exprAllowed = true;
};

types$1.dollarBraceL.updateContext = function() {
  this.context.push(types.b_tmpl);
  this.exprAllowed = true;
};

types$1.parenL.updateContext = function(prevType) {
  var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;
  this.context.push(statementParens ? types.p_stat : types.p_expr);
  this.exprAllowed = true;
};

types$1.incDec.updateContext = function() {
  // tokExprAllowed stays unchanged
};

types$1._function.updateContext = types$1._class.updateContext = function(prevType) {
  if (prevType.beforeExpr && prevType !== types$1._else &&
      !(prevType === types$1.semi && this.curContext() !== types.p_stat) &&
      !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
      !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat))
    { this.context.push(types.f_expr); }
  else
    { this.context.push(types.f_stat); }
  this.exprAllowed = false;
};

types$1.backQuote.updateContext = function() {
  if (this.curContext() === types.q_tmpl)
    { this.context.pop(); }
  else
    { this.context.push(types.q_tmpl); }
  this.exprAllowed = false;
};

types$1.star.updateContext = function(prevType) {
  if (prevType === types$1._function) {
    var index = this.context.length - 1;
    if (this.context[index] === types.f_expr)
      { this.context[index] = types.f_expr_gen; }
    else
      { this.context[index] = types.f_gen; }
  }
  this.exprAllowed = true;
};

types$1.name.updateContext = function(prevType) {
  var allowed = false;
  if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {
    if (this.value === "of" && !this.exprAllowed ||
        this.value === "yield" && this.inGeneratorContext())
      { allowed = true; }
  }
  this.exprAllowed = allowed;
};

// A recursive descent parser operates by defining functions for all
// syntactic elements, and recursively calling those, each function
// advancing the input stream and returning an AST node. Precedence
// of constructs (for example, the fact that `!x[1]` means `!(x[1])`
// instead of `(!x)[1]` is handled by the fact that the parser
// function that parses unary prefix operators is called first, and
// in turn calls the function that parses `[]` subscripts — that
// way, it'll receive the node for `x[1]` already parsed, and wraps
// *that* in the unary operator node.
//
// Acorn uses an [operator precedence parser][opp] to handle binary
// operator precedence, because it is much more compact than using
// the technique outlined above, which uses different, nesting
// functions to specify precedence, for all of the ten binary
// precedence levels that JavaScript defines.
//
// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser


var pp$5 = Parser$1.prototype;

// Check if property name clashes with already added.
// Object/class getters and setters are not allowed to clash —
// either with each other or with an init property — and in
// strict mode, init properties are also not allowed to be repeated.

pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
    { return }
  if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
    { return }
  var key = prop.key;
  var name;
  switch (key.type) {
  case "Identifier": name = key.name; break
  case "Literal": name = String(key.value); break
  default: return
  }
  var kind = prop.kind;
  if (this.options.ecmaVersion >= 6) {
    if (name === "__proto__" && kind === "init") {
      if (propHash.proto) {
        if (refDestructuringErrors) {
          if (refDestructuringErrors.doubleProto < 0) {
            refDestructuringErrors.doubleProto = key.start;
          }
        } else {
          this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
        }
      }
      propHash.proto = true;
    }
    return
  }
  name = "$" + name;
  var other = propHash[name];
  if (other) {
    var redefinition;
    if (kind === "init") {
      redefinition = this.strict && other.init || other.get || other.set;
    } else {
      redefinition = other.init || other[kind];
    }
    if (redefinition)
      { this.raiseRecoverable(key.start, "Redefinition of property"); }
  } else {
    other = propHash[name] = {
      init: false,
      get: false,
      set: false
    };
  }
  other[kind] = true;
};

// ### Expression parsing

// These nest, from the most general expression type at the top to
// 'atomic', nondivisible expression types at the bottom. Most of
// the functions will simply let the function(s) below them parse,
// and, *if* the syntactic construct they handle is present, wrap
// the AST node that the inner parser gave them in another node.

// Parse a full expression. The optional arguments are used to
// forbid the `in` operator (in for loops initalization expressions)
// and provide reference for storing '=' operator inside shorthand
// property assignment in contexts where both object expression
// and object pattern might appear (so it's possible to raise
// delayed syntax error at correct position).

pp$5.parseExpression = function(forInit, refDestructuringErrors) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  if (this.type === types$1.comma) {
    var node = this.startNodeAt(startPos, startLoc);
    node.expressions = [expr];
    while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
    return this.finishNode(node, "SequenceExpression")
  }
  return expr
};

// Parse an assignment expression. This includes applications of
// operators like `+=`.

pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
  if (this.isContextual("yield")) {
    if (this.inGenerator) { return this.parseYield(forInit) }
    // The tokenizer will assume an expression is allowed after
    // `yield`, but this isn't that kind of yield
    else { this.exprAllowed = false; }
  }

  var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
  if (refDestructuringErrors) {
    oldParenAssign = refDestructuringErrors.parenthesizedAssign;
    oldTrailingComma = refDestructuringErrors.trailingComma;
    oldDoubleProto = refDestructuringErrors.doubleProto;
    refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  } else {
    refDestructuringErrors = new DestructuringErrors;
    ownDestructuringErrors = true;
  }

  var startPos = this.start, startLoc = this.startLoc;
  if (this.type === types$1.parenL || this.type === types$1.name) {
    this.potentialArrowAt = this.start;
    this.potentialArrowInForAwait = forInit === "await";
  }
  var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
  if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  if (this.type.isAssign) {
    var node = this.startNodeAt(startPos, startLoc);
    node.operator = this.value;
    if (this.type === types$1.eq)
      { left = this.toAssignable(left, false, refDestructuringErrors); }
    if (!ownDestructuringErrors) {
      refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
    }
    if (refDestructuringErrors.shorthandAssign >= left.start)
      { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
    if (this.type === types$1.eq)
      { this.checkLValPattern(left); }
    else
      { this.checkLValSimple(left); }
    node.left = left;
    this.next();
    node.right = this.parseMaybeAssign(forInit);
    if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; }
    return this.finishNode(node, "AssignmentExpression")
  } else {
    if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  }
  if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  return left
};

// Parse a ternary conditional (`?:`) operator.

pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseExprOps(forInit, refDestructuringErrors);
  if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  if (this.eat(types$1.question)) {
    var node = this.startNodeAt(startPos, startLoc);
    node.test = expr;
    node.consequent = this.parseMaybeAssign();
    this.expect(types$1.colon);
    node.alternate = this.parseMaybeAssign(forInit);
    return this.finishNode(node, "ConditionalExpression")
  }
  return expr
};

// Start the precedence parser.

pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
  if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
};

// Parse binary operators with the operator precedence parsing
// algorithm. `left` is the left-hand side of the operator.
// `minPrec` provides context that allows the function to stop and
// defer further parser to one of its callers when it encounters an
// operator that has a lower precedence than the set it is parsing.

pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
  var prec = this.type.binop;
  if (prec != null && (!forInit || this.type !== types$1._in)) {
    if (prec > minPrec) {
      var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;
      var coalesce = this.type === types$1.coalesce;
      if (coalesce) {
        // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
        // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
        prec = types$1.logicalAND.binop;
      }
      var op = this.value;
      this.next();
      var startPos = this.start, startLoc = this.startLoc;
      var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
      var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
      if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) {
        this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
      }
      return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
    }
  }
  return left
};

pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); }
  var node = this.startNodeAt(startPos, startLoc);
  node.left = left;
  node.operator = op;
  node.right = right;
  return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
};

// Parse unary operators, both prefix and postfix.

pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
  var startPos = this.start, startLoc = this.startLoc, expr;
  if (this.isContextual("await") && this.canAwait) {
    expr = this.parseAwait(forInit);
    sawUnary = true;
  } else if (this.type.prefix) {
    var node = this.startNode(), update = this.type === types$1.incDec;
    node.operator = this.value;
    node.prefix = true;
    this.next();
    node.argument = this.parseMaybeUnary(null, true, update, forInit);
    this.checkExpressionErrors(refDestructuringErrors, true);
    if (update) { this.checkLValSimple(node.argument); }
    else if (this.strict && node.operator === "delete" &&
             node.argument.type === "Identifier")
      { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
    else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
      { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
    else { sawUnary = true; }
    expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  } else if (!sawUnary && this.type === types$1.privateId) {
    if (forInit || this.privateNameStack.length === 0) { this.unexpected(); }
    expr = this.parsePrivateIdent();
    // only could be private fields in 'in', such as #x in obj
    if (this.type !== types$1._in) { this.unexpected(); }
  } else {
    expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
    if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
    while (this.type.postfix && !this.canInsertSemicolon()) {
      var node$1 = this.startNodeAt(startPos, startLoc);
      node$1.operator = this.value;
      node$1.prefix = false;
      node$1.argument = expr;
      this.checkLValSimple(expr);
      this.next();
      expr = this.finishNode(node$1, "UpdateExpression");
    }
  }

  if (!incDec && this.eat(types$1.starstar)) {
    if (sawUnary)
      { this.unexpected(this.lastTokStart); }
    else
      { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) }
  } else {
    return expr
  }
};

function isPrivateFieldAccess(node) {
  return (
    node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
    node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
  )
}

// Parse call, dot, and `[]`-subscript expressions.

pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseExprAtom(refDestructuringErrors, forInit);
  if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
    { return expr }
  var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
  if (refDestructuringErrors && result.type === "MemberExpression") {
    if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
    if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
    if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
  }
  return result
};

pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {
  var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
      this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
      this.potentialArrowAt === base.start;
  var optionalChained = false;

  while (true) {
    var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);

    if (element.optional) { optionalChained = true; }
    if (element === base || element.type === "ArrowFunctionExpression") {
      if (optionalChained) {
        var chainNode = this.startNodeAt(startPos, startLoc);
        chainNode.expression = element;
        element = this.finishNode(chainNode, "ChainExpression");
      }
      return element
    }

    base = element;
  }
};

pp$5.shouldParseAsyncArrow = function() {
  return !this.canInsertSemicolon() && this.eat(types$1.arrow)
};

pp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) {
  return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)
};

pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
  var optionalSupported = this.options.ecmaVersion >= 11;
  var optional = optionalSupported && this.eat(types$1.questionDot);
  if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }

  var computed = this.eat(types$1.bracketL);
  if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) {
    var node = this.startNodeAt(startPos, startLoc);
    node.object = base;
    if (computed) {
      node.property = this.parseExpression();
      this.expect(types$1.bracketR);
    } else if (this.type === types$1.privateId && base.type !== "Super") {
      node.property = this.parsePrivateIdent();
    } else {
      node.property = this.parseIdent(this.options.allowReserved !== "never");
    }
    node.computed = !!computed;
    if (optionalSupported) {
      node.optional = optional;
    }
    base = this.finishNode(node, "MemberExpression");
  } else if (!noCalls && this.eat(types$1.parenL)) {
    var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
    this.yieldPos = 0;
    this.awaitPos = 0;
    this.awaitIdentPos = 0;
    var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
    if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) {
      this.checkPatternErrors(refDestructuringErrors, false);
      this.checkYieldAwaitInDefaultParams();
      if (this.awaitIdentPos > 0)
        { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
      this.yieldPos = oldYieldPos;
      this.awaitPos = oldAwaitPos;
      this.awaitIdentPos = oldAwaitIdentPos;
      return this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit)
    }
    this.checkExpressionErrors(refDestructuringErrors, true);
    this.yieldPos = oldYieldPos || this.yieldPos;
    this.awaitPos = oldAwaitPos || this.awaitPos;
    this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
    var node$1 = this.startNodeAt(startPos, startLoc);
    node$1.callee = base;
    node$1.arguments = exprList;
    if (optionalSupported) {
      node$1.optional = optional;
    }
    base = this.finishNode(node$1, "CallExpression");
  } else if (this.type === types$1.backQuote) {
    if (optional || optionalChained) {
      this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
    }
    var node$2 = this.startNodeAt(startPos, startLoc);
    node$2.tag = base;
    node$2.quasi = this.parseTemplate({isTagged: true});
    base = this.finishNode(node$2, "TaggedTemplateExpression");
  }
  return base
};

// Parse an atomic expression — either a single token that is an
// expression, an expression started by a keyword like `function` or
// `new`, or an expression wrapped in punctuation like `()`, `[]`,
// or `{}`.

pp$5.parseExprAtom = function(refDestructuringErrors, forInit, forNew) {
  // If a division operator appears in an expression position, the
  // tokenizer got confused, and we force it to read a regexp instead.
  if (this.type === types$1.slash) { this.readRegexp(); }

  var node, canBeArrow = this.potentialArrowAt === this.start;
  switch (this.type) {
  case types$1._super:
    if (!this.allowSuper)
      { this.raise(this.start, "'super' keyword outside a method"); }
    node = this.startNode();
    this.next();
    if (this.type === types$1.parenL && !this.allowDirectSuper)
      { this.raise(node.start, "super() call outside constructor of a subclass"); }
    // The `super` keyword can appear at below:
    // SuperProperty:
    //     super [ Expression ]
    //     super . IdentifierName
    // SuperCall:
    //     super ( Arguments )
    if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL)
      { this.unexpected(); }
    return this.finishNode(node, "Super")

  case types$1._this:
    node = this.startNode();
    this.next();
    return this.finishNode(node, "ThisExpression")

  case types$1.name:
    var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
    var id = this.parseIdent(false);
    if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {
      this.overrideContext(types.f_expr);
      return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)
    }
    if (canBeArrow && !this.canInsertSemicolon()) {
      if (this.eat(types$1.arrow))
        { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) }
      if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc &&
          (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
        id = this.parseIdent(false);
        if (this.canInsertSemicolon() || !this.eat(types$1.arrow))
          { this.unexpected(); }
        return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)
      }
    }
    return id

  case types$1.regexp:
    var value = this.value;
    node = this.parseLiteral(value.value);
    node.regex = {pattern: value.pattern, flags: value.flags};
    return node

  case types$1.num: case types$1.string:
    return this.parseLiteral(this.value)

  case types$1._null: case types$1._true: case types$1._false:
    node = this.startNode();
    node.value = this.type === types$1._null ? null : this.type === types$1._true;
    node.raw = this.type.keyword;
    this.next();
    return this.finishNode(node, "Literal")

  case types$1.parenL:
    var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
    if (refDestructuringErrors) {
      if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
        { refDestructuringErrors.parenthesizedAssign = start; }
      if (refDestructuringErrors.parenthesizedBind < 0)
        { refDestructuringErrors.parenthesizedBind = start; }
    }
    return expr

  case types$1.bracketL:
    node = this.startNode();
    this.next();
    node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);
    return this.finishNode(node, "ArrayExpression")

  case types$1.braceL:
    this.overrideContext(types.b_expr);
    return this.parseObj(false, refDestructuringErrors)

  case types$1._function:
    node = this.startNode();
    this.next();
    return this.parseFunction(node, 0)

  case types$1._class:
    return this.parseClass(this.startNode(), false)

  case types$1._new:
    return this.parseNew()

  case types$1.backQuote:
    return this.parseTemplate()

  case types$1._import:
    if (this.options.ecmaVersion >= 11) {
      return this.parseExprImport(forNew)
    } else {
      return this.unexpected()
    }

  default:
    return this.parseExprAtomDefault()
  }
};

pp$5.parseExprAtomDefault = function() {
  this.unexpected();
};

pp$5.parseExprImport = function(forNew) {
  var node = this.startNode();

  // Consume `import` as an identifier for `import.meta`.
  // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
  if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
  var meta = this.parseIdent(true);

  if (this.type === types$1.parenL && !forNew) {
    return this.parseDynamicImport(node)
  } else if (this.type === types$1.dot) {
    node.meta = meta;
    return this.parseImportMeta(node)
  } else {
    this.unexpected();
  }
};

pp$5.parseDynamicImport = function(node) {
  this.next(); // skip `(`

  // Parse node.source.
  node.source = this.parseMaybeAssign();

  // Verify ending.
  if (!this.eat(types$1.parenR)) {
    var errorPos = this.start;
    if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {
      this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
    } else {
      this.unexpected(errorPos);
    }
  }

  return this.finishNode(node, "ImportExpression")
};

pp$5.parseImportMeta = function(node) {
  this.next(); // skip `.`

  var containsEsc = this.containsEsc;
  node.property = this.parseIdent(true);

  if (node.property.name !== "meta")
    { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
  if (containsEsc)
    { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
  if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
    { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }

  return this.finishNode(node, "MetaProperty")
};

pp$5.parseLiteral = function(value) {
  var node = this.startNode();
  node.value = value;
  node.raw = this.input.slice(this.start, this.end);
  if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
  this.next();
  return this.finishNode(node, "Literal")
};

pp$5.parseParenExpression = function() {
  this.expect(types$1.parenL);
  var val = this.parseExpression();
  this.expect(types$1.parenR);
  return val
};

pp$5.shouldParseArrow = function(exprList) {
  return !this.canInsertSemicolon()
};

pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
  var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  if (this.options.ecmaVersion >= 6) {
    this.next();

    var innerStartPos = this.start, innerStartLoc = this.startLoc;
    var exprList = [], first = true, lastIsComma = false;
    var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
    this.yieldPos = 0;
    this.awaitPos = 0;
    // Do not save awaitIdentPos to allow checking awaits nested in parameters
    while (this.type !== types$1.parenR) {
      first ? first = false : this.expect(types$1.comma);
      if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {
        lastIsComma = true;
        break
      } else if (this.type === types$1.ellipsis) {
        spreadStart = this.start;
        exprList.push(this.parseParenItem(this.parseRestBinding()));
        if (this.type === types$1.comma) {
          this.raiseRecoverable(
            this.start,
            "Comma is not permitted after the rest element"
          );
        }
        break
      } else {
        exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
      }
    }
    var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
    this.expect(types$1.parenR);

    if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$1.arrow)) {
      this.checkPatternErrors(refDestructuringErrors, false);
      this.checkYieldAwaitInDefaultParams();
      this.yieldPos = oldYieldPos;
      this.awaitPos = oldAwaitPos;
      return this.parseParenArrowList(startPos, startLoc, exprList, forInit)
    }

    if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
    if (spreadStart) { this.unexpected(spreadStart); }
    this.checkExpressionErrors(refDestructuringErrors, true);
    this.yieldPos = oldYieldPos || this.yieldPos;
    this.awaitPos = oldAwaitPos || this.awaitPos;

    if (exprList.length > 1) {
      val = this.startNodeAt(innerStartPos, innerStartLoc);
      val.expressions = exprList;
      this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
    } else {
      val = exprList[0];
    }
  } else {
    val = this.parseParenExpression();
  }

  if (this.options.preserveParens) {
    var par = this.startNodeAt(startPos, startLoc);
    par.expression = val;
    return this.finishNode(par, "ParenthesizedExpression")
  } else {
    return val
  }
};

pp$5.parseParenItem = function(item) {
  return item
};

pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
  return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit)
};

// New's precedence is slightly tricky. It must allow its argument to
// be a `[]` or dot subscript expression, but not a call — at least,
// not without wrapping it in parentheses. Thus, it uses the noCalls
// argument to parseSubscripts to prevent it from consuming the
// argument list.

var empty = [];

pp$5.parseNew = function() {
  if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
  var node = this.startNode();
  var meta = this.parseIdent(true);
  if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) {
    node.meta = meta;
    var containsEsc = this.containsEsc;
    node.property = this.parseIdent(true);
    if (node.property.name !== "target")
      { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
    if (containsEsc)
      { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
    if (!this.allowNewDotTarget)
      { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); }
    return this.finishNode(node, "MetaProperty")
  }
  var startPos = this.start, startLoc = this.startLoc;
  node.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false);
  if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); }
  else { node.arguments = empty; }
  return this.finishNode(node, "NewExpression")
};

// Parse template expression.

pp$5.parseTemplateElement = function(ref) {
  var isTagged = ref.isTagged;

  var elem = this.startNode();
  if (this.type === types$1.invalidTemplate) {
    if (!isTagged) {
      this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
    }
    elem.value = {
      raw: this.value,
      cooked: null
    };
  } else {
    elem.value = {
      raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
      cooked: this.value
    };
  }
  this.next();
  elem.tail = this.type === types$1.backQuote;
  return this.finishNode(elem, "TemplateElement")
};

pp$5.parseTemplate = function(ref) {
  if ( ref === void 0 ) ref = {};
  var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;

  var node = this.startNode();
  this.next();
  node.expressions = [];
  var curElt = this.parseTemplateElement({isTagged: isTagged});
  node.quasis = [curElt];
  while (!curElt.tail) {
    if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); }
    this.expect(types$1.dollarBraceL);
    node.expressions.push(this.parseExpression());
    this.expect(types$1.braceR);
    node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  }
  this.next();
  return this.finishNode(node, "TemplateLiteral")
};

pp$5.isAsyncProp = function(prop) {
  return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
    (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1.star)) &&
    !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
};

// Parse an object literal or binding pattern.

pp$5.parseObj = function(isPattern, refDestructuringErrors) {
  var node = this.startNode(), first = true, propHash = {};
  node.properties = [];
  this.next();
  while (!this.eat(types$1.braceR)) {
    if (!first) {
      this.expect(types$1.comma);
      if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break }
    } else { first = false; }

    var prop = this.parseProperty(isPattern, refDestructuringErrors);
    if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
    node.properties.push(prop);
  }
  return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
};

pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
  var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {
    if (isPattern) {
      prop.argument = this.parseIdent(false);
      if (this.type === types$1.comma) {
        this.raiseRecoverable(this.start, "Comma is not permitted after the rest element");
      }
      return this.finishNode(prop, "RestElement")
    }
    // Parse argument.
    prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
    // To disallow trailing comma via `this.toAssignable()`.
    if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
      refDestructuringErrors.trailingComma = this.start;
    }
    // Finish
    return this.finishNode(prop, "SpreadElement")
  }
  if (this.options.ecmaVersion >= 6) {
    prop.method = false;
    prop.shorthand = false;
    if (isPattern || refDestructuringErrors) {
      startPos = this.start;
      startLoc = this.startLoc;
    }
    if (!isPattern)
      { isGenerator = this.eat(types$1.star); }
  }
  var containsEsc = this.containsEsc;
  this.parsePropertyName(prop);
  if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
    isAsync = true;
    isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);
    this.parsePropertyName(prop);
  } else {
    isAsync = false;
  }
  this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  return this.finishNode(prop, "Property")
};

pp$5.parseGetterSetter = function(prop) {
  prop.kind = prop.key.name;
  this.parsePropertyName(prop);
  prop.value = this.parseMethod(false);
  var paramCount = prop.kind === "get" ? 0 : 1;
  if (prop.value.params.length !== paramCount) {
    var start = prop.value.start;
    if (prop.kind === "get")
      { this.raiseRecoverable(start, "getter should have no params"); }
    else
      { this.raiseRecoverable(start, "setter should have exactly one param"); }
  } else {
    if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
      { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  }
};

pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  if ((isGenerator || isAsync) && this.type === types$1.colon)
    { this.unexpected(); }

  if (this.eat(types$1.colon)) {
    prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
    prop.kind = "init";
  } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {
    if (isPattern) { this.unexpected(); }
    prop.kind = "init";
    prop.method = true;
    prop.value = this.parseMethod(isGenerator, isAsync);
  } else if (!isPattern && !containsEsc &&
             this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
             (prop.key.name === "get" || prop.key.name === "set") &&
             (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {
    if (isGenerator || isAsync) { this.unexpected(); }
    this.parseGetterSetter(prop);
  } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
    if (isGenerator || isAsync) { this.unexpected(); }
    this.checkUnreserved(prop.key);
    if (prop.key.name === "await" && !this.awaitIdentPos)
      { this.awaitIdentPos = startPos; }
    prop.kind = "init";
    if (isPattern) {
      prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
    } else if (this.type === types$1.eq && refDestructuringErrors) {
      if (refDestructuringErrors.shorthandAssign < 0)
        { refDestructuringErrors.shorthandAssign = this.start; }
      prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
    } else {
      prop.value = this.copyNode(prop.key);
    }
    prop.shorthand = true;
  } else { this.unexpected(); }
};

pp$5.parsePropertyName = function(prop) {
  if (this.options.ecmaVersion >= 6) {
    if (this.eat(types$1.bracketL)) {
      prop.computed = true;
      prop.key = this.parseMaybeAssign();
      this.expect(types$1.bracketR);
      return prop.key
    } else {
      prop.computed = false;
    }
  }
  return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
};

// Initialize empty function node.

pp$5.initFunction = function(node) {
  node.id = null;
  if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
  if (this.options.ecmaVersion >= 8) { node.async = false; }
};

// Parse object or class method.

pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;

  this.initFunction(node);
  if (this.options.ecmaVersion >= 6)
    { node.generator = isGenerator; }
  if (this.options.ecmaVersion >= 8)
    { node.async = !!isAsync; }

  this.yieldPos = 0;
  this.awaitPos = 0;
  this.awaitIdentPos = 0;
  this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));

  this.expect(types$1.parenL);
  node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  this.checkYieldAwaitInDefaultParams();
  this.parseFunctionBody(node, false, true, false);

  this.yieldPos = oldYieldPos;
  this.awaitPos = oldAwaitPos;
  this.awaitIdentPos = oldAwaitIdentPos;
  return this.finishNode(node, "FunctionExpression")
};

// Parse arrow function expression with given parameters.

pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {
  var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;

  this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
  this.initFunction(node);
  if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }

  this.yieldPos = 0;
  this.awaitPos = 0;
  this.awaitIdentPos = 0;

  node.params = this.toAssignableList(params, true);
  this.parseFunctionBody(node, true, false, forInit);

  this.yieldPos = oldYieldPos;
  this.awaitPos = oldAwaitPos;
  this.awaitIdentPos = oldAwaitIdentPos;
  return this.finishNode(node, "ArrowFunctionExpression")
};

// Parse function body and check parameters.

pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
  var isExpression = isArrowFunction && this.type !== types$1.braceL;
  var oldStrict = this.strict, useStrict = false;

  if (isExpression) {
    node.body = this.parseMaybeAssign(forInit);
    node.expression = true;
    this.checkParams(node, false);
  } else {
    var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
    if (!oldStrict || nonSimple) {
      useStrict = this.strictDirective(this.end);
      // If this is a strict mode function, verify that argument names
      // are not repeated, and it does not try to bind the words `eval`
      // or `arguments`.
      if (useStrict && nonSimple)
        { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
    }
    // Start a new scope with regard to labels and the `inFunction`
    // flag (restore them to their old value afterwards).
    var oldLabels = this.labels;
    this.labels = [];
    if (useStrict) { this.strict = true; }

    // Add the params to varDeclaredNames to ensure that an error is thrown
    // if a let/const declaration in the function clashes with one of the params.
    this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
    // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
    if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
    node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
    node.expression = false;
    this.adaptDirectivePrologue(node.body.body);
    this.labels = oldLabels;
  }
  this.exitScope();
};

pp$5.isSimpleParamList = function(params) {
  for (var i = 0, list = params; i < list.length; i += 1)
    {
    var param = list[i];

    if (param.type !== "Identifier") { return false
  } }
  return true
};

// Checks function params for various disallowed patterns such as using "eval"
// or "arguments" and duplicate parameters.

pp$5.checkParams = function(node, allowDuplicates) {
  var nameHash = Object.create(null);
  for (var i = 0, list = node.params; i < list.length; i += 1)
    {
    var param = list[i];

    this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
  }
};

// Parses a comma-separated list of expressions, and returns them as
// an array. `close` is the token type that ends the list, and
// `allowEmpty` can be turned on to allow subsequent commas with
// nothing in between them to be parsed as `null` (which is needed
// for array literals).

pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  var elts = [], first = true;
  while (!this.eat(close)) {
    if (!first) {
      this.expect(types$1.comma);
      if (allowTrailingComma && this.afterTrailingComma(close)) { break }
    } else { first = false; }

    var elt = (void 0);
    if (allowEmpty && this.type === types$1.comma)
      { elt = null; }
    else if (this.type === types$1.ellipsis) {
      elt = this.parseSpread(refDestructuringErrors);
      if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0)
        { refDestructuringErrors.trailingComma = this.start; }
    } else {
      elt = this.parseMaybeAssign(false, refDestructuringErrors);
    }
    elts.push(elt);
  }
  return elts
};

pp$5.checkUnreserved = function(ref) {
  var start = ref.start;
  var end = ref.end;
  var name = ref.name;

  if (this.inGenerator && name === "yield")
    { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
  if (this.inAsync && name === "await")
    { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
  if (this.currentThisScope().inClassFieldInit && name === "arguments")
    { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
  if (this.inClassStaticBlock && (name === "arguments" || name === "await"))
    { this.raise(start, ("Cannot use " + name + " in class static initialization block")); }
  if (this.keywords.test(name))
    { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  if (this.options.ecmaVersion < 6 &&
    this.input.slice(start, end).indexOf("\\") !== -1) { return }
  var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  if (re.test(name)) {
    if (!this.inAsync && name === "await")
      { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
    this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
  }
};

// Parse the next token as an identifier. If `liberal` is true (used
// when parsing properties), it will also convert keywords into
// identifiers.

pp$5.parseIdent = function(liberal) {
  var node = this.parseIdentNode();
  this.next(!!liberal);
  this.finishNode(node, "Identifier");
  if (!liberal) {
    this.checkUnreserved(node);
    if (node.name === "await" && !this.awaitIdentPos)
      { this.awaitIdentPos = node.start; }
  }
  return node
};

pp$5.parseIdentNode = function() {
  var node = this.startNode();
  if (this.type === types$1.name) {
    node.name = this.value;
  } else if (this.type.keyword) {
    node.name = this.type.keyword;

    // To fix https://github.com/acornjs/acorn/issues/575
    // `class` and `function` keywords push new context into this.context.
    // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
    // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
    if ((node.name === "class" || node.name === "function") &&
      (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
      this.context.pop();
    }
  } else {
    this.unexpected();
  }
  return node
};

pp$5.parsePrivateIdent = function() {
  var node = this.startNode();
  if (this.type === types$1.privateId) {
    node.name = this.value;
  } else {
    this.unexpected();
  }
  this.next();
  this.finishNode(node, "PrivateIdentifier");

  // For validating existence
  if (this.privateNameStack.length === 0) {
    this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
  } else {
    this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
  }

  return node
};

// Parses yield expression inside generator.

pp$5.parseYield = function(forInit) {
  if (!this.yieldPos) { this.yieldPos = this.start; }

  var node = this.startNode();
  this.next();
  if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) {
    node.delegate = false;
    node.argument = null;
  } else {
    node.delegate = this.eat(types$1.star);
    node.argument = this.parseMaybeAssign(forInit);
  }
  return this.finishNode(node, "YieldExpression")
};

pp$5.parseAwait = function(forInit) {
  if (!this.awaitPos) { this.awaitPos = this.start; }

  var node = this.startNode();
  this.next();
  node.argument = this.parseMaybeUnary(null, true, false, forInit);
  return this.finishNode(node, "AwaitExpression")
};

var pp$4 = Parser$1.prototype;

// This function is used to raise exceptions on parse errors. It
// takes an offset integer (into the current `input`) to indicate
// the location of the error, attaches the position to the end
// of the error message, and then raises a `SyntaxError` with that
// message.

pp$4.raise = function(pos, message) {
  var loc = getLineInfo(this.input, pos);
  message += " (" + loc.line + ":" + loc.column + ")";
  var err = new SyntaxError(message);
  err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  throw err
};

pp$4.raiseRecoverable = pp$4.raise;

pp$4.curPosition = function() {
  if (this.options.locations) {
    return new Position(this.curLine, this.pos - this.lineStart)
  }
};

var pp$3 = Parser$1.prototype;

var Scope$1 = function Scope(flags) {
  this.flags = flags;
  // A list of var-declared names in the current lexical scope
  this.var = [];
  // A list of lexically-declared names in the current lexical scope
  this.lexical = [];
  // A list of lexically-declared FunctionDeclaration names in the current lexical scope
  this.functions = [];
  // A switch to disallow the identifier reference 'arguments'
  this.inClassFieldInit = false;
};

// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.

pp$3.enterScope = function(flags) {
  this.scopeStack.push(new Scope$1(flags));
};

pp$3.exitScope = function() {
  this.scopeStack.pop();
};

// The spec says:
// > At the top level of a function, or script, function declarations are
// > treated like var declarations rather than like lexical declarations.
pp$3.treatFunctionsAsVarInScope = function(scope) {
  return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
};

pp$3.declareName = function(name, bindingType, pos) {
  var redeclared = false;
  if (bindingType === BIND_LEXICAL) {
    var scope = this.currentScope();
    redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
    scope.lexical.push(name);
    if (this.inModule && (scope.flags & SCOPE_TOP))
      { delete this.undefinedExports[name]; }
  } else if (bindingType === BIND_SIMPLE_CATCH) {
    var scope$1 = this.currentScope();
    scope$1.lexical.push(name);
  } else if (bindingType === BIND_FUNCTION) {
    var scope$2 = this.currentScope();
    if (this.treatFunctionsAsVar)
      { redeclared = scope$2.lexical.indexOf(name) > -1; }
    else
      { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
    scope$2.functions.push(name);
  } else {
    for (var i = this.scopeStack.length - 1; i >= 0; --i) {
      var scope$3 = this.scopeStack[i];
      if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
          !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
        redeclared = true;
        break
      }
      scope$3.var.push(name);
      if (this.inModule && (scope$3.flags & SCOPE_TOP))
        { delete this.undefinedExports[name]; }
      if (scope$3.flags & SCOPE_VAR) { break }
    }
  }
  if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
};

pp$3.checkLocalExport = function(id) {
  // scope.functions must be empty as Module code is always strict.
  if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
      this.scopeStack[0].var.indexOf(id.name) === -1) {
    this.undefinedExports[id.name] = id;
  }
};

pp$3.currentScope = function() {
  return this.scopeStack[this.scopeStack.length - 1]
};

pp$3.currentVarScope = function() {
  for (var i = this.scopeStack.length - 1;; i--) {
    var scope = this.scopeStack[i];
    if (scope.flags & SCOPE_VAR) { return scope }
  }
};

// Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
pp$3.currentThisScope = function() {
  for (var i = this.scopeStack.length - 1;; i--) {
    var scope = this.scopeStack[i];
    if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
  }
};

var Node$1 = function Node(parser, pos, loc) {
  this.type = "";
  this.start = pos;
  this.end = 0;
  if (parser.options.locations)
    { this.loc = new SourceLocation(parser, loc); }
  if (parser.options.directSourceFile)
    { this.sourceFile = parser.options.directSourceFile; }
  if (parser.options.ranges)
    { this.range = [pos, 0]; }
};

// Start an AST node, attaching a start offset.

var pp$2 = Parser$1.prototype;

pp$2.startNode = function() {
  return new Node$1(this, this.start, this.startLoc)
};

pp$2.startNodeAt = function(pos, loc) {
  return new Node$1(this, pos, loc)
};

// Finish an AST node, adding `type` and `end` properties.

function finishNodeAt(node, type, pos, loc) {
  node.type = type;
  node.end = pos;
  if (this.options.locations)
    { node.loc.end = loc; }
  if (this.options.ranges)
    { node.range[1] = pos; }
  return node
}

pp$2.finishNode = function(node, type) {
  return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
};

// Finish node at given position

pp$2.finishNodeAt = function(node, type, pos, loc) {
  return finishNodeAt.call(this, node, type, pos, loc)
};

pp$2.copyNode = function(node) {
  var newNode = new Node$1(this, node.start, this.startLoc);
  for (var prop in node) { newNode[prop] = node[prop]; }
  return newNode
};

// This file contains Unicode properties extracted from the ECMAScript specification.
// The lists are extracted like so:
// $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)

// #table-binary-unicode-properties
var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
var ecma11BinaryProperties = ecma10BinaryProperties;
var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
var ecma13BinaryProperties = ecma12BinaryProperties;
var ecma14BinaryProperties = ecma13BinaryProperties;

var unicodeBinaryProperties = {
  9: ecma9BinaryProperties,
  10: ecma10BinaryProperties,
  11: ecma11BinaryProperties,
  12: ecma12BinaryProperties,
  13: ecma13BinaryProperties,
  14: ecma14BinaryProperties
};

// #table-binary-unicode-properties-of-strings
var ecma14BinaryPropertiesOfStrings = "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji";

var unicodeBinaryPropertiesOfStrings = {
  9: "",
  10: "",
  11: "",
  12: "",
  13: "",
  14: ecma14BinaryPropertiesOfStrings
};

// #table-unicode-general-category-values
var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";

// #table-unicode-script-values
var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
var ecma14ScriptValues = ecma13ScriptValues + " Hrkt Katakana_Or_Hiragana Kawi Nag_Mundari Nagm Unknown Zzzz";

var unicodeScriptValues = {
  9: ecma9ScriptValues,
  10: ecma10ScriptValues,
  11: ecma11ScriptValues,
  12: ecma12ScriptValues,
  13: ecma13ScriptValues,
  14: ecma14ScriptValues
};

var data = {};
function buildUnicodeData(ecmaVersion) {
  var d = data[ecmaVersion] = {
    binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
    binaryOfStrings: wordsRegexp(unicodeBinaryPropertiesOfStrings[ecmaVersion]),
    nonBinary: {
      General_Category: wordsRegexp(unicodeGeneralCategoryValues),
      Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
    }
  };
  d.nonBinary.Script_Extensions = d.nonBinary.Script;

  d.nonBinary.gc = d.nonBinary.General_Category;
  d.nonBinary.sc = d.nonBinary.Script;
  d.nonBinary.scx = d.nonBinary.Script_Extensions;
}

for (var i$2 = 0, list$1 = [9, 10, 11, 12, 13, 14]; i$2 < list$1.length; i$2 += 1) {
  var ecmaVersion = list$1[i$2];

  buildUnicodeData(ecmaVersion);
}

var pp$1 = Parser$1.prototype;

var RegExpValidationState = function RegExpValidationState(parser) {
  this.parser = parser;
  this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "") + (parser.options.ecmaVersion >= 15 ? "v" : "");
  this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion];
  this.source = "";
  this.flags = "";
  this.start = 0;
  this.switchU = false;
  this.switchV = false;
  this.switchN = false;
  this.pos = 0;
  this.lastIntValue = 0;
  this.lastStringValue = "";
  this.lastAssertionIsQuantifiable = false;
  this.numCapturingParens = 0;
  this.maxBackReference = 0;
  this.groupNames = [];
  this.backReferenceNames = [];
};

RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
  var unicodeSets = flags.indexOf("v") !== -1;
  var unicode = flags.indexOf("u") !== -1;
  this.start = start | 0;
  this.source = pattern + "";
  this.flags = flags;
  if (unicodeSets && this.parser.options.ecmaVersion >= 15) {
    this.switchU = true;
    this.switchV = true;
    this.switchN = true;
  } else {
    this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
    this.switchV = false;
    this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  }
};

RegExpValidationState.prototype.raise = function raise (message) {
  this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
};

// If u flag is given, this returns the code point at the index (it combines a surrogate pair).
// Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
RegExpValidationState.prototype.at = function at (i, forceU) {
    if ( forceU === void 0 ) forceU = false;

  var s = this.source;
  var l = s.length;
  if (i >= l) {
    return -1
  }
  var c = s.charCodeAt(i);
  if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
    return c
  }
  var next = s.charCodeAt(i + 1);
  return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
};

RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
    if ( forceU === void 0 ) forceU = false;

  var s = this.source;
  var l = s.length;
  if (i >= l) {
    return l
  }
  var c = s.charCodeAt(i), next;
  if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
      (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
    return i + 1
  }
  return i + 2
};

RegExpValidationState.prototype.current = function current (forceU) {
    if ( forceU === void 0 ) forceU = false;

  return this.at(this.pos, forceU)
};

RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
    if ( forceU === void 0 ) forceU = false;

  return this.at(this.nextIndex(this.pos, forceU), forceU)
};

RegExpValidationState.prototype.advance = function advance (forceU) {
    if ( forceU === void 0 ) forceU = false;

  this.pos = this.nextIndex(this.pos, forceU);
};

RegExpValidationState.prototype.eat = function eat (ch, forceU) {
    if ( forceU === void 0 ) forceU = false;

  if (this.current(forceU) === ch) {
    this.advance(forceU);
    return true
  }
  return false
};

RegExpValidationState.prototype.eatChars = function eatChars (chs, forceU) {
    if ( forceU === void 0 ) forceU = false;

  var pos = this.pos;
  for (var i = 0, list = chs; i < list.length; i += 1) {
    var ch = list[i];

      var current = this.at(pos, forceU);
    if (current === -1 || current !== ch) {
      return false
    }
    pos = this.nextIndex(pos, forceU);
  }
  this.pos = pos;
  return true
};

/**
 * Validate the flags part of a given RegExpLiteral.
 *
 * @param {RegExpValidationState} state The state to validate RegExp.
 * @returns {void}
 */
pp$1.validateRegExpFlags = function(state) {
  var validFlags = state.validFlags;
  var flags = state.flags;

  var u = false;
  var v = false;

  for (var i = 0; i < flags.length; i++) {
    var flag = flags.charAt(i);
    if (validFlags.indexOf(flag) === -1) {
      this.raise(state.start, "Invalid regular expression flag");
    }
    if (flags.indexOf(flag, i + 1) > -1) {
      this.raise(state.start, "Duplicate regular expression flag");
    }
    if (flag === "u") { u = true; }
    if (flag === "v") { v = true; }
  }
  if (this.options.ecmaVersion >= 15 && u && v) {
    this.raise(state.start, "Invalid regular expression flag");
  }
};

/**
 * Validate the pattern part of a given RegExpLiteral.
 *
 * @param {RegExpValidationState} state The state to validate RegExp.
 * @returns {void}
 */
pp$1.validateRegExpPattern = function(state) {
  this.regexp_pattern(state);

  // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
  // parsing contains a |GroupName|, reparse with the goal symbol
  // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
  // exception if _P_ did not conform to the grammar, if any elements of _P_
  // were not matched by the parse, or if any Early Error conditions exist.
  if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
    state.switchN = true;
    this.regexp_pattern(state);
  }
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
pp$1.regexp_pattern = function(state) {
  state.pos = 0;
  state.lastIntValue = 0;
  state.lastStringValue = "";
  state.lastAssertionIsQuantifiable = false;
  state.numCapturingParens = 0;
  state.maxBackReference = 0;
  state.groupNames.length = 0;
  state.backReferenceNames.length = 0;

  this.regexp_disjunction(state);

  if (state.pos !== state.source.length) {
    // Make the same messages as V8.
    if (state.eat(0x29 /* ) */)) {
      state.raise("Unmatched ')'");
    }
    if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
      state.raise("Lone quantifier brackets");
    }
  }
  if (state.maxBackReference > state.numCapturingParens) {
    state.raise("Invalid escape");
  }
  for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
    var name = list[i];

    if (state.groupNames.indexOf(name) === -1) {
      state.raise("Invalid named capture referenced");
    }
  }
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
pp$1.regexp_disjunction = function(state) {
  this.regexp_alternative(state);
  while (state.eat(0x7C /* | */)) {
    this.regexp_alternative(state);
  }

  // Make the same message as V8.
  if (this.regexp_eatQuantifier(state, true)) {
    state.raise("Nothing to repeat");
  }
  if (state.eat(0x7B /* { */)) {
    state.raise("Lone quantifier brackets");
  }
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
pp$1.regexp_alternative = function(state) {
  while (state.pos < state.source.length && this.regexp_eatTerm(state))
    { }
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
pp$1.regexp_eatTerm = function(state) {
  if (this.regexp_eatAssertion(state)) {
    // Handle `QuantifiableAssertion Quantifier` alternative.
    // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
    // is a QuantifiableAssertion.
    if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
      // Make the same message as V8.
      if (state.switchU) {
        state.raise("Invalid quantifier");
      }
    }
    return true
  }

  if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
    this.regexp_eatQuantifier(state);
    return true
  }

  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
pp$1.regexp_eatAssertion = function(state) {
  var start = state.pos;
  state.lastAssertionIsQuantifiable = false;

  // ^, $
  if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
    return true
  }

  // \b \B
  if (state.eat(0x5C /* \ */)) {
    if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
      return true
    }
    state.pos = start;
  }

  // Lookahead / Lookbehind
  if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
    var lookbehind = false;
    if (this.options.ecmaVersion >= 9) {
      lookbehind = state.eat(0x3C /* < */);
    }
    if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
      this.regexp_disjunction(state);
      if (!state.eat(0x29 /* ) */)) {
        state.raise("Unterminated group");
      }
      state.lastAssertionIsQuantifiable = !lookbehind;
      return true
    }
  }

  state.pos = start;
  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
pp$1.regexp_eatQuantifier = function(state, noError) {
  if ( noError === void 0 ) noError = false;

  if (this.regexp_eatQuantifierPrefix(state, noError)) {
    state.eat(0x3F /* ? */);
    return true
  }
  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
  return (
    state.eat(0x2A /* * */) ||
    state.eat(0x2B /* + */) ||
    state.eat(0x3F /* ? */) ||
    this.regexp_eatBracedQuantifier(state, noError)
  )
};
pp$1.regexp_eatBracedQuantifier = function(state, noError) {
  var start = state.pos;
  if (state.eat(0x7B /* { */)) {
    var min = 0, max = -1;
    if (this.regexp_eatDecimalDigits(state)) {
      min = state.lastIntValue;
      if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
        max = state.lastIntValue;
      }
      if (state.eat(0x7D /* } */)) {
        // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
        if (max !== -1 && max < min && !noError) {
          state.raise("numbers out of order in {} quantifier");
        }
        return true
      }
    }
    if (state.switchU && !noError) {
      state.raise("Incomplete quantifier");
    }
    state.pos = start;
  }
  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
pp$1.regexp_eatAtom = function(state) {
  return (
    this.regexp_eatPatternCharacters(state) ||
    state.eat(0x2E /* . */) ||
    this.regexp_eatReverseSolidusAtomEscape(state) ||
    this.regexp_eatCharacterClass(state) ||
    this.regexp_eatUncapturingGroup(state) ||
    this.regexp_eatCapturingGroup(state)
  )
};
pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
  var start = state.pos;
  if (state.eat(0x5C /* \ */)) {
    if (this.regexp_eatAtomEscape(state)) {
      return true
    }
    state.pos = start;
  }
  return false
};
pp$1.regexp_eatUncapturingGroup = function(state) {
  var start = state.pos;
  if (state.eat(0x28 /* ( */)) {
    if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
      this.regexp_disjunction(state);
      if (state.eat(0x29 /* ) */)) {
        return true
      }
      state.raise("Unterminated group");
    }
    state.pos = start;
  }
  return false
};
pp$1.regexp_eatCapturingGroup = function(state) {
  if (state.eat(0x28 /* ( */)) {
    if (this.options.ecmaVersion >= 9) {
      this.regexp_groupSpecifier(state);
    } else if (state.current() === 0x3F /* ? */) {
      state.raise("Invalid group");
    }
    this.regexp_disjunction(state);
    if (state.eat(0x29 /* ) */)) {
      state.numCapturingParens += 1;
      return true
    }
    state.raise("Unterminated group");
  }
  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
pp$1.regexp_eatExtendedAtom = function(state) {
  return (
    state.eat(0x2E /* . */) ||
    this.regexp_eatReverseSolidusAtomEscape(state) ||
    this.regexp_eatCharacterClass(state) ||
    this.regexp_eatUncapturingGroup(state) ||
    this.regexp_eatCapturingGroup(state) ||
    this.regexp_eatInvalidBracedQuantifier(state) ||
    this.regexp_eatExtendedPatternCharacter(state)
  )
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
  if (this.regexp_eatBracedQuantifier(state, true)) {
    state.raise("Nothing to repeat");
  }
  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
pp$1.regexp_eatSyntaxCharacter = function(state) {
  var ch = state.current();
  if (isSyntaxCharacter(ch)) {
    state.lastIntValue = ch;
    state.advance();
    return true
  }
  return false
};
function isSyntaxCharacter(ch) {
  return (
    ch === 0x24 /* $ */ ||
    ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
    ch === 0x2E /* . */ ||
    ch === 0x3F /* ? */ ||
    ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
    ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  )
}

// https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
// But eat eager.
pp$1.regexp_eatPatternCharacters = function(state) {
  var start = state.pos;
  var ch = 0;
  while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
    state.advance();
  }
  return state.pos !== start
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
pp$1.regexp_eatExtendedPatternCharacter = function(state) {
  var ch = state.current();
  if (
    ch !== -1 &&
    ch !== 0x24 /* $ */ &&
    !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
    ch !== 0x2E /* . */ &&
    ch !== 0x3F /* ? */ &&
    ch !== 0x5B /* [ */ &&
    ch !== 0x5E /* ^ */ &&
    ch !== 0x7C /* | */
  ) {
    state.advance();
    return true
  }
  return false
};

// GroupSpecifier ::
//   [empty]
//   `?` GroupName
pp$1.regexp_groupSpecifier = function(state) {
  if (state.eat(0x3F /* ? */)) {
    if (this.regexp_eatGroupName(state)) {
      if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
        state.raise("Duplicate capture group name");
      }
      state.groupNames.push(state.lastStringValue);
      return
    }
    state.raise("Invalid group");
  }
};

// GroupName ::
//   `<` RegExpIdentifierName `>`
// Note: this updates `state.lastStringValue` property with the eaten name.
pp$1.regexp_eatGroupName = function(state) {
  state.lastStringValue = "";
  if (state.eat(0x3C /* < */)) {
    if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
      return true
    }
    state.raise("Invalid capture group name");
  }
  return false
};

// RegExpIdentifierName ::
//   RegExpIdentifierStart
//   RegExpIdentifierName RegExpIdentifierPart
// Note: this updates `state.lastStringValue` property with the eaten name.
pp$1.regexp_eatRegExpIdentifierName = function(state) {
  state.lastStringValue = "";
  if (this.regexp_eatRegExpIdentifierStart(state)) {
    state.lastStringValue += codePointToString(state.lastIntValue);
    while (this.regexp_eatRegExpIdentifierPart(state)) {
      state.lastStringValue += codePointToString(state.lastIntValue);
    }
    return true
  }
  return false
};

// RegExpIdentifierStart ::
//   UnicodeIDStart
//   `$`
//   `_`
//   `\` RegExpUnicodeEscapeSequence[+U]
pp$1.regexp_eatRegExpIdentifierStart = function(state) {
  var start = state.pos;
  var forceU = this.options.ecmaVersion >= 11;
  var ch = state.current(forceU);
  state.advance(forceU);

  if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
    ch = state.lastIntValue;
  }
  if (isRegExpIdentifierStart(ch)) {
    state.lastIntValue = ch;
    return true
  }

  state.pos = start;
  return false
};
function isRegExpIdentifierStart(ch) {
  return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
}

// RegExpIdentifierPart ::
//   UnicodeIDContinue
//   `$`
//   `_`
//   `\` RegExpUnicodeEscapeSequence[+U]
//   <ZWNJ>
//   <ZWJ>
pp$1.regexp_eatRegExpIdentifierPart = function(state) {
  var start = state.pos;
  var forceU = this.options.ecmaVersion >= 11;
  var ch = state.current(forceU);
  state.advance(forceU);

  if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
    ch = state.lastIntValue;
  }
  if (isRegExpIdentifierPart(ch)) {
    state.lastIntValue = ch;
    return true
  }

  state.pos = start;
  return false
};
function isRegExpIdentifierPart(ch) {
  return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
}

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
pp$1.regexp_eatAtomEscape = function(state) {
  if (
    this.regexp_eatBackReference(state) ||
    this.regexp_eatCharacterClassEscape(state) ||
    this.regexp_eatCharacterEscape(state) ||
    (state.switchN && this.regexp_eatKGroupName(state))
  ) {
    return true
  }
  if (state.switchU) {
    // Make the same message as V8.
    if (state.current() === 0x63 /* c */) {
      state.raise("Invalid unicode escape");
    }
    state.raise("Invalid escape");
  }
  return false
};
pp$1.regexp_eatBackReference = function(state) {
  var start = state.pos;
  if (this.regexp_eatDecimalEscape(state)) {
    var n = state.lastIntValue;
    if (state.switchU) {
      // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
      if (n > state.maxBackReference) {
        state.maxBackReference = n;
      }
      return true
    }
    if (n <= state.numCapturingParens) {
      return true
    }
    state.pos = start;
  }
  return false
};
pp$1.regexp_eatKGroupName = function(state) {
  if (state.eat(0x6B /* k */)) {
    if (this.regexp_eatGroupName(state)) {
      state.backReferenceNames.push(state.lastStringValue);
      return true
    }
    state.raise("Invalid named reference");
  }
  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
pp$1.regexp_eatCharacterEscape = function(state) {
  return (
    this.regexp_eatControlEscape(state) ||
    this.regexp_eatCControlLetter(state) ||
    this.regexp_eatZero(state) ||
    this.regexp_eatHexEscapeSequence(state) ||
    this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
    (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
    this.regexp_eatIdentityEscape(state)
  )
};
pp$1.regexp_eatCControlLetter = function(state) {
  var start = state.pos;
  if (state.eat(0x63 /* c */)) {
    if (this.regexp_eatControlLetter(state)) {
      return true
    }
    state.pos = start;
  }
  return false
};
pp$1.regexp_eatZero = function(state) {
  if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
    state.lastIntValue = 0;
    state.advance();
    return true
  }
  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
pp$1.regexp_eatControlEscape = function(state) {
  var ch = state.current();
  if (ch === 0x74 /* t */) {
    state.lastIntValue = 0x09; /* \t */
    state.advance();
    return true
  }
  if (ch === 0x6E /* n */) {
    state.lastIntValue = 0x0A; /* \n */
    state.advance();
    return true
  }
  if (ch === 0x76 /* v */) {
    state.lastIntValue = 0x0B; /* \v */
    state.advance();
    return true
  }
  if (ch === 0x66 /* f */) {
    state.lastIntValue = 0x0C; /* \f */
    state.advance();
    return true
  }
  if (ch === 0x72 /* r */) {
    state.lastIntValue = 0x0D; /* \r */
    state.advance();
    return true
  }
  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
pp$1.regexp_eatControlLetter = function(state) {
  var ch = state.current();
  if (isControlLetter(ch)) {
    state.lastIntValue = ch % 0x20;
    state.advance();
    return true
  }
  return false
};
function isControlLetter(ch) {
  return (
    (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
    (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
  )
}

// https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  if ( forceU === void 0 ) forceU = false;

  var start = state.pos;
  var switchU = forceU || state.switchU;

  if (state.eat(0x75 /* u */)) {
    if (this.regexp_eatFixedHexDigits(state, 4)) {
      var lead = state.lastIntValue;
      if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
        var leadSurrogateEnd = state.pos;
        if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
          var trail = state.lastIntValue;
          if (trail >= 0xDC00 && trail <= 0xDFFF) {
            state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
            return true
          }
        }
        state.pos = leadSurrogateEnd;
        state.lastIntValue = lead;
      }
      return true
    }
    if (
      switchU &&
      state.eat(0x7B /* { */) &&
      this.regexp_eatHexDigits(state) &&
      state.eat(0x7D /* } */) &&
      isValidUnicode(state.lastIntValue)
    ) {
      return true
    }
    if (switchU) {
      state.raise("Invalid unicode escape");
    }
    state.pos = start;
  }

  return false
};
function isValidUnicode(ch) {
  return ch >= 0 && ch <= 0x10FFFF
}

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
pp$1.regexp_eatIdentityEscape = function(state) {
  if (state.switchU) {
    if (this.regexp_eatSyntaxCharacter(state)) {
      return true
    }
    if (state.eat(0x2F /* / */)) {
      state.lastIntValue = 0x2F; /* / */
      return true
    }
    return false
  }

  var ch = state.current();
  if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
    state.lastIntValue = ch;
    state.advance();
    return true
  }

  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
pp$1.regexp_eatDecimalEscape = function(state) {
  state.lastIntValue = 0;
  var ch = state.current();
  if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
    do {
      state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
      state.advance();
    } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
    return true
  }
  return false
};

// Return values used by character set parsing methods, needed to
// forbid negation of sets that can match strings.
var CharSetNone = 0; // Nothing parsed
var CharSetOk = 1; // Construct parsed, cannot contain strings
var CharSetString = 2; // Construct parsed, can contain strings

// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
pp$1.regexp_eatCharacterClassEscape = function(state) {
  var ch = state.current();

  if (isCharacterClassEscape(ch)) {
    state.lastIntValue = -1;
    state.advance();
    return CharSetOk
  }

  var negate = false;
  if (
    state.switchU &&
    this.options.ecmaVersion >= 9 &&
    ((negate = ch === 0x50 /* P */) || ch === 0x70 /* p */)
  ) {
    state.lastIntValue = -1;
    state.advance();
    var result;
    if (
      state.eat(0x7B /* { */) &&
      (result = this.regexp_eatUnicodePropertyValueExpression(state)) &&
      state.eat(0x7D /* } */)
    ) {
      if (negate && result === CharSetString) { state.raise("Invalid property name"); }
      return result
    }
    state.raise("Invalid property name");
  }

  return CharSetNone
};

function isCharacterClassEscape(ch) {
  return (
    ch === 0x64 /* d */ ||
    ch === 0x44 /* D */ ||
    ch === 0x73 /* s */ ||
    ch === 0x53 /* S */ ||
    ch === 0x77 /* w */ ||
    ch === 0x57 /* W */
  )
}

// UnicodePropertyValueExpression ::
//   UnicodePropertyName `=` UnicodePropertyValue
//   LoneUnicodePropertyNameOrValue
pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
  var start = state.pos;

  // UnicodePropertyName `=` UnicodePropertyValue
  if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
    var name = state.lastStringValue;
    if (this.regexp_eatUnicodePropertyValue(state)) {
      var value = state.lastStringValue;
      this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
      return CharSetOk
    }
  }
  state.pos = start;

  // LoneUnicodePropertyNameOrValue
  if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
    var nameOrValue = state.lastStringValue;
    return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue)
  }
  return CharSetNone
};

pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  if (!hasOwn(state.unicodeProperties.nonBinary, name))
    { state.raise("Invalid property name"); }
  if (!state.unicodeProperties.nonBinary[name].test(value))
    { state.raise("Invalid property value"); }
};

pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  if (state.unicodeProperties.binary.test(nameOrValue)) { return CharSetOk }
  if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) { return CharSetString }
  state.raise("Invalid property name");
};

// UnicodePropertyName ::
//   UnicodePropertyNameCharacters
pp$1.regexp_eatUnicodePropertyName = function(state) {
  var ch = 0;
  state.lastStringValue = "";
  while (isUnicodePropertyNameCharacter(ch = state.current())) {
    state.lastStringValue += codePointToString(ch);
    state.advance();
  }
  return state.lastStringValue !== ""
};

function isUnicodePropertyNameCharacter(ch) {
  return isControlLetter(ch) || ch === 0x5F /* _ */
}

// UnicodePropertyValue ::
//   UnicodePropertyValueCharacters
pp$1.regexp_eatUnicodePropertyValue = function(state) {
  var ch = 0;
  state.lastStringValue = "";
  while (isUnicodePropertyValueCharacter(ch = state.current())) {
    state.lastStringValue += codePointToString(ch);
    state.advance();
  }
  return state.lastStringValue !== ""
};
function isUnicodePropertyValueCharacter(ch) {
  return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
}

// LoneUnicodePropertyNameOrValue ::
//   UnicodePropertyValueCharacters
pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  return this.regexp_eatUnicodePropertyValue(state)
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
pp$1.regexp_eatCharacterClass = function(state) {
  if (state.eat(0x5B /* [ */)) {
    var negate = state.eat(0x5E /* ^ */);
    var result = this.regexp_classContents(state);
    if (!state.eat(0x5D /* ] */))
      { state.raise("Unterminated character class"); }
    if (negate && result === CharSetString)
      { state.raise("Negated character class may contain strings"); }
    return true
  }
  return false
};

// https://tc39.es/ecma262/#prod-ClassContents
// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
pp$1.regexp_classContents = function(state) {
  if (state.current() === 0x5D /* ] */) { return CharSetOk }
  if (state.switchV) { return this.regexp_classSetExpression(state) }
  this.regexp_nonEmptyClassRanges(state);
  return CharSetOk
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
pp$1.regexp_nonEmptyClassRanges = function(state) {
  while (this.regexp_eatClassAtom(state)) {
    var left = state.lastIntValue;
    if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
      var right = state.lastIntValue;
      if (state.switchU && (left === -1 || right === -1)) {
        state.raise("Invalid character class");
      }
      if (left !== -1 && right !== -1 && left > right) {
        state.raise("Range out of order in character class");
      }
    }
  }
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
pp$1.regexp_eatClassAtom = function(state) {
  var start = state.pos;

  if (state.eat(0x5C /* \ */)) {
    if (this.regexp_eatClassEscape(state)) {
      return true
    }
    if (state.switchU) {
      // Make the same message as V8.
      var ch$1 = state.current();
      if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
        state.raise("Invalid class escape");
      }
      state.raise("Invalid escape");
    }
    state.pos = start;
  }

  var ch = state.current();
  if (ch !== 0x5D /* ] */) {
    state.lastIntValue = ch;
    state.advance();
    return true
  }

  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
pp$1.regexp_eatClassEscape = function(state) {
  var start = state.pos;

  if (state.eat(0x62 /* b */)) {
    state.lastIntValue = 0x08; /* <BS> */
    return true
  }

  if (state.switchU && state.eat(0x2D /* - */)) {
    state.lastIntValue = 0x2D; /* - */
    return true
  }

  if (!state.switchU && state.eat(0x63 /* c */)) {
    if (this.regexp_eatClassControlLetter(state)) {
      return true
    }
    state.pos = start;
  }

  return (
    this.regexp_eatCharacterClassEscape(state) ||
    this.regexp_eatCharacterEscape(state)
  )
};

// https://tc39.es/ecma262/#prod-ClassSetExpression
// https://tc39.es/ecma262/#prod-ClassUnion
// https://tc39.es/ecma262/#prod-ClassIntersection
// https://tc39.es/ecma262/#prod-ClassSubtraction
pp$1.regexp_classSetExpression = function(state) {
  var result = CharSetOk, subResult;
  if (this.regexp_eatClassSetRange(state)) ; else if (subResult = this.regexp_eatClassSetOperand(state)) {
    if (subResult === CharSetString) { result = CharSetString; }
    // https://tc39.es/ecma262/#prod-ClassIntersection
    var start = state.pos;
    while (state.eatChars([0x26, 0x26] /* && */)) {
      if (
        state.current() !== 0x26 /* & */ &&
        (subResult = this.regexp_eatClassSetOperand(state))
      ) {
        if (subResult !== CharSetString) { result = CharSetOk; }
        continue
      }
      state.raise("Invalid character in character class");
    }
    if (start !== state.pos) { return result }
    // https://tc39.es/ecma262/#prod-ClassSubtraction
    while (state.eatChars([0x2D, 0x2D] /* -- */)) {
      if (this.regexp_eatClassSetOperand(state)) { continue }
      state.raise("Invalid character in character class");
    }
    if (start !== state.pos) { return result }
  } else {
    state.raise("Invalid character in character class");
  }
  // https://tc39.es/ecma262/#prod-ClassUnion
  for (;;) {
    if (this.regexp_eatClassSetRange(state)) { continue }
    subResult = this.regexp_eatClassSetOperand(state);
    if (!subResult) { return result }
    if (subResult === CharSetString) { result = CharSetString; }
  }
};

// https://tc39.es/ecma262/#prod-ClassSetRange
pp$1.regexp_eatClassSetRange = function(state) {
  var start = state.pos;
  if (this.regexp_eatClassSetCharacter(state)) {
    var left = state.lastIntValue;
    if (state.eat(0x2D /* - */) && this.regexp_eatClassSetCharacter(state)) {
      var right = state.lastIntValue;
      if (left !== -1 && right !== -1 && left > right) {
        state.raise("Range out of order in character class");
      }
      return true
    }
    state.pos = start;
  }
  return false
};

// https://tc39.es/ecma262/#prod-ClassSetOperand
pp$1.regexp_eatClassSetOperand = function(state) {
  if (this.regexp_eatClassSetCharacter(state)) { return CharSetOk }
  return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state)
};

// https://tc39.es/ecma262/#prod-NestedClass
pp$1.regexp_eatNestedClass = function(state) {
  var start = state.pos;
  if (state.eat(0x5B /* [ */)) {
    var negate = state.eat(0x5E /* ^ */);
    var result = this.regexp_classContents(state);
    if (state.eat(0x5D /* ] */)) {
      if (negate && result === CharSetString) {
        state.raise("Negated character class may contain strings");
      }
      return result
    }
    state.pos = start;
  }
  if (state.eat(0x5C /* \ */)) {
    var result$1 = this.regexp_eatCharacterClassEscape(state);
    if (result$1) {
      return result$1
    }
    state.pos = start;
  }
  return null
};

// https://tc39.es/ecma262/#prod-ClassStringDisjunction
pp$1.regexp_eatClassStringDisjunction = function(state) {
  var start = state.pos;
  if (state.eatChars([0x5C, 0x71] /* \q */)) {
    if (state.eat(0x7B /* { */)) {
      var result = this.regexp_classStringDisjunctionContents(state);
      if (state.eat(0x7D /* } */)) {
        return result
      }
    } else {
      // Make the same message as V8.
      state.raise("Invalid escape");
    }
    state.pos = start;
  }
  return null
};

// https://tc39.es/ecma262/#prod-ClassStringDisjunctionContents
pp$1.regexp_classStringDisjunctionContents = function(state) {
  var result = this.regexp_classString(state);
  while (state.eat(0x7C /* | */)) {
    if (this.regexp_classString(state) === CharSetString) { result = CharSetString; }
  }
  return result
};

// https://tc39.es/ecma262/#prod-ClassString
// https://tc39.es/ecma262/#prod-NonEmptyClassString
pp$1.regexp_classString = function(state) {
  var count = 0;
  while (this.regexp_eatClassSetCharacter(state)) { count++; }
  return count === 1 ? CharSetOk : CharSetString
};

// https://tc39.es/ecma262/#prod-ClassSetCharacter
pp$1.regexp_eatClassSetCharacter = function(state) {
  var start = state.pos;
  if (state.eat(0x5C /* \ */)) {
    if (
      this.regexp_eatCharacterEscape(state) ||
      this.regexp_eatClassSetReservedPunctuator(state)
    ) {
      return true
    }
    if (state.eat(0x62 /* b */)) {
      state.lastIntValue = 0x08; /* <BS> */
      return true
    }
    state.pos = start;
    return false
  }
  var ch = state.current();
  if (ch < 0 || ch === state.lookahead() && isClassSetReservedDoublePunctuatorCharacter(ch)) { return false }
  if (isClassSetSyntaxCharacter(ch)) { return false }
  state.advance();
  state.lastIntValue = ch;
  return true
};

// https://tc39.es/ecma262/#prod-ClassSetReservedDoublePunctuator
function isClassSetReservedDoublePunctuatorCharacter(ch) {
  return (
    ch === 0x21 /* ! */ ||
    ch >= 0x23 /* # */ && ch <= 0x26 /* & */ ||
    ch >= 0x2A /* * */ && ch <= 0x2C /* , */ ||
    ch === 0x2E /* . */ ||
    ch >= 0x3A /* : */ && ch <= 0x40 /* @ */ ||
    ch === 0x5E /* ^ */ ||
    ch === 0x60 /* ` */ ||
    ch === 0x7E /* ~ */
  )
}

// https://tc39.es/ecma262/#prod-ClassSetSyntaxCharacter
function isClassSetSyntaxCharacter(ch) {
  return (
    ch === 0x28 /* ( */ ||
    ch === 0x29 /* ) */ ||
    ch === 0x2D /* - */ ||
    ch === 0x2F /* / */ ||
    ch >= 0x5B /* [ */ && ch <= 0x5D /* ] */ ||
    ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  )
}

// https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator
pp$1.regexp_eatClassSetReservedPunctuator = function(state) {
  var ch = state.current();
  if (isClassSetReservedPunctuator(ch)) {
    state.lastIntValue = ch;
    state.advance();
    return true
  }
  return false
};

// https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator
function isClassSetReservedPunctuator(ch) {
  return (
    ch === 0x21 /* ! */ ||
    ch === 0x23 /* # */ ||
    ch === 0x25 /* % */ ||
    ch === 0x26 /* & */ ||
    ch === 0x2C /* , */ ||
    ch === 0x2D /* - */ ||
    ch >= 0x3A /* : */ && ch <= 0x3E /* > */ ||
    ch === 0x40 /* @ */ ||
    ch === 0x60 /* ` */ ||
    ch === 0x7E /* ~ */
  )
}

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
pp$1.regexp_eatClassControlLetter = function(state) {
  var ch = state.current();
  if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
    state.lastIntValue = ch % 0x20;
    state.advance();
    return true
  }
  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
pp$1.regexp_eatHexEscapeSequence = function(state) {
  var start = state.pos;
  if (state.eat(0x78 /* x */)) {
    if (this.regexp_eatFixedHexDigits(state, 2)) {
      return true
    }
    if (state.switchU) {
      state.raise("Invalid escape");
    }
    state.pos = start;
  }
  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
pp$1.regexp_eatDecimalDigits = function(state) {
  var start = state.pos;
  var ch = 0;
  state.lastIntValue = 0;
  while (isDecimalDigit(ch = state.current())) {
    state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
    state.advance();
  }
  return state.pos !== start
};
function isDecimalDigit(ch) {
  return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
}

// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
pp$1.regexp_eatHexDigits = function(state) {
  var start = state.pos;
  var ch = 0;
  state.lastIntValue = 0;
  while (isHexDigit(ch = state.current())) {
    state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
    state.advance();
  }
  return state.pos !== start
};
function isHexDigit(ch) {
  return (
    (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
    (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
    (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  )
}
function hexToInt(ch) {
  if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
    return 10 + (ch - 0x41 /* A */)
  }
  if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
    return 10 + (ch - 0x61 /* a */)
  }
  return ch - 0x30 /* 0 */
}

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
// Allows only 0-377(octal) i.e. 0-255(decimal).
pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
  if (this.regexp_eatOctalDigit(state)) {
    var n1 = state.lastIntValue;
    if (this.regexp_eatOctalDigit(state)) {
      var n2 = state.lastIntValue;
      if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
        state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
      } else {
        state.lastIntValue = n1 * 8 + n2;
      }
    } else {
      state.lastIntValue = n1;
    }
    return true
  }
  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
pp$1.regexp_eatOctalDigit = function(state) {
  var ch = state.current();
  if (isOctalDigit(ch)) {
    state.lastIntValue = ch - 0x30; /* 0 */
    state.advance();
    return true
  }
  state.lastIntValue = 0;
  return false
};
function isOctalDigit(ch) {
  return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
}

// https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
// And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
pp$1.regexp_eatFixedHexDigits = function(state, length) {
  var start = state.pos;
  state.lastIntValue = 0;
  for (var i = 0; i < length; ++i) {
    var ch = state.current();
    if (!isHexDigit(ch)) {
      state.pos = start;
      return false
    }
    state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
    state.advance();
  }
  return true
};

// Object type used to represent tokens. Note that normally, tokens
// simply exist as properties on the parser object. This is only
// used for the onToken callback and the external tokenizer.

var Token = function Token(p) {
  this.type = p.type;
  this.value = p.value;
  this.start = p.start;
  this.end = p.end;
  if (p.options.locations)
    { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
  if (p.options.ranges)
    { this.range = [p.start, p.end]; }
};

// ## Tokenizer

var pp$a = Parser$1.prototype;

// Move to the next token

pp$a.next = function(ignoreEscapeSequenceInKeyword) {
  if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
    { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
  if (this.options.onToken)
    { this.options.onToken(new Token(this)); }

  this.lastTokEnd = this.end;
  this.lastTokStart = this.start;
  this.lastTokEndLoc = this.endLoc;
  this.lastTokStartLoc = this.startLoc;
  this.nextToken();
};

pp$a.getToken = function() {
  this.next();
  return new Token(this)
};

// If we're in an ES6 environment, make parsers iterable
if (typeof Symbol !== "undefined")
  { pp$a[Symbol.iterator] = function() {
    var this$1$1 = this;

    return {
      next: function () {
        var token = this$1$1.getToken();
        return {
          done: token.type === types$1.eof,
          value: token
        }
      }
    }
  }; }

// Toggle strict mode. Re-reads the next number or string to please
// pedantic tests (`"use strict"; 010;` should fail).

// Read a single token, updating the parser object's token-related
// properties.

pp$a.nextToken = function() {
  var curContext = this.curContext();
  if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }

  this.start = this.pos;
  if (this.options.locations) { this.startLoc = this.curPosition(); }
  if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) }

  if (curContext.override) { return curContext.override(this) }
  else { this.readToken(this.fullCharCodeAtPos()); }
};

pp$a.readToken = function(code) {
  // Identifier or keyword. '\uXXXX' sequences are allowed in
  // identifiers, so '\' also dispatches to that.
  if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
    { return this.readWord() }

  return this.getTokenFromCode(code)
};

pp$a.fullCharCodeAtPos = function() {
  var code = this.input.charCodeAt(this.pos);
  if (code <= 0xd7ff || code >= 0xdc00) { return code }
  var next = this.input.charCodeAt(this.pos + 1);
  return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
};

pp$a.skipBlockComment = function() {
  var startLoc = this.options.onComment && this.curPosition();
  var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  this.pos = end + 2;
  if (this.options.locations) {
    for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) {
      ++this.curLine;
      pos = this.lineStart = nextBreak;
    }
  }
  if (this.options.onComment)
    { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
                           startLoc, this.curPosition()); }
};

pp$a.skipLineComment = function(startSkip) {
  var start = this.pos;
  var startLoc = this.options.onComment && this.curPosition();
  var ch = this.input.charCodeAt(this.pos += startSkip);
  while (this.pos < this.input.length && !isNewLine(ch)) {
    ch = this.input.charCodeAt(++this.pos);
  }
  if (this.options.onComment)
    { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
                           startLoc, this.curPosition()); }
};

// Called at the start of the parse and after every token. Skips
// whitespace and comments, and.

pp$a.skipSpace = function() {
  loop: while (this.pos < this.input.length) {
    var ch = this.input.charCodeAt(this.pos);
    switch (ch) {
    case 32: case 160: // ' '
      ++this.pos;
      break
    case 13:
      if (this.input.charCodeAt(this.pos + 1) === 10) {
        ++this.pos;
      }
    case 10: case 8232: case 8233:
      ++this.pos;
      if (this.options.locations) {
        ++this.curLine;
        this.lineStart = this.pos;
      }
      break
    case 47: // '/'
      switch (this.input.charCodeAt(this.pos + 1)) {
      case 42: // '*'
        this.skipBlockComment();
        break
      case 47:
        this.skipLineComment(2);
        break
      default:
        break loop
      }
      break
    default:
      if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
        ++this.pos;
      } else {
        break loop
      }
    }
  }
};

// Called at the end of every token. Sets `end`, `val`, and
// maintains `context` and `exprAllowed`, and skips the space after
// the token, so that the next one's `start` will point at the
// right position.

pp$a.finishToken = function(type, val) {
  this.end = this.pos;
  if (this.options.locations) { this.endLoc = this.curPosition(); }
  var prevType = this.type;
  this.type = type;
  this.value = val;

  this.updateContext(prevType);
};

// ### Token reading

// This is the function that is called to fetch the next token. It
// is somewhat obscure, because it works in character codes rather
// than characters, and because operator parsing has been inlined
// into it.
//
// All in the name of speed.
//
pp$a.readToken_dot = function() {
  var next = this.input.charCodeAt(this.pos + 1);
  if (next >= 48 && next <= 57) { return this.readNumber(true) }
  var next2 = this.input.charCodeAt(this.pos + 2);
  if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
    this.pos += 3;
    return this.finishToken(types$1.ellipsis)
  } else {
    ++this.pos;
    return this.finishToken(types$1.dot)
  }
};

pp$a.readToken_slash = function() { // '/'
  var next = this.input.charCodeAt(this.pos + 1);
  if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  if (next === 61) { return this.finishOp(types$1.assign, 2) }
  return this.finishOp(types$1.slash, 1)
};

pp$a.readToken_mult_modulo_exp = function(code) { // '%*'
  var next = this.input.charCodeAt(this.pos + 1);
  var size = 1;
  var tokentype = code === 42 ? types$1.star : types$1.modulo;

  // exponentiation operator ** and **=
  if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
    ++size;
    tokentype = types$1.starstar;
    next = this.input.charCodeAt(this.pos + 2);
  }

  if (next === 61) { return this.finishOp(types$1.assign, size + 1) }
  return this.finishOp(tokentype, size)
};

pp$a.readToken_pipe_amp = function(code) { // '|&'
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === code) {
    if (this.options.ecmaVersion >= 12) {
      var next2 = this.input.charCodeAt(this.pos + 2);
      if (next2 === 61) { return this.finishOp(types$1.assign, 3) }
    }
    return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2)
  }
  if (next === 61) { return this.finishOp(types$1.assign, 2) }
  return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1)
};

pp$a.readToken_caret = function() { // '^'
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === 61) { return this.finishOp(types$1.assign, 2) }
  return this.finishOp(types$1.bitwiseXOR, 1)
};

pp$a.readToken_plus_min = function(code) { // '+-'
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === code) {
    if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
        (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
      // A `-->` line comment
      this.skipLineComment(3);
      this.skipSpace();
      return this.nextToken()
    }
    return this.finishOp(types$1.incDec, 2)
  }
  if (next === 61) { return this.finishOp(types$1.assign, 2) }
  return this.finishOp(types$1.plusMin, 1)
};

pp$a.readToken_lt_gt = function(code) { // '<>'
  var next = this.input.charCodeAt(this.pos + 1);
  var size = 1;
  if (next === code) {
    size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
    if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) }
    return this.finishOp(types$1.bitShift, size)
  }
  if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
      this.input.charCodeAt(this.pos + 3) === 45) {
    // `<!--`, an XML-style comment that should be interpreted as a line comment
    this.skipLineComment(4);
    this.skipSpace();
    return this.nextToken()
  }
  if (next === 61) { size = 2; }
  return this.finishOp(types$1.relational, size)
};

pp$a.readToken_eq_excl = function(code) { // '=!'
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
    this.pos += 2;
    return this.finishToken(types$1.arrow)
  }
  return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1)
};

pp$a.readToken_question = function() { // '?'
  var ecmaVersion = this.options.ecmaVersion;
  if (ecmaVersion >= 11) {
    var next = this.input.charCodeAt(this.pos + 1);
    if (next === 46) {
      var next2 = this.input.charCodeAt(this.pos + 2);
      if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) }
    }
    if (next === 63) {
      if (ecmaVersion >= 12) {
        var next2$1 = this.input.charCodeAt(this.pos + 2);
        if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) }
      }
      return this.finishOp(types$1.coalesce, 2)
    }
  }
  return this.finishOp(types$1.question, 1)
};

pp$a.readToken_numberSign = function() { // '#'
  var ecmaVersion = this.options.ecmaVersion;
  var code = 35; // '#'
  if (ecmaVersion >= 13) {
    ++this.pos;
    code = this.fullCharCodeAtPos();
    if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
      return this.finishToken(types$1.privateId, this.readWord1())
    }
  }

  this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
};

pp$a.getTokenFromCode = function(code) {
  switch (code) {
  // The interpretation of a dot depends on whether it is followed
  // by a digit or another two dots.
  case 46: // '.'
    return this.readToken_dot()

  // Punctuation tokens.
  case 40: ++this.pos; return this.finishToken(types$1.parenL)
  case 41: ++this.pos; return this.finishToken(types$1.parenR)
  case 59: ++this.pos; return this.finishToken(types$1.semi)
  case 44: ++this.pos; return this.finishToken(types$1.comma)
  case 91: ++this.pos; return this.finishToken(types$1.bracketL)
  case 93: ++this.pos; return this.finishToken(types$1.bracketR)
  case 123: ++this.pos; return this.finishToken(types$1.braceL)
  case 125: ++this.pos; return this.finishToken(types$1.braceR)
  case 58: ++this.pos; return this.finishToken(types$1.colon)

  case 96: // '`'
    if (this.options.ecmaVersion < 6) { break }
    ++this.pos;
    return this.finishToken(types$1.backQuote)

  case 48: // '0'
    var next = this.input.charCodeAt(this.pos + 1);
    if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
    if (this.options.ecmaVersion >= 6) {
      if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
      if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
    }

  // Anything else beginning with a digit is an integer, octal
  // number, or float.
  case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
    return this.readNumber(false)

  // Quotes produce strings.
  case 34: case 39: // '"', "'"
    return this.readString(code)

  // Operators are parsed inline in tiny state machines. '=' (61) is
  // often referred to. `finishOp` simply skips the amount of
  // characters it is given as second argument, and returns a token
  // of the type given by its first argument.
  case 47: // '/'
    return this.readToken_slash()

  case 37: case 42: // '%*'
    return this.readToken_mult_modulo_exp(code)

  case 124: case 38: // '|&'
    return this.readToken_pipe_amp(code)

  case 94: // '^'
    return this.readToken_caret()

  case 43: case 45: // '+-'
    return this.readToken_plus_min(code)

  case 60: case 62: // '<>'
    return this.readToken_lt_gt(code)

  case 61: case 33: // '=!'
    return this.readToken_eq_excl(code)

  case 63: // '?'
    return this.readToken_question()

  case 126: // '~'
    return this.finishOp(types$1.prefix, 1)

  case 35: // '#'
    return this.readToken_numberSign()
  }

  this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
};

pp$a.finishOp = function(type, size) {
  var str = this.input.slice(this.pos, this.pos + size);
  this.pos += size;
  return this.finishToken(type, str)
};

pp$a.readRegexp = function() {
  var escaped, inClass, start = this.pos;
  for (;;) {
    if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
    var ch = this.input.charAt(this.pos);
    if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
    if (!escaped) {
      if (ch === "[") { inClass = true; }
      else if (ch === "]" && inClass) { inClass = false; }
      else if (ch === "/" && !inClass) { break }
      escaped = ch === "\\";
    } else { escaped = false; }
    ++this.pos;
  }
  var pattern = this.input.slice(start, this.pos);
  ++this.pos;
  var flagsStart = this.pos;
  var flags = this.readWord1();
  if (this.containsEsc) { this.unexpected(flagsStart); }

  // Validate pattern
  var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  state.reset(start, pattern, flags);
  this.validateRegExpFlags(state);
  this.validateRegExpPattern(state);

  // Create Literal#value property value.
  var value = null;
  try {
    value = new RegExp(pattern, flags);
  } catch (e) {
    // ESTree requires null if it failed to instantiate RegExp object.
    // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
  }

  return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value})
};

// Read an integer in the given radix. Return null if zero digits
// were read, the integer value otherwise. When `len` is given, this
// will return `null` unless the integer has exactly `len` digits.

pp$a.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  // `len` is used for character escape sequences. In that case, disallow separators.
  var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;

  // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
  // and isn't fraction part nor exponent part. In that case, if the first digit
  // is zero then disallow separators.
  var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;

  var start = this.pos, total = 0, lastCode = 0;
  for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
    var code = this.input.charCodeAt(this.pos), val = (void 0);

    if (allowSeparators && code === 95) {
      if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
      if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
      if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
      lastCode = code;
      continue
    }

    if (code >= 97) { val = code - 97 + 10; } // a
    else if (code >= 65) { val = code - 65 + 10; } // A
    else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
    else { val = Infinity; }
    if (val >= radix) { break }
    lastCode = code;
    total = total * radix + val;
  }

  if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
  if (this.pos === start || len != null && this.pos - start !== len) { return null }

  return total
};

function stringToNumber(str, isLegacyOctalNumericLiteral) {
  if (isLegacyOctalNumericLiteral) {
    return parseInt(str, 8)
  }

  // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
  return parseFloat(str.replace(/_/g, ""))
}

function stringToBigInt(str) {
  if (typeof BigInt !== "function") {
    return null
  }

  // `BigInt(value)` throws syntax error if the string contains numeric separators.
  return BigInt(str.replace(/_/g, ""))
}

pp$a.readRadixNumber = function(radix) {
  var start = this.pos;
  this.pos += 2; // 0x
  var val = this.readInt(radix);
  if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
    val = stringToBigInt(this.input.slice(start, this.pos));
    ++this.pos;
  } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  return this.finishToken(types$1.num, val)
};

// Read an integer, octal integer, or floating-point number.

pp$a.readNumber = function(startsWithDot) {
  var start = this.pos;
  if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
  var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  if (octal && this.strict) { this.raise(start, "Invalid number"); }
  var next = this.input.charCodeAt(this.pos);
  if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
    var val$1 = stringToBigInt(this.input.slice(start, this.pos));
    ++this.pos;
    if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
    return this.finishToken(types$1.num, val$1)
  }
  if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
  if (next === 46 && !octal) { // '.'
    ++this.pos;
    this.readInt(10);
    next = this.input.charCodeAt(this.pos);
  }
  if ((next === 69 || next === 101) && !octal) { // 'eE'
    next = this.input.charCodeAt(++this.pos);
    if (next === 43 || next === 45) { ++this.pos; } // '+-'
    if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  }
  if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }

  var val = stringToNumber(this.input.slice(start, this.pos), octal);
  return this.finishToken(types$1.num, val)
};

// Read a string value, interpreting backslash-escapes.

pp$a.readCodePoint = function() {
  var ch = this.input.charCodeAt(this.pos), code;

  if (ch === 123) { // '{'
    if (this.options.ecmaVersion < 6) { this.unexpected(); }
    var codePos = ++this.pos;
    code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
    ++this.pos;
    if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  } else {
    code = this.readHexChar(4);
  }
  return code
};

pp$a.readString = function(quote) {
  var out = "", chunkStart = ++this.pos;
  for (;;) {
    if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
    var ch = this.input.charCodeAt(this.pos);
    if (ch === quote) { break }
    if (ch === 92) { // '\'
      out += this.input.slice(chunkStart, this.pos);
      out += this.readEscapedChar(false);
      chunkStart = this.pos;
    } else if (ch === 0x2028 || ch === 0x2029) {
      if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); }
      ++this.pos;
      if (this.options.locations) {
        this.curLine++;
        this.lineStart = this.pos;
      }
    } else {
      if (isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); }
      ++this.pos;
    }
  }
  out += this.input.slice(chunkStart, this.pos++);
  return this.finishToken(types$1.string, out)
};

// Reads template string tokens.

var INVALID_TEMPLATE_ESCAPE_ERROR = {};

pp$a.tryReadTemplateToken = function() {
  this.inTemplateElement = true;
  try {
    this.readTmplToken();
  } catch (err) {
    if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
      this.readInvalidTemplateToken();
    } else {
      throw err
    }
  }

  this.inTemplateElement = false;
};

pp$a.invalidStringToken = function(position, message) {
  if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
    throw INVALID_TEMPLATE_ESCAPE_ERROR
  } else {
    this.raise(position, message);
  }
};

pp$a.readTmplToken = function() {
  var out = "", chunkStart = this.pos;
  for (;;) {
    if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
    var ch = this.input.charCodeAt(this.pos);
    if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
      if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {
        if (ch === 36) {
          this.pos += 2;
          return this.finishToken(types$1.dollarBraceL)
        } else {
          ++this.pos;
          return this.finishToken(types$1.backQuote)
        }
      }
      out += this.input.slice(chunkStart, this.pos);
      return this.finishToken(types$1.template, out)
    }
    if (ch === 92) { // '\'
      out += this.input.slice(chunkStart, this.pos);
      out += this.readEscapedChar(true);
      chunkStart = this.pos;
    } else if (isNewLine(ch)) {
      out += this.input.slice(chunkStart, this.pos);
      ++this.pos;
      switch (ch) {
      case 13:
        if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
      case 10:
        out += "\n";
        break
      default:
        out += String.fromCharCode(ch);
        break
      }
      if (this.options.locations) {
        ++this.curLine;
        this.lineStart = this.pos;
      }
      chunkStart = this.pos;
    } else {
      ++this.pos;
    }
  }
};

// Reads a template token to search for the end, without validating any escape sequences
pp$a.readInvalidTemplateToken = function() {
  for (; this.pos < this.input.length; this.pos++) {
    switch (this.input[this.pos]) {
    case "\\":
      ++this.pos;
      break

    case "$":
      if (this.input[this.pos + 1] !== "{") {
        break
      }

    // falls through
    case "`":
      return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos))

    // no default
    }
  }
  this.raise(this.start, "Unterminated template");
};

// Used to read escaped characters

pp$a.readEscapedChar = function(inTemplate) {
  var ch = this.input.charCodeAt(++this.pos);
  ++this.pos;
  switch (ch) {
  case 110: return "\n" // 'n' -> '\n'
  case 114: return "\r" // 'r' -> '\r'
  case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  case 117: return codePointToString(this.readCodePoint()) // 'u'
  case 116: return "\t" // 't' -> '\t'
  case 98: return "\b" // 'b' -> '\b'
  case 118: return "\u000b" // 'v' -> '\u000b'
  case 102: return "\f" // 'f' -> '\f'
  case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  case 10: // ' \n'
    if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
    return ""
  case 56:
  case 57:
    if (this.strict) {
      this.invalidStringToken(
        this.pos - 1,
        "Invalid escape sequence"
      );
    }
    if (inTemplate) {
      var codePos = this.pos - 1;

      this.invalidStringToken(
        codePos,
        "Invalid escape sequence in template string"
      );
    }
  default:
    if (ch >= 48 && ch <= 55) {
      var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
      var octal = parseInt(octalStr, 8);
      if (octal > 255) {
        octalStr = octalStr.slice(0, -1);
        octal = parseInt(octalStr, 8);
      }
      this.pos += octalStr.length - 1;
      ch = this.input.charCodeAt(this.pos);
      if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
        this.invalidStringToken(
          this.pos - 1 - octalStr.length,
          inTemplate
            ? "Octal literal in template string"
            : "Octal literal in strict mode"
        );
      }
      return String.fromCharCode(octal)
    }
    if (isNewLine(ch)) {
      // Unicode new line characters after \ get removed from output in both
      // template literals and strings
      return ""
    }
    return String.fromCharCode(ch)
  }
};

// Used to read character escape sequences ('\x', '\u', '\U').

pp$a.readHexChar = function(len) {
  var codePos = this.pos;
  var n = this.readInt(16, len);
  if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  return n
};

// Read an identifier, and return it as a string. Sets `this.containsEsc`
// to whether the word contained a '\u' escape.
//
// Incrementally adds only escaped chars, adding other chunks as-is
// as a micro-optimization.

pp$a.readWord1 = function() {
  this.containsEsc = false;
  var word = "", first = true, chunkStart = this.pos;
  var astral = this.options.ecmaVersion >= 6;
  while (this.pos < this.input.length) {
    var ch = this.fullCharCodeAtPos();
    if (isIdentifierChar(ch, astral)) {
      this.pos += ch <= 0xffff ? 1 : 2;
    } else if (ch === 92) { // "\"
      this.containsEsc = true;
      word += this.input.slice(chunkStart, this.pos);
      var escStart = this.pos;
      if (this.input.charCodeAt(++this.pos) !== 117) // "u"
        { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
      ++this.pos;
      var esc = this.readCodePoint();
      if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
        { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
      word += codePointToString(esc);
      chunkStart = this.pos;
    } else {
      break
    }
    first = false;
  }
  return word + this.input.slice(chunkStart, this.pos)
};

// Read an identifier or keyword token. Will check for reserved
// words when necessary.

pp$a.readWord = function() {
  var word = this.readWord1();
  var type = types$1.name;
  if (this.keywords.test(word)) {
    type = keywords[word];
  }
  return this.finishToken(type, word)
};

// Acorn is a tiny, fast JavaScript parser written in JavaScript.
//
// Acorn was written by Marijn Haverbeke, Ingvar Stepanyan, and
// various contributors and released under an MIT license.
//
// Git repositories for Acorn are available at
//
//     http://marijnhaverbeke.nl/git/acorn
//     https://github.com/acornjs/acorn.git
//
// Please use the [github bug tracker][ghbt] to report issues.
//
// [ghbt]: https://github.com/acornjs/acorn/issues
//
// [walk]: util/walk.js


var version = "8.9.0";

Parser$1.acorn = {
  Parser: Parser$1,
  version: version,
  defaultOptions: defaultOptions,
  Position: Position,
  SourceLocation: SourceLocation,
  getLineInfo: getLineInfo,
  Node: Node$1,
  TokenType: TokenType,
  tokTypes: types$1,
  keywordTypes: keywords,
  TokContext: TokContext,
  tokContexts: types,
  isIdentifierChar: isIdentifierChar,
  isIdentifierStart: isIdentifierStart,
  Token: Token,
  isNewLine: isNewLine,
  lineBreak: lineBreak,
  lineBreakG: lineBreakG,
  nonASCIIwhitespace: nonASCIIwhitespace
};

// The main exported interface (under `self.acorn` when in the
// browser) is a `parse` function that takes a code string and
// returns an abstract syntax tree as specified by [Mozilla parser
// API][api].
//
// [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API

function parse$b(input, options) {
  return Parser$1.parse(input, options)
}

// This function tries to parse a single expression at a given
// offset in a string. Useful for parsing mixed-language formats
// that embed JavaScript expressions.

function parseExpressionAt$1(input, pos, options) {
  return Parser$1.parseExpressionAt(input, pos, options)
}

/**
 * @template T
 * @overload
 * @param {T[][]} nodes
 * @param {T[]} [target]
 * @returns {T[]}
 */

/**
 * @template T
 * @overload
 * @param {T[]} nodes
 * @param {T[]} [target]
 * @returns {T[]}
 */

/**
 * @param {any[]} nodes
 * @param {any[]} [target]
 * @returns {any[]}
 */
function flatten$1(nodes, target = []) {
	for (let i = 0; i < nodes.length; i += 1) {
		const node = nodes[i];
		if (Array.isArray(node)) {
			flatten$1(node, target);
		} else {
			target.push(node);
		}
	}

	return target;
}

const regex_whitespace = /\s/;
const regex_whitespaces = /\s+/;
const regex_starts_with_whitespace = /^\s/;
const regex_starts_with_whitespaces = /^[ \t\r\n]*/;
const regex_ends_with_whitespace = /\s$/;
const regex_ends_with_whitespaces = /[ \t\r\n]*$/;
const regex_only_whitespaces = /^[ \t\n\r\f]+$/;

const regex_whitespace_characters = /\s/g;
const regex_non_whitespace_character = /\S/;

const regex_starts_with_newline = /^\r?\n/;
const regex_not_newline_characters = /[^\n]/g;

const regex_double_quotes = /"/g;

const regex_backslashes = /\\/g;

const regex_starts_with_underscore = /^_/;
const regex_ends_with_underscore = /_$/;

const regex_dimensions = /^(?:offset|client)(?:Width|Height)$/;

const regex_content_rect = /^(?:contentRect)$/;
const regex_content_box_size = /^(?:contentBoxSize)$/;
const regex_border_box_size = /^(?:borderBoxSize)$/;
const regex_device_pixel_content_box_size = /^(?:devicePixelContentBoxSize)$/;
const regex_box_size =
	/^(?:contentRect|contentBoxSize|borderBoxSize|devicePixelContentBoxSize)$/;

const regex_svelte_ignore = /^\s*svelte-ignore\s+([\s\S]+)\s*$/m;

/**
 * @param {string} text
 * @returns {string[]}
 */
function extract_svelte_ignore(text) {
	const match = regex_svelte_ignore.exec(text);
	return match
		? match[1]
				.split(regex_whitespace)
				.map((x) => x.trim())
				.filter(Boolean)
		: [];
}

/**
 * @param {import('estree').Node} node
 * @returns {string[]}
 */
function extract_svelte_ignore_from_comments(node) {
	return flatten$1(
		(node.leadingComments || []).map((comment) => extract_svelte_ignore(comment.value))
	);
}

/**
 * @param {number} position
 * @param {import('../interfaces.js').TemplateNode[]} template_nodes
 * @returns {string[]}
 */
function extract_ignores_above_position(position, template_nodes) {
	const previous_node_idx = template_nodes.findIndex((child) => child.end === position);
	if (previous_node_idx === -1) {
		return [];
	}
	for (let i = previous_node_idx; i >= 0; i--) {
		const node = template_nodes[i];
		if (node.type !== 'Comment' && node.type !== 'Text') {
			return [];
		}
		if (node.type === 'Comment') {
			if (node.ignores.length) {
				return node.ignores;
			}
		}
	}
	return [];
}

/**
 * @param {import('../compile/nodes/interfaces.js').INode} node
 * @returns {string[]}
 */
function extract_ignores_above_node(node) {
	/**
	 * This utilizes the fact that node has a prev and a next attribute
	 * which means that it can find svelte-ignores along
	 * the nodes on the same level as itself who share the same parent.
	 */
	let cur_node = node.prev;
	while (cur_node) {
		if (cur_node.type !== 'Comment' && cur_node.type !== 'Text') {
			return [];
		}
		if (cur_node.type === 'Comment' && cur_node.ignores.length) {
			return cur_node.ignores;
		}
		cur_node = cur_node.prev;
	}
	return [];
}

/**
 * @param {string} name
 * @param {string[]} names
 */
function fuzzymatch(name, names) {
	const set = new FuzzySet(names);
	const matches = set.get(name);
	return matches && matches[0] && matches[0][0] > 0.7 ? matches[0][1] : null;
}

// adapted from https://github.com/Glench/fuzzyset.js/blob/master/lib/fuzzyset.js
// BSD Licensed
const GRAM_SIZE_LOWER = 2;
const GRAM_SIZE_UPPER = 3;
// return an edit distance from 0 to 1

/**
 * @param {string} str1
 * @param {string} str2
 */
function _distance(str1, str2) {
	if (str1 === null && str2 === null) {
		throw 'Trying to compare two null values';
	}
	if (str1 === null || str2 === null) return 0;
	str1 = String(str1);
	str2 = String(str2);
	const distance = levenshtein(str1, str2);
	if (str1.length > str2.length) {
		return 1 - distance / str1.length;
	} else {
		return 1 - distance / str2.length;
	}
}

// helper functions

/**
 * @param {string} str1
 * @param {string} str2
 */
function levenshtein(str1, str2) {
	/**
	 * @type {number[]}
	 */
	const current = [];
	let prev;
	let value;
	for (let i = 0; i <= str2.length; i++) {
		for (let j = 0; j <= str1.length; j++) {
			if (i && j) {
				if (str1.charAt(j - 1) === str2.charAt(i - 1)) {
					value = prev;
				} else {
					value = Math.min(current[j], current[j - 1], prev) + 1;
				}
			} else {
				value = i + j;
			}
			prev = current[j];
			current[j] = value;
		}
	}
	return current.pop();
}

const non_word_regex = /[^\w, ]+/;

/**
 * @param {string} value
 * @param {any} gram_size
 */
function iterate_grams(value, gram_size = 2) {
	const simplified = '-' + value.toLowerCase().replace(non_word_regex, '') + '-';
	const len_diff = gram_size - simplified.length;
	const results = [];
	if (len_diff > 0) {
		for (let i = 0; i < len_diff; ++i) {
			value += '-';
		}
	}
	for (let i = 0; i < simplified.length - gram_size + 1; ++i) {
		results.push(simplified.slice(i, i + gram_size));
	}
	return results;
}

/**
 * @param {string} value
 * @param {any} gram_size
 */
function gram_counter(value, gram_size = 2) {
	// return an object where key=gram, value=number of occurrences
	const result = {};
	const grams = iterate_grams(value, gram_size);
	let i = 0;
	for (i; i < grams.length; ++i) {
		if (grams[i] in result) {
			result[grams[i]] += 1;
		} else {
			result[grams[i]] = 1;
		}
	}
	return result;
}

/**
 * @param {any} a
 * @param {any} b
 */
function sort_descending(a, b) {
	return b[0] - a[0];
}

class FuzzySet {
	exact_set = {};
	match_dict = {};
	items = {};

	/**
	 * @param {string[]} arr
	 */
	constructor(arr) {
		// initialization
		for (let i = GRAM_SIZE_LOWER; i < GRAM_SIZE_UPPER + 1; ++i) {
			this.items[i] = [];
		}
		// add all the items to the set
		for (let i = 0; i < arr.length; ++i) {
			this.add(arr[i]);
		}
	}

	/**
	 * @param {string} value
	 */
	add(value) {
		const normalized_value = value.toLowerCase();
		if (normalized_value in this.exact_set) {
			return false;
		}
		let i = GRAM_SIZE_LOWER;
		for (i; i < GRAM_SIZE_UPPER + 1; ++i) {
			this._add(value, i);
		}
	}

	/**
	 * @param {string} value
	 * @param {number} gram_size
	 */
	_add(value, gram_size) {
		const normalized_value = value.toLowerCase();
		const items = this.items[gram_size] || [];
		const index = items.length;
		items.push(0);
		const gram_counts = gram_counter(normalized_value, gram_size);
		let sum_of_square_gram_counts = 0;
		let gram;
		let gram_count;
		for (gram in gram_counts) {
			gram_count = gram_counts[gram];
			sum_of_square_gram_counts += Math.pow(gram_count, 2);
			if (gram in this.match_dict) {
				this.match_dict[gram].push([index, gram_count]);
			} else {
				this.match_dict[gram] = [[index, gram_count]];
			}
		}
		const vector_normal = Math.sqrt(sum_of_square_gram_counts);
		items[index] = [vector_normal, normalized_value];
		this.items[gram_size] = items;
		this.exact_set[normalized_value] = value;
	}

	/**
	 * @param {string} value
	 */
	get(value) {
		const normalized_value = value.toLowerCase();
		const result = this.exact_set[normalized_value];
		if (result) {
			return [[1, result]];
		}
		let results = [];
		// start with high gram size and if there are no results, go to lower gram sizes
		for (let gram_size = GRAM_SIZE_UPPER; gram_size >= GRAM_SIZE_LOWER; --gram_size) {
			results = this.__get(value, gram_size);
			if (results) {
				return results;
			}
		}
		return null;
	}

	/**
	 * @param {string} value
	 * @param {number} gram_size
	 */
	__get(value, gram_size) {
		const normalized_value = value.toLowerCase();
		const matches = {};
		const gram_counts = gram_counter(normalized_value, gram_size);
		const items = this.items[gram_size];
		let sum_of_square_gram_counts = 0;
		let gram;
		let gram_count;
		let i;
		let index;
		let other_gram_count;
		for (gram in gram_counts) {
			gram_count = gram_counts[gram];
			sum_of_square_gram_counts += Math.pow(gram_count, 2);
			if (gram in this.match_dict) {
				for (i = 0; i < this.match_dict[gram].length; ++i) {
					index = this.match_dict[gram][i][0];
					other_gram_count = this.match_dict[gram][i][1];
					if (index in matches) {
						matches[index] += gram_count * other_gram_count;
					} else {
						matches[index] = gram_count * other_gram_count;
					}
				}
			}
		}
		const vector_normal = Math.sqrt(sum_of_square_gram_counts);
		let results = [];
		let match_score;
		// build a results list of [score, str]
		for (const match_index in matches) {
			match_score = matches[match_index];
			results.push([match_score / (vector_normal * items[match_index][0]), items[match_index][1]]);
		}
		results.sort(sort_descending);
		let new_results = [];
		const end_index = Math.min(50, results.length);
		// truncate somewhat arbitrarily to 50
		for (let i = 0; i < end_index; ++i) {
			new_results.push([_distance(results[i][1], normalized_value), results[i][1]]);
		}
		results = new_results;
		results.sort(sort_descending);
		new_results = [];
		for (let i = 0; i < results.length; ++i) {
			if (results[i][0] == results[0][0]) {
				new_results.push([results[i][0], this.exact_set[results[i][1]]]);
			}
		}
		return new_results;
	}
}

/** regex of all html void element names */
const void_element_names =
	/^(?:area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)$/;

/** regex of all html element names. svg and math are omitted because they belong to the svg elements namespace */
const html_element_names =
	/^(?:a|abbr|address|area|article|aside|audio|b|base|bdi|bdo|blockquote|body|br|button|canvas|caption|cite|code|col|colgroup|data|datalist|dd|del|details|dfn|dialog|div|dl|dt|em|embed|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|head|header|hr|html|i|iframe|img|input|ins|kbd|label|legend|li|link|main|map|mark|meta|meter|nav|noscript|object|ol|optgroup|option|output|p|param|picture|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|small|source|span|strong|style|sub|summary|sup|table|tbody|td|template|textarea|tfoot|th|thead|time|title|tr|track|u|ul|var|video|wbr)$/;

/** regex of all svg element names */
const svg$1 =
	/^(?:altGlyph|altGlyphDef|altGlyphItem|animate|animateColor|animateMotion|animateTransform|circle|clipPath|color-profile|cursor|defs|desc|discard|ellipse|feBlend|feColorMatrix|feComponentTransfer|feComposite|feConvolveMatrix|feDiffuseLighting|feDisplacementMap|feDistantLight|feDropShadow|feFlood|feFuncA|feFuncB|feFuncG|feFuncR|feGaussianBlur|feImage|feMerge|feMergeNode|feMorphology|feOffset|fePointLight|feSpecularLighting|feSpotLight|feTile|feTurbulence|filter|font|font-face|font-face-format|font-face-name|font-face-src|font-face-uri|foreignObject|g|glyph|glyphRef|hatch|hatchpath|hkern|image|line|linearGradient|marker|mask|mesh|meshgradient|meshpatch|meshrow|metadata|missing-glyph|mpath|path|pattern|polygon|polyline|radialGradient|rect|set|solidcolor|stop|svg|switch|symbol|text|textPath|tref|tspan|unknown|use|view|vkern)$/;

/**
 * @param {string} name
 * @returns {boolean}
 */
function is_void(name) {
	return void_element_names.test(name) || name.toLowerCase() === '!doctype';
}

/**
 * @param {string} name
 * @returns {boolean}
 */
function is_html(name) {
	return html_element_names.test(name);
}

/**
 * @param {string} name
 * @returns {boolean}
 */
function is_svg(name) {
	return svg$1.test(name);
}

/**
 * @param {string[]} items
 * @param {string} [conjunction]
 */
function list(items, conjunction = 'or') {
	if (items.length === 1) return items[0];
	return `${items.slice(0, -1).join(', ')} ${conjunction} ${items[items.length - 1]}`;
}

// All parser errors should be listed and accessed from here

/**
 * @internal
 */
var parser_errors = {
	/**
	 * @param {string} message
	 */
	css_syntax_error: (message) => ({
		code: 'css-syntax-error',
		message
	}),
	duplicate_attribute: {
		code: 'duplicate-attribute',
		message: 'Attributes need to be unique'
	},
	/**
	 * @param {string} slug
	 * @param {string} name
	 */
	duplicate_element: (slug, name) => ({
		code: `duplicate-${slug}`,
		message: `A component can only have one <${name}> tag`
	}),
	duplicate_style: {
		code: 'duplicate-style',
		message: 'You can only have one top-level <style> tag per component'
	},
	empty_attribute_shorthand: {
		code: 'empty-attribute-shorthand',
		message: 'Attribute shorthand cannot be empty'
	},
	/**
	 * @param {string} type
	 */
	empty_directive_name: (type) => ({
		code: 'empty-directive-name',
		message: `${type} name cannot be empty`
	}),
	empty_global_selector: {
		code: 'css-syntax-error',
		message: ':global() must contain a selector'
	},
	expected_block_type: {
		code: 'expected-block-type',
		message: 'Expected if, each or await'
	},
	expected_name: {
		code: 'expected-name',
		message: 'Expected name'
	},
	/** @param {string} block */
	invalid_catch_placement_unclosed_block: (block) => ({
		code: 'invalid-catch-placement',
		message: `Expected to close ${block} before seeing {:catch} block`
	}),
	invalid_catch_placement_without_await: {
		code: 'invalid-catch-placement',
		message: 'Cannot have an {:catch} block outside an {#await ...} block'
	},
	invalid_component_definition: {
		code: 'invalid-component-definition',
		message: 'invalid component definition'
	},
	/**
	 * @param {string} name
	 */
	invalid_closing_tag_unopened: (name) => ({
		code: 'invalid-closing-tag',
		message: `</${name}> attempted to close an element that was not open`
	}),
	/**
	 * @param {string} name
	 * @param {string} reason
	 */
	invalid_closing_tag_autoclosed: (name, reason) => ({
		code: 'invalid-closing-tag',
		message: `</${name}> attempted to close <${name}> that was already automatically closed by <${reason}>`
	}),
	invalid_debug_args: {
		code: 'invalid-debug-args',
		message: '{@debug ...} arguments must be identifiers, not arbitrary expressions'
	},
	invalid_declaration: {
		code: 'invalid-declaration',
		message: 'Declaration cannot be empty'
	},
	invalid_directive_value: {
		code: 'invalid-directive-value',
		message: 'Directive value must be a JavaScript expression enclosed in curly braces'
	},
	invalid_elseif: {
		code: 'invalid-elseif',
		message: "'elseif' should be 'else if'"
	},
	invalid_elseif_placement_outside_if: {
		code: 'invalid-elseif-placement',
		message: 'Cannot have an {:else if ...} block outside an {#if ...} block'
	},
	/**
	 * @param {string} block
	 */
	invalid_elseif_placement_unclosed_block: (block) => ({
		code: 'invalid-elseif-placement',
		message: `Expected to close ${block} before seeing {:else if ...} block`
	}),
	invalid_else_placement_outside_if: {
		code: 'invalid-else-placement',
		message: 'Cannot have an {:else} block outside an {#if ...} or {#each ...} block'
	},
	/**
	 * @param {string} block
	 */
	invalid_else_placement_unclosed_block: (block) => ({
		code: 'invalid-else-placement',
		message: `Expected to close ${block} before seeing {:else} block`
	}),
	/**
	 * @param {string} slug
	 * @param {string} name
	 */
	invalid_element_content: (slug, name) => ({
		code: `invalid-${slug}-content`,
		message: `<${name}> cannot have children`
	}),
	invalid_element_definition: {
		code: 'invalid-element-definition',
		message: 'Invalid element definition'
	},
	/**
	 * @param {string} slug
	 * @param {string} name
	 */
	invalid_element_placement: (slug, name) => ({
		code: `invalid-${slug}-placement`,
		message: `<${name}> tags cannot be inside elements or blocks`
	}),
	/**
	 * @param {string} location
	 * @param {string} name
	 */
	invalid_logic_block_placement: (location, name) => ({
		code: 'invalid-logic-block-placement',
		message: `{#${name}} logic block cannot be ${location}`
	}),
	/**
	 * @param {string} location
	 * @param {string} name
	 */
	invalid_tag_placement: (location, name) => ({
		code: 'invalid-tag-placement',
		message: `{@${name}} tag cannot be ${location}`
	}),
	/**
	 * @param {string} name
	 */
	invalid_ref_directive: (name) => ({
		code: 'invalid-ref-directive',
		message: `The ref directive is no longer supported — use \`bind:this={${name}}\` instead`
	}),
	invalid_ref_selector: {
		code: 'invalid-ref-selector',
		message: 'ref selectors are no longer supported'
	},
	invalid_self_placement: {
		code: 'invalid-self-placement',
		message:
			'<svelte:self> components can only exist inside {#if} blocks, {#each} blocks, or slots passed to components'
	},
	invalid_script_instance: {
		code: 'invalid-script',
		message: 'A component can only have one instance-level <script> element'
	},
	invalid_script_module: {
		code: 'invalid-script',
		message: 'A component can only have one <script context="module"> element'
	},
	invalid_script_context_attribute: {
		code: 'invalid-script',
		message: 'context attribute must be static'
	},
	invalid_script_context_value: {
		code: 'invalid-script',
		message: 'If the context attribute is supplied, its value must be "module"'
	},
	invalid_tag_name: {
		code: 'invalid-tag-name',
		message: 'Expected valid tag name'
	},
	/**
	 * @param {string[]} tags
	 * @param {string} match
	 */
	invalid_tag_name_svelte_element: (tags, match) => ({
		code: 'invalid-tag-name',
		message: `Valid <svelte:...> tag names are ${list(tags)}${
			match ? ' (did you mean ' + match + '?)' : ''
		}`
	}),
	/** @param {string} block */
	invalid_then_placement_unclosed_block: (block) => ({
		code: 'invalid-then-placement',
		message: `Expected to close ${block} before seeing {:then} block`
	}),
	invalid_then_placement_without_await: {
		code: 'invalid-then-placement',
		message: 'Cannot have an {:then} block outside an {#await ...} block'
	},
	/**
	 * @param {string} name
	 */
	invalid_void_content: (name) => ({
		code: 'invalid-void-content',
		message: `<${name}> is a void element and cannot have children, or a closing tag`
	}),
	missing_component_definition: {
		code: 'missing-component-definition',
		message: "<svelte:component> must have a 'this' attribute"
	},
	missing_attribute_value: {
		code: 'missing-attribute-value',
		message: 'Expected value for the attribute'
	},
	missing_element_definition: {
		code: 'missing-element-definition',
		message: "<svelte:element> must have a 'this' attribute"
	},
	unclosed_script: {
		code: 'unclosed-script',
		message: '<script> must have a closing tag'
	},
	unclosed_style: {
		code: 'unclosed-style',
		message: '<style> must have a closing tag'
	},
	unclosed_comment: {
		code: 'unclosed-comment',
		message: 'comment was left open, expected -->'
	},
	/**
	 * @param {string} token
	 */
	unclosed_attribute_value: (token) => ({
		code: 'unclosed-attribute-value',
		message: `Expected to close the attribute value with ${token}`
	}),
	unexpected_block_close: {
		code: 'unexpected-block-close',
		message: 'Unexpected block closing tag'
	},
	unexpected_eof: {
		code: 'unexpected-eof',
		message: 'Unexpected end of input'
	},
	/**
	 * @param {string} token
	 */
	unexpected_eof_token: (token) => ({
		code: 'unexpected-eof',
		message: `Unexpected ${token}`
	}),
	/**
	 * @param {string} token
	 */
	unexpected_token: (token) => ({
		code: 'unexpected-token',
		message: `Expected ${token}`
	}),
	unexpected_token_destructure: {
		code: 'unexpected-token',
		message: 'Expected identifier or destructure pattern'
	}
};

/**
 * @typedef { import('estree').Node} Node
 * @typedef {{
 *   skip: () => void;
 *   remove: () => void;
 *   replace: (node: Node) => void;
 * }} WalkerContext
 */

class WalkerBase {
	constructor() {
		/** @type {boolean} */
		this.should_skip = false;

		/** @type {boolean} */
		this.should_remove = false;

		/** @type {Node | null} */
		this.replacement = null;

		/** @type {WalkerContext} */
		this.context = {
			skip: () => (this.should_skip = true),
			remove: () => (this.should_remove = true),
			replace: (node) => (this.replacement = node)
		};
	}

	/**
	 * @template {Node} Parent
	 * @param {Parent | null | undefined} parent
	 * @param {keyof Parent | null | undefined} prop
	 * @param {number | null | undefined} index
	 * @param {Node} node
	 */
	replace(parent, prop, index, node) {
		if (parent && prop) {
			if (index != null) {
				/** @type {Array<Node>} */ (parent[prop])[index] = node;
			} else {
				/** @type {Node} */ (parent[prop]) = node;
			}
		}
	}

	/**
	 * @template {Node} Parent
	 * @param {Parent | null | undefined} parent
	 * @param {keyof Parent | null | undefined} prop
	 * @param {number | null | undefined} index
	 */
	remove(parent, prop, index) {
		if (parent && prop) {
			if (index !== null && index !== undefined) {
				/** @type {Array<Node>} */ (parent[prop]).splice(index, 1);
			} else {
				delete parent[prop];
			}
		}
	}
}

/**
 * @typedef { import('estree').Node} Node
 * @typedef { import('./walker.js').WalkerContext} WalkerContext
 * @typedef {(
 *    this: WalkerContext,
 *    node: Node,
 *    parent: Node | null,
 *    key: string | number | symbol | null | undefined,
 *    index: number | null | undefined
 * ) => void} SyncHandler
 */

class SyncWalker extends WalkerBase {
	/**
	 *
	 * @param {SyncHandler} [enter]
	 * @param {SyncHandler} [leave]
	 */
	constructor(enter, leave) {
		super();

		/** @type {boolean} */
		this.should_skip = false;

		/** @type {boolean} */
		this.should_remove = false;

		/** @type {Node | null} */
		this.replacement = null;

		/** @type {WalkerContext} */
		this.context = {
			skip: () => (this.should_skip = true),
			remove: () => (this.should_remove = true),
			replace: (node) => (this.replacement = node)
		};

		/** @type {SyncHandler | undefined} */
		this.enter = enter;

		/** @type {SyncHandler | undefined} */
		this.leave = leave;
	}

	/**
	 * @template {Node} Parent
	 * @param {Node} node
	 * @param {Parent | null} parent
	 * @param {keyof Parent} [prop]
	 * @param {number | null} [index]
	 * @returns {Node | null}
	 */
	visit(node, parent, prop, index) {
		if (node) {
			if (this.enter) {
				const _should_skip = this.should_skip;
				const _should_remove = this.should_remove;
				const _replacement = this.replacement;
				this.should_skip = false;
				this.should_remove = false;
				this.replacement = null;

				this.enter.call(this.context, node, parent, prop, index);

				if (this.replacement) {
					node = this.replacement;
					this.replace(parent, prop, index, node);
				}

				if (this.should_remove) {
					this.remove(parent, prop, index);
				}

				const skipped = this.should_skip;
				const removed = this.should_remove;

				this.should_skip = _should_skip;
				this.should_remove = _should_remove;
				this.replacement = _replacement;

				if (skipped) return node;
				if (removed) return null;
			}

			/** @type {keyof Node} */
			let key;

			for (key in node) {
				/** @type {unknown} */
				const value = node[key];

				if (value && typeof value === 'object') {
					if (Array.isArray(value)) {
						const nodes = /** @type {Array<unknown>} */ (value);
						for (let i = 0; i < nodes.length; i += 1) {
							const item = nodes[i];
							if (isNode(item)) {
								if (!this.visit(item, node, key, i)) {
									// removed
									i--;
								}
							}
						}
					} else if (isNode(value)) {
						this.visit(value, node, key, null);
					}
				}
			}

			if (this.leave) {
				const _replacement = this.replacement;
				const _should_remove = this.should_remove;
				this.replacement = null;
				this.should_remove = false;

				this.leave.call(this.context, node, parent, prop, index);

				if (this.replacement) {
					node = this.replacement;
					this.replace(parent, prop, index, node);
				}

				if (this.should_remove) {
					this.remove(parent, prop, index);
				}

				const removed = this.should_remove;

				this.replacement = _replacement;
				this.should_remove = _should_remove;

				if (removed) return null;
			}
		}

		return node;
	}
}

/**
 * Ducktype a node.
 *
 * @param {unknown} value
 * @returns {value is Node}
 */
function isNode(value) {
	return (
		value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string'
	);
}

/**
 * @typedef {import('estree').Node} Node
 * @typedef {import('./sync.js').SyncHandler} SyncHandler
 * @typedef {import('./async.js').AsyncHandler} AsyncHandler
 */

/**
 * @param {Node} ast
 * @param {{
 *   enter?: SyncHandler
 *   leave?: SyncHandler
 * }} walker
 * @returns {Node | null}
 */
function walk(ast, { enter, leave }) {
	const instance = new SyncWalker(enter, leave);
	return instance.visit(ast, null);
}

// generate an ID that is, to all intents and purposes, unique
const id = Math.round(Math.random() * 1e20).toString(36);
const re$1 = new RegExp(`_${id}_(?:(\\d+)|(AT)|(HASH))_(\\w+)?`, 'g');

/** @typedef {import('estree').Comment} Comment */
/** @typedef {import('estree').Node} Node */

/**
 * @typedef {Node & {
 *   start: number;
 *   end: number;
 *   has_trailing_newline?: boolean
 * }} NodeWithLocation
 */

/**
 * @typedef {Comment & {
 *   start: number;
 *   end: number;
 *   has_trailing_newline?: boolean
 * }} CommentWithLocation
 */

/**
 * @param {CommentWithLocation[]} comments
 * @param {string} raw
 */
const get_comment_handlers = (comments, raw) => ({
	// pass to acorn options
	/**
	 * @param {boolean} block
	 * @param {string} value
	 * @param {number} start
	 * @param {number} end
	 */
	onComment: (block, value, start, end) => {
		if (block && /\n/.test(value)) {
			let a = start;
			while (a > 0 && raw[a - 1] !== '\n') a -= 1;

			let b = a;
			while (/[ \t]/.test(raw[b])) b += 1;

			const indentation = raw.slice(a, b);
			value = value.replace(new RegExp(`^${indentation}`, 'gm'), '');
		}

		comments.push({ type: block ? 'Block' : 'Line', value, start, end });
	},

	// pass to estree-walker options
	/** @param {NodeWithLocation} node */
	enter(node) {
		let comment;

		while (comments[0] && comments[0].start < node.start) {
			comment = comments.shift();

			comment.value = comment.value.replace(
				re$1,
				(match, id, at, hash, value) => {
					if (hash) return `#${value}`;
					if (at) return `@${value}`;

					return match;
				}
			);

			const next = comments[0] || node;
			comment.has_trailing_newline =
				comment.type === 'Line' ||
				/\n/.test(raw.slice(comment.end, next.start));

			(node.leadingComments || (node.leadingComments = [])).push(comment);
		}
	},

	/** @param {NodeWithLocation} node */
	leave(node) {
		if (comments[0]) {
			const slice = raw.slice(node.end, comments[0].start);

			if (/^[,) \t]*$/.test(slice)) {
				node.trailingComments = [comments.shift()];
			}
		}
	}
});

/** @typedef { import('estree').Node} Node */
/** @typedef {Node | {
 *   type: 'PropertyDefinition';
 *   computed: boolean;
 *   value: Node
 * }} NodeWithPropertyDefinition */

/**
 *
 * @param {NodeWithPropertyDefinition} node
 * @param {NodeWithPropertyDefinition} parent
 * @returns {boolean}
 */
function is_reference (node, parent) {
	if (node.type === 'MemberExpression') {
		return !node.computed && is_reference(node.object, node);
	}

	if (node.type === 'Identifier') {
		if (!parent) return true;

		switch (parent.type) {
			// disregard `bar` in `foo.bar`
			case 'MemberExpression': return parent.computed || node === parent.object;

			// disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
			case 'MethodDefinition': return parent.computed;

			// disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
			case 'PropertyDefinition': return parent.computed || node === parent.value;

			// disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
			case 'Property': return parent.computed || node === parent.value;

			// disregard the `bar` in `export { foo as bar }` or
			// the foo in `import { foo as bar }`
			case 'ExportSpecifier':
			case 'ImportSpecifier': return node === parent.local;

			// disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
			case 'LabeledStatement':
			case 'BreakStatement':
			case 'ContinueStatement': return false;
			default: return true;
		}
	}

	return false;
}

/** @param {import('estree').Node} expression */
function analyze(expression) {
	/** @typedef {import('estree').Node} Node */

	/** @type {WeakMap<Node, Scope>} */
	const map = new WeakMap();

	/** @type {Map<string, Node>} */
	const globals = new Map();

	const scope = new Scope(null, false);

	/** @type {[Scope, import('estree').Identifier][]} */
	const references = [];
	/** @type {Scope} */
	let current_scope = scope;

	walk(expression, {
		enter(node, parent) {
			switch (node.type) {
				case 'Identifier':
					if (parent && is_reference(node, parent)) {
						references.push([current_scope, node]);
					}
					break;

				case 'ImportDeclaration':
					node.specifiers.forEach((specifier) => {
						current_scope.declarations.set(specifier.local.name, specifier);
					});
					break;

				case 'FunctionExpression':
				case 'FunctionDeclaration':
				case 'ArrowFunctionExpression':
					if (node.type === 'FunctionDeclaration') {
						if (node.id) {
							current_scope.declarations.set(node.id.name, node);
						}

						map.set(node, current_scope = new Scope(current_scope, false));
					} else {
						map.set(node, current_scope = new Scope(current_scope, false));

						if (node.type === 'FunctionExpression' && node.id) {
							current_scope.declarations.set(node.id.name, node);
						}
					}

					node.params.forEach(param => {
						extract_names(param).forEach(name => {
							current_scope.declarations.set(name, node);
						});
					});
					break;

				case 'ForStatement':
				case 'ForInStatement':
				case 'ForOfStatement':
					map.set(node, current_scope = new Scope(current_scope, true));
					break;

				case 'BlockStatement':
					map.set(node, current_scope = new Scope(current_scope, true));
					break;

				case 'ClassDeclaration':
				case 'VariableDeclaration':
					current_scope.add_declaration(node);
					break;

				case 'CatchClause':
					map.set(node, current_scope = new Scope(current_scope, true));

					if (node.param) {
						extract_names(node.param).forEach(name => {
							if (node.param) {
								current_scope.declarations.set(name, node.param);
							}
						});
					}
					break;
			}
		},

		leave(node) {
			if (map.has(node) && current_scope !== null && current_scope.parent) {
				current_scope = current_scope.parent;
			}
		}
	});

	for (let i = references.length - 1; i >= 0; --i) {
		const [scope, reference] = references[i];

		if (!scope.references.has(reference.name)) {
			add_reference(scope, reference.name);
		}
		if (!scope.find_owner(reference.name)) {
			globals.set(reference.name, reference);
		}
	}

	return { map, scope, globals };
}

/**
 * @param {Scope} scope
 * @param {string} name
 */
function add_reference(scope, name) {
	scope.references.add(name);
	if (scope.parent) add_reference(scope.parent, name);
}

class Scope {
	/**
	 * @param {Scope | null} parent 
	 * @param {boolean} block 
	 */
	constructor(parent, block) {
		/** @type {Scope | null} */
		this.parent = parent;

		/** @type {boolean} */
		this.block = block;

		/** @type {Map<string, import('estree').Node>} */
		this.declarations = new Map();

		/** @type {Set<string>} */
		this.initialised_declarations = new Set();

		/** @type {Set<string>} */
		this.references = new Set();
	}

	/**
	 * @param {import('estree').VariableDeclaration | import('estree').ClassDeclaration} node
	 */
	add_declaration(node) {
		if (node.type === 'VariableDeclaration') {
			if (node.kind === 'var' && this.block && this.parent) {
				this.parent.add_declaration(node);
			} else {
				/** @param {import('estree').VariableDeclarator} declarator */
				const handle_declarator = (declarator) => {
					extract_names(declarator.id).forEach(name => {
						this.declarations.set(name, node);
						if (declarator.init) this.initialised_declarations.add(name);
					});				};

				node.declarations.forEach(handle_declarator);
			}
		} else if (node.id) {
			this.declarations.set(node.id.name, node);
		}
	}

	/**
	 * @param {string} name
	 * @returns {Scope | null}
	 */
	find_owner(name) {
		if (this.declarations.has(name)) return this;
		return this.parent && this.parent.find_owner(name);
	}

	/**
	 * @param {string} name
	 * @returns {boolean}
	 */
	has(name) {
		return (
			this.declarations.has(name) || (!!this.parent && this.parent.has(name))
		);
	}
}

/**
 * @param {import('estree').Node} param
 * @returns {string[]}
 */
function extract_names(param) {
	return extract_identifiers(param).map(node => node.name);
}

/**
 * @param {import('estree').Node} param
 * @param {import('estree').Identifier[]} nodes
 * @returns {import('estree').Identifier[]}
 */
function extract_identifiers(param, nodes = []) {
	switch (param.type) {
		case 'Identifier':
			nodes.push(param);
			break;

		case 'MemberExpression':
			let object = param;
			while (object.type === 'MemberExpression') {
				object = /** @type {any} */ (object.object);
			}
			nodes.push(/** @type {any} */ (object));
			break;

		case 'ObjectPattern':
			/** @param {import('estree').Property | import('estree').RestElement} prop */
			const handle_prop = (prop) => {
				if (prop.type === 'RestElement') {
					extract_identifiers(prop.argument, nodes);
				} else {
					extract_identifiers(prop.value, nodes);
				}
			};

			param.properties.forEach(handle_prop);
			break;

		case 'ArrayPattern':
			/** @param {import('estree').Node} element */
			const handle_element = (element) => {
				if (element) extract_identifiers(element, nodes);
			};

			param.elements.forEach((element) => {
				if (element) {
					handle_element(element);
				}
			});
			break;

		case 'RestElement':
			extract_identifiers(param.argument, nodes);
			break;

		case 'AssignmentPattern':
			extract_identifiers(param.left, nodes);
			break;
	}

	return nodes;
}

/**
 * Does `array.push` for all `items`. Needed because `array.push(...items)` throws
 * "Maximum call stack size exceeded" when `items` is too big of an array.
 *
 * @param {any[]} array
 * @param {any[]} items
 */
function push_array$1(array, items) {
	for (let i = 0; i < items.length; i++) {
		array.push(items[i]);
	}
}

// heavily based on https://github.com/davidbonnet/astring
// released under MIT license https://github.com/davidbonnet/astring/blob/master/LICENSE


/** @typedef {import('estree').ArrowFunctionExpression} ArrowFunctionExpression */
/** @typedef {import('estree').BinaryExpression} BinaryExpression */
/** @typedef {import('estree').CallExpression} CallExpression */
/** @typedef {import('estree').Comment} Comment */
/** @typedef {import('estree').ExportSpecifier} ExportSpecifier */
/** @typedef {import('estree').Expression} Expression */
/** @typedef {import('estree').FunctionDeclaration} FunctionDeclaration */
/** @typedef {import('estree').ImportDeclaration} ImportDeclaration */
/** @typedef {import('estree').ImportSpecifier} ImportSpecifier */
/** @typedef {import('estree').Literal} Literal */
/** @typedef {import('estree').LogicalExpression} LogicalExpression */
/** @typedef {import('estree').NewExpression} NewExpression */
/** @typedef {import('estree').Node} Node */
/** @typedef {import('estree').ObjectExpression} ObjectExpression */
/** @typedef {import('estree').Pattern} Pattern */
/** @typedef {import('estree').Property} Property */
/** @typedef {import('estree').PropertyDefinition} PropertyDefinition */
/** @typedef {import('estree').SequenceExpression} SequenceExpression */
/** @typedef {import('estree').SimpleCallExpression} SimpleCallExpression */
/** @typedef {import('estree').SwitchStatement} SwitchStatement */
/** @typedef {import('estree').VariableDeclaration} VariableDeclaration */
/** @typedef {import('estree').StaticBlock} StaticBlock */
/** @typedef {import('estree').PrivateIdentifier} PrivateIdenifier*/

/**
 * @typedef {{
 *   content: string;
 *   loc?: {
 *     start: { line: number; column: number; };
 *     end: { line: number; column: number; };
 *   };
 *   has_newline: boolean;
 * }} Chunk
 */

/**
 * @typedef {(node: any, state: State) => Chunk[]} Handler
 */

/**
 * @typedef {{
 *   indent: string;
 *   scope: any; // TODO import from periscopic
 *   scope_map: WeakMap<Node, any>;
 *   getName: (name: string) => string;
 *   deconflicted: WeakMap<Node, Map<string, string>>;
 *   comments: Comment[];
 * }} State
 */

/**
 * @param {Node} node
 * @param {State} state
 * @returns {Chunk[]}
 */
function handle(node, state) {
	const handler = handlers$1[node.type];

	if (!handler) {
		throw new Error(`Not implemented ${node.type}`);
	}

	const result = handler(node, state);

	if (node.leadingComments) {
		result.unshift(
			c(
				node.leadingComments
					.map((comment) =>
						comment.type === 'Block'
							? `/*${comment.value}*/${
									/** @type {any} */ (comment).has_trailing_newline
										? `\n${state.indent}`
										: ` `
							  }`
							: `//${comment.value}${
									/** @type {any} */ (comment).has_trailing_newline
										? `\n${state.indent}`
										: ` `
							  }`
					)
					.join(``)
			)
		);
	}

	if (node.trailingComments) {
		state.comments.push(node.trailingComments[0]); // there is only ever one
	}

	return result;
}

/**
 * @param {string} content
 * @param {Node} [node]
 * @returns {Chunk}
 */
function c(content, node) {
	return {
		content,
		loc: node && node.loc,
		has_newline: /\n/.test(content)
	};
}

const OPERATOR_PRECEDENCE = {
	'||': 2,
	'&&': 3,
	'??': 4,
	'|': 5,
	'^': 6,
	'&': 7,
	'==': 8,
	'!=': 8,
	'===': 8,
	'!==': 8,
	'<': 9,
	'>': 9,
	'<=': 9,
	'>=': 9,
	in: 9,
	instanceof: 9,
	'<<': 10,
	'>>': 10,
	'>>>': 10,
	'+': 11,
	'-': 11,
	'*': 12,
	'%': 12,
	'/': 12,
	'**': 13
};

/** @type {Record<string, number>} */
const EXPRESSIONS_PRECEDENCE = {
	ArrayExpression: 20,
	TaggedTemplateExpression: 20,
	ThisExpression: 20,
	Identifier: 20,
	Literal: 18,
	TemplateLiteral: 20,
	Super: 20,
	SequenceExpression: 20,
	MemberExpression: 19,
	CallExpression: 19,
	NewExpression: 19,
	AwaitExpression: 17,
	ClassExpression: 17,
	FunctionExpression: 17,
	ObjectExpression: 17,
	UpdateExpression: 16,
	UnaryExpression: 15,
	BinaryExpression: 14,
	LogicalExpression: 13,
	ConditionalExpression: 4,
	ArrowFunctionExpression: 3,
	AssignmentExpression: 3,
	YieldExpression: 2,
	RestElement: 1
};

/**
 *
 * @param {Expression} node
 * @param {BinaryExpression | LogicalExpression} parent
 * @param {boolean} is_right
 * @returns
 */
function needs_parens(node, parent, is_right) {
	// special case where logical expressions and coalesce expressions cannot be mixed,
	// either of them need to be wrapped with parentheses
	if (
		node.type === 'LogicalExpression' &&
		parent.type === 'LogicalExpression' &&
		((parent.operator === '??' && node.operator !== '??') ||
			(parent.operator !== '??' && node.operator === '??'))
	) {
		return true;
	}

	const precedence = EXPRESSIONS_PRECEDENCE[node.type];
	const parent_precedence = EXPRESSIONS_PRECEDENCE[parent.type];

	if (precedence !== parent_precedence) {
		// Different node types
		return (
			(!is_right &&
				precedence === 15 &&
				parent_precedence === 14 &&
				parent.operator === '**') ||
			precedence < parent_precedence
		);
	}

	if (precedence !== 13 && precedence !== 14) {
		// Not a `LogicalExpression` or `BinaryExpression`
		return false;
	}

	if (
		/** @type {BinaryExpression} */ (node).operator === '**' &&
		parent.operator === '**'
	) {
		// Exponentiation operator has right-to-left associativity
		return !is_right;
	}

	if (is_right) {
		// Parenthesis are used if both operators have the same precedence
		return (
			OPERATOR_PRECEDENCE[/** @type {BinaryExpression} */ (node).operator] <=
			OPERATOR_PRECEDENCE[parent.operator]
		);
	}

	return (
		OPERATOR_PRECEDENCE[/** @type {BinaryExpression} */ (node).operator] <
		OPERATOR_PRECEDENCE[parent.operator]
	);
}

/** @param {Node} node */
function has_call_expression(node) {
	while (node) {
		if (node.type[0] === 'CallExpression') {
			return true;
		} else if (node.type === 'MemberExpression') {
			node = node.object;
		} else {
			return false;
		}
	}
}

/** @param {Chunk[]} chunks */
const has_newline = (chunks) => {
	for (let i = 0; i < chunks.length; i += 1) {
		if (chunks[i].has_newline) return true;
	}
	return false;
};

/** @param {Chunk[]} chunks */
const get_length = (chunks) => {
	let total = 0;
	for (let i = 0; i < chunks.length; i += 1) {
		total += chunks[i].content.length;
	}
	return total;
};

/**
 * @param {number} a
 * @param {number} b
 */
const sum = (a, b) => a + b;

/**
 * @param {Chunk[][]} nodes
 * @param {Chunk} separator
 * @returns {Chunk[]}
 */
const join$1 = (nodes, separator) => {
	if (nodes.length === 0) return [];

	const joined = [...nodes[0]];
	for (let i = 1; i < nodes.length; i += 1) {
		joined.push(separator);
		push_array$1(joined, nodes[i]);
	}
	return joined;
};

/**
 * @param {(node: any, state: State) => Chunk[]} fn
 */
const scoped = (fn) => {
	/**
	 * @param {any} node
	 * @param {State} state
	 */
	const scoped_fn = (node, state) => {
		return fn(node, {
			...state,
			scope: state.scope_map.get(node)
		});
	};

	return scoped_fn;
};

/**
 * @param {string} name
 * @param {Set<string>} names
 */
const deconflict = (name, names) => {
	const original = name;
	let i = 1;

	while (names.has(name)) {
		name = `${original}$${i++}`;
	}

	return name;
};

/**
 * @param {Node[]} nodes
 * @param {State} state
 */
const handle_body = (nodes, state) => {
	const chunks = [];

	const body = nodes.map((statement) => {
		const chunks = handle(statement, {
			...state,
			indent: state.indent
		});

		let add_newline = false;

		while (state.comments.length) {
			const comment = state.comments.shift();
			const prefix = add_newline ? `\n${state.indent}` : ` `;

			chunks.push(
				c(
					comment.type === 'Block'
						? `${prefix}/*${comment.value}*/`
						: `${prefix}//${comment.value}`
				)
			);

			add_newline = comment.type === 'Line';
		}

		return chunks;
	});

	let needed_padding = false;

	for (let i = 0; i < body.length; i += 1) {
		const needs_padding = has_newline(body[i]);

		if (i > 0) {
			chunks.push(
				c(
					needs_padding || needed_padding
						? `\n\n${state.indent}`
						: `\n${state.indent}`
				)
			);
		}

		push_array$1(chunks, body[i]);

		needed_padding = needs_padding;
	}

	return chunks;
};

/**
 * @param {VariableDeclaration} node
 * @param {State} state
 */
const handle_var_declaration = (node, state) => {
	const chunks = [c(`${node.kind} `)];

	const declarators = node.declarations.map((d) =>
		handle(d, {
			...state,
			indent: state.indent + (node.declarations.length === 1 ? '' : '\t')
		})
	);

	const multiple_lines =
		declarators.some(has_newline) ||
		declarators.map(get_length).reduce(sum, 0) +
			(state.indent.length + declarators.length - 1) * 2 >
			80;

	const separator = c(multiple_lines ? `,\n${state.indent}\t` : ', ');

	push_array$1(chunks, join$1(declarators, separator));

	return chunks;
};

/** @type {Record<string, Handler>} */
const handlers$1 = {
	Program(node, state) {
		return handle_body(node.body, state);
	},

	BlockStatement: scoped((node, state) => {
		return [
			c(`{\n${state.indent}\t`),
			...handle_body(node.body, { ...state, indent: state.indent + '\t' }),
			c(`\n${state.indent}}`)
		];
	}),

	EmptyStatement(node, state) {
		return [c(';')];
	},

	ParenthesizedExpression(node, state) {
		return handle(node.expression, state);
	},

	ExpressionStatement(node, state) {
		if (
			node.expression.type === 'AssignmentExpression' &&
			node.expression.left.type === 'ObjectPattern'
		) {
			// is an AssignmentExpression to an ObjectPattern
			return [c('('), ...handle(node.expression, state), c(');')];
		}

		return [...handle(node.expression, state), c(';')];
	},

	IfStatement(node, state) {
		const chunks = [
			c('if ('),
			...handle(node.test, state),
			c(') '),
			...handle(node.consequent, state)
		];

		if (node.alternate) {
			chunks.push(c(' else '));
			push_array$1(chunks, handle(node.alternate, state));
		}

		return chunks;
	},

	LabeledStatement(node, state) {
		return [...handle(node.label, state), c(': '), ...handle(node.body, state)];
	},

	BreakStatement(node, state) {
		return node.label
			? [c('break '), ...handle(node.label, state), c(';')]
			: [c('break;')];
	},

	ContinueStatement(node, state) {
		return node.label
			? [c('continue '), ...handle(node.label, state), c(';')]
			: [c('continue;')];
	},

	WithStatement(node, state) {
		return [
			c('with ('),
			...handle(node.object, state),
			c(') '),
			...handle(node.body, state)
		];
	},

	SwitchStatement(/** @type {SwitchStatement} */ node, state) {
		const chunks = [
			c('switch ('),
			...handle(node.discriminant, state),
			c(') {')
		];

		node.cases.forEach((block) => {
			if (block.test) {
				chunks.push(c(`\n${state.indent}\tcase `));
				push_array$1(
					chunks,
					handle(block.test, { ...state, indent: `${state.indent}\t` })
				);
				chunks.push(c(':'));
			} else {
				chunks.push(c(`\n${state.indent}\tdefault:`));
			}

			block.consequent.forEach((statement) => {
				chunks.push(c(`\n${state.indent}\t\t`));
				push_array$1(
					chunks,
					handle(statement, { ...state, indent: `${state.indent}\t\t` })
				);
			});
		});

		chunks.push(c(`\n${state.indent}}`));

		return chunks;
	},

	ReturnStatement(node, state) {
		if (node.argument) {
			const contains_comment =
				node.argument.leadingComments &&
				node.argument.leadingComments.some(
					(
						/** @type import('../utils/comments.js').CommentWithLocation */ comment
					) => comment.has_trailing_newline
				);
			return [
				c(contains_comment ? 'return (' : 'return '),
				...handle(node.argument, state),
				c(contains_comment ? ');' : ';')
			];
		} else {
			return [c('return;')];
		}
	},

	ThrowStatement(node, state) {
		return [c('throw '), ...handle(node.argument, state), c(';')];
	},

	TryStatement(node, state) {
		const chunks = [c('try '), ...handle(node.block, state)];

		if (node.handler) {
			if (node.handler.param) {
				chunks.push(c(' catch('));
				push_array$1(chunks, handle(node.handler.param, state));
				chunks.push(c(') '));
			} else {
				chunks.push(c(' catch '));
			}

			push_array$1(chunks, handle(node.handler.body, state));
		}

		if (node.finalizer) {
			chunks.push(c(' finally '));
			push_array$1(chunks, handle(node.finalizer, state));
		}

		return chunks;
	},

	WhileStatement(node, state) {
		return [
			c('while ('),
			...handle(node.test, state),
			c(') '),
			...handle(node.body, state)
		];
	},

	DoWhileStatement(node, state) {
		return [
			c('do '),
			...handle(node.body, state),
			c(' while ('),
			...handle(node.test, state),
			c(');')
		];
	},

	ForStatement: scoped((node, state) => {
		const chunks = [c('for (')];

		if (node.init) {
			if (node.init.type === 'VariableDeclaration') {
				push_array$1(chunks, handle_var_declaration(node.init, state));
			} else {
				push_array$1(chunks, handle(node.init, state));
			}
		}

		chunks.push(c('; '));
		if (node.test) push_array$1(chunks, handle(node.test, state));
		chunks.push(c('; '));
		if (node.update) push_array$1(chunks, handle(node.update, state));

		chunks.push(c(') '));
		push_array$1(chunks, handle(node.body, state));

		return chunks;
	}),

	ForInStatement: scoped((node, state) => {
		const chunks = [c(`for ${node.await ? 'await ' : ''}(`)];

		if (node.left.type === 'VariableDeclaration') {
			push_array$1(chunks, handle_var_declaration(node.left, state));
		} else {
			push_array$1(chunks, handle(node.left, state));
		}

		chunks.push(c(node.type === 'ForInStatement' ? ` in ` : ` of `));
		push_array$1(chunks, handle(node.right, state));
		chunks.push(c(') '));
		push_array$1(chunks, handle(node.body, state));

		return chunks;
	}),

	DebuggerStatement(node, state) {
		return [c('debugger', node), c(';')];
	},

	FunctionDeclaration: scoped(
		(/** @type {FunctionDeclaration} */ node, state) => {
			const chunks = [];

			if (node.async) chunks.push(c('async '));
			chunks.push(c(node.generator ? 'function* ' : 'function '));
			if (node.id) push_array$1(chunks, handle(node.id, state));
			chunks.push(c('('));

			const params = node.params.map((p) =>
				handle(p, {
					...state,
					indent: state.indent + '\t'
				})
			);

			const multiple_lines =
				params.some(has_newline) ||
				params.map(get_length).reduce(sum, 0) +
					(state.indent.length + params.length - 1) * 2 >
					80;

			const separator = c(multiple_lines ? `,\n${state.indent}` : ', ');

			if (multiple_lines) {
				chunks.push(c(`\n${state.indent}\t`));
				push_array$1(chunks, join$1(params, separator));
				chunks.push(c(`\n${state.indent}`));
			} else {
				push_array$1(chunks, join$1(params, separator));
			}

			chunks.push(c(') '));
			push_array$1(chunks, handle(node.body, state));

			return chunks;
		}
	),

	VariableDeclaration(node, state) {
		return handle_var_declaration(node, state).concat(c(';'));
	},

	VariableDeclarator(node, state) {
		if (node.init) {
			return [...handle(node.id, state), c(' = '), ...handle(node.init, state)];
		} else {
			return handle(node.id, state);
		}
	},

	ClassDeclaration(node, state) {
		const chunks = [c('class ')];

		if (node.id) {
			push_array$1(chunks, handle(node.id, state));
			chunks.push(c(' '));
		}

		if (node.superClass) {
			chunks.push(c('extends '));
			push_array$1(chunks, handle(node.superClass, state));
			chunks.push(c(' '));
		}

		push_array$1(chunks, handle(node.body, state));

		return chunks;
	},

	ImportDeclaration(/** @type {ImportDeclaration} */ node, state) {
		const chunks = [c('import ')];

		const { length } = node.specifiers;
		const source = handle(node.source, state);

		if (length > 0) {
			let i = 0;

			while (i < length) {
				if (i > 0) {
					chunks.push(c(', '));
				}

				const specifier = node.specifiers[i];

				if (specifier.type === 'ImportDefaultSpecifier') {
					chunks.push(c(specifier.local.name, specifier));
					i += 1;
				} else if (specifier.type === 'ImportNamespaceSpecifier') {
					chunks.push(c('* as ' + specifier.local.name, specifier));
					i += 1;
				} else {
					break;
				}
			}

			if (i < length) {
				// we have named specifiers
				const specifiers = node.specifiers
					.slice(i)
					.map((/** @type {ImportSpecifier} */ specifier) => {
						const name = handle(specifier.imported, state)[0];
						const as = handle(specifier.local, state)[0];

						if (name.content === as.content) {
							return [as];
						}

						return [name, c(' as '), as];
					});

				const width =
					get_length(chunks) +
					specifiers.map(get_length).reduce(sum, 0) +
					2 * specifiers.length +
					6 +
					get_length(source);

				if (width > 80) {
					chunks.push(c(`{\n\t`));
					push_array$1(chunks, join$1(specifiers, c(',\n\t')));
					chunks.push(c('\n}'));
				} else {
					chunks.push(c(`{ `));
					push_array$1(chunks, join$1(specifiers, c(', ')));
					chunks.push(c(' }'));
				}
			}

			chunks.push(c(' from '));
		}

		push_array$1(chunks, source);
		chunks.push(c(';'));

		return chunks;
	},

	ImportExpression(node, state) {
		return [c('import('), ...handle(node.source, state), c(')')];
	},

	ExportDefaultDeclaration(node, state) {
		const chunks = [c(`export default `), ...handle(node.declaration, state)];

		if (node.declaration.type !== 'FunctionDeclaration') {
			chunks.push(c(';'));
		}

		return chunks;
	},

	ExportNamedDeclaration(node, state) {
		const chunks = [c('export ')];

		if (node.declaration) {
			push_array$1(chunks, handle(node.declaration, state));
		} else {
			const specifiers = node.specifiers.map(
				(/** @type {ExportSpecifier} */ specifier) => {
					const name = handle(specifier.local, state)[0];
					const as = handle(specifier.exported, state)[0];

					if (name.content === as.content) {
						return [name];
					}

					return [name, c(' as '), as];
				}
			);

			const width =
				7 + specifiers.map(get_length).reduce(sum, 0) + 2 * specifiers.length;

			if (width > 80) {
				chunks.push(c('{\n\t'));
				push_array$1(chunks, join$1(specifiers, c(',\n\t')));
				chunks.push(c('\n}'));
			} else {
				chunks.push(c('{ '));
				push_array$1(chunks, join$1(specifiers, c(', ')));
				chunks.push(c(' }'));
			}

			if (node.source) {
				chunks.push(c(' from '));
				push_array$1(chunks, handle(node.source, state));
			}
		}

		chunks.push(c(';'));

		return chunks;
	},

	ExportAllDeclaration(node, state) {
		return [c(`export * from `), ...handle(node.source, state), c(`;`)];
	},

	MethodDefinition(node, state) {
		const chunks = [];

		if (node.static) {
			chunks.push(c('static '));
		}

		if (node.kind === 'get' || node.kind === 'set') {
			// Getter or setter
			chunks.push(c(node.kind + ' '));
		}

		if (node.value.async) {
			chunks.push(c('async '));
		}

		if (node.value.generator) {
			chunks.push(c('*'));
		}

		if (node.computed) {
			chunks.push(c('['));
			push_array$1(chunks, handle(node.key, state));
			chunks.push(c(']'));
		} else {
			push_array$1(chunks, handle(node.key, state));
		}

		chunks.push(c('('));

		const { params } = node.value;
		for (let i = 0; i < params.length; i += 1) {
			push_array$1(chunks, handle(params[i], state));
			if (i < params.length - 1) chunks.push(c(', '));
		}

		chunks.push(c(') '));
		push_array$1(chunks, handle(node.value.body, state));

		return chunks;
	},

	ArrowFunctionExpression: scoped(
		(/** @type {ArrowFunctionExpression} */ node, state) => {
			const chunks = [];

			if (node.async) chunks.push(c('async '));

			if (node.params.length === 1 && node.params[0].type === 'Identifier') {
				push_array$1(chunks, handle(node.params[0], state));
			} else {
				const params = node.params.map((param) =>
					handle(param, {
						...state,
						indent: state.indent + '\t'
					})
				);

				chunks.push(c('('));
				push_array$1(chunks, join$1(params, c(', ')));
				chunks.push(c(')'));
			}

			chunks.push(c(' => '));

			if (
				node.body.type === 'ObjectExpression' ||
				(node.body.type === 'AssignmentExpression' &&
					node.body.left.type === 'ObjectPattern')
			) {
				chunks.push(c('('));
				push_array$1(chunks, handle(node.body, state));
				chunks.push(c(')'));
			} else {
				push_array$1(chunks, handle(node.body, state));
			}

			return chunks;
		}
	),

	ThisExpression(node, state) {
		return [c('this', node)];
	},

	Super(node, state) {
		return [c('super', node)];
	},

	RestElement(node, state) {
		return [c('...'), ...handle(node.argument, state)];
	},

	YieldExpression(node, state) {
		if (node.argument) {
			return [
				c(node.delegate ? `yield* ` : `yield `),
				...handle(node.argument, state)
			];
		}

		return [c(node.delegate ? `yield*` : `yield`)];
	},

	AwaitExpression(node, state) {
		if (node.argument) {
			const precedence = EXPRESSIONS_PRECEDENCE[node.argument.type];

			if (precedence && precedence < EXPRESSIONS_PRECEDENCE.AwaitExpression) {
				return [c('await ('), ...handle(node.argument, state), c(')')];
			} else {
				return [c('await '), ...handle(node.argument, state)];
			}
		}

		return [c('await')];
	},

	TemplateLiteral(node, state) {
		const chunks = [c('`')];

		const { quasis, expressions } = node;

		for (let i = 0; i < expressions.length; i++) {
			chunks.push(c(quasis[i].value.raw), c('${'));
			push_array$1(chunks, handle(expressions[i], state));
			chunks.push(c('}'));
		}

		chunks.push(c(quasis[quasis.length - 1].value.raw), c('`'));

		return chunks;
	},

	TaggedTemplateExpression(node, state) {
		return handle(node.tag, state).concat(handle(node.quasi, state));
	},

	ArrayExpression(node, state) {
		const chunks = [c('[')];

		/** @type {Chunk[][]} */
		const elements = [];

		/** @type {Chunk[]} */
		let sparse_commas = [];

		for (let i = 0; i < node.elements.length; i += 1) {
			// can't use map/forEach because of sparse arrays
			const element = node.elements[i];
			if (element) {
				elements.push([
					...sparse_commas,
					...handle(element, {
						...state,
						indent: state.indent + '\t'
					})
				]);
				sparse_commas = [];
			} else {
				sparse_commas.push(c(','));
			}
		}

		const multiple_lines =
			elements.some(has_newline) ||
			elements.map(get_length).reduce(sum, 0) +
				(state.indent.length + elements.length - 1) * 2 >
				80;

		if (multiple_lines) {
			chunks.push(c(`\n${state.indent}\t`));
			push_array$1(chunks, join$1(elements, c(`,\n${state.indent}\t`)));
			chunks.push(c(`\n${state.indent}`));
			push_array$1(chunks, sparse_commas);
		} else {
			push_array$1(chunks, join$1(elements, c(', ')));
			push_array$1(chunks, sparse_commas);
		}

		chunks.push(c(']'));

		return chunks;
	},

	ObjectExpression(/** @type {ObjectExpression} */ node, state) {
		if (node.properties.length === 0) {
			return [c('{}')];
		}

		let has_inline_comment = false;

		/** @type {Chunk[]} */
		const chunks = [];
		const separator = c(', ');

		node.properties.forEach((p, i) => {
			push_array$1(
				chunks,
				handle(p, {
					...state,
					indent: state.indent + '\t'
				})
			);

			if (state.comments.length) {
				// TODO generalise this, so it works with ArrayExpressions and other things.
				// At present, stuff will just get appended to the closest statement/declaration
				chunks.push(c(', '));

				while (state.comments.length) {
					const comment = state.comments.shift();

					chunks.push(
						c(
							comment.type === 'Block'
								? `/*${comment.value}*/\n${state.indent}\t`
								: `//${comment.value}\n${state.indent}\t`
						)
					);

					if (comment.type === 'Line') {
						has_inline_comment = true;
					}
				}
			} else {
				if (i < node.properties.length - 1) {
					chunks.push(separator);
				}
			}
		});

		const multiple_lines =
			has_inline_comment || has_newline(chunks) || get_length(chunks) > 40;

		if (multiple_lines) {
			separator.content = `,\n${state.indent}\t`;
		}

		return [
			c(multiple_lines ? `{\n${state.indent}\t` : `{ `),
			...chunks,
			c(multiple_lines ? `\n${state.indent}}` : ` }`)
		];
	},

	Property(node, state) {
		const value = handle(node.value, state);

		if (node.key === node.value) {
			return value;
		}

		// special case
		if (
			!node.computed &&
			node.value.type === 'AssignmentPattern' &&
			node.value.left.type === 'Identifier' &&
			node.value.left.name === node.key.name
		) {
			return value;
		}

		if (
			!node.computed &&
			node.value.type === 'Identifier' &&
			((node.key.type === 'Identifier' && node.key.name === value[0].content) ||
				(node.key.type === 'Literal' && node.key.value === value[0].content))
		) {
			return value;
		}

		const key = handle(node.key, state);

		if (node.value.type === 'FunctionExpression' && !node.value.id) {
			state = {
				...state,
				scope: state.scope_map.get(node.value)
			};

			const chunks = node.kind !== 'init' ? [c(`${node.kind} `)] : [];

			if (node.value.async) {
				chunks.push(c('async '));
			}
			if (node.value.generator) {
				chunks.push(c('*'));
			}

			push_array$1(chunks, node.computed ? [c('['), ...key, c(']')] : key);
			chunks.push(c('('));
			push_array$1(
				chunks,
				join$1(
					node.value.params.map((/** @type {Pattern} */ param) =>
						handle(param, state)
					),
					c(', ')
				)
			);
			chunks.push(c(') '));
			push_array$1(chunks, handle(node.value.body, state));

			return chunks;
		}

		if (node.computed) {
			return [c('['), ...key, c(']: '), ...value];
		}

		return [...key, c(': '), ...value];
	},

	ObjectPattern(node, state) {
		const chunks = [c('{ ')];

		for (let i = 0; i < node.properties.length; i += 1) {
			push_array$1(chunks, handle(node.properties[i], state));
			if (i < node.properties.length - 1) chunks.push(c(', '));
		}

		chunks.push(c(' }'));

		return chunks;
	},

	SequenceExpression(/** @type {SequenceExpression} */ node, state) {
		const expressions = node.expressions.map((e) => handle(e, state));

		return [c('('), ...join$1(expressions, c(', ')), c(')')];
	},

	UnaryExpression(node, state) {
		const chunks = [c(node.operator)];

		if (node.operator.length > 1) {
			chunks.push(c(' '));
		}

		if (
			EXPRESSIONS_PRECEDENCE[node.argument.type] <
			EXPRESSIONS_PRECEDENCE.UnaryExpression
		) {
			chunks.push(c('('));
			push_array$1(chunks, handle(node.argument, state));
			chunks.push(c(')'));
		} else {
			push_array$1(chunks, handle(node.argument, state));
		}

		return chunks;
	},

	UpdateExpression(node, state) {
		return node.prefix
			? [c(node.operator), ...handle(node.argument, state)]
			: [...handle(node.argument, state), c(node.operator)];
	},

	AssignmentExpression(node, state) {
		return [
			...handle(node.left, state),
			c(` ${node.operator || '='} `),
			...handle(node.right, state)
		];
	},

	BinaryExpression(node, state) {
		/**
		 * @type any[]
		 */
		const chunks = [];

		// TODO
		// const is_in = node.operator === 'in';
		// if (is_in) {
		// 	// Avoids confusion in `for` loops initializers
		// 	chunks.push(c('('));
		// }

		if (needs_parens(node.left, node, false)) {
			chunks.push(c('('));
			push_array$1(chunks, handle(node.left, state));
			chunks.push(c(')'));
		} else {
			push_array$1(chunks, handle(node.left, state));
		}

		chunks.push(c(` ${node.operator} `));

		if (needs_parens(node.right, node, true)) {
			chunks.push(c('('));
			push_array$1(chunks, handle(node.right, state));
			chunks.push(c(')'));
		} else {
			push_array$1(chunks, handle(node.right, state));
		}

		return chunks;
	},

	ConditionalExpression(node, state) {
		/**
		 * @type any[]
		 */
		const chunks = [];

		if (
			EXPRESSIONS_PRECEDENCE[node.test.type] >
			EXPRESSIONS_PRECEDENCE.ConditionalExpression
		) {
			push_array$1(chunks, handle(node.test, state));
		} else {
			chunks.push(c('('));
			push_array$1(chunks, handle(node.test, state));
			chunks.push(c(')'));
		}

		const child_state = { ...state, indent: state.indent + '\t' };

		const consequent = handle(node.consequent, child_state);
		const alternate = handle(node.alternate, child_state);

		const multiple_lines =
			has_newline(consequent) ||
			has_newline(alternate) ||
			get_length(chunks) + get_length(consequent) + get_length(alternate) > 50;

		if (multiple_lines) {
			chunks.push(c(`\n${state.indent}? `));
			push_array$1(chunks, consequent);
			chunks.push(c(`\n${state.indent}: `));
			push_array$1(chunks, alternate);
		} else {
			chunks.push(c(` ? `));
			push_array$1(chunks, consequent);
			chunks.push(c(` : `));
			push_array$1(chunks, alternate);
		}

		return chunks;
	},

	NewExpression(/** @type {NewExpression} */ node, state) {
		const chunks = [c('new ')];

		if (
			EXPRESSIONS_PRECEDENCE[node.callee.type] <
				EXPRESSIONS_PRECEDENCE.CallExpression ||
			has_call_expression(node.callee)
		) {
			chunks.push(c('('));
			push_array$1(chunks, handle(node.callee, state));
			chunks.push(c(')'));
		} else {
			push_array$1(chunks, handle(node.callee, state));
		}

		// TODO this is copied from CallExpression — DRY it out
		const args = node.arguments.map((arg) =>
			handle(arg, {
				...state,
				indent: state.indent + '\t'
			})
		);

		const separator = args.some(has_newline) // TODO or length exceeds 80
			? c(',\n' + state.indent)
			: c(', ');

		chunks.push(c('('));
		push_array$1(chunks, join$1(args, separator));
		chunks.push(c(')'));

		return chunks;
	},

	ChainExpression(node, state) {
		return handle(node.expression, state);
	},

	CallExpression(/** @type {CallExpression} */ node, state) {
		/**
		 * @type any[]
		 */
		const chunks = [];

		if (
			EXPRESSIONS_PRECEDENCE[node.callee.type] <
			EXPRESSIONS_PRECEDENCE.CallExpression
		) {
			chunks.push(c('('));
			push_array$1(chunks, handle(node.callee, state));
			chunks.push(c(')'));
		} else {
			push_array$1(chunks, handle(node.callee, state));
		}

		if (/** @type {SimpleCallExpression} */ (node).optional) {
			chunks.push(c('?.'));
		}

		let has_inline_comment = false;
		let arg_chunks = [];
		outer: for (const arg of node.arguments) {
			const chunks = [];
			while (state.comments.length) {
				const comment = state.comments.shift();
				if (comment.type === 'Line') {
					has_inline_comment = true;
					break outer;
				}
				chunks.push(
					c(
						comment.type === 'Block'
							? `/*${comment.value}*/ `
							: `//${comment.value}`
					)
				);
			}
			push_array$1(chunks, handle(arg, state));
			arg_chunks.push(chunks);
		}

		const multiple_lines =
			has_inline_comment || arg_chunks.slice(0, -1).some(has_newline); // TODO or length exceeds 80
		if (multiple_lines) {
			// need to handle args again. TODO find alternative approach?
			const args = node.arguments.map((arg, i) => {
				const chunks = handle(arg, {
					...state,
					indent: `${state.indent}\t`
				});
				if (i < node.arguments.length - 1) chunks.push(c(','));
				while (state.comments.length) {
					const comment = state.comments.shift();
					chunks.push(
						c(
							comment.type === 'Block'
								? ` /*${comment.value}*/ `
								: ` //${comment.value}`
						)
					);
				}
				return chunks;
			});

			chunks.push(c(`(\n${state.indent}\t`));
			push_array$1(chunks, join$1(args, c(`\n${state.indent}\t`)));
			chunks.push(c(`\n${state.indent})`));
		} else {
			chunks.push(c('('));
			push_array$1(chunks, join$1(arg_chunks, c(', ')));
			chunks.push(c(')'));
		}

		return chunks;
	},

	MemberExpression(node, state) {
		/**
		 * @type any[]
		 */
		const chunks = [];

		if (
			EXPRESSIONS_PRECEDENCE[node.object.type] <
			EXPRESSIONS_PRECEDENCE.MemberExpression
		) {
			chunks.push(c('('));
			push_array$1(chunks, handle(node.object, state));
			chunks.push(c(')'));
		} else {
			push_array$1(chunks, handle(node.object, state));
		}

		if (node.computed) {
			if (node.optional) {
				chunks.push(c('?.'));
			}
			chunks.push(c('['));
			push_array$1(chunks, handle(node.property, state));
			chunks.push(c(']'));
		} else {
			chunks.push(c(node.optional ? '?.' : '.'));
			push_array$1(chunks, handle(node.property, state));
		}

		return chunks;
	},

	MetaProperty(node, state) {
		return [
			...handle(node.meta, state),
			c('.'),
			...handle(node.property, state)
		];
	},

	Identifier(node, state) {
		let name = node.name;

		if (name[0] === '@') {
			name = state.getName(name.slice(1));
		} else if (node.name[0] === '#') {
			const owner = state.scope.find_owner(node.name);

			if (!owner) {
				throw new Error(`Could not find owner for node`);
			}

			if (!state.deconflicted.has(owner)) {
				state.deconflicted.set(owner, new Map());
			}

			const deconflict_map = state.deconflicted.get(owner);

			if (!deconflict_map.has(node.name)) {
				deconflict_map.set(
					node.name,
					deconflict(node.name.slice(1), owner.references)
				);
			}

			name = deconflict_map.get(node.name);
		}

		return [c(name, node)];
	},

	Literal(/** @type {Literal} */ node, state) {
		if (typeof node.value === 'string') {
			return [
				// TODO do we need to handle weird unicode characters somehow?
				// str.replace(/\\u(\d{4})/g, (m, n) => String.fromCharCode(+n))
				c(
					(node.raw || JSON.stringify(node.value)).replace(
						re$1,
						(_m, _i, at, hash, name) => {
							if (at) return '@' + name;
							if (hash) return '#' + name;
							throw new Error(`this shouldn't happen`);
						}
					),
					node
				)
			];
		}

		return [c(node.raw || String(node.value), node)];
	},

	PropertyDefinition(/** @type {PropertyDefinition} */ node, state) {
		const chunks = [];

		if (node.static) {
			chunks.push(c('static '));
		}

		if (node.computed) {
			chunks.push(c('['), ...handle(node.key, state), c(']'));
		} else {
			chunks.push(...handle(node.key, state));
		}

		if (node.value) {
			chunks.push(c(' = '));

			chunks.push(...handle(node.value, state));
		}

		chunks.push(c(';'));

		return chunks;
	},

	StaticBlock(/** @type {StaticBlock} */ node, state) {
		const chunks = [c('static ')];

		push_array$1(chunks, handlers$1.BlockStatement(node, state));

		return chunks;
	},

	PrivateIdentifier(/** @type {PrivateIdenifier} */ node, state) {
		const chunks = [c('#')];

		push_array$1(chunks, [c(node.name, node)]);

		return chunks;
	}
};

handlers$1.ForOfStatement = handlers$1.ForInStatement;
handlers$1.FunctionExpression = handlers$1.FunctionDeclaration;
handlers$1.ClassExpression = handlers$1.ClassDeclaration;
handlers$1.ClassBody = handlers$1.BlockStatement;
handlers$1.SpreadElement = handlers$1.RestElement;
handlers$1.ArrayPattern = handlers$1.ArrayExpression;
handlers$1.LogicalExpression = handlers$1.BinaryExpression;
handlers$1.AssignmentPattern = handlers$1.AssignmentExpression;

const comma$1 = ','.charCodeAt(0);
const semicolon = ';'.charCodeAt(0);
const chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
const intToChar$1 = new Uint8Array(64); // 64 possible chars.
const charToInt$1 = new Uint8Array(128); // z is 122 in ASCII
for (let i = 0; i < chars$1.length; i++) {
    const c = chars$1.charCodeAt(i);
    intToChar$1[i] = c;
    charToInt$1[c] = i;
}
// Provide a fallback for older environments.
const td = typeof TextDecoder !== 'undefined'
    ? /* #__PURE__ */ new TextDecoder()
    : typeof Buffer !== 'undefined'
        ? {
            decode(buf) {
                const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
                return out.toString();
            },
        }
        : {
            decode(buf) {
                let out = '';
                for (let i = 0; i < buf.length; i++) {
                    out += String.fromCharCode(buf[i]);
                }
                return out;
            },
        };
function decode$1(mappings) {
    const state = new Int32Array(5);
    const decoded = [];
    let index = 0;
    do {
        const semi = indexOf$1(mappings, index);
        const line = [];
        let sorted = true;
        let lastCol = 0;
        state[0] = 0;
        for (let i = index; i < semi; i++) {
            let seg;
            i = decodeInteger$1(mappings, i, state, 0); // genColumn
            const col = state[0];
            if (col < lastCol)
                sorted = false;
            lastCol = col;
            if (hasMoreVlq$1(mappings, i, semi)) {
                i = decodeInteger$1(mappings, i, state, 1); // sourcesIndex
                i = decodeInteger$1(mappings, i, state, 2); // sourceLine
                i = decodeInteger$1(mappings, i, state, 3); // sourceColumn
                if (hasMoreVlq$1(mappings, i, semi)) {
                    i = decodeInteger$1(mappings, i, state, 4); // namesIndex
                    seg = [col, state[1], state[2], state[3], state[4]];
                }
                else {
                    seg = [col, state[1], state[2], state[3]];
                }
            }
            else {
                seg = [col];
            }
            line.push(seg);
        }
        if (!sorted)
            sort$1(line);
        decoded.push(line);
        index = semi + 1;
    } while (index <= mappings.length);
    return decoded;
}
function indexOf$1(mappings, index) {
    const idx = mappings.indexOf(';', index);
    return idx === -1 ? mappings.length : idx;
}
function decodeInteger$1(mappings, pos, state, j) {
    let value = 0;
    let shift = 0;
    let integer = 0;
    do {
        const c = mappings.charCodeAt(pos++);
        integer = charToInt$1[c];
        value |= (integer & 31) << shift;
        shift += 5;
    } while (integer & 32);
    const shouldNegate = value & 1;
    value >>>= 1;
    if (shouldNegate) {
        value = -0x80000000 | -value;
    }
    state[j] += value;
    return pos;
}
function hasMoreVlq$1(mappings, i, length) {
    if (i >= length)
        return false;
    return mappings.charCodeAt(i) !== comma$1;
}
function sort$1(line) {
    line.sort(sortComparator$2);
}
function sortComparator$2(a, b) {
    return a[0] - b[0];
}
function encode(decoded) {
    const state = new Int32Array(5);
    const bufLength = 1024 * 16;
    const subLength = bufLength - 36;
    const buf = new Uint8Array(bufLength);
    const sub = buf.subarray(0, subLength);
    let pos = 0;
    let out = '';
    for (let i = 0; i < decoded.length; i++) {
        const line = decoded[i];
        if (i > 0) {
            if (pos === bufLength) {
                out += td.decode(buf);
                pos = 0;
            }
            buf[pos++] = semicolon;
        }
        if (line.length === 0)
            continue;
        state[0] = 0;
        for (let j = 0; j < line.length; j++) {
            const segment = line[j];
            // We can push up to 5 ints, each int can take at most 7 chars, and we
            // may push a comma.
            if (pos > subLength) {
                out += td.decode(sub);
                buf.copyWithin(0, subLength, pos);
                pos -= subLength;
            }
            if (j > 0)
                buf[pos++] = comma$1;
            pos = encodeInteger(buf, pos, state, segment, 0); // genColumn
            if (segment.length === 1)
                continue;
            pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex
            pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine
            pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn
            if (segment.length === 4)
                continue;
            pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex
        }
    }
    return out + td.decode(buf.subarray(0, pos));
}
function encodeInteger(buf, pos, state, segment, j) {
    const next = segment[j];
    let num = next - state[j];
    state[j] = next;
    num = num < 0 ? (-num << 1) | 1 : num << 1;
    do {
        let clamped = num & 0b011111;
        num >>>= 5;
        if (num > 0)
            clamped |= 0b100000;
        buf[pos++] = intToChar$1[clamped];
    } while (num > 0);
    return pos;
}

/** @type {(str?: string) => string} str */
let btoa$2 = () => {
	throw new Error(
		'Unsupported environment: `window.btoa` or `Buffer` should be supported.'
	);
};

if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
	btoa$2 = (str) => window.btoa(unescape(encodeURIComponent(str)));
} else if (typeof Buffer === 'function') {
	btoa$2 = (str) => Buffer.from(str, 'utf-8').toString('base64');
}

/** @typedef {import('estree').Node} Node */

/**
 * @typedef {{
 *   file?: string;
 *   sourceMapSource?: string;
 *   sourceMapContent?: string;
 *   sourceMapEncodeMappings?: boolean; // default true
 *   getName?: (name: string) => string;
 * }} PrintOptions
 */

/**
 * @param {Node} node
 * @param {PrintOptions} opts
 * @returns {{ code: string, map: any }} // TODO
 */
function print(node, opts = {}) {
	if (Array.isArray(node)) {
		return print(
			{
				type: 'Program',
				body: node,
				sourceType: 'module'
			},
			opts
		);
	}

	const {
		getName = /** @param {string} x */ (x) => {
			throw new Error(`Unhandled sigil @${x}`);
		}
	} = opts;

	let { map: scope_map, scope } = analyze(node);
	const deconflicted = new WeakMap();

	const chunks = handle(node, {
		indent: '',
		getName,
		scope,
		scope_map,
		deconflicted,
		comments: []
	});

	/** @typedef {[number, number, number, number]} Segment */

	let code = '';
	let current_column = 0;

	/** @type {Segment[][]} */
	let mappings = [];

	/** @type {Segment[]} */
	let current_line = [];

	for (let i = 0; i < chunks.length; i += 1) {
		const chunk = chunks[i];

		code += chunk.content;

		if (chunk.loc) {
			current_line.push([
				current_column,
				0, // source index is always zero
				chunk.loc.start.line - 1,
				chunk.loc.start.column
			]);
		}

		for (let i = 0; i < chunk.content.length; i += 1) {
			if (chunk.content[i] === '\n') {
				mappings.push(current_line);
				current_line = [];
				current_column = 0;
			} else {
				current_column += 1;
			}
		}

		if (chunk.loc) {
			current_line.push([
				current_column,
				0, // source index is always zero
				chunk.loc.end.line - 1,
				chunk.loc.end.column
			]);
		}
	}

	mappings.push(current_line);

	const map = {
		version: 3,
		/** @type {string[]} */
		names: [],
		sources: [opts.sourceMapSource || null],
		sourcesContent: [opts.sourceMapContent || null],
		mappings:
			opts.sourceMapEncodeMappings == undefined || opts.sourceMapEncodeMappings
				? encode(mappings)
				: mappings
	};

	Object.defineProperties(map, {
		toString: {
			enumerable: false,
			value: function toString() {
				return JSON.stringify(this);
			}
		},
		toUrl: {
			enumerable: false,
			value: function toUrl() {
				return (
					'data:application/json;charset=utf-8;base64,' + btoa$2(this.toString())
				);
			}
		}
	});

	return {
		code,
		map
	};
}

/** @typedef {import('estree').Expression} Expression */
/** @typedef {import('estree').Node} Node */
/** @typedef {import('estree').ObjectExpression} ObjectExpression */
/** @typedef {import('estree').Property} Property */
/** @typedef {import('estree').SpreadElement} SpreadElement */

/** @typedef {import('./utils/comments').CommentWithLocation} CommentWithLocation */

/** @type {Record<string, string>} */
const sigils = {
	'@': 'AT',
	'#': 'HASH'
};

/** @param {TemplateStringsArray} strings */
const join = (strings) => {
	let str = strings[0];
	for (let i = 1; i < strings.length; i += 1) {
		str += `_${id}_${i - 1}_${strings[i]}`;
	}
	return str.replace(
		/([@#])(\w+)/g,
		(_m, sigil, name) => `_${id}_${sigils[sigil]}_${name}`
	);
};

/**
 * @param {any[]} array
 * @param {any[]} target
 */
const flatten_body = (array, target) => {
	for (let i = 0; i < array.length; i += 1) {
		const statement = array[i];
		if (Array.isArray(statement)) {
			flatten_body(statement, target);
			continue;
		}

		if (statement.type === 'ExpressionStatement') {
			if (statement.expression === EMPTY) continue;

			if (Array.isArray(statement.expression)) {
				// TODO this is hacktacular
				let node = statement.expression[0];
				while (Array.isArray(node)) node = node[0];
				if (node) node.leadingComments = statement.leadingComments;

				flatten_body(statement.expression, target);
				continue;
			}

			if (/(Expression|Literal)$/.test(statement.expression.type)) {
				target.push(statement);
				continue;
			}

			if (statement.leadingComments)
				statement.expression.leadingComments = statement.leadingComments;
			if (statement.trailingComments)
				statement.expression.trailingComments = statement.trailingComments;

			target.push(statement.expression);
			continue;
		}

		target.push(statement);
	}

	return target;
};

/**
 * @param {any[]} array
 * @param {any[]} target
 */
const flatten_properties = (array, target) => {
	for (let i = 0; i < array.length; i += 1) {
		const property = array[i];

		if (property.value === EMPTY) continue;

		if (property.key === property.value && Array.isArray(property.key)) {
			flatten_properties(property.key, target);
			continue;
		}

		target.push(property);
	}

	return target;
};

/**
 * @param {any[]} nodes
 * @param {any[]} target
 */
const flatten = (nodes, target) => {
	for (let i = 0; i < nodes.length; i += 1) {
		const node = nodes[i];

		if (node === EMPTY) continue;

		if (Array.isArray(node)) {
			flatten(node, target);
			continue;
		}

		target.push(node);
	}

	return target;
};

const EMPTY = { type: 'Empty' };

/**
 *
 * @param {CommentWithLocation[]} comments
 * @param {string} raw
 * @returns {any}
 */
const acorn_opts = (comments, raw) => {
	const { onComment } = get_comment_handlers(comments, raw);
	return {
		ecmaVersion: 2022,
		sourceType: 'module',
		allowAwaitOutsideFunction: true,
		allowImportExportEverywhere: true,
		allowReturnOutsideFunction: true,
		onComment
	};
};

/**
 * @param {string} raw
 * @param {Node} node
 * @param {any[]} values
 * @param {CommentWithLocation[]} comments
 */
const inject = (raw, node, values, comments) => {
	comments.forEach((comment) => {
		comment.value = comment.value.replace(re$1, (m, i) =>
			+i in values ? values[+i] : m
		);
	});

	const { enter, leave } = get_comment_handlers(comments, raw);

	return walk(node, {
		enter,

		/** @param {any} node */
		leave(node) {
			if (node.type === 'Identifier') {
				re$1.lastIndex = 0;
				const match = re$1.exec(node.name);

				if (match) {
					if (match[1]) {
						if (+match[1] in values) {
							let value = values[+match[1]];

							if (typeof value === 'string') {
								value = {
									type: 'Identifier',
									name: value,
									leadingComments: node.leadingComments,
									trailingComments: node.trailingComments
								};
							} else if (typeof value === 'number') {
								value = {
									type: 'Literal',
									value,
									leadingComments: node.leadingComments,
									trailingComments: node.trailingComments
								};
							}

							this.replace(value || EMPTY);
						}
					} else {
						node.name = `${match[2] ? `@` : `#`}${match[4]}`;
					}
				}
			}

			if (node.type === 'Literal') {
				if (typeof node.value === 'string') {
					re$1.lastIndex = 0;
					const new_value = /** @type {string} */ (node.value).replace(
						re$1,
						(m, i) => (+i in values ? values[+i] : m)
					);
					const has_changed = new_value !== node.value;
					node.value = new_value;
					if (has_changed && node.raw) {
						// preserve the quotes
						node.raw = `${node.raw[0]}${JSON.stringify(node.value).slice(
							1,
							-1
						)}${node.raw[node.raw.length - 1]}`;
					}
				}
			}

			if (node.type === 'TemplateElement') {
				re$1.lastIndex = 0;
				node.value.raw = /** @type {string} */ (node.value.raw).replace(
					re$1,
					(m, i) => (+i in values ? values[+i] : m)
				);
			}

			if (node.type === 'Program' || node.type === 'BlockStatement') {
				node.body = flatten_body(node.body, []);
			}

			if (node.type === 'ObjectExpression' || node.type === 'ObjectPattern') {
				node.properties = flatten_properties(node.properties, []);
			}

			if (node.type === 'ArrayExpression' || node.type === 'ArrayPattern') {
				node.elements = flatten(node.elements, []);
			}

			if (
				node.type === 'FunctionExpression' ||
				node.type === 'FunctionDeclaration' ||
				node.type === 'ArrowFunctionExpression'
			) {
				node.params = flatten(node.params, []);
			}

			if (node.type === 'CallExpression' || node.type === 'NewExpression') {
				node.arguments = flatten(node.arguments, []);
			}

			if (
				node.type === 'ImportDeclaration' ||
				node.type === 'ExportNamedDeclaration'
			) {
				node.specifiers = flatten(node.specifiers, []);
			}

			if (node.type === 'ForStatement') {
				node.init = node.init === EMPTY ? null : node.init;
				node.test = node.test === EMPTY ? null : node.test;
				node.update = node.update === EMPTY ? null : node.update;
			}

			leave(node);
		}
	});
};

/**
 *
 * @param {TemplateStringsArray} strings
 * @param  {any[]} values
 * @returns {Node[]}
 */
function b$1(strings, ...values) {
	const str = join(strings);

	/** @type {CommentWithLocation[]} */
	const comments = [];

	try {
		let ast = /** @type {any} */ (parse$b(str, acorn_opts(comments, str)));

		ast = inject(str, ast, values, comments);

		return ast.body;
	} catch (err) {
		handle_error(str, err);
	}
}

/**
 *
 * @param {TemplateStringsArray} strings
 * @param  {any[]} values
 * @returns {Expression & { start: Number, end: number }}
 */
function x$1(strings, ...values) {
	const str = join(strings);

	/** @type {CommentWithLocation[]} */
	const comments = [];

	try {
		let expression =
			/** @type {Expression & { start: Number, end: number }} */ (
				parseExpressionAt$1(str, 0, acorn_opts(comments, str))
			);
		const match = /\S+/.exec(str.slice(expression.end));
		if (match) {
			throw new Error(`Unexpected token '${match[0]}'`);
		}

		expression = /** @type {Expression & { start: Number, end: number }} */ (
			inject(str, expression, values, comments)
		);

		return expression;
	} catch (err) {
		handle_error(str, err);
	}
}

/**
 *
 * @param {TemplateStringsArray} strings
 * @param  {any[]} values
 * @returns {(Property | SpreadElement) & { start: Number, end: number }}
 */
function p(strings, ...values) {
	const str = `{${join(strings)}}`;

	/** @type {CommentWithLocation[]} */
	const comments = [];

	try {
		let expression = /** @type {any} */ (
			parseExpressionAt$1(str, 0, acorn_opts(comments, str))
		);

		expression = inject(str, expression, values, comments);

		return expression.properties[0];
	} catch (err) {
		handle_error(str, err);
	}
}

/**
 * @param {string} str
 * @param {Error} err
 */
function handle_error(str, err) {
	// TODO location/code frame

	re$1.lastIndex = 0;

	str = str.replace(re$1, (m, i, at, hash, name) => {
		if (at) return `@${name}`;
		if (hash) return `#${name}`;

		return '${...}';
	});

	console.log(`failed to parse:\n${str}`);
	throw err;
}

/**
 * @param {string} source
 * @param {any} opts
 */
const parse$a = (source, opts) => {
	/** @type {CommentWithLocation[]} */
	const comments = [];
	const { onComment, enter, leave } = get_comment_handlers(comments, source);
	const ast = /** @type {any} */ (parse$b(source, { onComment, ...opts }));
	walk(ast, { enter, leave });
	return ast;
};

/**
 * @param {string} source
 * @param {number} index
 * @param {any} opts
 */
const parseExpressionAt = (source, index, opts) => {
	/** @type {CommentWithLocation[]} */
	const comments = [];
	const { onComment, enter, leave } = get_comment_handlers(comments, source);
	const ast = /** @type {any} */ (
		parseExpressionAt$1(source, index, { onComment, ...opts })
	);
	walk(ast, { enter, leave });
	return ast;
};

/**
 * @param {string} source
 */
const parse$9 = (source) =>
	parse$a(source, {
		sourceType: 'module',
		ecmaVersion: 13,
		locations: true
	});

/**
 * @param {string} source
 * @param {number} index
 */
const parse_expression_at = (source, index) =>
	parseExpressionAt(source, index, {
		sourceType: 'module',
		ecmaVersion: 13,
		locations: true
	});

/**
 * @param {import('../index.js').Parser} parser
 * @returns {import('estree').Node | undefined}
 */
function read_expression(parser) {
	try {
		const node = parse_expression_at(parser.template, parser.index);

		let num_parens = 0;

		for (let i = parser.index; i < node.start; i += 1) {
			if (parser.template[i] === '(') num_parens += 1;
		}

		let index = node.end;
		while (num_parens > 0) {
			const char = parser.template[index];

			if (char === ')') {
				num_parens -= 1;
			} else if (!regex_whitespace.test(char)) {
				parser.error(parser_errors.unexpected_token(')'), index);
			}

			index += 1;
		}

		parser.index = index;

		return node;
	} catch (err) {
		parser.acorn_error(err);
	}
}

const regex_closing_script_tag = /<\/script\s*>/;
const regex_starts_with_closing_script_tag = /^<\/script\s*>/;

/**
 * @param {import('../index.js').Parser} parser
 * @param {any[]} attributes
 * @param {number} start
 * @returns {string}
 */
function get_context(parser, attributes, start) {
	const context = attributes.find((attribute) => attribute.name === 'context');
	if (!context) return 'default';
	if (context.value.length !== 1 || context.value[0].type !== 'Text') {
		parser.error(parser_errors.invalid_script_context_attribute, start);
	}
	const value = context.value[0].data;
	if (value !== 'module') {
		parser.error(parser_errors.invalid_script_context_value, context.start);
	}
	return value;
}

/**
 * @param {import('../index.js').Parser} parser
 * @param {number} start
 * @param {import('estree').Node[]} attributes
 * @returns {import('../../interfaces.js').Script}
 */
function read_script(parser, start, attributes) {
	const script_start = parser.index;
	const data = parser.read_until(regex_closing_script_tag, parser_errors.unclosed_script);
	if (parser.index >= parser.template.length) {
		parser.error(parser_errors.unclosed_script);
	}
	const source =
		parser.template.slice(0, script_start).replace(regex_not_newline_characters, ' ') + data;
	parser.read(regex_starts_with_closing_script_tag);

	/**
	 * @type {import('estree').Program}
	 */
	let ast;
	try {
		ast = parse$9(source);
	} catch (err) {
		parser.acorn_error(err);
	}
	// TODO is this necessary?
	/** @type {any} */ (ast).start = script_start;
	return {
		type: 'Script',
		start,
		end: parser.index,
		context: get_context(parser, attributes, start),
		content: ast
	};
}

var rs=Object.create;var tr=Object.defineProperty;var ns=Object.getOwnPropertyDescriptor;var os=Object.getOwnPropertyNames;var is=Object.getPrototypeOf,as=Object.prototype.hasOwnProperty;var Oe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),b=(e,t)=>{for(var r in t)tr(e,r,{get:t[r],enumerable:!0});},ss=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of os(t))!as.call(e,o)&&o!==r&&tr(e,o,{get:()=>t[o],enumerable:!(n=ns(t,o))||n.enumerable});return e};var ls=(e,t,r)=>(r=e!=null?rs(is(e)):{},ss(t||!e||!e.__esModule?tr(r,"default",{value:e,enumerable:!0}):r,e));var Jo=Oe(ur=>{var Zo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");ur.encode=function(e){if(0<=e&&e<Zo.length)return Zo[e];throw new TypeError("Must be between 0 and 63: "+e)};ur.decode=function(e){var t=65,r=90,n=97,o=122,i=48,s=57,u=43,c=47,a=26,l=52;return t<=e&&e<=r?e-t:n<=e&&e<=o?e-n+a:i<=e&&e<=s?e-i+l:e==u?62:e==c?63:-1};});var oi=Oe(hr=>{var ei=Jo(),pr=5,ti=1<<pr,ri=ti-1,ni=ti;function ks(e){return e<0?(-e<<1)+1:(e<<1)+0}function ws(e){var t=(e&1)===1,r=e>>1;return t?-r:r}hr.encode=function(t){var r="",n,o=ks(t);do n=o&ri,o>>>=pr,o>0&&(n|=ni),r+=ei.encode(n);while(o>0);return r};hr.decode=function(t,r,n){var o=t.length,i=0,s=0,u,c;do{if(r>=o)throw new Error("Expected more digits in base 64 VLQ value.");if(c=ei.decode(t.charCodeAt(r++)),c===-1)throw new Error("Invalid base64 digit: "+t.charAt(r-1));u=!!(c&ni),c&=ri,i=i+(c<<s),s+=pr;}while(u);n.value=ws(i),n.rest=r;};});var Et=Oe(K=>{function vs(e,t,r){if(t in e)return e[t];if(arguments.length===3)return r;throw new Error('"'+t+'" is a required argument.')}K.getArg=vs;var ii=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,Ss=/^data:.+\,.+$/;function nt(e){var t=e.match(ii);return t?{scheme:t[1],auth:t[2],host:t[3],port:t[4],path:t[5]}:null}K.urlParse=nt;function qe(e){var t="";return e.scheme&&(t+=e.scheme+":"),t+="//",e.auth&&(t+=e.auth+"@"),e.host&&(t+=e.host),e.port&&(t+=":"+e.port),e.path&&(t+=e.path),t}K.urlGenerate=qe;var Cs=32;function As(e){var t=[];return function(r){for(var n=0;n<t.length;n++)if(t[n].input===r){var o=t[0];return t[0]=t[n],t[n]=o,t[0].result}var i=e(r);return t.unshift({input:r,result:i}),t.length>Cs&&t.pop(),i}}var mr=As(function(t){var r=t,n=nt(t);if(n){if(!n.path)return t;r=n.path;}for(var o=K.isAbsolute(r),i=[],s=0,u=0;;)if(s=u,u=r.indexOf("/",s),u===-1){i.push(r.slice(s));break}else for(i.push(r.slice(s,u));u<r.length&&r[u]==="/";)u++;for(var c,a=0,u=i.length-1;u>=0;u--)c=i[u],c==="."?i.splice(u,1):c===".."?a++:a>0&&(c===""?(i.splice(u+1,a),a=0):(i.splice(u,2),a--));return r=i.join("/"),r===""&&(r=o?"/":"."),n?(n.path=r,qe(n)):r});K.normalize=mr;function ai(e,t){e===""&&(e="."),t===""&&(t=".");var r=nt(t),n=nt(e);if(n&&(e=n.path||"/"),r&&!r.scheme)return n&&(r.scheme=n.scheme),qe(r);if(r||t.match(Ss))return t;if(n&&!n.host&&!n.path)return n.host=t,qe(n);var o=t.charAt(0)==="/"?t:mr(e.replace(/\/+$/,"")+"/"+t);return n?(n.path=o,qe(n)):o}K.join=ai;K.isAbsolute=function(e){return e.charAt(0)==="/"||ii.test(e)};function Ts(e,t){e===""&&(e="."),e=e.replace(/\/$/,"");for(var r=0;t.indexOf(e+"/")!==0;){var n=e.lastIndexOf("/");if(n<0||(e=e.slice(0,n),e.match(/^([^\/]+:\/)?\/*$/)))return t;++r;}return Array(r+1).join("../")+t.substr(e.length+1)}K.relative=Ts;var si=function(){var e=Object.create(null);return !("__proto__"in e)}();function li(e){return e}function Es(e){return ci(e)?"$"+e:e}K.toSetString=si?li:Es;function Ls(e){return ci(e)?e.slice(1):e}K.fromSetString=si?li:Ls;function ci(e){if(!e)return !1;var t=e.length;if(t<9||e.charCodeAt(t-1)!==95||e.charCodeAt(t-2)!==95||e.charCodeAt(t-3)!==111||e.charCodeAt(t-4)!==116||e.charCodeAt(t-5)!==111||e.charCodeAt(t-6)!==114||e.charCodeAt(t-7)!==112||e.charCodeAt(t-8)!==95||e.charCodeAt(t-9)!==95)return !1;for(var r=t-10;r>=0;r--)if(e.charCodeAt(r)!==36)return !1;return !0}function Ps(e,t,r){var n=be(e.source,t.source);return n!==0||(n=e.originalLine-t.originalLine,n!==0)||(n=e.originalColumn-t.originalColumn,n!==0||r)||(n=e.generatedColumn-t.generatedColumn,n!==0)||(n=e.generatedLine-t.generatedLine,n!==0)?n:be(e.name,t.name)}K.compareByOriginalPositions=Ps;function Is(e,t,r){var n;return n=e.originalLine-t.originalLine,n!==0||(n=e.originalColumn-t.originalColumn,n!==0||r)||(n=e.generatedColumn-t.generatedColumn,n!==0)||(n=e.generatedLine-t.generatedLine,n!==0)?n:be(e.name,t.name)}K.compareByOriginalPositionsNoSource=Is;function Ds(e,t,r){var n=e.generatedLine-t.generatedLine;return n!==0||(n=e.generatedColumn-t.generatedColumn,n!==0||r)||(n=be(e.source,t.source),n!==0)||(n=e.originalLine-t.originalLine,n!==0)||(n=e.originalColumn-t.originalColumn,n!==0)?n:be(e.name,t.name)}K.compareByGeneratedPositionsDeflated=Ds;function Os(e,t,r){var n=e.generatedColumn-t.generatedColumn;return n!==0||r||(n=be(e.source,t.source),n!==0)||(n=e.originalLine-t.originalLine,n!==0)||(n=e.originalColumn-t.originalColumn,n!==0)?n:be(e.name,t.name)}K.compareByGeneratedPositionsDeflatedNoLine=Os;function be(e,t){return e===t?0:e===null?1:t===null?-1:e>t?1:-1}function Ns(e,t){var r=e.generatedLine-t.generatedLine;return r!==0||(r=e.generatedColumn-t.generatedColumn,r!==0)||(r=be(e.source,t.source),r!==0)||(r=e.originalLine-t.originalLine,r!==0)||(r=e.originalColumn-t.originalColumn,r!==0)?r:be(e.name,t.name)}K.compareByGeneratedPositionsInflated=Ns;function zs(e){return JSON.parse(e.replace(/^\)]}'[^\n]*\n/,""))}K.parseSourceMapInput=zs;function Ms(e,t,r){if(t=t||"",e&&(e[e.length-1]!=="/"&&t[0]!=="/"&&(e+="/"),t=e+t),r){var n=nt(r);if(!n)throw new Error("sourceMapURL could not be parsed");if(n.path){var o=n.path.lastIndexOf("/");o>=0&&(n.path=n.path.substring(0,o+1));}t=ai(qe(n),t);}return mr(t)}K.computeSourceURL=Ms;});var pi=Oe(ui=>{var fr=Et(),dr=Object.prototype.hasOwnProperty,Le=typeof Map<"u";function xe(){this._array=[],this._set=Le?new Map:Object.create(null);}xe.fromArray=function(t,r){for(var n=new xe,o=0,i=t.length;o<i;o++)n.add(t[o],r);return n};xe.prototype.size=function(){return Le?this._set.size:Object.getOwnPropertyNames(this._set).length};xe.prototype.add=function(t,r){var n=Le?t:fr.toSetString(t),o=Le?this.has(t):dr.call(this._set,n),i=this._array.length;(!o||r)&&this._array.push(t),o||(Le?this._set.set(t,i):this._set[n]=i);};xe.prototype.has=function(t){if(Le)return this._set.has(t);var r=fr.toSetString(t);return dr.call(this._set,r)};xe.prototype.indexOf=function(t){if(Le){var r=this._set.get(t);if(r>=0)return r}else {var n=fr.toSetString(t);if(dr.call(this._set,n))return this._set[n]}throw new Error('"'+t+'" is not in the set.')};xe.prototype.at=function(t){if(t>=0&&t<this._array.length)return this._array[t];throw new Error("No element indexed by "+t)};xe.prototype.toArray=function(){return this._array.slice()};ui.ArraySet=xe;});var fi=Oe(mi=>{var hi=Et();function Rs(e,t){var r=e.generatedLine,n=t.generatedLine,o=e.generatedColumn,i=t.generatedColumn;return n>r||n==r&&i>=o||hi.compareByGeneratedPositionsInflated(e,t)<=0}function Lt(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0};}Lt.prototype.unsortedForEach=function(t,r){this._array.forEach(t,r);};Lt.prototype.add=function(t){Rs(this._last,t)?(this._last=t,this._array.push(t)):(this._sorted=!1,this._array.push(t));};Lt.prototype.toArray=function(){return this._sorted||(this._array.sort(hi.compareByGeneratedPositionsInflated),this._sorted=!0),this._array};mi.MappingList=Lt;});var gi=Oe(di=>{var ot=oi(),j=Et(),Pt=pi().ArraySet,Fs=fi().MappingList;function oe(e){e||(e={}),this._file=j.getArg(e,"file",null),this._sourceRoot=j.getArg(e,"sourceRoot",null),this._skipValidation=j.getArg(e,"skipValidation",!1),this._sources=new Pt,this._names=new Pt,this._mappings=new Fs,this._sourcesContents=null;}oe.prototype._version=3;oe.fromSourceMap=function(t){var r=t.sourceRoot,n=new oe({file:t.file,sourceRoot:r});return t.eachMapping(function(o){var i={generated:{line:o.generatedLine,column:o.generatedColumn}};o.source!=null&&(i.source=o.source,r!=null&&(i.source=j.relative(r,i.source)),i.original={line:o.originalLine,column:o.originalColumn},o.name!=null&&(i.name=o.name)),n.addMapping(i);}),t.sources.forEach(function(o){var i=o;r!==null&&(i=j.relative(r,o)),n._sources.has(i)||n._sources.add(i);var s=t.sourceContentFor(o);s!=null&&n.setSourceContent(o,s);}),n};oe.prototype.addMapping=function(t){var r=j.getArg(t,"generated"),n=j.getArg(t,"original",null),o=j.getArg(t,"source",null),i=j.getArg(t,"name",null);this._skipValidation||this._validateMapping(r,n,o,i),o!=null&&(o=String(o),this._sources.has(o)||this._sources.add(o)),i!=null&&(i=String(i),this._names.has(i)||this._names.add(i)),this._mappings.add({generatedLine:r.line,generatedColumn:r.column,originalLine:n!=null&&n.line,originalColumn:n!=null&&n.column,source:o,name:i});};oe.prototype.setSourceContent=function(t,r){var n=t;this._sourceRoot!=null&&(n=j.relative(this._sourceRoot,n)),r!=null?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[j.toSetString(n)]=r):this._sourcesContents&&(delete this._sourcesContents[j.toSetString(n)],Object.keys(this._sourcesContents).length===0&&(this._sourcesContents=null));};oe.prototype.applySourceMap=function(t,r,n){var o=r;if(r==null){if(t.file==null)throw new Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);o=t.file;}var i=this._sourceRoot;i!=null&&(o=j.relative(i,o));var s=new Pt,u=new Pt;this._mappings.unsortedForEach(function(c){if(c.source===o&&c.originalLine!=null){var a=t.originalPositionFor({line:c.originalLine,column:c.originalColumn});a.source!=null&&(c.source=a.source,n!=null&&(c.source=j.join(n,c.source)),i!=null&&(c.source=j.relative(i,c.source)),c.originalLine=a.line,c.originalColumn=a.column,a.name!=null&&(c.name=a.name));}var l=c.source;l!=null&&!s.has(l)&&s.add(l);var p=c.name;p!=null&&!u.has(p)&&u.add(p);},this),this._sources=s,this._names=u,t.sources.forEach(function(c){var a=t.sourceContentFor(c);a!=null&&(n!=null&&(c=j.join(n,c)),i!=null&&(c=j.relative(i,c)),this.setSourceContent(c,a));},this);};oe.prototype._validateMapping=function(t,r,n,o){if(r&&typeof r.line!="number"&&typeof r.column!="number")throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if(!(t&&"line"in t&&"column"in t&&t.line>0&&t.column>=0&&!r&&!n&&!o)){if(t&&"line"in t&&"column"in t&&r&&"line"in r&&"column"in r&&t.line>0&&t.column>=0&&r.line>0&&r.column>=0&&n)return;throw new Error("Invalid mapping: "+JSON.stringify({generated:t,source:n,original:r,name:o}))}};oe.prototype._serializeMappings=function(){for(var t=0,r=1,n=0,o=0,i=0,s=0,u="",c,a,l,p,m=this._mappings.toArray(),f=0,P=m.length;f<P;f++){if(a=m[f],c="",a.generatedLine!==r)for(t=0;a.generatedLine!==r;)c+=";",r++;else if(f>0){if(!j.compareByGeneratedPositionsInflated(a,m[f-1]))continue;c+=",";}c+=ot.encode(a.generatedColumn-t),t=a.generatedColumn,a.source!=null&&(p=this._sources.indexOf(a.source),c+=ot.encode(p-s),s=p,c+=ot.encode(a.originalLine-1-o),o=a.originalLine-1,c+=ot.encode(a.originalColumn-n),n=a.originalColumn,a.name!=null&&(l=this._names.indexOf(a.name),c+=ot.encode(l-i),i=l)),u+=c;}return u};oe.prototype._generateSourcesContent=function(t,r){return t.map(function(n){if(!this._sourcesContents)return null;r!=null&&(n=j.relative(r,n));var o=j.toSetString(n);return Object.prototype.hasOwnProperty.call(this._sourcesContents,o)?this._sourcesContents[o]:null},this)};oe.prototype.toJSON=function(){var t={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return this._file!=null&&(t.file=this._file),this._sourceRoot!=null&&(t.sourceRoot=this._sourceRoot),this._sourcesContents&&(t.sourcesContent=this._generateSourcesContent(t.sources,t.sourceRoot)),t};oe.prototype.toString=function(){return JSON.stringify(this.toJSON())};di.SourceMapGenerator=oe;});var $e={};b($e,{AtKeyword:()=>I,BadString:()=>Ae,BadUrl:()=>Y,CDC:()=>U,CDO:()=>ue,Colon:()=>O,Comma:()=>G,Comment:()=>E,Delim:()=>g,Dimension:()=>y,EOF:()=>Xe,Function:()=>x,Hash:()=>v,Ident:()=>h,LeftCurlyBracket:()=>M,LeftParenthesis:()=>T,LeftSquareBracket:()=>q,Number:()=>d,Percentage:()=>A,RightCurlyBracket:()=>H,RightParenthesis:()=>w,RightSquareBracket:()=>V,Semicolon:()=>_,String:()=>W,Url:()=>F,WhiteSpace:()=>k$2});var Xe=0,h=1,x=2,I=3,v=4,W=5,Ae=6,F=7,Y=8,g=9,d=10,A=11,y=12,k$2=13,ue=14,U=15,O=16,_=17,G=18,q=19,V=20,T=21,w=22,M=23,H=24,E=25;function B(e){return e>=48&&e<=57}function ee(e){return B(e)||e>=65&&e<=70||e>=97&&e<=102}function yt(e){return e>=65&&e<=90}function cs(e){return e>=97&&e<=122}function us(e){return yt(e)||cs(e)}function ps(e){return e>=128}function xt(e){return us(e)||ps(e)||e===95}function Ne(e){return xt(e)||B(e)||e===45}function hs(e){return e>=0&&e<=8||e===11||e>=14&&e<=31||e===127}function Ze(e){return e===10||e===13||e===12}function pe(e){return Ze(e)||e===32||e===9}function $(e,t){return !(e!==92||Ze(t)||t===0)}function ze(e,t,r){return e===45?xt(t)||t===45||$(t,r):xt(e)?!0:e===92?$(e,t):!1}function kt(e,t,r){return e===43||e===45?B(t)?2:t===46&&B(r)?3:0:e===46?B(t)?2:0:B(e)?1:0}function wt(e){return e===65279||e===65534?1:0}var rr=new Array(128),ms=128,Je=130,nr=131,vt=132,or=133;for(let e=0;e<rr.length;e++)rr[e]=pe(e)&&Je||B(e)&&nr||xt(e)&&vt||hs(e)&&or||e||ms;function St(e){return e<128?rr[e]:vt}function Me(e,t){return t<e.length?e.charCodeAt(t):0}function Ct(e,t,r){return r===13&&Me(e,t+1)===10?2:1}function de(e,t,r){let n=e.charCodeAt(t);return yt(n)&&(n=n|32),n===r}function ge(e,t,r,n){if(r-t!==n.length||t<0||r>e.length)return !1;for(let o=t;o<r;o++){let i=n.charCodeAt(o-t),s=e.charCodeAt(o);if(yt(s)&&(s=s|32),s!==i)return !1}return !0}function qo(e,t){for(;t>=0&&pe(e.charCodeAt(t));t--);return t+1}function et(e,t){for(;t<e.length&&pe(e.charCodeAt(t));t++);return t}function ir(e,t){for(;t<e.length&&B(e.charCodeAt(t));t++);return t}function se(e,t){if(t+=2,ee(Me(e,t-1))){for(let n=Math.min(e.length,t+5);t<n&&ee(Me(e,t));t++);let r=Me(e,t);pe(r)&&(t+=Ct(e,t,r));}return t}function tt(e,t){for(;t<e.length;t++){let r=e.charCodeAt(t);if(!Ne(r)){if($(r,Me(e,t+1))){t=se(e,t)-1;continue}break}}return t}function Te(e,t){let r=e.charCodeAt(t);if((r===43||r===45)&&(r=e.charCodeAt(t+=1)),B(r)&&(t=ir(e,t+1),r=e.charCodeAt(t)),r===46&&B(e.charCodeAt(t+1))&&(t+=2,t=ir(e,t)),de(e,t,101)){let n=0;r=e.charCodeAt(t+1),(r===45||r===43)&&(n=1,r=e.charCodeAt(t+2)),B(r)&&(t=ir(e,t+1+n+1));}return t}function At(e,t){for(;t<e.length;t++){let r=e.charCodeAt(t);if(r===41){t++;break}$(r,Me(e,t+1))&&(t=se(e,t));}return t}function Re(e){if(e.length===1&&!ee(e.charCodeAt(0)))return e[0];let t=parseInt(e,16);return (t===0||t>=55296&&t<=57343||t>1114111)&&(t=65533),String.fromCodePoint(t)}var Fe=["EOF-token","ident-token","function-token","at-keyword-token","hash-token","string-token","bad-string-token","url-token","bad-url-token","delim-token","number-token","percentage-token","dimension-token","whitespace-token","CDO-token","CDC-token","colon-token","semicolon-token","comma-token","[-token","]-token","(-token",")-token","{-token","}-token"];function Be(e=null,t){return e===null||e.length<t?new Uint32Array(Math.max(t+1024,16384)):e}var Uo=10,fs=12,jo=13;function Wo(e){let t=e.source,r=t.length,n=t.length>0?wt(t.charCodeAt(0)):0,o=Be(e.lines,r),i=Be(e.columns,r),s=e.startLine,u=e.startColumn;for(let c=n;c<r;c++){let a=t.charCodeAt(c);o[c]=s,i[c]=u++,(a===Uo||a===jo||a===fs)&&(a===jo&&c+1<r&&t.charCodeAt(c+1)===Uo&&(c++,o[c]=s,i[c]=u),s++,u=1);}o[r]=s,i[r]=u,e.lines=o,e.columns=i,e.computed=!0;}var Tt=class{constructor(){this.lines=null,this.columns=null,this.computed=!1;}setSource(t,r=0,n=1,o=1){this.source=t,this.startOffset=r,this.startLine=n,this.startColumn=o,this.computed=!1;}getLocation(t,r){return this.computed||Wo(this),{source:r,offset:this.startOffset+t,line:this.lines[t],column:this.columns[t]}}getLocationRange(t,r,n){return this.computed||Wo(this),{source:n,start:{offset:this.startOffset+t,line:this.lines[t],column:this.columns[t]},end:{offset:this.startOffset+r,line:this.lines[r],column:this.columns[r]}}}};var ne=16777215,we=24,ds=new Map([[2,22],[21,22],[19,20],[23,24]]),rt=class{constructor(t,r){this.setSource(t,r);}reset(){this.eof=!1,this.tokenIndex=-1,this.tokenType=0,this.tokenStart=this.firstCharOffset,this.tokenEnd=this.firstCharOffset;}setSource(t="",r=()=>{}){t=String(t||"");let n=t.length,o=Be(this.offsetAndType,t.length+1),i=Be(this.balance,t.length+1),s=0,u=0,c=0,a=-1;for(this.offsetAndType=null,this.balance=null,r(t,(l,p,m)=>{switch(l){default:i[s]=n;break;case u:{let f=c&ne;for(c=i[f],u=c>>we,i[s]=f,i[f++]=s;f<s;f++)i[f]===n&&(i[f]=s);break}case 21:case 2:case 19:case 23:i[s]=c,u=ds.get(l),c=u<<we|s;break}o[s++]=l<<we|m,a===-1&&(a=p);}),o[s]=0<<we|n,i[s]=n,i[n]=n;c!==0;){let l=c&ne;c=i[l],i[l]=n;}this.source=t,this.firstCharOffset=a===-1?0:a,this.tokenCount=s,this.offsetAndType=o,this.balance=i,this.reset(),this.next();}lookupType(t){return t+=this.tokenIndex,t<this.tokenCount?this.offsetAndType[t]>>we:0}lookupOffset(t){return t+=this.tokenIndex,t<this.tokenCount?this.offsetAndType[t-1]&ne:this.source.length}lookupValue(t,r){return t+=this.tokenIndex,t<this.tokenCount?ge(this.source,this.offsetAndType[t-1]&ne,this.offsetAndType[t]&ne,r):!1}getTokenStart(t){return t===this.tokenIndex?this.tokenStart:t>0?t<this.tokenCount?this.offsetAndType[t-1]&ne:this.offsetAndType[this.tokenCount]&ne:this.firstCharOffset}substrToCursor(t){return this.source.substring(t,this.tokenStart)}isBalanceEdge(t){return this.balance[this.tokenIndex]<t}isDelim(t,r){return r?this.lookupType(r)===9&&this.source.charCodeAt(this.lookupOffset(r))===t:this.tokenType===9&&this.source.charCodeAt(this.tokenStart)===t}skip(t){let r=this.tokenIndex+t;r<this.tokenCount?(this.tokenIndex=r,this.tokenStart=this.offsetAndType[r-1]&ne,r=this.offsetAndType[r],this.tokenType=r>>we,this.tokenEnd=r&ne):(this.tokenIndex=this.tokenCount,this.next());}next(){let t=this.tokenIndex+1;t<this.tokenCount?(this.tokenIndex=t,this.tokenStart=this.tokenEnd,t=this.offsetAndType[t],this.tokenType=t>>we,this.tokenEnd=t&ne):(this.eof=!0,this.tokenIndex=this.tokenCount,this.tokenType=0,this.tokenStart=this.tokenEnd=this.source.length);}skipSC(){for(;this.tokenType===13||this.tokenType===25;)this.next();}skipUntilBalanced(t,r){let n=t,o,i;e:for(;n<this.tokenCount;n++){if(o=this.balance[n],o<t)break e;switch(i=n>0?this.offsetAndType[n-1]&ne:this.firstCharOffset,r(this.source.charCodeAt(i))){case 1:break e;case 2:n++;break e;default:this.balance[o]===n&&(n=o);}}this.skip(n-this.tokenIndex);}forEachToken(t){for(let r=0,n=this.firstCharOffset;r<this.tokenCount;r++){let o=n,i=this.offsetAndType[r],s=i&ne,u=i>>we;n=s,t(u,o,s,r);}}dump(){let t=new Array(this.tokenCount);return this.forEachToken((r,n,o,i)=>{t[i]={idx:i,type:Fe[r],chunk:this.source.substring(n,o),balance:this.balance[i]};}),t}};function ve(e,t){function r(p){return p<u?e.charCodeAt(p):0}function n(){if(a=Te(e,a),ze(r(a),r(a+1),r(a+2))){l=12,a=tt(e,a);return}if(r(a)===37){l=11,a++;return}l=10;}function o(){let p=a;if(a=tt(e,a),ge(e,p,a,"url")&&r(a)===40){if(a=et(e,a+1),r(a)===34||r(a)===39){l=2,a=p+4;return}s();return}if(r(a)===40){l=2,a++;return}l=1;}function i(p){for(p||(p=r(a++)),l=5;a<e.length;a++){let m=e.charCodeAt(a);switch(St(m)){case p:a++;return;case Je:if(Ze(m)){a+=Ct(e,a,m),l=6;return}break;case 92:if(a===e.length-1)break;let f=r(a+1);Ze(f)?a+=Ct(e,a+1,f):$(m,f)&&(a=se(e,a)-1);break}}}function s(){for(l=7,a=et(e,a);a<e.length;a++){let p=e.charCodeAt(a);switch(St(p)){case 41:a++;return;case Je:if(a=et(e,a),r(a)===41||a>=e.length){a<e.length&&a++;return}a=At(e,a),l=8;return;case 34:case 39:case 40:case or:a=At(e,a),l=8;return;case 92:if($(p,r(a+1))){a=se(e,a)-1;break}a=At(e,a),l=8;return}}}e=String(e||"");let u=e.length,c=wt(r(0)),a=c,l;for(;a<u;){let p=e.charCodeAt(a);switch(St(p)){case Je:l=13,a=et(e,a+1);break;case 34:i();break;case 35:Ne(r(a+1))||$(r(a+1),r(a+2))?(l=4,a=tt(e,a+1)):(l=9,a++);break;case 39:i();break;case 40:l=21,a++;break;case 41:l=22,a++;break;case 43:kt(p,r(a+1),r(a+2))?n():(l=9,a++);break;case 44:l=18,a++;break;case 45:kt(p,r(a+1),r(a+2))?n():r(a+1)===45&&r(a+2)===62?(l=15,a=a+3):ze(p,r(a+1),r(a+2))?o():(l=9,a++);break;case 46:kt(p,r(a+1),r(a+2))?n():(l=9,a++);break;case 47:r(a+1)===42?(l=25,a=e.indexOf("*/",a+2),a=a===-1?e.length:a+2):(l=9,a++);break;case 58:l=16,a++;break;case 59:l=17,a++;break;case 60:r(a+1)===33&&r(a+2)===45&&r(a+3)===45?(l=14,a=a+4):(l=9,a++);break;case 64:ze(r(a+1),r(a+2),r(a+3))?(l=3,a=tt(e,a+1)):(l=9,a++);break;case 91:l=19,a++;break;case 92:$(p,r(a+1))?o():(l=9,a++);break;case 93:l=20,a++;break;case 123:l=23,a++;break;case 125:l=24,a++;break;case nr:n();break;case vt:o();break;default:l=9,a++;}t(l,c,c=a);}}var _e=null,D=class{static createItem(t){return {prev:null,next:null,data:t}}constructor(){this.head=null,this.tail=null,this.cursor=null;}createItem(t){return D.createItem(t)}allocateCursor(t,r){let n;return _e!==null?(n=_e,_e=_e.cursor,n.prev=t,n.next=r,n.cursor=this.cursor):n={prev:t,next:r,cursor:this.cursor},this.cursor=n,n}releaseCursor(){let{cursor:t}=this;this.cursor=t.cursor,t.prev=null,t.next=null,t.cursor=_e,_e=t;}updateCursors(t,r,n,o){let{cursor:i}=this;for(;i!==null;)i.prev===t&&(i.prev=r),i.next===n&&(i.next=o),i=i.cursor;}*[Symbol.iterator](){for(let t=this.head;t!==null;t=t.next)yield t.data;}get size(){let t=0;for(let r=this.head;r!==null;r=r.next)t++;return t}get isEmpty(){return this.head===null}get first(){return this.head&&this.head.data}get last(){return this.tail&&this.tail.data}fromArray(t){let r=null;this.head=null;for(let n of t){let o=D.createItem(n);r!==null?r.next=o:this.head=o,o.prev=r,r=o;}return this.tail=r,this}toArray(){return [...this]}toJSON(){return [...this]}forEach(t,r=this){let n=this.allocateCursor(null,this.head);for(;n.next!==null;){let o=n.next;n.next=o.next,t.call(r,o.data,o,this);}this.releaseCursor();}forEachRight(t,r=this){let n=this.allocateCursor(this.tail,null);for(;n.prev!==null;){let o=n.prev;n.prev=o.prev,t.call(r,o.data,o,this);}this.releaseCursor();}reduce(t,r,n=this){let o=this.allocateCursor(null,this.head),i=r,s;for(;o.next!==null;)s=o.next,o.next=s.next,i=t.call(n,i,s.data,s,this);return this.releaseCursor(),i}reduceRight(t,r,n=this){let o=this.allocateCursor(this.tail,null),i=r,s;for(;o.prev!==null;)s=o.prev,o.prev=s.prev,i=t.call(n,i,s.data,s,this);return this.releaseCursor(),i}some(t,r=this){for(let n=this.head;n!==null;n=n.next)if(t.call(r,n.data,n,this))return !0;return !1}map(t,r=this){let n=new D;for(let o=this.head;o!==null;o=o.next)n.appendData(t.call(r,o.data,o,this));return n}filter(t,r=this){let n=new D;for(let o=this.head;o!==null;o=o.next)t.call(r,o.data,o,this)&&n.appendData(o.data);return n}nextUntil(t,r,n=this){if(t===null)return;let o=this.allocateCursor(null,t);for(;o.next!==null;){let i=o.next;if(o.next=i.next,r.call(n,i.data,i,this))break}this.releaseCursor();}prevUntil(t,r,n=this){if(t===null)return;let o=this.allocateCursor(t,null);for(;o.prev!==null;){let i=o.prev;if(o.prev=i.prev,r.call(n,i.data,i,this))break}this.releaseCursor();}clear(){this.head=null,this.tail=null;}copy(){let t=new D;for(let r of this)t.appendData(r);return t}prepend(t){return this.updateCursors(null,t,this.head,t),this.head!==null?(this.head.prev=t,t.next=this.head):this.tail=t,this.head=t,this}prependData(t){return this.prepend(D.createItem(t))}append(t){return this.insert(t)}appendData(t){return this.insert(D.createItem(t))}insert(t,r=null){if(r!==null)if(this.updateCursors(r.prev,t,r,t),r.prev===null){if(this.head!==r)throw new Error("before doesn't belong to list");this.head=t,r.prev=t,t.next=r,this.updateCursors(null,t);}else r.prev.next=t,t.prev=r.prev,r.prev=t,t.next=r;else this.updateCursors(this.tail,t,null,t),this.tail!==null?(this.tail.next=t,t.prev=this.tail):this.head=t,this.tail=t;return this}insertData(t,r){return this.insert(D.createItem(t),r)}remove(t){if(this.updateCursors(t,t.prev,t,t.next),t.prev!==null)t.prev.next=t.next;else {if(this.head!==t)throw new Error("item doesn't belong to list");this.head=t.next;}if(t.next!==null)t.next.prev=t.prev;else {if(this.tail!==t)throw new Error("item doesn't belong to list");this.tail=t.prev;}return t.prev=null,t.next=null,t}push(t){this.insert(D.createItem(t));}pop(){return this.tail!==null?this.remove(this.tail):null}unshift(t){this.prepend(D.createItem(t));}shift(){return this.head!==null?this.remove(this.head):null}prependList(t){return this.insertList(t,this.head)}appendList(t){return this.insertList(t)}insertList(t,r){return t.head===null?this:(r!=null?(this.updateCursors(r.prev,t.tail,r,t.head),r.prev!==null?(r.prev.next=t.head,t.head.prev=r.prev):this.head=t.head,r.prev=t.tail,t.tail.next=r):(this.updateCursors(this.tail,t.tail,null,t.head),this.tail!==null?(this.tail.next=t.head,t.head.prev=this.tail):this.head=t.head,this.tail=t.tail),t.head=null,t.tail=null,this)}replace(t,r){"head"in r?this.insertList(r,t):this.insert(r,t),this.remove(t);}};function Ee(e,t){let r=Object.create(SyntaxError.prototype),n=new Error;return Object.assign(r,{name:e,message:t,get stack(){return (n.stack||"").replace(/^(.+\n){1,3}/,`${e}: ${t}
`)}})}var ar=100,Ho=60,Yo="    ";function Go({source:e,line:t,column:r},n){function o(l,p){return i.slice(l,p).map((m,f)=>String(l+f+1).padStart(c)+" |"+m).join(`
`)}let i=e.split(/\r\n?|\n|\f/),s=Math.max(1,t-n)-1,u=Math.min(t+n,i.length+1),c=Math.max(4,String(u).length)+1,a=0;r+=(Yo.length-1)*(i[t-1].substr(0,r-1).match(/\t/g)||[]).length,r>ar&&(a=r-Ho+3,r=Ho-2);for(let l=s;l<=u;l++)l>=0&&l<i.length&&(i[l]=i[l].replace(/\t/g,Yo),i[l]=(a>0&&i[l].length>a?"\u2026":"")+i[l].substr(a,ar-2)+(i[l].length>a+ar-1?"\u2026":""));return [o(s,t),new Array(r+c+2).join("-")+"^",o(t,u)].filter(Boolean).join(`
`)}function sr(e,t,r,n,o){return Object.assign(Ee("SyntaxError",e),{source:t,offset:r,line:n,column:o,sourceFragment(s){return Go({source:t,line:n,column:o},isNaN(s)?0:s)},get formattedMessage(){return `Parse error: ${e}
`+Go({source:t,line:n,column:o},2)}})}function Vo(e){let t=this.createList(),r=!1,n={recognizer:e};for(;!this.eof;){switch(this.tokenType){case 25:this.next();continue;case 13:r=!0,this.next();continue}let o=e.getNode.call(this,n);if(o===void 0)break;r&&(e.onWhiteSpace&&e.onWhiteSpace.call(this,o,t,n),r=!1),t.push(o);}return r&&e.onWhiteSpace&&e.onWhiteSpace.call(this,null,t,n),t}var Ko=()=>{},gs=33,bs=35,lr=59,Qo=123,Xo=0;function xs(e){return function(){return this[e]()}}function cr(e){let t=Object.create(null);for(let r in e){let n=e[r],o=n.parse||n;o&&(t[r]=o);}return t}function ys(e){let t={context:Object.create(null),scope:Object.assign(Object.create(null),e.scope),atrule:cr(e.atrule),pseudo:cr(e.pseudo),node:cr(e.node)};for(let r in e.parseContext)switch(typeof e.parseContext[r]){case"function":t.context[r]=e.parseContext[r];break;case"string":t.context[r]=xs(e.parseContext[r]);break}return {config:t,...t,...t.node}}function $o(e){let t="",r="<unknown>",n=!1,o=Ko,i=!1,s=new Tt,u=Object.assign(new rt,ys(e||{}),{parseAtrulePrelude:!0,parseRulePrelude:!0,parseValue:!0,parseCustomProperty:!1,readSequence:Vo,consumeUntilBalanceEnd:()=>0,consumeUntilLeftCurlyBracket(a){return a===Qo?1:0},consumeUntilLeftCurlyBracketOrSemicolon(a){return a===Qo||a===lr?1:0},consumeUntilExclamationMarkOrSemicolon(a){return a===gs||a===lr?1:0},consumeUntilSemicolonIncluded(a){return a===lr?2:0},createList(){return new D},createSingleNodeList(a){return new D().appendData(a)},getFirstListNode(a){return a&&a.first},getLastListNode(a){return a&&a.last},parseWithFallback(a,l){let p=this.tokenIndex;try{return a.call(this)}catch(m){if(i)throw m;let f=l.call(this,p);return i=!0,o(m,f),i=!1,f}},lookupNonWSType(a){let l;do if(l=this.lookupType(a++),l!==13)return l;while(l!==Xo);return Xo},charCodeAt(a){return a>=0&&a<t.length?t.charCodeAt(a):0},substring(a,l){return t.substring(a,l)},substrToCursor(a){return this.source.substring(a,this.tokenStart)},cmpChar(a,l){return de(t,a,l)},cmpStr(a,l,p){return ge(t,a,l,p)},consume(a){let l=this.tokenStart;return this.eat(a),this.substrToCursor(l)},consumeFunctionName(){let a=t.substring(this.tokenStart,this.tokenEnd-1);return this.eat(2),a},consumeNumber(a){let l=t.substring(this.tokenStart,Te(t,this.tokenStart));return this.eat(a),l},eat(a){if(this.tokenType!==a){let l=Fe[a].slice(0,-6).replace(/-/g," ").replace(/^./,f=>f.toUpperCase()),p=`${/[[\](){}]/.test(l)?`"${l}"`:l} is expected`,m=this.tokenStart;switch(a){case 1:this.tokenType===2||this.tokenType===7?(m=this.tokenEnd-1,p="Identifier is expected but function found"):p="Identifier is expected";break;case 4:this.isDelim(bs)&&(this.next(),m++,p="Name is expected");break;case 11:this.tokenType===10&&(m=this.tokenEnd,p="Percent sign is expected");break}this.error(p,m);}this.next();},eatIdent(a){(this.tokenType!==1||this.lookupValue(0,a)===!1)&&this.error(`Identifier "${a}" is expected`),this.next();},eatDelim(a){this.isDelim(a)||this.error(`Delim "${String.fromCharCode(a)}" is expected`),this.next();},getLocation(a,l){return n?s.getLocationRange(a,l,r):null},getLocationFromList(a){if(n){let l=this.getFirstListNode(a),p=this.getLastListNode(a);return s.getLocationRange(l!==null?l.loc.start.offset-s.startOffset:this.tokenStart,p!==null?p.loc.end.offset-s.startOffset:this.tokenStart,r)}return null},error(a,l){let p=typeof l<"u"&&l<t.length?s.getLocation(l):this.eof?s.getLocation(qo(t,t.length-1)):s.getLocation(this.tokenStart);throw new sr(a||"Unexpected input",t,p.offset,p.line,p.column)}});return Object.assign(function(a,l){t=a,l=l||{},u.setSource(t,ve),s.setSource(t,l.offset,l.line,l.column),r=l.filename||"<unknown>",n=Boolean(l.positions),o=typeof l.onParseError=="function"?l.onParseError:Ko,i=!1,u.parseAtrulePrelude="parseAtrulePrelude"in l?Boolean(l.parseAtrulePrelude):!0,u.parseRulePrelude="parseRulePrelude"in l?Boolean(l.parseRulePrelude):!0,u.parseValue="parseValue"in l?Boolean(l.parseValue):!0,u.parseCustomProperty="parseCustomProperty"in l?Boolean(l.parseCustomProperty):!1;let{context:p="default",onComment:m}=l;if(!(p in u.context))throw new Error("Unknown context `"+p+"`");typeof m=="function"&&u.forEachToken((P,te,X)=>{if(P===25){let S=u.getLocation(te,X),R=ge(t,X-2,X,"*/")?t.slice(te+2,X-2):t.slice(te+2,X);m(R,S);}});let f=u.context[p].call(u,l);return u.eof||u.error(),f},{SyntaxError:sr,config:u.config})}var xi=ls(gi(),1),bi=new Set(["Atrule","Selector","Declaration"]);function yi(e){let t=new xi.SourceMapGenerator,r={line:1,column:0},n={line:0,column:0},o={line:1,column:0},i={generated:o},s=1,u=0,c=!1,a=e.node;e.node=function(m){if(m.loc&&m.loc.start&&bi.has(m.type)){let f=m.loc.start.line,P=m.loc.start.column-1;(n.line!==f||n.column!==P)&&(n.line=f,n.column=P,r.line=s,r.column=u,c&&(c=!1,(r.line!==o.line||r.column!==o.column)&&t.addMapping(i)),c=!0,t.addMapping({source:m.loc.source,original:n,generated:r}));}a.call(this,m),c&&bi.has(m.type)&&(o.line=s,o.column=u);};let l=e.emit;e.emit=function(m,f,P){for(let te=0;te<m.length;te++)m.charCodeAt(te)===10?(s++,u=0):u++;l(m,f,P);};let p=e.result;return e.result=function(){return c&&t.addMapping(i),{css:p(),map:t}},e}var It={};b(It,{safe:()=>br,spec:()=>Us});var Bs=43,_s=45,gr=(e,t)=>{if(e===9&&(e=t),typeof e=="string"){let r=e.charCodeAt(0);return r>127?32768:r<<8}return e},ki=[[1,1],[1,2],[1,7],[1,8],[1,"-"],[1,10],[1,11],[1,12],[1,15],[1,21],[3,1],[3,2],[3,7],[3,8],[3,"-"],[3,10],[3,11],[3,12],[3,15],[4,1],[4,2],[4,7],[4,8],[4,"-"],[4,10],[4,11],[4,12],[4,15],[12,1],[12,2],[12,7],[12,8],[12,"-"],[12,10],[12,11],[12,12],[12,15],["#",1],["#",2],["#",7],["#",8],["#","-"],["#",10],["#",11],["#",12],["#",15],["-",1],["-",2],["-",7],["-",8],["-","-"],["-",10],["-",11],["-",12],["-",15],[10,1],[10,2],[10,7],[10,8],[10,10],[10,11],[10,12],[10,"%"],[10,15],["@",1],["@",2],["@",7],["@",8],["@","-"],["@",15],[".",10],[".",11],[".",12],["+",10],["+",11],["+",12],["/","*"]],qs=ki.concat([[1,4],[12,4],[4,4],[3,21],[3,5],[3,16],[11,11],[11,12],[11,2],[11,"-"],[22,1],[22,2],[22,11],[22,12],[22,4],[22,"-"]]);function wi(e){let t=new Set(e.map(([r,n])=>gr(r)<<16|gr(n)));return function(r,n,o){let i=gr(n,o),s=o.charCodeAt(0);return (s===_s&&n!==1&&n!==2&&n!==15||s===Bs?t.has(r<<16|s<<8):t.has(r<<16|i))&&this.emit(" ",13,!0),i}}var Us=wi(ki),br=wi(qs);var js=92;function Ws(e,t){if(typeof t=="function"){let r=null;e.children.forEach(n=>{r!==null&&t.call(this,r),this.node(n),r=n;});return}e.children.forEach(this.node,this);}function Hs(e){ve(e,(t,r,n)=>{this.token(t,e.slice(r,n));});}function vi(e){let t=new Map;for(let r in e.node){let n=e.node[r];typeof(n.generate||n)=="function"&&t.set(r,n.generate||n);}return function(r,n){let o="",i=0,s={node(c){if(t.has(c.type))t.get(c.type).call(u,c);else throw new Error("Unknown node type: "+c.type)},tokenBefore:br,token(c,a){i=this.tokenBefore(i,c,a),this.emit(a,c,!1),c===9&&a.charCodeAt(0)===js&&this.emit(`
`,13,!0);},emit(c){o+=c;},result(){return o}};n&&(typeof n.decorator=="function"&&(s=n.decorator(s)),n.sourceMap&&(s=yi(s)),n.mode in It&&(s.tokenBefore=It[n.mode]));let u={node:c=>s.node(c),children:Ws,token:(c,a)=>s.token(c,a),tokenize:Hs};return s.node(r),s.result()}}function Si(e){return {fromPlainObject(t){return e(t,{enter(r){r.children&&!(r.children instanceof D)&&(r.children=new D().fromArray(r.children));}}),t},toPlainObject(t){return e(t,{leave(r){r.children&&r.children instanceof D&&(r.children=r.children.toArray());}}),t}}}var{hasOwnProperty:xr}=Object.prototype,it=function(){};function Ci(e){return typeof e=="function"?e:it}function Ai(e,t){return function(r,n,o){r.type===t&&e.call(this,r,n,o);}}function Ys(e,t){let r=t.structure,n=[];for(let o in r){if(xr.call(r,o)===!1)continue;let i=r[o],s={name:o,type:!1,nullable:!1};Array.isArray(i)||(i=[i]);for(let u of i)u===null?s.nullable=!0:typeof u=="string"?s.type="node":Array.isArray(u)&&(s.type="list");s.type&&n.push(s);}return n.length?{context:t.walkContext,fields:n}:null}function Gs(e){let t={};for(let r in e.node)if(xr.call(e.node,r)){let n=e.node[r];if(!n.structure)throw new Error("Missed `structure` field in `"+r+"` node type definition");t[r]=Ys(r,n);}return t}function Ti(e,t){let r=e.fields.slice(),n=e.context,o=typeof n=="string";return t&&r.reverse(),function(i,s,u,c){let a;o&&(a=s[n],s[n]=i);for(let l of r){let p=i[l.name];if(!l.nullable||p){if(l.type==="list"){if(t?p.reduceRight(c,!1):p.reduce(c,!1))return !0}else if(u(p))return !0}}o&&(s[n]=a);}}function Ei({StyleSheet:e,Atrule:t,Rule:r,Block:n,DeclarationList:o}){return {Atrule:{StyleSheet:e,Atrule:t,Rule:r,Block:n},Rule:{StyleSheet:e,Atrule:t,Rule:r,Block:n},Declaration:{StyleSheet:e,Atrule:t,Rule:r,Block:n,DeclarationList:o}}}function Li(e){let t=Gs(e),r={},n={},o=Symbol("break-walk"),i=Symbol("skip-node");for(let a in t)xr.call(t,a)&&t[a]!==null&&(r[a]=Ti(t[a],!1),n[a]=Ti(t[a],!0));let s=Ei(r),u=Ei(n),c=function(a,l){function p(S,R,ke){let z=m.call(X,S,R,ke);return z===o?!0:z===i?!1:!!(P.hasOwnProperty(S.type)&&P[S.type](S,X,p,te)||f.call(X,S,R,ke)===o)}let m=it,f=it,P=r,te=(S,R,ke,z)=>S||p(R,ke,z),X={break:o,skip:i,root:a,stylesheet:null,atrule:null,atrulePrelude:null,rule:null,selector:null,block:null,declaration:null,function:null};if(typeof l=="function")m=l;else if(l&&(m=Ci(l.enter),f=Ci(l.leave),l.reverse&&(P=n),l.visit)){if(s.hasOwnProperty(l.visit))P=l.reverse?u[l.visit]:s[l.visit];else if(!t.hasOwnProperty(l.visit))throw new Error("Bad value `"+l.visit+"` for `visit` option (should be: "+Object.keys(t).sort().join(", ")+")");m=Ai(m,l.visit),f=Ai(f,l.visit);}if(m===it&&f===it)throw new Error("Neither `enter` nor `leave` walker handler is set or both aren't a function");p(a);};return c.break=o,c.skip=i,c.find=function(a,l){let p=null;return c(a,function(m,f,P){if(l.call(this,m,f,P))return p=m,o}),p},c.findLast=function(a,l){let p=null;return c(a,{reverse:!0,enter(m,f,P){if(l.call(this,m,f,P))return p=m,o}}),p},c.findAll=function(a,l){let p=[];return c(a,function(m,f,P){l.call(this,m,f,P)&&p.push(m);}),p},c}function Vs(e){return e}function Ks(e){let{min:t,max:r,comma:n}=e;return t===0&&r===0?n?"#?":"*":t===0&&r===1?"?":t===1&&r===0?n?"#":"+":t===1&&r===1?"":(n?"#":"")+(t===r?"{"+t+"}":"{"+t+","+(r!==0?r:"")+"}")}function Qs(e){switch(e.type){case"Range":return " ["+(e.min===null?"-\u221E":e.min)+","+(e.max===null?"\u221E":e.max)+"]";default:throw new Error("Unknown node type `"+e.type+"`")}}function Xs(e,t,r,n){let o=e.combinator===" "||n?e.combinator:" "+e.combinator+" ",i=e.terms.map(s=>yr(s,t,r,n)).join(o);return e.explicit||r?(n||i[0]===","?"[":"[ ")+i+(n?"]":" ]"):i}function yr(e,t,r,n){let o;switch(e.type){case"Group":o=Xs(e,t,r,n)+(e.disallowEmpty?"!":"");break;case"Multiplier":return yr(e.term,t,r,n)+t(Ks(e),e);case"Type":o="<"+e.name+(e.opts?t(Qs(e.opts),e.opts):"")+">";break;case"Property":o="<'"+e.name+"'>";break;case"Keyword":o=e.name;break;case"AtKeyword":o="@"+e.name;break;case"Function":o=e.name+"(";break;case"String":case"Token":o=e.value;break;case"Comma":o=",";break;default:throw new Error("Unknown node type `"+e.type+"`")}return t(o,e)}function Pe(e,t){let r=Vs,n=!1,o=!1;return typeof t=="function"?r=t:t&&(n=Boolean(t.forceBraces),o=Boolean(t.compact),typeof t.decorate=="function"&&(r=t.decorate)),yr(e,r,n,o)}var Pi={offset:0,line:1,column:1};function $s(e,t){let r=e.tokens,n=e.longestMatch,o=n<r.length&&r[n].node||null,i=o!==t?o:null,s=0,u=0,c=0,a="",l,p;for(let m=0;m<r.length;m++){let f=r[m].value;m===n&&(u=f.length,s=a.length),i!==null&&r[m].node===i&&(m<=n?c++:c=0),a+=f;}return n===r.length||c>1?(l=Dt(i||t,"end")||at(Pi,a),p=at(l)):(l=Dt(i,"start")||at(Dt(t,"start")||Pi,a.slice(0,s)),p=Dt(i,"end")||at(l,a.substr(s,u))),{css:a,mismatchOffset:s,mismatchLength:u,start:l,end:p}}function Dt(e,t){let r=e&&e.loc&&e.loc[t];return r?"line"in r?at(r):r:null}function at({offset:e,line:t,column:r},n){let o={offset:e,line:t,column:r};if(n){let i=n.split(/\n|\r\n?|\f/);o.offset+=n.length,o.line+=i.length-1,o.column=i.length===1?o.column+n.length:i.pop().length+1;}return o}var Ue=function(e,t){let r=Ee("SyntaxReferenceError",e+(t?" `"+t+"`":""));return r.reference=t,r},Ii=function(e,t,r,n){let o=Ee("SyntaxMatchError",e),{css:i,mismatchOffset:s,mismatchLength:u,start:c,end:a}=$s(n,r);return o.rawMessage=e,o.syntax=t?Pe(t):"<generic>",o.css=i,o.mismatchOffset=s,o.mismatchLength=u,o.message=e+`
  syntax: `+o.syntax+`
   value: `+(i||"<empty string>")+`
  --------`+new Array(o.mismatchOffset+1).join("-")+"^",Object.assign(o,c),o.loc={source:r&&r.loc&&r.loc.source||"<unknown>",start:c,end:a},o};var Ot=new Map,je=new Map,Nt=45,zt=Zs,kr=Js;function Mt(e,t){return t=t||0,e.length-t>=2&&e.charCodeAt(t)===Nt&&e.charCodeAt(t+1)===Nt}function wr(e,t){if(t=t||0,e.length-t>=3&&e.charCodeAt(t)===Nt&&e.charCodeAt(t+1)!==Nt){let r=e.indexOf("-",t+2);if(r!==-1)return e.substring(t,r+1)}return ""}function Zs(e){if(Ot.has(e))return Ot.get(e);let t=e.toLowerCase(),r=Ot.get(t);if(r===void 0){let n=Mt(t,0),o=n?"":wr(t,0);r=Object.freeze({basename:t.substr(o.length),name:t,prefix:o,vendor:o,custom:n});}return Ot.set(e,r),r}function Js(e){if(je.has(e))return je.get(e);let t=e,r=e[0];r==="/"?r=e[1]==="/"?"//":"/":r!=="_"&&r!=="*"&&r!=="$"&&r!=="#"&&r!=="+"&&r!=="&"&&(r="");let n=Mt(t,r.length);if(!n&&(t=t.toLowerCase(),je.has(t))){let u=je.get(t);return je.set(e,u),u}let o=n?"":wr(t,r.length),i=t.substr(0,r.length+o.length),s=Object.freeze({basename:t.substr(i.length),name:t.substr(r.length),hack:r,vendor:o,prefix:i,custom:n});return je.set(e,s),s}var Rt=["initial","inherit","unset","revert","revert-layer"];var lt=43,he=45,vr=110,We=!0,tl=!1;function Cr(e,t){return e!==null&&e.type===9&&e.value.charCodeAt(0)===t}function st(e,t,r){for(;e!==null&&(e.type===13||e.type===25);)e=r(++t);return t}function Se(e,t,r,n){if(!e)return 0;let o=e.value.charCodeAt(t);if(o===lt||o===he){if(r)return 0;t++;}for(;t<e.value.length;t++)if(!B(e.value.charCodeAt(t)))return 0;return n+1}function Sr(e,t,r){let n=!1,o=st(e,t,r);if(e=r(o),e===null)return t;if(e.type!==10)if(Cr(e,lt)||Cr(e,he)){if(n=!0,o=st(r(++o),o,r),e=r(o),e===null||e.type!==10)return 0}else return t;if(!n){let i=e.value.charCodeAt(0);if(i!==lt&&i!==he)return 0}return Se(e,n?0:1,n,o)}function Ar(e,t){let r=0;if(!e)return 0;if(e.type===10)return Se(e,0,tl,r);if(e.type===1&&e.value.charCodeAt(0)===he){if(!de(e.value,1,vr))return 0;switch(e.value.length){case 2:return Sr(t(++r),r,t);case 3:return e.value.charCodeAt(2)!==he?0:(r=st(t(++r),r,t),e=t(r),Se(e,0,We,r));default:return e.value.charCodeAt(2)!==he?0:Se(e,3,We,r)}}else if(e.type===1||Cr(e,lt)&&t(r+1).type===1){if(e.type!==1&&(e=t(++r)),e===null||!de(e.value,0,vr))return 0;switch(e.value.length){case 1:return Sr(t(++r),r,t);case 2:return e.value.charCodeAt(1)!==he?0:(r=st(t(++r),r,t),e=t(r),Se(e,0,We,r));default:return e.value.charCodeAt(1)!==he?0:Se(e,2,We,r)}}else if(e.type===12){let n=e.value.charCodeAt(0),o=n===lt||n===he?1:0,i=o;for(;i<e.value.length&&B(e.value.charCodeAt(i));i++);return i===o||!de(e.value,i,vr)?0:i+1===e.value.length?Sr(t(++r),r,t):e.value.charCodeAt(i+1)!==he?0:i+2===e.value.length?(r=st(t(++r),r,t),e=t(r),Se(e,0,We,r)):Se(e,i+2,We,r)}return 0}var rl=43,Di=45,Oi=63,nl=117;function Tr(e,t){return e!==null&&e.type===9&&e.value.charCodeAt(0)===t}function ol(e,t){return e.value.charCodeAt(0)===t}function ct(e,t,r){let n=0;for(let o=t;o<e.value.length;o++){let i=e.value.charCodeAt(o);if(i===Di&&r&&n!==0)return ct(e,t+n+1,!1),6;if(!ee(i)||++n>6)return 0}return n}function Ft(e,t,r){if(!e)return 0;for(;Tr(r(t),Oi);){if(++e>6)return 0;t++;}return t}function Er(e,t){let r=0;if(e===null||e.type!==1||!de(e.value,0,nl)||(e=t(++r),e===null))return 0;if(Tr(e,rl))return e=t(++r),e===null?0:e.type===1?Ft(ct(e,0,!0),++r,t):Tr(e,Oi)?Ft(1,++r,t):0;if(e.type===10){let n=ct(e,1,!0);return n===0?0:(e=t(++r),e===null?r:e.type===12||e.type===10?!ol(e,Di)||!ct(e,1,!1)?0:r+1:Ft(n,r,t))}return e.type===12?Ft(ct(e,1,!0),++r,t):0}var il=["calc(","-moz-calc(","-webkit-calc("],Lr=new Map([[2,22],[21,22],[19,20],[23,24]]);function le(e,t){return t<e.length?e.charCodeAt(t):0}function Ni(e,t){return ge(e,0,e.length,t)}function zi(e,t){for(let r=0;r<t.length;r++)if(Ni(e,t[r]))return !0;return !1}function Mi(e,t){return t!==e.length-2?!1:le(e,t)===92&&B(le(e,t+1))}function Bt(e,t,r){if(e&&e.type==="Range"){let n=Number(r!==void 0&&r!==t.length?t.substr(0,r):t);if(isNaN(n)||e.min!==null&&n<e.min&&typeof e.min!="string"||e.max!==null&&n>e.max&&typeof e.max!="string")return !0}return !1}function al(e,t){let r=0,n=[],o=0;e:do{switch(e.type){case 24:case 22:case 20:if(e.type!==r)break e;if(r=n.pop(),n.length===0){o++;break e}break;case 2:case 21:case 19:case 23:n.push(r),r=Lr.get(e.type);break}o++;}while(e=t(o));return o}function ie(e){return function(t,r,n){return t===null?0:t.type===2&&zi(t.value,il)?al(t,r):e(t,r,n)}}function N(e){return function(t){return t===null||t.type!==e?0:1}}function sl(e){if(e===null||e.type!==1)return 0;let t=e.value.toLowerCase();return zi(t,Rt)||Ni(t,"default")?0:1}function ll(e){return e===null||e.type!==1||le(e.value,0)!==45||le(e.value,1)!==45?0:1}function cl(e){if(e===null||e.type!==4)return 0;let t=e.value.length;if(t!==4&&t!==5&&t!==7&&t!==9)return 0;for(let r=1;r<t;r++)if(!ee(le(e.value,r)))return 0;return 1}function ul(e){return e===null||e.type!==4||!ze(le(e.value,1),le(e.value,2),le(e.value,3))?0:1}function pl(e,t){if(!e)return 0;let r=0,n=[],o=0;e:do{switch(e.type){case 6:case 8:break e;case 24:case 22:case 20:if(e.type!==r)break e;r=n.pop();break;case 17:if(r===0)break e;break;case 9:if(r===0&&e.value==="!")break e;break;case 2:case 21:case 19:case 23:n.push(r),r=Lr.get(e.type);break}o++;}while(e=t(o));return o}function hl(e,t){if(!e)return 0;let r=0,n=[],o=0;e:do{switch(e.type){case 6:case 8:break e;case 24:case 22:case 20:if(e.type!==r)break e;r=n.pop();break;case 2:case 21:case 19:case 23:n.push(r),r=Lr.get(e.type);break}o++;}while(e=t(o));return o}function ye(e){return e&&(e=new Set(e)),function(t,r,n){if(t===null||t.type!==12)return 0;let o=Te(t.value,0);if(e!==null){let i=t.value.indexOf("\\",o),s=i===-1||!Mi(t.value,i)?t.value.substr(o):t.value.substring(o,i);if(e.has(s.toLowerCase())===!1)return 0}return Bt(n,t.value,o)?0:1}}function ml(e,t,r){return e===null||e.type!==11||Bt(r,e.value,e.value.length-1)?0:1}function Ri(e){return typeof e!="function"&&(e=function(){return 0}),function(t,r,n){return t!==null&&t.type===10&&Number(t.value)===0?1:e(t,r,n)}}function fl(e,t,r){if(e===null)return 0;let n=Te(e.value,0);return !(n===e.value.length)&&!Mi(e.value,n)||Bt(r,e.value,n)?0:1}function dl(e,t,r){if(e===null||e.type!==10)return 0;let n=le(e.value,0)===43||le(e.value,0)===45?1:0;for(;n<e.value.length;n++)if(!B(le(e.value,n)))return 0;return Bt(r,e.value,n)?0:1}var gl={"ident-token":N(1),"function-token":N(2),"at-keyword-token":N(3),"hash-token":N(4),"string-token":N(5),"bad-string-token":N(6),"url-token":N(7),"bad-url-token":N(8),"delim-token":N(9),"number-token":N(10),"percentage-token":N(11),"dimension-token":N(12),"whitespace-token":N(13),"CDO-token":N(14),"CDC-token":N(15),"colon-token":N(16),"semicolon-token":N(17),"comma-token":N(18),"[-token":N(19),"]-token":N(20),"(-token":N(21),")-token":N(22),"{-token":N(23),"}-token":N(24)},bl={string:N(5),ident:N(1),percentage:ie(ml),zero:Ri(),number:ie(fl),integer:ie(dl),"custom-ident":sl,"custom-property-name":ll,"hex-color":cl,"id-selector":ul,"an-plus-b":Ar,urange:Er,"declaration-value":pl,"any-value":hl};function xl(e){let{angle:t,decibel:r,frequency:n,flex:o,length:i,resolution:s,semitones:u,time:c}=e||{};return {dimension:ie(ye(null)),angle:ie(ye(t)),decibel:ie(ye(r)),frequency:ie(ye(n)),flex:ie(ye(o)),length:ie(Ri(ye(i))),resolution:ie(ye(s)),semitones:ie(ye(u)),time:ie(ye(c))}}function Fi(e){return {...gl,...bl,...xl(e)}}var _t={};b(_t,{angle:()=>kl,decibel:()=>Al,flex:()=>Cl,frequency:()=>vl,length:()=>yl,resolution:()=>Sl,semitones:()=>Tl,time:()=>wl});var yl=["cm","mm","q","in","pt","pc","px","em","rem","ex","rex","cap","rcap","ch","rch","ic","ric","lh","rlh","vw","svw","lvw","dvw","vh","svh","lvh","dvh","vi","svi","lvi","dvi","vb","svb","lvb","dvb","vmin","svmin","lvmin","dvmin","vmax","svmax","lvmax","dvmax","cqw","cqh","cqi","cqb","cqmin","cqmax"],kl=["deg","grad","rad","turn"],wl=["s","ms"],vl=["hz","khz"],Sl=["dpi","dpcm","dppx","x"],Cl=["fr"],Al=["db"],Tl=["st"];var $i={};b($i,{SyntaxError:()=>qt,generate:()=>Pe,parse:()=>Ge,walk:()=>Vt});function qt(e,t,r){return Object.assign(Ee("SyntaxError",e),{input:t,offset:r,rawMessage:e,message:e+`
  `+t+`
--`+new Array((r||t.length)+1).join("-")+"^"})}var El=9,Ll=10,Pl=12,Il=13,Dl=32,Ut=class{constructor(t){this.str=t,this.pos=0;}charCodeAt(t){return t<this.str.length?this.str.charCodeAt(t):0}charCode(){return this.charCodeAt(this.pos)}nextCharCode(){return this.charCodeAt(this.pos+1)}nextNonWsCode(t){return this.charCodeAt(this.findWsEnd(t))}findWsEnd(t){for(;t<this.str.length;t++){let r=this.str.charCodeAt(t);if(r!==Il&&r!==Ll&&r!==Pl&&r!==Dl&&r!==El)break}return t}substringToPos(t){return this.str.substring(this.pos,this.pos=t)}eat(t){this.charCode()!==t&&this.error("Expect `"+String.fromCharCode(t)+"`"),this.pos++;}peek(){return this.pos<this.str.length?this.str.charAt(this.pos++):""}error(t){throw new qt(t,this.str,this.pos)}};var Ol=9,Nl=10,zl=12,Ml=13,Rl=32,Yi=33,Dr=35,Bi=38,jt=39,Gi=40,Fl=41,Vi=42,Or=43,Nr=44,_i=45,zr=60,Ki=62,Ir=63,Bl=64,Gt=91,Mr=93,Wt=123,qi=124,Ui=125,ji=8734,ut=new Uint8Array(128).map((e,t)=>/[a-zA-Z0-9\-]/.test(String.fromCharCode(t))?1:0),Wi={" ":1,"&&":2,"||":3,"|":4};function Ht(e){return e.substringToPos(e.findWsEnd(e.pos))}function He(e){let t=e.pos;for(;t<e.str.length;t++){let r=e.str.charCodeAt(t);if(r>=128||ut[r]===0)break}return e.pos===t&&e.error("Expect a keyword"),e.substringToPos(t)}function Yt(e){let t=e.pos;for(;t<e.str.length;t++){let r=e.str.charCodeAt(t);if(r<48||r>57)break}return e.pos===t&&e.error("Expect a number"),e.substringToPos(t)}function _l(e){let t=e.str.indexOf("'",e.pos+1);return t===-1&&(e.pos=e.str.length,e.error("Expect an apostrophe")),e.substringToPos(t+1)}function Hi(e){let t=null,r=null;return e.eat(Wt),t=Yt(e),e.charCode()===Nr?(e.pos++,e.charCode()!==Ui&&(r=Yt(e))):r=t,e.eat(Ui),{min:Number(t),max:r?Number(r):0}}function ql(e){let t=null,r=!1;switch(e.charCode()){case Vi:e.pos++,t={min:0,max:0};break;case Or:e.pos++,t={min:1,max:0};break;case Ir:e.pos++,t={min:0,max:1};break;case Dr:e.pos++,r=!0,e.charCode()===Wt?t=Hi(e):e.charCode()===Ir?(e.pos++,t={min:0,max:0}):t={min:1,max:0};break;case Wt:t=Hi(e);break;default:return null}return {type:"Multiplier",comma:r,min:t.min,max:t.max,term:null}}function Ye(e,t){let r=ql(e);return r!==null?(r.term=t,e.charCode()===Dr&&e.charCodeAt(e.pos-1)===Or?Ye(e,r):r):t}function Pr(e){let t=e.peek();return t===""?null:{type:"Token",value:t}}function Ul(e){let t;return e.eat(zr),e.eat(jt),t=He(e),e.eat(jt),e.eat(Ki),Ye(e,{type:"Property",name:t})}function jl(e){let t=null,r=null,n=1;return e.eat(Gt),e.charCode()===_i&&(e.peek(),n=-1),n==-1&&e.charCode()===ji?e.peek():(t=n*Number(Yt(e)),ut[e.charCode()]!==0&&(t+=He(e))),Ht(e),e.eat(Nr),Ht(e),e.charCode()===ji?e.peek():(n=1,e.charCode()===_i&&(e.peek(),n=-1),r=n*Number(Yt(e)),ut[e.charCode()]!==0&&(r+=He(e))),e.eat(Mr),{type:"Range",min:t,max:r}}function Wl(e){let t,r=null;return e.eat(zr),t=He(e),e.charCode()===Gi&&e.nextCharCode()===Fl&&(e.pos+=2,t+="()"),e.charCodeAt(e.findWsEnd(e.pos))===Gt&&(Ht(e),r=jl(e)),e.eat(Ki),Ye(e,{type:"Type",name:t,opts:r})}function Hl(e){let t=He(e);return e.charCode()===Gi?(e.pos++,{type:"Function",name:t}):Ye(e,{type:"Keyword",name:t})}function Yl(e,t){function r(o,i){return {type:"Group",terms:o,combinator:i,disallowEmpty:!1,explicit:!1}}let n;for(t=Object.keys(t).sort((o,i)=>Wi[o]-Wi[i]);t.length>0;){n=t.shift();let o=0,i=0;for(;o<e.length;o++){let s=e[o];s.type==="Combinator"&&(s.value===n?(i===-1&&(i=o-1),e.splice(o,1),o--):(i!==-1&&o-i>1&&(e.splice(i,o-i,r(e.slice(i,o),n)),o=i+1),i=-1));}i!==-1&&t.length&&e.splice(i,o-i,r(e.slice(i,o),n));}return n}function Qi(e){let t=[],r={},n,o=null,i=e.pos;for(;n=Vl(e);)n.type!=="Spaces"&&(n.type==="Combinator"?((o===null||o.type==="Combinator")&&(e.pos=i,e.error("Unexpected combinator")),r[n.value]=!0):o!==null&&o.type!=="Combinator"&&(r[" "]=!0,t.push({type:"Combinator",value:" "})),t.push(n),o=n,i=e.pos);return o!==null&&o.type==="Combinator"&&(e.pos-=i,e.error("Unexpected combinator")),{type:"Group",terms:t,combinator:Yl(t,r)||" ",disallowEmpty:!1,explicit:!1}}function Gl(e){let t;return e.eat(Gt),t=Qi(e),e.eat(Mr),t.explicit=!0,e.charCode()===Yi&&(e.pos++,t.disallowEmpty=!0),t}function Vl(e){let t=e.charCode();if(t<128&&ut[t]===1)return Hl(e);switch(t){case Mr:break;case Gt:return Ye(e,Gl(e));case zr:return e.nextCharCode()===jt?Ul(e):Wl(e);case qi:return {type:"Combinator",value:e.substringToPos(e.pos+(e.nextCharCode()===qi?2:1))};case Bi:return e.pos++,e.eat(Bi),{type:"Combinator",value:"&&"};case Nr:return e.pos++,{type:"Comma"};case jt:return Ye(e,{type:"String",value:_l(e)});case Rl:case Ol:case Nl:case Ml:case zl:return {type:"Spaces",value:Ht(e)};case Bl:return t=e.nextCharCode(),t<128&&ut[t]===1?(e.pos++,{type:"AtKeyword",name:He(e)}):Pr(e);case Vi:case Or:case Ir:case Dr:case Yi:break;case Wt:if(t=e.nextCharCode(),t<48||t>57)return Pr(e);break;default:return Pr(e)}}function Ge(e){let t=new Ut(e),r=Qi(t);return t.pos!==e.length&&t.error("Unexpected input"),r.terms.length===1&&r.terms[0].type==="Group"?r.terms[0]:r}var pt=function(){};function Xi(e){return typeof e=="function"?e:pt}function Vt(e,t,r){function n(s){switch(o.call(r,s),s.type){case"Group":s.terms.forEach(n);break;case"Multiplier":n(s.term);break;case"Type":case"Property":case"Keyword":case"AtKeyword":case"Function":case"String":case"Token":case"Comma":break;default:throw new Error("Unknown type: "+s.type)}i.call(r,s);}let o=pt,i=pt;if(typeof t=="function"?o=t:t&&(o=Xi(t.enter),i=Xi(t.leave)),o===pt&&i===pt)throw new Error("Neither `enter` nor `leave` walker handler is set or both aren't a function");n(e);}var Kl={decorator(e){let t=[],r=null;return {...e,node(n){let o=r;r=n,e.node.call(this,n),r=o;},emit(n,o,i){t.push({type:o,value:n,node:i?null:r});},result(){return t}}}};function Ql(e){let t=[];return ve(e,(r,n,o)=>t.push({type:r,value:e.slice(n,o),node:null})),t}function Zi(e,t){return typeof e=="string"?Ql(e):t.generate(e,Kl)}var C={type:"Match"},L={type:"Mismatch"},Kt={type:"DisallowEmpty"},Xl=40,$l=41;function Z(e,t,r){return t===C&&r===L||e===C&&t===C&&r===C?e:(e.type==="If"&&e.else===L&&t===C&&(t=e.then,e=e.match),{type:"If",match:e,then:t,else:r})}function ea(e){return e.length>2&&e.charCodeAt(e.length-2)===Xl&&e.charCodeAt(e.length-1)===$l}function Ji(e){return e.type==="Keyword"||e.type==="AtKeyword"||e.type==="Function"||e.type==="Type"&&ea(e.name)}function Rr(e,t,r){switch(e){case" ":{let n=C;for(let o=t.length-1;o>=0;o--){let i=t[o];n=Z(i,n,L);}return n}case"|":{let n=L,o=null;for(let i=t.length-1;i>=0;i--){let s=t[i];if(Ji(s)&&(o===null&&i>0&&Ji(t[i-1])&&(o=Object.create(null),n=Z({type:"Enum",map:o},C,n)),o!==null)){let u=(ea(s.name)?s.name.slice(0,-1):s.name).toLowerCase();if(!(u in o)){o[u]=s;continue}}o=null,n=Z(s,C,n);}return n}case"&&":{if(t.length>5)return {type:"MatchOnce",terms:t,all:!0};let n=L;for(let o=t.length-1;o>=0;o--){let i=t[o],s;t.length>1?s=Rr(e,t.filter(function(u){return u!==i}),!1):s=C,n=Z(i,s,n);}return n}case"||":{if(t.length>5)return {type:"MatchOnce",terms:t,all:!1};let n=r?C:L;for(let o=t.length-1;o>=0;o--){let i=t[o],s;t.length>1?s=Rr(e,t.filter(function(u){return u!==i}),!0):s=C,n=Z(i,s,n);}return n}}}function Zl(e){let t=C,r=Fr(e.term);if(e.max===0)r=Z(r,Kt,L),t=Z(r,null,L),t.then=Z(C,C,t),e.comma&&(t.then.else=Z({type:"Comma",syntax:e},t,L));else for(let n=e.min||1;n<=e.max;n++)e.comma&&t!==C&&(t=Z({type:"Comma",syntax:e},t,L)),t=Z(r,Z(C,C,t),L);if(e.min===0)t=Z(C,C,t);else for(let n=0;n<e.min-1;n++)e.comma&&t!==C&&(t=Z({type:"Comma",syntax:e},t,L)),t=Z(r,t,L);return t}function Fr(e){if(typeof e=="function")return {type:"Generic",fn:e};switch(e.type){case"Group":{let t=Rr(e.combinator,e.terms.map(Fr),!1);return e.disallowEmpty&&(t=Z(t,Kt,L)),t}case"Multiplier":return Zl(e);case"Type":case"Property":return {type:e.type,name:e.name,syntax:e};case"Keyword":return {type:e.type,name:e.name.toLowerCase(),syntax:e};case"AtKeyword":return {type:e.type,name:"@"+e.name.toLowerCase(),syntax:e};case"Function":return {type:e.type,name:e.name.toLowerCase()+"(",syntax:e};case"String":return e.value.length===3?{type:"Token",value:e.value.charAt(1),syntax:e}:{type:e.type,value:e.value.substr(1,e.value.length-2).replace(/\\'/g,"'"),syntax:e};case"Token":return {type:e.type,value:e.value,syntax:e};case"Comma":return {type:e.type,syntax:e};default:throw new Error("Unknown node type:",e.type)}}function Qt(e,t){return typeof e=="string"&&(e=Ge(e)),{type:"MatchGraph",match:Fr(e),syntax:t||null,source:e}}var {hasOwnProperty:ta}=Object.prototype,Jl=0,ec=1,_r=2,aa=3,ra="Match",tc="Mismatch",rc="Maximum iteration number exceeded (please fill an issue on https://github.com/csstree/csstree/issues)",na=15e3;function oc(e){let t=null,r=null,n=e;for(;n!==null;)r=n.prev,n.prev=t,t=n,n=r;return t}function Br(e,t){if(e.length!==t.length)return !1;for(let r=0;r<e.length;r++){let n=t.charCodeAt(r),o=e.charCodeAt(r);if(o>=65&&o<=90&&(o=o|32),o!==n)return !1}return !0}function ic(e){return e.type!==9?!1:e.value!=="?"}function oa(e){return e===null?!0:e.type===18||e.type===2||e.type===21||e.type===19||e.type===23||ic(e)}function ia(e){return e===null?!0:e.type===22||e.type===20||e.type===24||e.type===9&&e.value==="/"}function ac(e,t,r){function n(){do R++,S=R<e.length?e[R]:null;while(S!==null&&(S.type===13||S.type===25))}function o(ae){let fe=R+ae;return fe<e.length?e[fe]:null}function i(ae,fe){return {nextState:ae,matchStack:z,syntaxStack:p,thenStack:m,tokenIndex:R,prev:fe}}function s(ae){m={nextState:ae,matchStack:z,syntaxStack:p,prev:m};}function u(ae){f=i(ae,f);}function c(){z={type:ec,syntax:t.syntax,token:S,prev:z},n(),P=null,R>ke&&(ke=R);}function a(){p={syntax:t.syntax,opts:t.syntax.opts||p!==null&&p.opts||null,prev:p},z={type:_r,syntax:t.syntax,token:z.token,prev:z};}function l(){z.type===_r?z=z.prev:z={type:aa,syntax:p.syntax,token:z.token,prev:z},p=p.prev;}let p=null,m=null,f=null,P=null,te=0,X=null,S=null,R=-1,ke=0,z={type:Jl,syntax:null,token:null,prev:null};for(n();X===null&&++te<na;)switch(t.type){case"Match":if(m===null){if(S!==null&&(R!==e.length-1||S.value!=="\\0"&&S.value!=="\\9")){t=L;break}X=ra;break}if(t=m.nextState,t===Kt)if(m.matchStack===z){t=L;break}else t=C;for(;m.syntaxStack!==p;)l();m=m.prev;break;case"Mismatch":if(P!==null&&P!==!1)(f===null||R>f.tokenIndex)&&(f=P,P=!1);else if(f===null){X=tc;break}t=f.nextState,m=f.thenStack,p=f.syntaxStack,z=f.matchStack,R=f.tokenIndex,S=R<e.length?e[R]:null,f=f.prev;break;case"MatchGraph":t=t.match;break;case"If":t.else!==L&&u(t.else),t.then!==C&&s(t.then),t=t.match;break;case"MatchOnce":t={type:"MatchOnceBuffer",syntax:t,index:0,mask:0};break;case"MatchOnceBuffer":{let Q=t.syntax.terms;if(t.index===Q.length){if(t.mask===0||t.syntax.all){t=L;break}t=C;break}if(t.mask===(1<<Q.length)-1){t=C;break}for(;t.index<Q.length;t.index++){let J=1<<t.index;if((t.mask&J)===0){u(t),s({type:"AddMatchOnce",syntax:t.syntax,mask:t.mask|J}),t=Q[t.index++];break}}break}case"AddMatchOnce":t={type:"MatchOnceBuffer",syntax:t.syntax,index:0,mask:t.mask};break;case"Enum":if(S!==null){let Q=S.value.toLowerCase();if(Q.indexOf("\\")!==-1&&(Q=Q.replace(/\\[09].*$/,"")),ta.call(t.map,Q)){t=t.map[Q];break}}t=L;break;case"Generic":{let Q=p!==null?p.opts:null,J=R+Math.floor(t.fn(S,o,Q));if(!isNaN(J)&&J>R){for(;R<J;)c();t=C;}else t=L;break}case"Type":case"Property":{let Q=t.type==="Type"?"types":"properties",J=ta.call(r,Q)?r[Q][t.name]:null;if(!J||!J.match)throw new Error("Bad syntax reference: "+(t.type==="Type"?"<"+t.name+">":"<'"+t.name+"'>"));if(P!==!1&&S!==null&&t.type==="Type"&&(t.name==="custom-ident"&&S.type===1||t.name==="length"&&S.value==="0")){P===null&&(P=i(t,f)),t=L;break}a(),t=J.match;break}case"Keyword":{let Q=t.name;if(S!==null){let J=S.value;if(J.indexOf("\\")!==-1&&(J=J.replace(/\\[09].*$/,"")),Br(J,Q)){c(),t=C;break}}t=L;break}case"AtKeyword":case"Function":if(S!==null&&Br(S.value,t.name)){c(),t=C;break}t=L;break;case"Token":if(S!==null&&S.value===t.value){c(),t=C;break}t=L;break;case"Comma":S!==null&&S.type===18?oa(z.token)?t=L:(c(),t=ia(S)?L:C):t=oa(z.token)||ia(S)?C:L;break;case"String":let ae="",fe=R;for(;fe<e.length&&ae.length<t.value.length;fe++)ae+=e[fe].value;if(Br(ae,t.value)){for(;R<fe;)c();t=C;}else t=L;break;default:throw new Error("Unknown node type: "+t.type)}switch(X){case null:console.warn("[csstree-match] BREAK after "+na+" iterations"),X=rc,z=null;break;case ra:for(;p!==null;)l();break;default:z=null;}return {tokens:e,reason:X,iterations:te,match:z,longestMatch:ke}}function qr(e,t,r){let n=ac(e,t,r||{});if(n.match===null)return n;let o=n.match,i=n.match={syntax:t.syntax||null,match:[]},s=[i];for(o=oc(o).prev;o!==null;){switch(o.type){case _r:i.match.push(i={syntax:o.syntax,match:[]}),s.push(i);break;case aa:s.pop(),i=s[s.length-1];break;default:i.match.push({syntax:o.syntax||null,token:o.token.value,node:o.token.node});}o=o.prev;}return n}var jr={};b(jr,{getTrace:()=>sa,isKeyword:()=>cc,isProperty:()=>lc,isType:()=>sc});function sa(e){function t(o){return o===null?!1:o.type==="Type"||o.type==="Property"||o.type==="Keyword"}function r(o){if(Array.isArray(o.match)){for(let i=0;i<o.match.length;i++)if(r(o.match[i]))return t(o.syntax)&&n.unshift(o.syntax),!0}else if(o.node===e)return n=t(o.syntax)?[o.syntax]:[],!0;return !1}let n=null;return this.matched!==null&&r(this.matched),n}function sc(e,t){return Ur(this,e,r=>r.type==="Type"&&r.name===t)}function lc(e,t){return Ur(this,e,r=>r.type==="Property"&&r.name===t)}function cc(e){return Ur(this,e,t=>t.type==="Keyword")}function Ur(e,t,r){let n=sa.call(e,t);return n===null?!1:n.some(r)}function la(e){return "node"in e?e.node:la(e.match[0])}function ca(e){return "node"in e?e.node:ca(e.match[e.match.length-1])}function Wr(e,t,r,n,o){function i(u){if(u.syntax!==null&&u.syntax.type===n&&u.syntax.name===o){let c=la(u),a=ca(u);e.syntax.walk(t,function(l,p,m){if(l===c){let f=new D;do{if(f.appendData(p.data),p.data===a)break;p=p.next;}while(p!==null);s.push({parent:m,nodes:f});}});}Array.isArray(u.match)&&u.match.forEach(i);}let s=[];return r.matched!==null&&i(r.matched),s}var{hasOwnProperty:ht}=Object.prototype;function Hr(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e&&e>=0}function ua(e){return Boolean(e)&&Hr(e.offset)&&Hr(e.line)&&Hr(e.column)}function uc(e,t){return function(n,o){if(!n||n.constructor!==Object)return o(n,"Type of node should be an Object");for(let i in n){let s=!0;if(ht.call(n,i)!==!1){if(i==="type")n.type!==e&&o(n,"Wrong node type `"+n.type+"`, expected `"+e+"`");else if(i==="loc"){if(n.loc===null)continue;if(n.loc&&n.loc.constructor===Object)if(typeof n.loc.source!="string")i+=".source";else if(!ua(n.loc.start))i+=".start";else if(!ua(n.loc.end))i+=".end";else continue;s=!1;}else if(t.hasOwnProperty(i)){s=!1;for(let u=0;!s&&u<t[i].length;u++){let c=t[i][u];switch(c){case String:s=typeof n[i]=="string";break;case Boolean:s=typeof n[i]=="boolean";break;case null:s=n[i]===null;break;default:typeof c=="string"?s=n[i]&&n[i].type===c:Array.isArray(c)&&(s=n[i]instanceof D);}}}else o(n,"Unknown field `"+i+"` for "+e+" node type");s||o(n,"Bad value for `"+e+"."+i+"`");}}for(let i in t)ht.call(t,i)&&ht.call(n,i)===!1&&o(n,"Field `"+e+"."+i+"` is missed");}}function pc(e,t){let r=t.structure,n={type:String,loc:!0},o={type:'"'+e+'"'};for(let i in r){if(ht.call(r,i)===!1)continue;let s=[],u=n[i]=Array.isArray(r[i])?r[i].slice():[r[i]];for(let c=0;c<u.length;c++){let a=u[c];if(a===String||a===Boolean)s.push(a.name);else if(a===null)s.push("null");else if(typeof a=="string")s.push("<"+a+">");else if(Array.isArray(a))s.push("List");else throw new Error("Wrong value `"+a+"` in `"+e+"."+i+"` structure definition")}o[i]=s.join(" | ");}return {docs:o,check:uc(e,n)}}function pa(e){let t={};if(e.node){for(let r in e.node)if(ht.call(e.node,r)){let n=e.node[r];if(n.structure)t[r]=pc(r,n);else throw new Error("Missed `structure` field in `"+r+"` node type definition")}}return t}var hc=Qt(Rt.join(" | "));function Yr(e,t,r){let n={};for(let o in e)e[o].syntax&&(n[o]=r?e[o].syntax:Pe(e[o].syntax,{compact:t}));return n}function mc(e,t,r){let n={};for(let[o,i]of Object.entries(e))n[o]={prelude:i.prelude&&(r?i.prelude.syntax:Pe(i.prelude.syntax,{compact:t})),descriptors:i.descriptors&&Yr(i.descriptors,t,r)};return n}function fc(e){for(let t=0;t<e.length;t++)if(e[t].value.toLowerCase()==="var(")return !0;return !1}function ce(e,t,r){return {matched:e,iterations:r,error:t,...jr}}function Ve(e,t,r,n){let o=Zi(r,e.syntax),i;return fc(o)?ce(null,new Error("Matching for a tree with var() is not supported")):(n&&(i=qr(o,e.cssWideKeywordsSyntax,e)),(!n||!i.match)&&(i=qr(o,t.match,e),!i.match)?ce(null,new Ii(i.reason,t.syntax,r,i),i.iterations):ce(i.match,null,i.iterations))}var Ke=class{constructor(t,r,n){if(this.cssWideKeywordsSyntax=hc,this.syntax=r,this.generic=!1,this.units={..._t},this.atrules=Object.create(null),this.properties=Object.create(null),this.types=Object.create(null),this.structure=n||pa(t),t){if(t.units)for(let o of Object.keys(_t))Array.isArray(t.units[o])&&(this.units[o]=t.units[o]);if(t.types)for(let o in t.types)this.addType_(o,t.types[o]);if(t.generic){this.generic=!0;for(let[o,i]of Object.entries(Fi(this.units)))this.addType_(o,i);}if(t.atrules)for(let o in t.atrules)this.addAtrule_(o,t.atrules[o]);if(t.properties)for(let o in t.properties)this.addProperty_(o,t.properties[o]);}}checkStructure(t){function r(i,s){o.push({node:i,message:s});}let n=this.structure,o=[];return this.syntax.walk(t,function(i){n.hasOwnProperty(i.type)?n[i.type].check(i,r):r(i,"Unknown node type `"+i.type+"`");}),o.length?o:!1}createDescriptor(t,r,n,o=null){let i={type:r,name:n},s={type:r,name:n,parent:o,serializable:typeof t=="string"||t&&typeof t.type=="string",syntax:null,match:null};return typeof t=="function"?s.match=Qt(t,i):(typeof t=="string"?Object.defineProperty(s,"syntax",{get(){return Object.defineProperty(s,"syntax",{value:Ge(t)}),s.syntax}}):s.syntax=t,Object.defineProperty(s,"match",{get(){return Object.defineProperty(s,"match",{value:Qt(s.syntax,i)}),s.match}})),s}addAtrule_(t,r){!r||(this.atrules[t]={type:"Atrule",name:t,prelude:r.prelude?this.createDescriptor(r.prelude,"AtrulePrelude",t):null,descriptors:r.descriptors?Object.keys(r.descriptors).reduce((n,o)=>(n[o]=this.createDescriptor(r.descriptors[o],"AtruleDescriptor",o,t),n),Object.create(null)):null});}addProperty_(t,r){!r||(this.properties[t]=this.createDescriptor(r,"Property",t));}addType_(t,r){!r||(this.types[t]=this.createDescriptor(r,"Type",t));}checkAtruleName(t){if(!this.getAtrule(t))return new Ue("Unknown at-rule","@"+t)}checkAtrulePrelude(t,r){let n=this.checkAtruleName(t);if(n)return n;let o=this.getAtrule(t);if(!o.prelude&&r)return new SyntaxError("At-rule `@"+t+"` should not contain a prelude");if(o.prelude&&!r&&!Ve(this,o.prelude,"",!1).matched)return new SyntaxError("At-rule `@"+t+"` should contain a prelude")}checkAtruleDescriptorName(t,r){let n=this.checkAtruleName(t);if(n)return n;let o=this.getAtrule(t),i=zt(r);if(!o.descriptors)return new SyntaxError("At-rule `@"+t+"` has no known descriptors");if(!o.descriptors[i.name]&&!o.descriptors[i.basename])return new Ue("Unknown at-rule descriptor",r)}checkPropertyName(t){if(!this.getProperty(t))return new Ue("Unknown property",t)}matchAtrulePrelude(t,r){let n=this.checkAtrulePrelude(t,r);if(n)return ce(null,n);let o=this.getAtrule(t);return o.prelude?Ve(this,o.prelude,r||"",!1):ce(null,null)}matchAtruleDescriptor(t,r,n){let o=this.checkAtruleDescriptorName(t,r);if(o)return ce(null,o);let i=this.getAtrule(t),s=zt(r);return Ve(this,i.descriptors[s.name]||i.descriptors[s.basename],n,!1)}matchDeclaration(t){return t.type!=="Declaration"?ce(null,new Error("Not a Declaration node")):this.matchProperty(t.property,t.value)}matchProperty(t,r){if(kr(t).custom)return ce(null,new Error("Lexer matching doesn't applicable for custom properties"));let n=this.checkPropertyName(t);return n?ce(null,n):Ve(this,this.getProperty(t),r,!0)}matchType(t,r){let n=this.getType(t);return n?Ve(this,n,r,!1):ce(null,new Ue("Unknown type",t))}match(t,r){return typeof t!="string"&&(!t||!t.type)?ce(null,new Ue("Bad syntax")):((typeof t=="string"||!t.match)&&(t=this.createDescriptor(t,"Type","anonymous")),Ve(this,t,r,!1))}findValueFragments(t,r,n,o){return Wr(this,r,this.matchProperty(t,r),n,o)}findDeclarationValueFragments(t,r,n){return Wr(this,t.value,this.matchDeclaration(t),r,n)}findAllFragments(t,r,n){let o=[];return this.syntax.walk(t,{visit:"Declaration",enter:i=>{o.push.apply(o,this.findDeclarationValueFragments(i,r,n));}}),o}getAtrule(t,r=!0){let n=zt(t);return (n.vendor&&r?this.atrules[n.name]||this.atrules[n.basename]:this.atrules[n.name])||null}getAtrulePrelude(t,r=!0){let n=this.getAtrule(t,r);return n&&n.prelude||null}getAtruleDescriptor(t,r){return this.atrules.hasOwnProperty(t)&&this.atrules.declarators&&this.atrules[t].declarators[r]||null}getProperty(t,r=!0){let n=kr(t);return (n.vendor&&r?this.properties[n.name]||this.properties[n.basename]:this.properties[n.name])||null}getType(t){return hasOwnProperty.call(this.types,t)?this.types[t]:null}validate(){function t(o,i,s,u){if(s.has(i))return s.get(i);s.set(i,!1),u.syntax!==null&&Vt(u.syntax,function(c){if(c.type!=="Type"&&c.type!=="Property")return;let a=c.type==="Type"?o.types:o.properties,l=c.type==="Type"?r:n;(!hasOwnProperty.call(a,c.name)||t(o,c.name,l,a[c.name]))&&s.set(i,!0);},this);}let r=new Map,n=new Map;for(let o in this.types)t(this,o,r,this.types[o]);for(let o in this.properties)t(this,o,n,this.properties[o]);return r=[...r.keys()].filter(o=>r.get(o)),n=[...n.keys()].filter(o=>n.get(o)),r.length||n.length?{types:r,properties:n}:null}dump(t,r){return {generic:this.generic,units:this.units,types:Yr(this.types,!r,t),properties:Yr(this.properties,!r,t),atrules:mc(this.atrules,!r,t)}}toString(){return JSON.stringify(this.dump())}};function Gr(e,t){return typeof t=="string"&&/^\s*\|/.test(t)?typeof e=="string"?e+t:t.replace(/^\s*\|\s*/,""):t||null}function ha(e,t){let r=Object.create(null);for(let[n,o]of Object.entries(e))if(o){r[n]={};for(let i of Object.keys(o))t.includes(i)&&(r[n][i]=o[i]);}return r}function mt(e,t){let r={...e};for(let[n,o]of Object.entries(t))switch(n){case"generic":r[n]=Boolean(o);break;case"units":r[n]={...e[n]};for(let[i,s]of Object.entries(o))r[n][i]=Array.isArray(s)?s:[];break;case"atrules":r[n]={...e[n]};for(let[i,s]of Object.entries(o)){let u=r[n][i]||{},c=r[n][i]={prelude:u.prelude||null,descriptors:{...u.descriptors}};if(!!s){c.prelude=s.prelude?Gr(c.prelude,s.prelude):c.prelude||null;for(let[a,l]of Object.entries(s.descriptors||{}))c.descriptors[a]=l?Gr(c.descriptors[a],l):null;Object.keys(c.descriptors).length||(c.descriptors=null);}}break;case"types":case"properties":r[n]={...e[n]};for(let[i,s]of Object.entries(o))r[n][i]=Gr(r[n][i],s);break;case"scope":r[n]={...e[n]};for(let[i,s]of Object.entries(o))r[n][i]={...r[n][i],...s};break;case"parseContext":r[n]={...e[n],...o};break;case"atrule":case"pseudo":r[n]={...e[n],...ha(o,["parse"])};break;case"node":r[n]={...e[n],...ha(o,["name","structure","parse","generate","walkContext"])};break}return r}function ma(e){let t=$o(e),r=Li(e),n=vi(e),{fromPlainObject:o,toPlainObject:i}=Si(r),s={lexer:null,createLexer:u=>new Ke(u,s,s.lexer.structure),tokenize:ve,parse:t,generate:n,walk:r,find:r.find,findLast:r.findLast,findAll:r.findAll,fromPlainObject:o,toPlainObject:i,fork(u){let c=mt({},e);return ma(typeof u=="function"?u(c,Object.assign):mt(c,u))}};return s.lexer=new Ke({generic:!0,units:e.units,types:e.types,atrules:e.atrules,properties:e.properties,node:e.node},s),s}var Vr=e=>ma(mt({},e));var fa={generic:!0,units:{angle:["deg","grad","rad","turn"],decibel:["db"],flex:["fr"],frequency:["hz","khz"],length:["cm","mm","q","in","pt","pc","px","em","rem","ex","rex","cap","rcap","ch","rch","ic","ric","lh","rlh","vw","svw","lvw","dvw","vh","svh","lvh","dvh","vi","svi","lvi","dvi","vb","svb","lvb","dvb","vmin","svmin","lvmin","dvmin","vmax","svmax","lvmax","dvmax","cqw","cqh","cqi","cqb","cqmin","cqmax"],resolution:["dpi","dpcm","dppx","x"],semitones:["st"],time:["s","ms"]},types:{"abs()":"abs( <calc-sum> )","absolute-size":"xx-small|x-small|small|medium|large|x-large|xx-large|xxx-large","acos()":"acos( <calc-sum> )","alpha-value":"<number>|<percentage>","angle-percentage":"<angle>|<percentage>","angular-color-hint":"<angle-percentage>","angular-color-stop":"<color>&&<color-stop-angle>?","angular-color-stop-list":"[<angular-color-stop> [, <angular-color-hint>]?]# , <angular-color-stop>","animateable-feature":"scroll-position|contents|<custom-ident>","asin()":"asin( <calc-sum> )","atan()":"atan( <calc-sum> )","atan2()":"atan2( <calc-sum> , <calc-sum> )",attachment:"scroll|fixed|local","attr()":"attr( <attr-name> <type-or-unit>? [, <attr-fallback>]? )","attr-matcher":"['~'|'|'|'^'|'$'|'*']? '='","attr-modifier":"i|s","attribute-selector":"'[' <wq-name> ']'|'[' <wq-name> <attr-matcher> [<string-token>|<ident-token>] <attr-modifier>? ']'","auto-repeat":"repeat( [auto-fill|auto-fit] , [<line-names>? <fixed-size>]+ <line-names>? )","auto-track-list":"[<line-names>? [<fixed-size>|<fixed-repeat>]]* <line-names>? <auto-repeat> [<line-names>? [<fixed-size>|<fixed-repeat>]]* <line-names>?",axis:"block|inline|vertical|horizontal","baseline-position":"[first|last]? baseline","basic-shape":"<inset()>|<circle()>|<ellipse()>|<polygon()>|<path()>","bg-image":"none|<image>","bg-layer":"<bg-image>||<bg-position> [/ <bg-size>]?||<repeat-style>||<attachment>||<box>||<box>","bg-position":"[[left|center|right|top|bottom|<length-percentage>]|[left|center|right|<length-percentage>] [top|center|bottom|<length-percentage>]|[center|[left|right] <length-percentage>?]&&[center|[top|bottom] <length-percentage>?]]","bg-size":"[<length-percentage>|auto]{1,2}|cover|contain","blur()":"blur( <length> )","blend-mode":"normal|multiply|screen|overlay|darken|lighten|color-dodge|color-burn|hard-light|soft-light|difference|exclusion|hue|saturation|color|luminosity",box:"border-box|padding-box|content-box","brightness()":"brightness( <number-percentage> )","calc()":"calc( <calc-sum> )","calc-sum":"<calc-product> [['+'|'-'] <calc-product>]*","calc-product":"<calc-value> ['*' <calc-value>|'/' <number>]*","calc-value":"<number>|<dimension>|<percentage>|<calc-constant>|( <calc-sum> )","calc-constant":"e|pi|infinity|-infinity|NaN","cf-final-image":"<image>|<color>","cf-mixing-image":"<percentage>?&&<image>","circle()":"circle( [<shape-radius>]? [at <position>]? )","clamp()":"clamp( <calc-sum>#{3} )","class-selector":"'.' <ident-token>","clip-source":"<url>",color:"<rgb()>|<rgba()>|<hsl()>|<hsla()>|<hwb()>|<lab()>|<lch()>|<hex-color>|<named-color>|currentcolor|<deprecated-system-color>","color-stop":"<color-stop-length>|<color-stop-angle>","color-stop-angle":"<angle-percentage>{1,2}","color-stop-length":"<length-percentage>{1,2}","color-stop-list":"[<linear-color-stop> [, <linear-color-hint>]?]# , <linear-color-stop>",combinator:"'>'|'+'|'~'|['||']","common-lig-values":"[common-ligatures|no-common-ligatures]","compat-auto":"searchfield|textarea|push-button|slider-horizontal|checkbox|radio|square-button|menulist|listbox|meter|progress-bar|button","composite-style":"clear|copy|source-over|source-in|source-out|source-atop|destination-over|destination-in|destination-out|destination-atop|xor","compositing-operator":"add|subtract|intersect|exclude","compound-selector":"[<type-selector>? <subclass-selector>* [<pseudo-element-selector> <pseudo-class-selector>*]*]!","compound-selector-list":"<compound-selector>#","complex-selector":"<compound-selector> [<combinator>? <compound-selector>]*","complex-selector-list":"<complex-selector>#","conic-gradient()":"conic-gradient( [from <angle>]? [at <position>]? , <angular-color-stop-list> )","contextual-alt-values":"[contextual|no-contextual]","content-distribution":"space-between|space-around|space-evenly|stretch","content-list":"[<string>|contents|<image>|<counter>|<quote>|<target>|<leader()>|<attr()>]+","content-position":"center|start|end|flex-start|flex-end","content-replacement":"<image>","contrast()":"contrast( [<number-percentage>] )","cos()":"cos( <calc-sum> )",counter:"<counter()>|<counters()>","counter()":"counter( <counter-name> , <counter-style>? )","counter-name":"<custom-ident>","counter-style":"<counter-style-name>|symbols( )","counter-style-name":"<custom-ident>","counters()":"counters( <counter-name> , <string> , <counter-style>? )","cross-fade()":"cross-fade( <cf-mixing-image> , <cf-final-image>? )","cubic-bezier-timing-function":"ease|ease-in|ease-out|ease-in-out|cubic-bezier( <number [0,1]> , <number> , <number [0,1]> , <number> )","deprecated-system-color":"ActiveBorder|ActiveCaption|AppWorkspace|Background|ButtonFace|ButtonHighlight|ButtonShadow|ButtonText|CaptionText|GrayText|Highlight|HighlightText|InactiveBorder|InactiveCaption|InactiveCaptionText|InfoBackground|InfoText|Menu|MenuText|Scrollbar|ThreeDDarkShadow|ThreeDFace|ThreeDHighlight|ThreeDLightShadow|ThreeDShadow|Window|WindowFrame|WindowText","discretionary-lig-values":"[discretionary-ligatures|no-discretionary-ligatures]","display-box":"contents|none","display-inside":"flow|flow-root|table|flex|grid|ruby","display-internal":"table-row-group|table-header-group|table-footer-group|table-row|table-cell|table-column-group|table-column|table-caption|ruby-base|ruby-text|ruby-base-container|ruby-text-container","display-legacy":"inline-block|inline-list-item|inline-table|inline-flex|inline-grid","display-listitem":"<display-outside>?&&[flow|flow-root]?&&list-item","display-outside":"block|inline|run-in","drop-shadow()":"drop-shadow( <length>{2,3} <color>? )","east-asian-variant-values":"[jis78|jis83|jis90|jis04|simplified|traditional]","east-asian-width-values":"[full-width|proportional-width]","element()":"element( <custom-ident> , [first|start|last|first-except]? )|element( <id-selector> )","ellipse()":"ellipse( [<shape-radius>{2}]? [at <position>]? )","ending-shape":"circle|ellipse","env()":"env( <custom-ident> , <declaration-value>? )","exp()":"exp( <calc-sum> )","explicit-track-list":"[<line-names>? <track-size>]+ <line-names>?","family-name":"<string>|<custom-ident>+","feature-tag-value":"<string> [<integer>|on|off]?","feature-type":"@stylistic|@historical-forms|@styleset|@character-variant|@swash|@ornaments|@annotation","feature-value-block":"<feature-type> '{' <feature-value-declaration-list> '}'","feature-value-block-list":"<feature-value-block>+","feature-value-declaration":"<custom-ident> : <integer>+ ;","feature-value-declaration-list":"<feature-value-declaration>","feature-value-name":"<custom-ident>","fill-rule":"nonzero|evenodd","filter-function":"<blur()>|<brightness()>|<contrast()>|<drop-shadow()>|<grayscale()>|<hue-rotate()>|<invert()>|<opacity()>|<saturate()>|<sepia()>","filter-function-list":"[<filter-function>|<url>]+","final-bg-layer":"<'background-color'>||<bg-image>||<bg-position> [/ <bg-size>]?||<repeat-style>||<attachment>||<box>||<box>","fixed-breadth":"<length-percentage>","fixed-repeat":"repeat( [<integer [1,\u221E]>] , [<line-names>? <fixed-size>]+ <line-names>? )","fixed-size":"<fixed-breadth>|minmax( <fixed-breadth> , <track-breadth> )|minmax( <inflexible-breadth> , <fixed-breadth> )","font-stretch-absolute":"normal|ultra-condensed|extra-condensed|condensed|semi-condensed|semi-expanded|expanded|extra-expanded|ultra-expanded|<percentage>","font-variant-css21":"[normal|small-caps]","font-weight-absolute":"normal|bold|<number [1,1000]>","frequency-percentage":"<frequency>|<percentage>","general-enclosed":"[<function-token> <any-value> )]|( <ident> <any-value> )","generic-family":"serif|sans-serif|cursive|fantasy|monospace|-apple-system","generic-name":"serif|sans-serif|cursive|fantasy|monospace","geometry-box":"<shape-box>|fill-box|stroke-box|view-box",gradient:"<linear-gradient()>|<repeating-linear-gradient()>|<radial-gradient()>|<repeating-radial-gradient()>|<conic-gradient()>|<repeating-conic-gradient()>|<-legacy-gradient>","grayscale()":"grayscale( <number-percentage> )","grid-line":"auto|<custom-ident>|[<integer>&&<custom-ident>?]|[span&&[<integer>||<custom-ident>]]","historical-lig-values":"[historical-ligatures|no-historical-ligatures]","hsl()":"hsl( <hue> <percentage> <percentage> [/ <alpha-value>]? )|hsl( <hue> , <percentage> , <percentage> , <alpha-value>? )","hsla()":"hsla( <hue> <percentage> <percentage> [/ <alpha-value>]? )|hsla( <hue> , <percentage> , <percentage> , <alpha-value>? )",hue:"<number>|<angle>","hue-rotate()":"hue-rotate( <angle> )","hwb()":"hwb( [<hue>|none] [<percentage>|none] [<percentage>|none] [/ [<alpha-value>|none]]? )","hypot()":"hypot( <calc-sum># )",image:"<url>|<image()>|<image-set()>|<element()>|<paint()>|<cross-fade()>|<gradient>","image()":"image( <image-tags>? [<image-src>? , <color>?]! )","image-set()":"image-set( <image-set-option># )","image-set-option":"[<image>|<string>] [<resolution>||type( <string> )]","image-src":"<url>|<string>","image-tags":"ltr|rtl","inflexible-breadth":"<length-percentage>|min-content|max-content|auto","inset()":"inset( <length-percentage>{1,4} [round <'border-radius'>]? )","invert()":"invert( <number-percentage> )","keyframes-name":"<custom-ident>|<string>","keyframe-block":"<keyframe-selector># { <declaration-list> }","keyframe-block-list":"<keyframe-block>+","keyframe-selector":"from|to|<percentage>","lab()":"lab( [<percentage>|<number>|none] [<percentage>|<number>|none] [<percentage>|<number>|none] [/ [<alpha-value>|none]]? )","layer()":"layer( <layer-name> )","layer-name":"<ident> ['.' <ident>]*","lch()":"lch( [<percentage>|<number>|none] [<percentage>|<number>|none] [<hue>|none] [/ [<alpha-value>|none]]? )","leader()":"leader( <leader-type> )","leader-type":"dotted|solid|space|<string>","length-percentage":"<length>|<percentage>","line-names":"'[' <custom-ident>* ']'","line-name-list":"[<line-names>|<name-repeat>]+","line-style":"none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset","line-width":"<length>|thin|medium|thick","linear-color-hint":"<length-percentage>","linear-color-stop":"<color> <color-stop-length>?","linear-gradient()":"linear-gradient( [<angle>|to <side-or-corner>]? , <color-stop-list> )","log()":"log( <calc-sum> , <calc-sum>? )","mask-layer":"<mask-reference>||<position> [/ <bg-size>]?||<repeat-style>||<geometry-box>||[<geometry-box>|no-clip]||<compositing-operator>||<masking-mode>","mask-position":"[<length-percentage>|left|center|right] [<length-percentage>|top|center|bottom]?","mask-reference":"none|<image>|<mask-source>","mask-source":"<url>","masking-mode":"alpha|luminance|match-source","matrix()":"matrix( <number>#{6} )","matrix3d()":"matrix3d( <number>#{16} )","max()":"max( <calc-sum># )","media-and":"<media-in-parens> [and <media-in-parens>]+","media-condition":"<media-not>|<media-and>|<media-or>|<media-in-parens>","media-condition-without-or":"<media-not>|<media-and>|<media-in-parens>","media-feature":"( [<mf-plain>|<mf-boolean>|<mf-range>] )","media-in-parens":"( <media-condition> )|<media-feature>|<general-enclosed>","media-not":"not <media-in-parens>","media-or":"<media-in-parens> [or <media-in-parens>]+","media-query":"<media-condition>|[not|only]? <media-type> [and <media-condition-without-or>]?","media-query-list":"<media-query>#","media-type":"<ident>","mf-boolean":"<mf-name>","mf-name":"<ident>","mf-plain":"<mf-name> : <mf-value>","mf-range":"<mf-name> ['<'|'>']? '='? <mf-value>|<mf-value> ['<'|'>']? '='? <mf-name>|<mf-value> '<' '='? <mf-name> '<' '='? <mf-value>|<mf-value> '>' '='? <mf-name> '>' '='? <mf-value>","mf-value":"<number>|<dimension>|<ident>|<ratio>","min()":"min( <calc-sum># )","minmax()":"minmax( [<length-percentage>|min-content|max-content|auto] , [<length-percentage>|<flex>|min-content|max-content|auto] )","mod()":"mod( <calc-sum> , <calc-sum> )","name-repeat":"repeat( [<integer [1,\u221E]>|auto-fill] , <line-names>+ )","named-color":"transparent|aliceblue|antiquewhite|aqua|aquamarine|azure|beige|bisque|black|blanchedalmond|blue|blueviolet|brown|burlywood|cadetblue|chartreuse|chocolate|coral|cornflowerblue|cornsilk|crimson|cyan|darkblue|darkcyan|darkgoldenrod|darkgray|darkgreen|darkgrey|darkkhaki|darkmagenta|darkolivegreen|darkorange|darkorchid|darkred|darksalmon|darkseagreen|darkslateblue|darkslategray|darkslategrey|darkturquoise|darkviolet|deeppink|deepskyblue|dimgray|dimgrey|dodgerblue|firebrick|floralwhite|forestgreen|fuchsia|gainsboro|ghostwhite|gold|goldenrod|gray|green|greenyellow|grey|honeydew|hotpink|indianred|indigo|ivory|khaki|lavender|lavenderblush|lawngreen|lemonchiffon|lightblue|lightcoral|lightcyan|lightgoldenrodyellow|lightgray|lightgreen|lightgrey|lightpink|lightsalmon|lightseagreen|lightskyblue|lightslategray|lightslategrey|lightsteelblue|lightyellow|lime|limegreen|linen|magenta|maroon|mediumaquamarine|mediumblue|mediumorchid|mediumpurple|mediumseagreen|mediumslateblue|mediumspringgreen|mediumturquoise|mediumvioletred|midnightblue|mintcream|mistyrose|moccasin|navajowhite|navy|oldlace|olive|olivedrab|orange|orangered|orchid|palegoldenrod|palegreen|paleturquoise|palevioletred|papayawhip|peachpuff|peru|pink|plum|powderblue|purple|rebeccapurple|red|rosybrown|royalblue|saddlebrown|salmon|sandybrown|seagreen|seashell|sienna|silver|skyblue|slateblue|slategray|slategrey|snow|springgreen|steelblue|tan|teal|thistle|tomato|turquoise|violet|wheat|white|whitesmoke|yellow|yellowgreen|<-non-standard-color>","namespace-prefix":"<ident>","ns-prefix":"[<ident-token>|'*']? '|'","number-percentage":"<number>|<percentage>","numeric-figure-values":"[lining-nums|oldstyle-nums]","numeric-fraction-values":"[diagonal-fractions|stacked-fractions]","numeric-spacing-values":"[proportional-nums|tabular-nums]",nth:"<an-plus-b>|even|odd","opacity()":"opacity( [<number-percentage>] )","overflow-position":"unsafe|safe","outline-radius":"<length>|<percentage>","page-body":"<declaration>? [; <page-body>]?|<page-margin-box> <page-body>","page-margin-box":"<page-margin-box-type> '{' <declaration-list> '}'","page-margin-box-type":"@top-left-corner|@top-left|@top-center|@top-right|@top-right-corner|@bottom-left-corner|@bottom-left|@bottom-center|@bottom-right|@bottom-right-corner|@left-top|@left-middle|@left-bottom|@right-top|@right-middle|@right-bottom","page-selector-list":"[<page-selector>#]?","page-selector":"<pseudo-page>+|<ident> <pseudo-page>*","page-size":"A5|A4|A3|B5|B4|JIS-B5|JIS-B4|letter|legal|ledger","path()":"path( [<fill-rule> ,]? <string> )","paint()":"paint( <ident> , <declaration-value>? )","perspective()":"perspective( [<length [0,\u221E]>|none] )","polygon()":"polygon( <fill-rule>? , [<length-percentage> <length-percentage>]# )",position:"[[left|center|right]||[top|center|bottom]|[left|center|right|<length-percentage>] [top|center|bottom|<length-percentage>]?|[[left|right] <length-percentage>]&&[[top|bottom] <length-percentage>]]","pow()":"pow( <calc-sum> , <calc-sum> )","pseudo-class-selector":"':' <ident-token>|':' <function-token> <any-value> ')'","pseudo-element-selector":"':' <pseudo-class-selector>","pseudo-page":": [left|right|first|blank]",quote:"open-quote|close-quote|no-open-quote|no-close-quote","radial-gradient()":"radial-gradient( [<ending-shape>||<size>]? [at <position>]? , <color-stop-list> )",ratio:"<number [0,\u221E]> [/ <number [0,\u221E]>]?","relative-selector":"<combinator>? <complex-selector>","relative-selector-list":"<relative-selector>#","relative-size":"larger|smaller","rem()":"rem( <calc-sum> , <calc-sum> )","repeat-style":"repeat-x|repeat-y|[repeat|space|round|no-repeat]{1,2}","repeating-conic-gradient()":"repeating-conic-gradient( [from <angle>]? [at <position>]? , <angular-color-stop-list> )","repeating-linear-gradient()":"repeating-linear-gradient( [<angle>|to <side-or-corner>]? , <color-stop-list> )","repeating-radial-gradient()":"repeating-radial-gradient( [<ending-shape>||<size>]? [at <position>]? , <color-stop-list> )","reversed-counter-name":"reversed( <counter-name> )","rgb()":"rgb( <percentage>{3} [/ <alpha-value>]? )|rgb( <number>{3} [/ <alpha-value>]? )|rgb( <percentage>#{3} , <alpha-value>? )|rgb( <number>#{3} , <alpha-value>? )","rgba()":"rgba( <percentage>{3} [/ <alpha-value>]? )|rgba( <number>{3} [/ <alpha-value>]? )|rgba( <percentage>#{3} , <alpha-value>? )|rgba( <number>#{3} , <alpha-value>? )","rotate()":"rotate( [<angle>|<zero>] )","rotate3d()":"rotate3d( <number> , <number> , <number> , [<angle>|<zero>] )","rotateX()":"rotateX( [<angle>|<zero>] )","rotateY()":"rotateY( [<angle>|<zero>] )","rotateZ()":"rotateZ( [<angle>|<zero>] )","round()":"round( <rounding-strategy>? , <calc-sum> , <calc-sum> )","rounding-strategy":"nearest|up|down|to-zero","saturate()":"saturate( <number-percentage> )","scale()":"scale( [<number>|<percentage>]#{1,2} )","scale3d()":"scale3d( [<number>|<percentage>]#{3} )","scaleX()":"scaleX( [<number>|<percentage>] )","scaleY()":"scaleY( [<number>|<percentage>] )","scaleZ()":"scaleZ( [<number>|<percentage>] )",scroller:"root|nearest","self-position":"center|start|end|self-start|self-end|flex-start|flex-end","shape-radius":"<length-percentage>|closest-side|farthest-side","sign()":"sign( <calc-sum> )","skew()":"skew( [<angle>|<zero>] , [<angle>|<zero>]? )","skewX()":"skewX( [<angle>|<zero>] )","skewY()":"skewY( [<angle>|<zero>] )","sepia()":"sepia( <number-percentage> )",shadow:"inset?&&<length>{2,4}&&<color>?","shadow-t":"[<length>{2,3}&&<color>?]",shape:"rect( <top> , <right> , <bottom> , <left> )|rect( <top> <right> <bottom> <left> )","shape-box":"<box>|margin-box","side-or-corner":"[left|right]||[top|bottom]","sin()":"sin( <calc-sum> )","single-animation":"<time>||<easing-function>||<time>||<single-animation-iteration-count>||<single-animation-direction>||<single-animation-fill-mode>||<single-animation-play-state>||[none|<keyframes-name>]","single-animation-direction":"normal|reverse|alternate|alternate-reverse","single-animation-fill-mode":"none|forwards|backwards|both","single-animation-iteration-count":"infinite|<number>","single-animation-play-state":"running|paused","single-animation-timeline":"auto|none|<timeline-name>|scroll( <axis>? <scroller>? )","single-transition":"[none|<single-transition-property>]||<time>||<easing-function>||<time>","single-transition-property":"all|<custom-ident>",size:"closest-side|farthest-side|closest-corner|farthest-corner|<length>|<length-percentage>{2}","sqrt()":"sqrt( <calc-sum> )","step-position":"jump-start|jump-end|jump-none|jump-both|start|end","step-timing-function":"step-start|step-end|steps( <integer> [, <step-position>]? )","subclass-selector":"<id-selector>|<class-selector>|<attribute-selector>|<pseudo-class-selector>","supports-condition":"not <supports-in-parens>|<supports-in-parens> [and <supports-in-parens>]*|<supports-in-parens> [or <supports-in-parens>]*","supports-in-parens":"( <supports-condition> )|<supports-feature>|<general-enclosed>","supports-feature":"<supports-decl>|<supports-selector-fn>","supports-decl":"( <declaration> )","supports-selector-fn":"selector( <complex-selector> )",symbol:"<string>|<image>|<custom-ident>","tan()":"tan( <calc-sum> )",target:"<target-counter()>|<target-counters()>|<target-text()>","target-counter()":"target-counter( [<string>|<url>] , <custom-ident> , <counter-style>? )","target-counters()":"target-counters( [<string>|<url>] , <custom-ident> , <string> , <counter-style>? )","target-text()":"target-text( [<string>|<url>] , [content|before|after|first-letter]? )","time-percentage":"<time>|<percentage>","timeline-name":"<custom-ident>|<string>","easing-function":"linear|<cubic-bezier-timing-function>|<step-timing-function>","track-breadth":"<length-percentage>|<flex>|min-content|max-content|auto","track-list":"[<line-names>? [<track-size>|<track-repeat>]]+ <line-names>?","track-repeat":"repeat( [<integer [1,\u221E]>] , [<line-names>? <track-size>]+ <line-names>? )","track-size":"<track-breadth>|minmax( <inflexible-breadth> , <track-breadth> )|fit-content( <length-percentage> )","transform-function":"<matrix()>|<translate()>|<translateX()>|<translateY()>|<scale()>|<scaleX()>|<scaleY()>|<rotate()>|<skew()>|<skewX()>|<skewY()>|<matrix3d()>|<translate3d()>|<translateZ()>|<scale3d()>|<scaleZ()>|<rotate3d()>|<rotateX()>|<rotateY()>|<rotateZ()>|<perspective()>","transform-list":"<transform-function>+","translate()":"translate( <length-percentage> , <length-percentage>? )","translate3d()":"translate3d( <length-percentage> , <length-percentage> , <length> )","translateX()":"translateX( <length-percentage> )","translateY()":"translateY( <length-percentage> )","translateZ()":"translateZ( <length> )","type-or-unit":"string|color|url|integer|number|length|angle|time|frequency|cap|ch|em|ex|ic|lh|rlh|rem|vb|vi|vw|vh|vmin|vmax|mm|Q|cm|in|pt|pc|px|deg|grad|rad|turn|ms|s|Hz|kHz|%","type-selector":"<wq-name>|<ns-prefix>? '*'","var()":"var( <custom-property-name> , <declaration-value>? )","viewport-length":"auto|<length-percentage>","visual-box":"content-box|padding-box|border-box","wq-name":"<ns-prefix>? <ident-token>","-legacy-gradient":"<-webkit-gradient()>|<-legacy-linear-gradient>|<-legacy-repeating-linear-gradient>|<-legacy-radial-gradient>|<-legacy-repeating-radial-gradient>","-legacy-linear-gradient":"-moz-linear-gradient( <-legacy-linear-gradient-arguments> )|-webkit-linear-gradient( <-legacy-linear-gradient-arguments> )|-o-linear-gradient( <-legacy-linear-gradient-arguments> )","-legacy-repeating-linear-gradient":"-moz-repeating-linear-gradient( <-legacy-linear-gradient-arguments> )|-webkit-repeating-linear-gradient( <-legacy-linear-gradient-arguments> )|-o-repeating-linear-gradient( <-legacy-linear-gradient-arguments> )","-legacy-linear-gradient-arguments":"[<angle>|<side-or-corner>]? , <color-stop-list>","-legacy-radial-gradient":"-moz-radial-gradient( <-legacy-radial-gradient-arguments> )|-webkit-radial-gradient( <-legacy-radial-gradient-arguments> )|-o-radial-gradient( <-legacy-radial-gradient-arguments> )","-legacy-repeating-radial-gradient":"-moz-repeating-radial-gradient( <-legacy-radial-gradient-arguments> )|-webkit-repeating-radial-gradient( <-legacy-radial-gradient-arguments> )|-o-repeating-radial-gradient( <-legacy-radial-gradient-arguments> )","-legacy-radial-gradient-arguments":"[<position> ,]? [[[<-legacy-radial-gradient-shape>||<-legacy-radial-gradient-size>]|[<length>|<percentage>]{2}] ,]? <color-stop-list>","-legacy-radial-gradient-size":"closest-side|closest-corner|farthest-side|farthest-corner|contain|cover","-legacy-radial-gradient-shape":"circle|ellipse","-non-standard-font":"-apple-system-body|-apple-system-headline|-apple-system-subheadline|-apple-system-caption1|-apple-system-caption2|-apple-system-footnote|-apple-system-short-body|-apple-system-short-headline|-apple-system-short-subheadline|-apple-system-short-caption1|-apple-system-short-footnote|-apple-system-tall-body","-non-standard-color":"-moz-ButtonDefault|-moz-ButtonHoverFace|-moz-ButtonHoverText|-moz-CellHighlight|-moz-CellHighlightText|-moz-Combobox|-moz-ComboboxText|-moz-Dialog|-moz-DialogText|-moz-dragtargetzone|-moz-EvenTreeRow|-moz-Field|-moz-FieldText|-moz-html-CellHighlight|-moz-html-CellHighlightText|-moz-mac-accentdarkestshadow|-moz-mac-accentdarkshadow|-moz-mac-accentface|-moz-mac-accentlightesthighlight|-moz-mac-accentlightshadow|-moz-mac-accentregularhighlight|-moz-mac-accentregularshadow|-moz-mac-chrome-active|-moz-mac-chrome-inactive|-moz-mac-focusring|-moz-mac-menuselect|-moz-mac-menushadow|-moz-mac-menutextselect|-moz-MenuHover|-moz-MenuHoverText|-moz-MenuBarText|-moz-MenuBarHoverText|-moz-nativehyperlinktext|-moz-OddTreeRow|-moz-win-communicationstext|-moz-win-mediatext|-moz-activehyperlinktext|-moz-default-background-color|-moz-default-color|-moz-hyperlinktext|-moz-visitedhyperlinktext|-webkit-activelink|-webkit-focus-ring-color|-webkit-link|-webkit-text","-non-standard-image-rendering":"optimize-contrast|-moz-crisp-edges|-o-crisp-edges|-webkit-optimize-contrast","-non-standard-overflow":"-moz-scrollbars-none|-moz-scrollbars-horizontal|-moz-scrollbars-vertical|-moz-hidden-unscrollable","-non-standard-width":"fill-available|min-intrinsic|intrinsic|-moz-available|-moz-fit-content|-moz-min-content|-moz-max-content|-webkit-min-content|-webkit-max-content","-webkit-gradient()":"-webkit-gradient( <-webkit-gradient-type> , <-webkit-gradient-point> [, <-webkit-gradient-point>|, <-webkit-gradient-radius> , <-webkit-gradient-point>] [, <-webkit-gradient-radius>]? [, <-webkit-gradient-color-stop>]* )","-webkit-gradient-color-stop":"from( <color> )|color-stop( [<number-zero-one>|<percentage>] , <color> )|to( <color> )","-webkit-gradient-point":"[left|center|right|<length-percentage>] [top|center|bottom|<length-percentage>]","-webkit-gradient-radius":"<length>|<percentage>","-webkit-gradient-type":"linear|radial","-webkit-mask-box-repeat":"repeat|stretch|round","-webkit-mask-clip-style":"border|border-box|padding|padding-box|content|content-box|text","-ms-filter-function-list":"<-ms-filter-function>+","-ms-filter-function":"<-ms-filter-function-progid>|<-ms-filter-function-legacy>","-ms-filter-function-progid":"'progid:' [<ident-token> '.']* [<ident-token>|<function-token> <any-value>? )]","-ms-filter-function-legacy":"<ident-token>|<function-token> <any-value>? )","-ms-filter":"<string>",age:"child|young|old","attr-name":"<wq-name>","attr-fallback":"<any-value>","bg-clip":"<box>|border|text",bottom:"<length>|auto","container-name":"<custom-ident>","container-condition":"not <query-in-parens>|<query-in-parens> [[and <query-in-parens>]*|[or <query-in-parens>]*]","generic-voice":"[<age>? <gender> <integer>?]",gender:"male|female|neutral",left:"<length>|auto","mask-image":"<mask-reference>#",paint:"none|<color>|<url> [none|<color>]?|context-fill|context-stroke",right:"<length>|auto","scroll-timeline-axis":"block|inline|vertical|horizontal","scroll-timeline-name":"none|<custom-ident>","single-animation-composition":"replace|add|accumulate","svg-length":"<percentage>|<length>|<number>","svg-writing-mode":"lr-tb|rl-tb|tb-rl|lr|rl|tb",top:"<length>|auto",x:"<number>",y:"<number>",declaration:"<ident-token> : <declaration-value>? ['!' important]?","declaration-list":"[<declaration>? ';']* <declaration>?",url:"url( <string> <url-modifier>* )|<url-token>","url-modifier":"<ident>|<function-token> <any-value> )","number-zero-one":"<number [0,1]>","number-one-or-greater":"<number [1,\u221E]>","query-in-parens":"( <container-condition> )|( <size-feature> )|style( <style-query> )|<general-enclosed>","size-feature":"<mf-plain>|<mf-boolean>|<mf-range>","style-feature":"<declaration>","style-query":"<style-condition>|<style-feature>","style-condition":"not <style-in-parens>|<style-in-parens> [[and <style-in-parens>]*|[or <style-in-parens>]*]","style-in-parens":"( <style-condition> )|( <style-feature> )|<general-enclosed>","-non-standard-display":"-ms-inline-flexbox|-ms-grid|-ms-inline-grid|-webkit-flex|-webkit-inline-flex|-webkit-box|-webkit-inline-box|-moz-inline-stack|-moz-box|-moz-inline-box"},properties:{"--*":"<declaration-value>","-ms-accelerator":"false|true","-ms-block-progression":"tb|rl|bt|lr","-ms-content-zoom-chaining":"none|chained","-ms-content-zooming":"none|zoom","-ms-content-zoom-limit":"<'-ms-content-zoom-limit-min'> <'-ms-content-zoom-limit-max'>","-ms-content-zoom-limit-max":"<percentage>","-ms-content-zoom-limit-min":"<percentage>","-ms-content-zoom-snap":"<'-ms-content-zoom-snap-type'>||<'-ms-content-zoom-snap-points'>","-ms-content-zoom-snap-points":"snapInterval( <percentage> , <percentage> )|snapList( <percentage># )","-ms-content-zoom-snap-type":"none|proximity|mandatory","-ms-filter":"<string>","-ms-flow-from":"[none|<custom-ident>]#","-ms-flow-into":"[none|<custom-ident>]#","-ms-grid-columns":"none|<track-list>|<auto-track-list>","-ms-grid-rows":"none|<track-list>|<auto-track-list>","-ms-high-contrast-adjust":"auto|none","-ms-hyphenate-limit-chars":"auto|<integer>{1,3}","-ms-hyphenate-limit-lines":"no-limit|<integer>","-ms-hyphenate-limit-zone":"<percentage>|<length>","-ms-ime-align":"auto|after","-ms-overflow-style":"auto|none|scrollbar|-ms-autohiding-scrollbar","-ms-scrollbar-3dlight-color":"<color>","-ms-scrollbar-arrow-color":"<color>","-ms-scrollbar-base-color":"<color>","-ms-scrollbar-darkshadow-color":"<color>","-ms-scrollbar-face-color":"<color>","-ms-scrollbar-highlight-color":"<color>","-ms-scrollbar-shadow-color":"<color>","-ms-scrollbar-track-color":"<color>","-ms-scroll-chaining":"chained|none","-ms-scroll-limit":"<'-ms-scroll-limit-x-min'> <'-ms-scroll-limit-y-min'> <'-ms-scroll-limit-x-max'> <'-ms-scroll-limit-y-max'>","-ms-scroll-limit-x-max":"auto|<length>","-ms-scroll-limit-x-min":"<length>","-ms-scroll-limit-y-max":"auto|<length>","-ms-scroll-limit-y-min":"<length>","-ms-scroll-rails":"none|railed","-ms-scroll-snap-points-x":"snapInterval( <length-percentage> , <length-percentage> )|snapList( <length-percentage># )","-ms-scroll-snap-points-y":"snapInterval( <length-percentage> , <length-percentage> )|snapList( <length-percentage># )","-ms-scroll-snap-type":"none|proximity|mandatory","-ms-scroll-snap-x":"<'-ms-scroll-snap-type'> <'-ms-scroll-snap-points-x'>","-ms-scroll-snap-y":"<'-ms-scroll-snap-type'> <'-ms-scroll-snap-points-y'>","-ms-scroll-translation":"none|vertical-to-horizontal","-ms-text-autospace":"none|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space","-ms-touch-select":"grippers|none","-ms-user-select":"none|element|text","-ms-wrap-flow":"auto|both|start|end|maximum|clear","-ms-wrap-margin":"<length>","-ms-wrap-through":"wrap|none","-moz-appearance":"none|button|button-arrow-down|button-arrow-next|button-arrow-previous|button-arrow-up|button-bevel|button-focus|caret|checkbox|checkbox-container|checkbox-label|checkmenuitem|dualbutton|groupbox|listbox|listitem|menuarrow|menubar|menucheckbox|menuimage|menuitem|menuitemtext|menulist|menulist-button|menulist-text|menulist-textfield|menupopup|menuradio|menuseparator|meterbar|meterchunk|progressbar|progressbar-vertical|progresschunk|progresschunk-vertical|radio|radio-container|radio-label|radiomenuitem|range|range-thumb|resizer|resizerpanel|scale-horizontal|scalethumbend|scalethumb-horizontal|scalethumbstart|scalethumbtick|scalethumb-vertical|scale-vertical|scrollbarbutton-down|scrollbarbutton-left|scrollbarbutton-right|scrollbarbutton-up|scrollbarthumb-horizontal|scrollbarthumb-vertical|scrollbartrack-horizontal|scrollbartrack-vertical|searchfield|separator|sheet|spinner|spinner-downbutton|spinner-textfield|spinner-upbutton|splitter|statusbar|statusbarpanel|tab|tabpanel|tabpanels|tab-scroll-arrow-back|tab-scroll-arrow-forward|textfield|textfield-multiline|toolbar|toolbarbutton|toolbarbutton-dropdown|toolbargripper|toolbox|tooltip|treeheader|treeheadercell|treeheadersortarrow|treeitem|treeline|treetwisty|treetwistyopen|treeview|-moz-mac-unified-toolbar|-moz-win-borderless-glass|-moz-win-browsertabbar-toolbox|-moz-win-communicationstext|-moz-win-communications-toolbox|-moz-win-exclude-glass|-moz-win-glass|-moz-win-mediatext|-moz-win-media-toolbox|-moz-window-button-box|-moz-window-button-box-maximized|-moz-window-button-close|-moz-window-button-maximize|-moz-window-button-minimize|-moz-window-button-restore|-moz-window-frame-bottom|-moz-window-frame-left|-moz-window-frame-right|-moz-window-titlebar|-moz-window-titlebar-maximized","-moz-binding":"<url>|none","-moz-border-bottom-colors":"<color>+|none","-moz-border-left-colors":"<color>+|none","-moz-border-right-colors":"<color>+|none","-moz-border-top-colors":"<color>+|none","-moz-context-properties":"none|[fill|fill-opacity|stroke|stroke-opacity]#","-moz-float-edge":"border-box|content-box|margin-box|padding-box","-moz-force-broken-image-icon":"0|1","-moz-image-region":"<shape>|auto","-moz-orient":"inline|block|horizontal|vertical","-moz-outline-radius":"<outline-radius>{1,4} [/ <outline-radius>{1,4}]?","-moz-outline-radius-bottomleft":"<outline-radius>","-moz-outline-radius-bottomright":"<outline-radius>","-moz-outline-radius-topleft":"<outline-radius>","-moz-outline-radius-topright":"<outline-radius>","-moz-stack-sizing":"ignore|stretch-to-fit","-moz-text-blink":"none|blink","-moz-user-focus":"ignore|normal|select-after|select-before|select-menu|select-same|select-all|none","-moz-user-input":"auto|none|enabled|disabled","-moz-user-modify":"read-only|read-write|write-only","-moz-window-dragging":"drag|no-drag","-moz-window-shadow":"default|menu|tooltip|sheet|none","-webkit-appearance":"none|button|button-bevel|caps-lock-indicator|caret|checkbox|default-button|inner-spin-button|listbox|listitem|media-controls-background|media-controls-fullscreen-background|media-current-time-display|media-enter-fullscreen-button|media-exit-fullscreen-button|media-fullscreen-button|media-mute-button|media-overlay-play-button|media-play-button|media-seek-back-button|media-seek-forward-button|media-slider|media-sliderthumb|media-time-remaining-display|media-toggle-closed-captions-button|media-volume-slider|media-volume-slider-container|media-volume-sliderthumb|menulist|menulist-button|menulist-text|menulist-textfield|meter|progress-bar|progress-bar-value|push-button|radio|scrollbarbutton-down|scrollbarbutton-left|scrollbarbutton-right|scrollbarbutton-up|scrollbargripper-horizontal|scrollbargripper-vertical|scrollbarthumb-horizontal|scrollbarthumb-vertical|scrollbartrack-horizontal|scrollbartrack-vertical|searchfield|searchfield-cancel-button|searchfield-decoration|searchfield-results-button|searchfield-results-decoration|slider-horizontal|slider-vertical|sliderthumb-horizontal|sliderthumb-vertical|square-button|textarea|textfield|-apple-pay-button","-webkit-border-before":"<'border-width'>||<'border-style'>||<color>","-webkit-border-before-color":"<color>","-webkit-border-before-style":"<'border-style'>","-webkit-border-before-width":"<'border-width'>","-webkit-box-reflect":"[above|below|right|left]? <length>? <image>?","-webkit-line-clamp":"none|<integer>","-webkit-mask":"[<mask-reference>||<position> [/ <bg-size>]?||<repeat-style>||[<box>|border|padding|content|text]||[<box>|border|padding|content]]#","-webkit-mask-attachment":"<attachment>#","-webkit-mask-clip":"[<box>|border|padding|content|text]#","-webkit-mask-composite":"<composite-style>#","-webkit-mask-image":"<mask-reference>#","-webkit-mask-origin":"[<box>|border|padding|content]#","-webkit-mask-position":"<position>#","-webkit-mask-position-x":"[<length-percentage>|left|center|right]#","-webkit-mask-position-y":"[<length-percentage>|top|center|bottom]#","-webkit-mask-repeat":"<repeat-style>#","-webkit-mask-repeat-x":"repeat|no-repeat|space|round","-webkit-mask-repeat-y":"repeat|no-repeat|space|round","-webkit-mask-size":"<bg-size>#","-webkit-overflow-scrolling":"auto|touch","-webkit-tap-highlight-color":"<color>","-webkit-text-fill-color":"<color>","-webkit-text-stroke":"<length>||<color>","-webkit-text-stroke-color":"<color>","-webkit-text-stroke-width":"<length>","-webkit-touch-callout":"default|none","-webkit-user-modify":"read-only|read-write|read-write-plaintext-only","accent-color":"auto|<color>","align-content":"normal|<baseline-position>|<content-distribution>|<overflow-position>? <content-position>","align-items":"normal|stretch|<baseline-position>|[<overflow-position>? <self-position>]","align-self":"auto|normal|stretch|<baseline-position>|<overflow-position>? <self-position>","align-tracks":"[normal|<baseline-position>|<content-distribution>|<overflow-position>? <content-position>]#",all:"initial|inherit|unset|revert|revert-layer",animation:"<single-animation>#","animation-composition":"<single-animation-composition>#","animation-delay":"<time>#","animation-direction":"<single-animation-direction>#","animation-duration":"<time>#","animation-fill-mode":"<single-animation-fill-mode>#","animation-iteration-count":"<single-animation-iteration-count>#","animation-name":"[none|<keyframes-name>]#","animation-play-state":"<single-animation-play-state>#","animation-timing-function":"<easing-function>#","animation-timeline":"<single-animation-timeline>#",appearance:"none|auto|textfield|menulist-button|<compat-auto>","aspect-ratio":"auto|<ratio>",azimuth:"<angle>|[[left-side|far-left|left|center-left|center|center-right|right|far-right|right-side]||behind]|leftwards|rightwards","backdrop-filter":"none|<filter-function-list>","backface-visibility":"visible|hidden",background:"[<bg-layer> ,]* <final-bg-layer>","background-attachment":"<attachment>#","background-blend-mode":"<blend-mode>#","background-clip":"<bg-clip>#","background-color":"<color>","background-image":"<bg-image>#","background-origin":"<box>#","background-position":"<bg-position>#","background-position-x":"[center|[[left|right|x-start|x-end]? <length-percentage>?]!]#","background-position-y":"[center|[[top|bottom|y-start|y-end]? <length-percentage>?]!]#","background-repeat":"<repeat-style>#","background-size":"<bg-size>#","block-overflow":"clip|ellipsis|<string>","block-size":"<'width'>",border:"<line-width>||<line-style>||<color>","border-block":"<'border-top-width'>||<'border-top-style'>||<color>","border-block-color":"<'border-top-color'>{1,2}","border-block-style":"<'border-top-style'>","border-block-width":"<'border-top-width'>","border-block-end":"<'border-top-width'>||<'border-top-style'>||<color>","border-block-end-color":"<'border-top-color'>","border-block-end-style":"<'border-top-style'>","border-block-end-width":"<'border-top-width'>","border-block-start":"<'border-top-width'>||<'border-top-style'>||<color>","border-block-start-color":"<'border-top-color'>","border-block-start-style":"<'border-top-style'>","border-block-start-width":"<'border-top-width'>","border-bottom":"<line-width>||<line-style>||<color>","border-bottom-color":"<'border-top-color'>","border-bottom-left-radius":"<length-percentage>{1,2}","border-bottom-right-radius":"<length-percentage>{1,2}","border-bottom-style":"<line-style>","border-bottom-width":"<line-width>","border-collapse":"collapse|separate","border-color":"<color>{1,4}","border-end-end-radius":"<length-percentage>{1,2}","border-end-start-radius":"<length-percentage>{1,2}","border-image":"<'border-image-source'>||<'border-image-slice'> [/ <'border-image-width'>|/ <'border-image-width'>? / <'border-image-outset'>]?||<'border-image-repeat'>","border-image-outset":"[<length>|<number>]{1,4}","border-image-repeat":"[stretch|repeat|round|space]{1,2}","border-image-slice":"<number-percentage>{1,4}&&fill?","border-image-source":"none|<image>","border-image-width":"[<length-percentage>|<number>|auto]{1,4}","border-inline":"<'border-top-width'>||<'border-top-style'>||<color>","border-inline-end":"<'border-top-width'>||<'border-top-style'>||<color>","border-inline-color":"<'border-top-color'>{1,2}","border-inline-style":"<'border-top-style'>","border-inline-width":"<'border-top-width'>","border-inline-end-color":"<'border-top-color'>","border-inline-end-style":"<'border-top-style'>","border-inline-end-width":"<'border-top-width'>","border-inline-start":"<'border-top-width'>||<'border-top-style'>||<color>","border-inline-start-color":"<'border-top-color'>","border-inline-start-style":"<'border-top-style'>","border-inline-start-width":"<'border-top-width'>","border-left":"<line-width>||<line-style>||<color>","border-left-color":"<color>","border-left-style":"<line-style>","border-left-width":"<line-width>","border-radius":"<length-percentage>{1,4} [/ <length-percentage>{1,4}]?","border-right":"<line-width>||<line-style>||<color>","border-right-color":"<color>","border-right-style":"<line-style>","border-right-width":"<line-width>","border-spacing":"<length> <length>?","border-start-end-radius":"<length-percentage>{1,2}","border-start-start-radius":"<length-percentage>{1,2}","border-style":"<line-style>{1,4}","border-top":"<line-width>||<line-style>||<color>","border-top-color":"<color>","border-top-left-radius":"<length-percentage>{1,2}","border-top-right-radius":"<length-percentage>{1,2}","border-top-style":"<line-style>","border-top-width":"<line-width>","border-width":"<line-width>{1,4}",bottom:"<length>|<percentage>|auto","box-align":"start|center|end|baseline|stretch","box-decoration-break":"slice|clone","box-direction":"normal|reverse|inherit","box-flex":"<number>","box-flex-group":"<integer>","box-lines":"single|multiple","box-ordinal-group":"<integer>","box-orient":"horizontal|vertical|inline-axis|block-axis|inherit","box-pack":"start|center|end|justify","box-shadow":"none|<shadow>#","box-sizing":"content-box|border-box","break-after":"auto|avoid|always|all|avoid-page|page|left|right|recto|verso|avoid-column|column|avoid-region|region","break-before":"auto|avoid|always|all|avoid-page|page|left|right|recto|verso|avoid-column|column|avoid-region|region","break-inside":"auto|avoid|avoid-page|avoid-column|avoid-region","caption-side":"top|bottom|block-start|block-end|inline-start|inline-end",caret:"<'caret-color'>||<'caret-shape'>","caret-color":"auto|<color>","caret-shape":"auto|bar|block|underscore",clear:"none|left|right|both|inline-start|inline-end",clip:"<shape>|auto","clip-path":"<clip-source>|[<basic-shape>||<geometry-box>]|none",color:"<color>","print-color-adjust":"economy|exact","color-scheme":"normal|[light|dark|<custom-ident>]+&&only?","column-count":"<integer>|auto","column-fill":"auto|balance|balance-all","column-gap":"normal|<length-percentage>","column-rule":"<'column-rule-width'>||<'column-rule-style'>||<'column-rule-color'>","column-rule-color":"<color>","column-rule-style":"<'border-style'>","column-rule-width":"<'border-width'>","column-span":"none|all","column-width":"<length>|auto",columns:"<'column-width'>||<'column-count'>",contain:"none|strict|content|[[size||inline-size]||layout||style||paint]","contain-intrinsic-size":"[none|<length>|auto <length>]{1,2}","contain-intrinsic-block-size":"none|<length>|auto <length>","contain-intrinsic-height":"none|<length>|auto <length>","contain-intrinsic-inline-size":"none|<length>|auto <length>","contain-intrinsic-width":"none|<length>|auto <length>",content:"normal|none|[<content-replacement>|<content-list>] [/ [<string>|<counter>]+]?","content-visibility":"visible|auto|hidden","counter-increment":"[<counter-name> <integer>?]+|none","counter-reset":"[<counter-name> <integer>?|<reversed-counter-name> <integer>?]+|none","counter-set":"[<counter-name> <integer>?]+|none",cursor:"[[<url> [<x> <y>]? ,]* [auto|default|none|context-menu|help|pointer|progress|wait|cell|crosshair|text|vertical-text|alias|copy|move|no-drop|not-allowed|e-resize|n-resize|ne-resize|nw-resize|s-resize|se-resize|sw-resize|w-resize|ew-resize|ns-resize|nesw-resize|nwse-resize|col-resize|row-resize|all-scroll|zoom-in|zoom-out|grab|grabbing|hand|-webkit-grab|-webkit-grabbing|-webkit-zoom-in|-webkit-zoom-out|-moz-grab|-moz-grabbing|-moz-zoom-in|-moz-zoom-out]]",direction:"ltr|rtl",display:"[<display-outside>||<display-inside>]|<display-listitem>|<display-internal>|<display-box>|<display-legacy>|<-non-standard-display>","empty-cells":"show|hide",filter:"none|<filter-function-list>|<-ms-filter-function-list>",flex:"none|[<'flex-grow'> <'flex-shrink'>?||<'flex-basis'>]","flex-basis":"content|<'width'>","flex-direction":"row|row-reverse|column|column-reverse","flex-flow":"<'flex-direction'>||<'flex-wrap'>","flex-grow":"<number>","flex-shrink":"<number>","flex-wrap":"nowrap|wrap|wrap-reverse",float:"left|right|none|inline-start|inline-end",font:"[[<'font-style'>||<font-variant-css21>||<'font-weight'>||<'font-stretch'>]? <'font-size'> [/ <'line-height'>]? <'font-family'>]|caption|icon|menu|message-box|small-caption|status-bar","font-family":"[<family-name>|<generic-family>]#","font-feature-settings":"normal|<feature-tag-value>#","font-kerning":"auto|normal|none","font-language-override":"normal|<string>","font-optical-sizing":"auto|none","font-variation-settings":"normal|[<string> <number>]#","font-size":"<absolute-size>|<relative-size>|<length-percentage>","font-size-adjust":"none|[ex-height|cap-height|ch-width|ic-width|ic-height]? [from-font|<number>]","font-smooth":"auto|never|always|<absolute-size>|<length>","font-stretch":"<font-stretch-absolute>","font-style":"normal|italic|oblique <angle>?","font-synthesis":"none|[weight||style||small-caps]","font-variant":"normal|none|[<common-lig-values>||<discretionary-lig-values>||<historical-lig-values>||<contextual-alt-values>||stylistic( <feature-value-name> )||historical-forms||styleset( <feature-value-name># )||character-variant( <feature-value-name># )||swash( <feature-value-name> )||ornaments( <feature-value-name> )||annotation( <feature-value-name> )||[small-caps|all-small-caps|petite-caps|all-petite-caps|unicase|titling-caps]||<numeric-figure-values>||<numeric-spacing-values>||<numeric-fraction-values>||ordinal||slashed-zero||<east-asian-variant-values>||<east-asian-width-values>||ruby]","font-variant-alternates":"normal|[stylistic( <feature-value-name> )||historical-forms||styleset( <feature-value-name># )||character-variant( <feature-value-name># )||swash( <feature-value-name> )||ornaments( <feature-value-name> )||annotation( <feature-value-name> )]","font-variant-caps":"normal|small-caps|all-small-caps|petite-caps|all-petite-caps|unicase|titling-caps","font-variant-east-asian":"normal|[<east-asian-variant-values>||<east-asian-width-values>||ruby]","font-variant-ligatures":"normal|none|[<common-lig-values>||<discretionary-lig-values>||<historical-lig-values>||<contextual-alt-values>]","font-variant-numeric":"normal|[<numeric-figure-values>||<numeric-spacing-values>||<numeric-fraction-values>||ordinal||slashed-zero]","font-variant-position":"normal|sub|super","font-weight":"<font-weight-absolute>|bolder|lighter","forced-color-adjust":"auto|none",gap:"<'row-gap'> <'column-gap'>?",grid:"<'grid-template'>|<'grid-template-rows'> / [auto-flow&&dense?] <'grid-auto-columns'>?|[auto-flow&&dense?] <'grid-auto-rows'>? / <'grid-template-columns'>","grid-area":"<grid-line> [/ <grid-line>]{0,3}","grid-auto-columns":"<track-size>+","grid-auto-flow":"[row|column]||dense","grid-auto-rows":"<track-size>+","grid-column":"<grid-line> [/ <grid-line>]?","grid-column-end":"<grid-line>","grid-column-gap":"<length-percentage>","grid-column-start":"<grid-line>","grid-gap":"<'grid-row-gap'> <'grid-column-gap'>?","grid-row":"<grid-line> [/ <grid-line>]?","grid-row-end":"<grid-line>","grid-row-gap":"<length-percentage>","grid-row-start":"<grid-line>","grid-template":"none|[<'grid-template-rows'> / <'grid-template-columns'>]|[<line-names>? <string> <track-size>? <line-names>?]+ [/ <explicit-track-list>]?","grid-template-areas":"none|<string>+","grid-template-columns":"none|<track-list>|<auto-track-list>|subgrid <line-name-list>?","grid-template-rows":"none|<track-list>|<auto-track-list>|subgrid <line-name-list>?","hanging-punctuation":"none|[first||[force-end|allow-end]||last]",height:"auto|<length>|<percentage>|min-content|max-content|fit-content|fit-content( <length-percentage> )","hyphenate-character":"auto|<string>",hyphens:"none|manual|auto","image-orientation":"from-image|<angle>|[<angle>? flip]","image-rendering":"auto|crisp-edges|pixelated|optimizeSpeed|optimizeQuality|<-non-standard-image-rendering>","image-resolution":"[from-image||<resolution>]&&snap?","ime-mode":"auto|normal|active|inactive|disabled","initial-letter":"normal|[<number> <integer>?]","initial-letter-align":"[auto|alphabetic|hanging|ideographic]","inline-size":"<'width'>","input-security":"auto|none",inset:"<'top'>{1,4}","inset-block":"<'top'>{1,2}","inset-block-end":"<'top'>","inset-block-start":"<'top'>","inset-inline":"<'top'>{1,2}","inset-inline-end":"<'top'>","inset-inline-start":"<'top'>",isolation:"auto|isolate","justify-content":"normal|<content-distribution>|<overflow-position>? [<content-position>|left|right]","justify-items":"normal|stretch|<baseline-position>|<overflow-position>? [<self-position>|left|right]|legacy|legacy&&[left|right|center]","justify-self":"auto|normal|stretch|<baseline-position>|<overflow-position>? [<self-position>|left|right]","justify-tracks":"[normal|<content-distribution>|<overflow-position>? [<content-position>|left|right]]#",left:"<length>|<percentage>|auto","letter-spacing":"normal|<length-percentage>","line-break":"auto|loose|normal|strict|anywhere","line-clamp":"none|<integer>","line-height":"normal|<number>|<length>|<percentage>","line-height-step":"<length>","list-style":"<'list-style-type'>||<'list-style-position'>||<'list-style-image'>","list-style-image":"<image>|none","list-style-position":"inside|outside","list-style-type":"<counter-style>|<string>|none",margin:"[<length>|<percentage>|auto]{1,4}","margin-block":"<'margin-left'>{1,2}","margin-block-end":"<'margin-left'>","margin-block-start":"<'margin-left'>","margin-bottom":"<length>|<percentage>|auto","margin-inline":"<'margin-left'>{1,2}","margin-inline-end":"<'margin-left'>","margin-inline-start":"<'margin-left'>","margin-left":"<length>|<percentage>|auto","margin-right":"<length>|<percentage>|auto","margin-top":"<length>|<percentage>|auto","margin-trim":"none|in-flow|all",mask:"<mask-layer>#","mask-border":"<'mask-border-source'>||<'mask-border-slice'> [/ <'mask-border-width'>? [/ <'mask-border-outset'>]?]?||<'mask-border-repeat'>||<'mask-border-mode'>","mask-border-mode":"luminance|alpha","mask-border-outset":"[<length>|<number>]{1,4}","mask-border-repeat":"[stretch|repeat|round|space]{1,2}","mask-border-slice":"<number-percentage>{1,4} fill?","mask-border-source":"none|<image>","mask-border-width":"[<length-percentage>|<number>|auto]{1,4}","mask-clip":"[<geometry-box>|no-clip]#","mask-composite":"<compositing-operator>#","mask-image":"<mask-reference>#","mask-mode":"<masking-mode>#","mask-origin":"<geometry-box>#","mask-position":"<position>#","mask-repeat":"<repeat-style>#","mask-size":"<bg-size>#","mask-type":"luminance|alpha","masonry-auto-flow":"[pack|next]||[definite-first|ordered]","math-depth":"auto-add|add( <integer> )|<integer>","math-shift":"normal|compact","math-style":"normal|compact","max-block-size":"<'max-width'>","max-height":"none|<length-percentage>|min-content|max-content|fit-content|fit-content( <length-percentage> )","max-inline-size":"<'max-width'>","max-lines":"none|<integer>","max-width":"none|<length-percentage>|min-content|max-content|fit-content|fit-content( <length-percentage> )|<-non-standard-width>","min-block-size":"<'min-width'>","min-height":"auto|<length>|<percentage>|min-content|max-content|fit-content|fit-content( <length-percentage> )","min-inline-size":"<'min-width'>","min-width":"auto|<length>|<percentage>|min-content|max-content|fit-content|fit-content( <length-percentage> )|<-non-standard-width>","mix-blend-mode":"<blend-mode>|plus-lighter","object-fit":"fill|contain|cover|none|scale-down","object-position":"<position>",offset:"[<'offset-position'>? [<'offset-path'> [<'offset-distance'>||<'offset-rotate'>]?]?]! [/ <'offset-anchor'>]?","offset-anchor":"auto|<position>","offset-distance":"<length-percentage>","offset-path":"none|ray( [<angle>&&<size>&&contain?] )|<path()>|<url>|[<basic-shape>||<geometry-box>]","offset-position":"auto|<position>","offset-rotate":"[auto|reverse]||<angle>",opacity:"<alpha-value>",order:"<integer>",orphans:"<integer>",outline:"[<'outline-color'>||<'outline-style'>||<'outline-width'>]","outline-color":"<color>|invert","outline-offset":"<length>","outline-style":"auto|<'border-style'>","outline-width":"<line-width>",overflow:"[visible|hidden|clip|scroll|auto]{1,2}|<-non-standard-overflow>","overflow-anchor":"auto|none","overflow-block":"visible|hidden|clip|scroll|auto","overflow-clip-box":"padding-box|content-box","overflow-clip-margin":"<visual-box>||<length [0,\u221E]>","overflow-inline":"visible|hidden|clip|scroll|auto","overflow-wrap":"normal|break-word|anywhere","overflow-x":"visible|hidden|clip|scroll|auto","overflow-y":"visible|hidden|clip|scroll|auto","overscroll-behavior":"[contain|none|auto]{1,2}","overscroll-behavior-block":"contain|none|auto","overscroll-behavior-inline":"contain|none|auto","overscroll-behavior-x":"contain|none|auto","overscroll-behavior-y":"contain|none|auto",padding:"[<length>|<percentage>]{1,4}","padding-block":"<'padding-left'>{1,2}","padding-block-end":"<'padding-left'>","padding-block-start":"<'padding-left'>","padding-bottom":"<length>|<percentage>","padding-inline":"<'padding-left'>{1,2}","padding-inline-end":"<'padding-left'>","padding-inline-start":"<'padding-left'>","padding-left":"<length>|<percentage>","padding-right":"<length>|<percentage>","padding-top":"<length>|<percentage>","page-break-after":"auto|always|avoid|left|right|recto|verso","page-break-before":"auto|always|avoid|left|right|recto|verso","page-break-inside":"auto|avoid","paint-order":"normal|[fill||stroke||markers]",perspective:"none|<length>","perspective-origin":"<position>","place-content":"<'align-content'> <'justify-content'>?","place-items":"<'align-items'> <'justify-items'>?","place-self":"<'align-self'> <'justify-self'>?","pointer-events":"auto|none|visiblePainted|visibleFill|visibleStroke|visible|painted|fill|stroke|all|inherit",position:"static|relative|absolute|sticky|fixed|-webkit-sticky",quotes:"none|auto|[<string> <string>]+",resize:"none|both|horizontal|vertical|block|inline",right:"<length>|<percentage>|auto",rotate:"none|<angle>|[x|y|z|<number>{3}]&&<angle>","row-gap":"normal|<length-percentage>","ruby-align":"start|center|space-between|space-around","ruby-merge":"separate|collapse|auto","ruby-position":"[alternate||[over|under]]|inter-character",scale:"none|<number>{1,3}","scrollbar-color":"auto|<color>{2}","scrollbar-gutter":"auto|stable&&both-edges?","scrollbar-width":"auto|thin|none","scroll-behavior":"auto|smooth","scroll-margin":"<length>{1,4}","scroll-margin-block":"<length>{1,2}","scroll-margin-block-start":"<length>","scroll-margin-block-end":"<length>","scroll-margin-bottom":"<length>","scroll-margin-inline":"<length>{1,2}","scroll-margin-inline-start":"<length>","scroll-margin-inline-end":"<length>","scroll-margin-left":"<length>","scroll-margin-right":"<length>","scroll-margin-top":"<length>","scroll-padding":"[auto|<length-percentage>]{1,4}","scroll-padding-block":"[auto|<length-percentage>]{1,2}","scroll-padding-block-start":"auto|<length-percentage>","scroll-padding-block-end":"auto|<length-percentage>","scroll-padding-bottom":"auto|<length-percentage>","scroll-padding-inline":"[auto|<length-percentage>]{1,2}","scroll-padding-inline-start":"auto|<length-percentage>","scroll-padding-inline-end":"auto|<length-percentage>","scroll-padding-left":"auto|<length-percentage>","scroll-padding-right":"auto|<length-percentage>","scroll-padding-top":"auto|<length-percentage>","scroll-snap-align":"[none|start|end|center]{1,2}","scroll-snap-coordinate":"none|<position>#","scroll-snap-destination":"<position>","scroll-snap-points-x":"none|repeat( <length-percentage> )","scroll-snap-points-y":"none|repeat( <length-percentage> )","scroll-snap-stop":"normal|always","scroll-snap-type":"none|[x|y|block|inline|both] [mandatory|proximity]?","scroll-snap-type-x":"none|mandatory|proximity","scroll-snap-type-y":"none|mandatory|proximity","scroll-timeline":"<scroll-timeline-name>||<scroll-timeline-axis>","scroll-timeline-axis":"block|inline|vertical|horizontal","scroll-timeline-name":"none|<custom-ident>","shape-image-threshold":"<alpha-value>","shape-margin":"<length-percentage>","shape-outside":"none|[<shape-box>||<basic-shape>]|<image>","tab-size":"<integer>|<length>","table-layout":"auto|fixed","text-align":"start|end|left|right|center|justify|match-parent","text-align-last":"auto|start|end|left|right|center|justify","text-combine-upright":"none|all|[digits <integer>?]","text-decoration":"<'text-decoration-line'>||<'text-decoration-style'>||<'text-decoration-color'>||<'text-decoration-thickness'>","text-decoration-color":"<color>","text-decoration-line":"none|[underline||overline||line-through||blink]|spelling-error|grammar-error","text-decoration-skip":"none|[objects||[spaces|[leading-spaces||trailing-spaces]]||edges||box-decoration]","text-decoration-skip-ink":"auto|all|none","text-decoration-style":"solid|double|dotted|dashed|wavy","text-decoration-thickness":"auto|from-font|<length>|<percentage>","text-emphasis":"<'text-emphasis-style'>||<'text-emphasis-color'>","text-emphasis-color":"<color>","text-emphasis-position":"[over|under]&&[right|left]","text-emphasis-style":"none|[[filled|open]||[dot|circle|double-circle|triangle|sesame]]|<string>","text-indent":"<length-percentage>&&hanging?&&each-line?","text-justify":"auto|inter-character|inter-word|none","text-orientation":"mixed|upright|sideways","text-overflow":"[clip|ellipsis|<string>]{1,2}","text-rendering":"auto|optimizeSpeed|optimizeLegibility|geometricPrecision","text-shadow":"none|<shadow-t>#","text-size-adjust":"none|auto|<percentage>","text-transform":"none|capitalize|uppercase|lowercase|full-width|full-size-kana","text-underline-offset":"auto|<length>|<percentage>","text-underline-position":"auto|from-font|[under||[left|right]]",top:"<length>|<percentage>|auto","touch-action":"auto|none|[[pan-x|pan-left|pan-right]||[pan-y|pan-up|pan-down]||pinch-zoom]|manipulation",transform:"none|<transform-list>","transform-box":"content-box|border-box|fill-box|stroke-box|view-box","transform-origin":"[<length-percentage>|left|center|right|top|bottom]|[[<length-percentage>|left|center|right]&&[<length-percentage>|top|center|bottom]] <length>?","transform-style":"flat|preserve-3d",transition:"<single-transition>#","transition-delay":"<time>#","transition-duration":"<time>#","transition-property":"none|<single-transition-property>#","transition-timing-function":"<easing-function>#",translate:"none|<length-percentage> [<length-percentage> <length>?]?","unicode-bidi":"normal|embed|isolate|bidi-override|isolate-override|plaintext|-moz-isolate|-moz-isolate-override|-moz-plaintext|-webkit-isolate|-webkit-isolate-override|-webkit-plaintext","user-select":"auto|text|none|contain|all","vertical-align":"baseline|sub|super|text-top|text-bottom|middle|top|bottom|<percentage>|<length>",visibility:"visible|hidden|collapse","white-space":"normal|pre|nowrap|pre-wrap|pre-line|break-spaces",widows:"<integer>",width:"auto|<length>|<percentage>|min-content|max-content|fit-content|fit-content( <length-percentage> )|fill|stretch|intrinsic|-moz-max-content|-webkit-max-content|-moz-fit-content|-webkit-fit-content","will-change":"auto|<animateable-feature>#","word-break":"normal|break-all|keep-all|break-word","word-spacing":"normal|<length>","word-wrap":"normal|break-word","writing-mode":"horizontal-tb|vertical-rl|vertical-lr|sideways-rl|sideways-lr|<svg-writing-mode>","z-index":"auto|<integer>",zoom:"normal|reset|<number>|<percentage>","-moz-background-clip":"padding|border","-moz-border-radius-bottomleft":"<'border-bottom-left-radius'>","-moz-border-radius-bottomright":"<'border-bottom-right-radius'>","-moz-border-radius-topleft":"<'border-top-left-radius'>","-moz-border-radius-topright":"<'border-bottom-right-radius'>","-moz-control-character-visibility":"visible|hidden","-moz-osx-font-smoothing":"auto|grayscale","-moz-user-select":"none|text|all|-moz-none","-ms-flex-align":"start|end|center|baseline|stretch","-ms-flex-item-align":"auto|start|end|center|baseline|stretch","-ms-flex-line-pack":"start|end|center|justify|distribute|stretch","-ms-flex-negative":"<'flex-shrink'>","-ms-flex-pack":"start|end|center|justify|distribute","-ms-flex-order":"<integer>","-ms-flex-positive":"<'flex-grow'>","-ms-flex-preferred-size":"<'flex-basis'>","-ms-interpolation-mode":"nearest-neighbor|bicubic","-ms-grid-column-align":"start|end|center|stretch","-ms-grid-row-align":"start|end|center|stretch","-ms-hyphenate-limit-last":"none|always|column|page|spread","-webkit-background-clip":"[<box>|border|padding|content|text]#","-webkit-column-break-after":"always|auto|avoid","-webkit-column-break-before":"always|auto|avoid","-webkit-column-break-inside":"always|auto|avoid","-webkit-font-smoothing":"auto|none|antialiased|subpixel-antialiased","-webkit-mask-box-image":"[<url>|<gradient>|none] [<length-percentage>{4} <-webkit-mask-box-repeat>{2}]?","-webkit-print-color-adjust":"economy|exact","-webkit-text-security":"none|circle|disc|square","-webkit-user-drag":"none|element|auto","-webkit-user-select":"auto|none|text|all","alignment-baseline":"auto|baseline|before-edge|text-before-edge|middle|central|after-edge|text-after-edge|ideographic|alphabetic|hanging|mathematical","baseline-shift":"baseline|sub|super|<svg-length>",behavior:"<url>+","clip-rule":"nonzero|evenodd",container:"<'container-name'> [/ <'container-type'>]?","container-name":"none|<custom-ident>+","container-type":"normal||[size|inline-size]",cue:"<'cue-before'> <'cue-after'>?","cue-after":"<url> <decibel>?|none","cue-before":"<url> <decibel>?|none","dominant-baseline":"auto|use-script|no-change|reset-size|ideographic|alphabetic|hanging|mathematical|central|middle|text-after-edge|text-before-edge",fill:"<paint>","fill-opacity":"<number-zero-one>","fill-rule":"nonzero|evenodd","glyph-orientation-horizontal":"<angle>","glyph-orientation-vertical":"<angle>",kerning:"auto|<svg-length>",marker:"none|<url>","marker-end":"none|<url>","marker-mid":"none|<url>","marker-start":"none|<url>",pause:"<'pause-before'> <'pause-after'>?","pause-after":"<time>|none|x-weak|weak|medium|strong|x-strong","pause-before":"<time>|none|x-weak|weak|medium|strong|x-strong",rest:"<'rest-before'> <'rest-after'>?","rest-after":"<time>|none|x-weak|weak|medium|strong|x-strong","rest-before":"<time>|none|x-weak|weak|medium|strong|x-strong","shape-rendering":"auto|optimizeSpeed|crispEdges|geometricPrecision",src:"[<url> [format( <string># )]?|local( <family-name> )]#",speak:"auto|none|normal","speak-as":"normal|spell-out||digits||[literal-punctuation|no-punctuation]",stroke:"<paint>","stroke-dasharray":"none|[<svg-length>+]#","stroke-dashoffset":"<svg-length>","stroke-linecap":"butt|round|square","stroke-linejoin":"miter|round|bevel","stroke-miterlimit":"<number-one-or-greater>","stroke-opacity":"<number-zero-one>","stroke-width":"<svg-length>","text-anchor":"start|middle|end","unicode-range":"<urange>#","voice-balance":"<number>|left|center|right|leftwards|rightwards","voice-duration":"auto|<time>","voice-family":"[[<family-name>|<generic-voice>] ,]* [<family-name>|<generic-voice>]|preserve","voice-pitch":"<frequency>&&absolute|[[x-low|low|medium|high|x-high]||[<frequency>|<semitones>|<percentage>]]","voice-range":"<frequency>&&absolute|[[x-low|low|medium|high|x-high]||[<frequency>|<semitones>|<percentage>]]","voice-rate":"[normal|x-slow|slow|medium|fast|x-fast]||<percentage>","voice-stress":"normal|strong|moderate|none|reduced","voice-volume":"silent|[[x-soft|soft|medium|loud|x-loud]||<decibel>]"},atrules:{charset:{prelude:"<string>",descriptors:null},"counter-style":{prelude:"<counter-style-name>",descriptors:{"additive-symbols":"[<integer>&&<symbol>]#",fallback:"<counter-style-name>",negative:"<symbol> <symbol>?",pad:"<integer>&&<symbol>",prefix:"<symbol>",range:"[[<integer>|infinite]{2}]#|auto","speak-as":"auto|bullets|numbers|words|spell-out|<counter-style-name>",suffix:"<symbol>",symbols:"<symbol>+",system:"cyclic|numeric|alphabetic|symbolic|additive|[fixed <integer>?]|[extends <counter-style-name>]"}},document:{prelude:"[<url>|url-prefix( <string> )|domain( <string> )|media-document( <string> )|regexp( <string> )]#",descriptors:null},"font-face":{prelude:null,descriptors:{"ascent-override":"normal|<percentage>","descent-override":"normal|<percentage>","font-display":"[auto|block|swap|fallback|optional]","font-family":"<family-name>","font-feature-settings":"normal|<feature-tag-value>#","font-variation-settings":"normal|[<string> <number>]#","font-stretch":"<font-stretch-absolute>{1,2}","font-style":"normal|italic|oblique <angle>{0,2}","font-weight":"<font-weight-absolute>{1,2}","font-variant":"normal|none|[<common-lig-values>||<discretionary-lig-values>||<historical-lig-values>||<contextual-alt-values>||stylistic( <feature-value-name> )||historical-forms||styleset( <feature-value-name># )||character-variant( <feature-value-name># )||swash( <feature-value-name> )||ornaments( <feature-value-name> )||annotation( <feature-value-name> )||[small-caps|all-small-caps|petite-caps|all-petite-caps|unicase|titling-caps]||<numeric-figure-values>||<numeric-spacing-values>||<numeric-fraction-values>||ordinal||slashed-zero||<east-asian-variant-values>||<east-asian-width-values>||ruby]","line-gap-override":"normal|<percentage>","size-adjust":"<percentage>",src:"[<url> [format( <string># )]?|local( <family-name> )]#","unicode-range":"<urange>#"}},"font-feature-values":{prelude:"<family-name>#",descriptors:null},import:{prelude:"[<string>|<url>] [layer|layer( <layer-name> )]? [supports( [<supports-condition>|<declaration>] )]? <media-query-list>?",descriptors:null},keyframes:{prelude:"<keyframes-name>",descriptors:null},layer:{prelude:"[<layer-name>#|<layer-name>?]",descriptors:null},media:{prelude:"<media-query-list>",descriptors:null},namespace:{prelude:"<namespace-prefix>? [<string>|<url>]",descriptors:null},page:{prelude:"<page-selector-list>",descriptors:{bleed:"auto|<length>",marks:"none|[crop||cross]",size:"<length>{1,2}|auto|[<page-size>||[portrait|landscape]]"}},property:{prelude:"<custom-property-name>",descriptors:{syntax:"<string>",inherits:"true|false","initial-value":"<string>"}},"scroll-timeline":{prelude:"<timeline-name>",descriptors:null},supports:{prelude:"<supports-condition>",descriptors:null},viewport:{prelude:null,descriptors:{height:"<viewport-length>{1,2}","max-height":"<viewport-length>","max-width":"<viewport-length>","max-zoom":"auto|<number>|<percentage>","min-height":"<viewport-length>","min-width":"<viewport-length>","min-zoom":"auto|<number>|<percentage>",orientation:"auto|portrait|landscape","user-zoom":"zoom|fixed","viewport-fit":"auto|contain|cover",width:"<viewport-length>{1,2}",zoom:"auto|<number>|<percentage>"}},container:{prelude:"[<container-name>]? <container-condition>",descriptors:null},nest:{prelude:"<complex-selector-list>",descriptors:null}}};var gt={};b(gt,{AnPlusB:()=>Xr,Atrule:()=>Zr,AtrulePrelude:()=>en,AttributeSelector:()=>nn,Block:()=>an,Brackets:()=>ln,CDC:()=>un,CDO:()=>hn,ClassSelector:()=>fn,Combinator:()=>gn,Comment:()=>xn,Declaration:()=>kn,DeclarationList:()=>Sn,Dimension:()=>An,Function:()=>En,Hash:()=>Pn,IdSelector:()=>Nn,Identifier:()=>Dn,MediaFeature:()=>Mn,MediaQuery:()=>Fn,MediaQueryList:()=>_n,NestingSelector:()=>Un,Nth:()=>Wn,Number:()=>Yn,Operator:()=>Vn,Parentheses:()=>Qn,Percentage:()=>$n,PseudoClassSelector:()=>Jn,PseudoElementSelector:()=>to,Ratio:()=>no,Raw:()=>io,Rule:()=>so,Selector:()=>co,SelectorList:()=>po,String:()=>bo,StyleSheet:()=>yo,TypeSelector:()=>vo,UnicodeRange:()=>Ao,Url:()=>Do,Value:()=>No,WhiteSpace:()=>Mo});var Xr={};b(Xr,{generate:()=>xc,name:()=>gc,parse:()=>Qr,structure:()=>bc});var me=43,re=45,Xt=110,Ie=!0,dc=!1;function $t(e,t){let r=this.tokenStart+e,n=this.charCodeAt(r);for((n===me||n===re)&&(t&&this.error("Number sign is not allowed"),r++);r<this.tokenEnd;r++)B(this.charCodeAt(r))||this.error("Integer is expected",r);}function Qe(e){return $t.call(this,0,e)}function Ce(e,t){if(!this.cmpChar(this.tokenStart+e,t)){let r="";switch(t){case Xt:r="N is expected";break;case re:r="HyphenMinus is expected";break}this.error(r,this.tokenStart+e);}}function Kr(){let e=0,t=0,r=this.tokenType;for(;r===13||r===25;)r=this.lookupType(++e);if(r!==10)if(this.isDelim(me,e)||this.isDelim(re,e)){t=this.isDelim(me,e)?me:re;do r=this.lookupType(++e);while(r===13||r===25);r!==10&&(this.skip(e),Qe.call(this,Ie));}else return null;return e>0&&this.skip(e),t===0&&(r=this.charCodeAt(this.tokenStart),r!==me&&r!==re&&this.error("Number sign is expected")),Qe.call(this,t!==0),t===re?"-"+this.consume(10):this.consume(10)}var gc="AnPlusB",bc={a:[String,null],b:[String,null]};function Qr(){let e=this.tokenStart,t=null,r=null;if(this.tokenType===10)Qe.call(this,dc),r=this.consume(10);else if(this.tokenType===1&&this.cmpChar(this.tokenStart,re))switch(t="-1",Ce.call(this,1,Xt),this.tokenEnd-this.tokenStart){case 2:this.next(),r=Kr.call(this);break;case 3:Ce.call(this,2,re),this.next(),this.skipSC(),Qe.call(this,Ie),r="-"+this.consume(10);break;default:Ce.call(this,2,re),$t.call(this,3,Ie),this.next(),r=this.substrToCursor(e+2);}else if(this.tokenType===1||this.isDelim(me)&&this.lookupType(1)===1){let n=0;switch(t="1",this.isDelim(me)&&(n=1,this.next()),Ce.call(this,0,Xt),this.tokenEnd-this.tokenStart){case 1:this.next(),r=Kr.call(this);break;case 2:Ce.call(this,1,re),this.next(),this.skipSC(),Qe.call(this,Ie),r="-"+this.consume(10);break;default:Ce.call(this,1,re),$t.call(this,2,Ie),this.next(),r=this.substrToCursor(e+n+1);}}else if(this.tokenType===12){let n=this.charCodeAt(this.tokenStart),o=n===me||n===re,i=this.tokenStart+o;for(;i<this.tokenEnd&&B(this.charCodeAt(i));i++);i===this.tokenStart+o&&this.error("Integer is expected",this.tokenStart+o),Ce.call(this,i-this.tokenStart,Xt),t=this.substring(e,i),i+1===this.tokenEnd?(this.next(),r=Kr.call(this)):(Ce.call(this,i-this.tokenStart+1,re),i+2===this.tokenEnd?(this.next(),this.skipSC(),Qe.call(this,Ie),r="-"+this.consume(10)):($t.call(this,i-this.tokenStart+2,Ie),this.next(),r=this.substrToCursor(i+1)));}else this.error();return t!==null&&t.charCodeAt(0)===me&&(t=t.substr(1)),r!==null&&r.charCodeAt(0)===me&&(r=r.substr(1)),{type:"AnPlusB",loc:this.getLocation(e,this.tokenStart),a:t,b:r}}function xc(e){if(e.a){let t=e.a==="+1"&&"n"||e.a==="1"&&"n"||e.a==="-1"&&"-n"||e.a+"n";if(e.b){let r=e.b[0]==="-"||e.b[0]==="+"?e.b:"+"+e.b;this.tokenize(t+r);}else this.tokenize(t);}else this.tokenize(e.b);}var Zr={};b(Zr,{generate:()=>Sc,name:()=>kc,parse:()=>$r,structure:()=>vc,walkContext:()=>wc});function da(e){return this.Raw(e,this.consumeUntilLeftCurlyBracketOrSemicolon,!0)}function yc(){for(let e=1,t;t=this.lookupType(e);e++){if(t===24)return !0;if(t===23||t===3)return !1}return !1}var kc="Atrule",wc="atrule",vc={name:String,prelude:["AtrulePrelude","Raw",null],block:["Block",null]};function $r(e=!1){let t=this.tokenStart,r,n,o=null,i=null;switch(this.eat(3),r=this.substrToCursor(t+1),n=r.toLowerCase(),this.skipSC(),this.eof===!1&&this.tokenType!==23&&this.tokenType!==17&&(this.parseAtrulePrelude?o=this.parseWithFallback(this.AtrulePrelude.bind(this,r,e),da):o=da.call(this,this.tokenIndex),this.skipSC()),this.tokenType){case 17:this.next();break;case 23:hasOwnProperty.call(this.atrule,n)&&typeof this.atrule[n].block=="function"?i=this.atrule[n].block.call(this,e):i=this.Block(yc.call(this));break}return {type:"Atrule",loc:this.getLocation(t,this.tokenStart),name:r,prelude:o,block:i}}function Sc(e){this.token(3,"@"+e.name),e.prelude!==null&&this.node(e.prelude),e.block?this.node(e.block):this.token(17,";");}var en={};b(en,{generate:()=>Ec,name:()=>Cc,parse:()=>Jr,structure:()=>Tc,walkContext:()=>Ac});var Cc="AtrulePrelude",Ac="atrulePrelude",Tc={children:[[]]};function Jr(e){let t=null;return e!==null&&(e=e.toLowerCase()),this.skipSC(),hasOwnProperty.call(this.atrule,e)&&typeof this.atrule[e].prelude=="function"?t=this.atrule[e].prelude.call(this):t=this.readSequence(this.scope.AtrulePrelude),this.skipSC(),this.eof!==!0&&this.tokenType!==23&&this.tokenType!==17&&this.error("Semicolon or block is expected"),{type:"AtrulePrelude",loc:this.getLocationFromList(t),children:t}}function Ec(e){this.children(e);}var nn={};b(nn,{generate:()=>Mc,name:()=>Nc,parse:()=>rn,structure:()=>zc});var Lc=36,ga=42,Zt=61,Pc=94,tn=124,Ic=126;function Dc(){this.eof&&this.error("Unexpected end of input");let e=this.tokenStart,t=!1;return this.isDelim(ga)?(t=!0,this.next()):this.isDelim(tn)||this.eat(1),this.isDelim(tn)?this.charCodeAt(this.tokenStart+1)!==Zt?(this.next(),this.eat(1)):t&&this.error("Identifier is expected",this.tokenEnd):t&&this.error("Vertical line is expected"),{type:"Identifier",loc:this.getLocation(e,this.tokenStart),name:this.substrToCursor(e)}}function Oc(){let e=this.tokenStart,t=this.charCodeAt(e);return t!==Zt&&t!==Ic&&t!==Pc&&t!==Lc&&t!==ga&&t!==tn&&this.error("Attribute selector (=, ~=, ^=, $=, *=, |=) is expected"),this.next(),t!==Zt&&(this.isDelim(Zt)||this.error("Equal sign is expected"),this.next()),this.substrToCursor(e)}var Nc="AttributeSelector",zc={name:"Identifier",matcher:[String,null],value:["String","Identifier",null],flags:[String,null]};function rn(){let e=this.tokenStart,t,r=null,n=null,o=null;return this.eat(19),this.skipSC(),t=Dc.call(this),this.skipSC(),this.tokenType!==20&&(this.tokenType!==1&&(r=Oc.call(this),this.skipSC(),n=this.tokenType===5?this.String():this.Identifier(),this.skipSC()),this.tokenType===1&&(o=this.consume(1),this.skipSC())),this.eat(20),{type:"AttributeSelector",loc:this.getLocation(e,this.tokenStart),name:t,matcher:r,value:n,flags:o}}function Mc(e){this.token(9,"["),this.node(e.name),e.matcher!==null&&(this.tokenize(e.matcher),this.node(e.value)),e.flags!==null&&this.token(1,e.flags),this.token(9,"]");}var an={};b(an,{generate:()=>Uc,name:()=>Bc,parse:()=>on,structure:()=>qc,walkContext:()=>_c});var Rc=38;function ya(e){return this.Raw(e,null,!0)}function ba(){return this.parseWithFallback(this.Rule,ya)}function xa(e){return this.Raw(e,this.consumeUntilSemicolonIncluded,!0)}function Fc(){if(this.tokenType===17)return xa.call(this,this.tokenIndex);let e=this.parseWithFallback(this.Declaration,xa);return this.tokenType===17&&this.next(),e}var Bc="Block",_c="block",qc={children:[["Atrule","Rule","Declaration"]]};function on(e){let t=e?Fc:ba,r=this.tokenStart,n=this.createList();this.eat(23);e:for(;!this.eof;)switch(this.tokenType){case 24:break e;case 13:case 25:this.next();break;case 3:n.push(this.parseWithFallback(this.Atrule.bind(this,e),ya));break;default:e&&this.isDelim(Rc)?n.push(ba.call(this)):n.push(t.call(this));}return this.eof||this.eat(24),{type:"Block",loc:this.getLocation(r,this.tokenStart),children:n}}function Uc(e){this.token(23,"{"),this.children(e,t=>{t.type==="Declaration"&&this.token(17,";");}),this.token(24,"}");}var ln={};b(ln,{generate:()=>Hc,name:()=>jc,parse:()=>sn,structure:()=>Wc});var jc="Brackets",Wc={children:[[]]};function sn(e,t){let r=this.tokenStart,n=null;return this.eat(19),n=e.call(this,t),this.eof||this.eat(20),{type:"Brackets",loc:this.getLocation(r,this.tokenStart),children:n}}function Hc(e){this.token(9,"["),this.children(e),this.token(9,"]");}var un={};b(un,{generate:()=>Vc,name:()=>Yc,parse:()=>cn,structure:()=>Gc});var Yc="CDC",Gc=[];function cn(){let e=this.tokenStart;return this.eat(15),{type:"CDC",loc:this.getLocation(e,this.tokenStart)}}function Vc(){this.token(15,"-->");}var hn={};b(hn,{generate:()=>Xc,name:()=>Kc,parse:()=>pn,structure:()=>Qc});var Kc="CDO",Qc=[];function pn(){let e=this.tokenStart;return this.eat(14),{type:"CDO",loc:this.getLocation(e,this.tokenStart)}}function Xc(){this.token(14,"<!--");}var fn={};b(fn,{generate:()=>eu,name:()=>Zc,parse:()=>mn,structure:()=>Jc});var $c=46,Zc="ClassSelector",Jc={name:String};function mn(){return this.eatDelim($c),{type:"ClassSelector",loc:this.getLocation(this.tokenStart-1,this.tokenEnd),name:this.consume(1)}}function eu(e){this.token(9,"."),this.token(1,e.name);}var gn={};b(gn,{generate:()=>au,name:()=>ou,parse:()=>dn,structure:()=>iu});var tu=43,ka=47,ru=62,nu=126,ou="Combinator",iu={name:String};function dn(){let e=this.tokenStart,t;switch(this.tokenType){case 13:t=" ";break;case 9:switch(this.charCodeAt(this.tokenStart)){case ru:case tu:case nu:this.next();break;case ka:this.next(),this.eatIdent("deep"),this.eatDelim(ka);break;default:this.error("Combinator is expected");}t=this.substrToCursor(e);break}return {type:"Combinator",loc:this.getLocation(e,this.tokenStart),name:t}}function au(e){this.tokenize(e.name);}var xn={};b(xn,{generate:()=>pu,name:()=>cu,parse:()=>bn,structure:()=>uu});var su=42,lu=47,cu="Comment",uu={value:String};function bn(){let e=this.tokenStart,t=this.tokenEnd;return this.eat(25),t-e+2>=2&&this.charCodeAt(t-2)===su&&this.charCodeAt(t-1)===lu&&(t-=2),{type:"Comment",loc:this.getLocation(e,this.tokenStart),value:this.substring(e+2,t)}}function pu(e){this.token(25,"/*"+e.value+"*/");}var kn={};b(kn,{generate:()=>Su,name:()=>ku,parse:()=>yn,structure:()=>vu,walkContext:()=>wu});var va=33,hu=35,mu=36,fu=38,du=42,gu=43,wa=47;function bu(e){return this.Raw(e,this.consumeUntilExclamationMarkOrSemicolon,!0)}function xu(e){return this.Raw(e,this.consumeUntilExclamationMarkOrSemicolon,!1)}function yu(){let e=this.tokenIndex,t=this.Value();return t.type!=="Raw"&&this.eof===!1&&this.tokenType!==17&&this.isDelim(va)===!1&&this.isBalanceEdge(e)===!1&&this.error(),t}var ku="Declaration",wu="declaration",vu={important:[Boolean,String],property:String,value:["Value","Raw"]};function yn(){let e=this.tokenStart,t=this.tokenIndex,r=Cu.call(this),n=Mt(r),o=n?this.parseCustomProperty:this.parseValue,i=n?xu:bu,s=!1,u;this.skipSC(),this.eat(16);let c=this.tokenIndex;if(n||this.skipSC(),o?u=this.parseWithFallback(yu,i):u=i.call(this,this.tokenIndex),n&&u.type==="Value"&&u.children.isEmpty){for(let a=c-this.tokenIndex;a<=0;a++)if(this.lookupType(a)===13){u.children.appendData({type:"WhiteSpace",loc:null,value:" "});break}}return this.isDelim(va)&&(s=Au.call(this),this.skipSC()),this.eof===!1&&this.tokenType!==17&&this.isBalanceEdge(t)===!1&&this.error(),{type:"Declaration",loc:this.getLocation(e,this.tokenStart),important:s,property:r,value:u}}function Su(e){this.token(1,e.property),this.token(16,":"),this.node(e.value),e.important&&(this.token(9,"!"),this.token(1,e.important===!0?"important":e.important));}function Cu(){let e=this.tokenStart;if(this.tokenType===9)switch(this.charCodeAt(this.tokenStart)){case du:case mu:case gu:case hu:case fu:this.next();break;case wa:this.next(),this.isDelim(wa)&&this.next();break}return this.tokenType===4?this.eat(4):this.eat(1),this.substrToCursor(e)}function Au(){this.eat(9),this.skipSC();let e=this.consume(1);return e==="important"?!0:e}var Sn={};b(Sn,{generate:()=>Pu,name:()=>Eu,parse:()=>vn,structure:()=>Lu});var Tu=38;function wn(e){return this.Raw(e,this.consumeUntilSemicolonIncluded,!0)}var Eu="DeclarationList",Lu={children:[["Declaration","Atrule","Rule"]]};function vn(){let e=this.createList();for(;!this.eof;)switch(this.tokenType){case 13:case 25:case 17:this.next();break;case 3:e.push(this.parseWithFallback(this.Atrule.bind(this,!0),wn));break;default:this.isDelim(Tu)?e.push(this.parseWithFallback(this.Rule,wn)):e.push(this.parseWithFallback(this.Declaration,wn));}return {type:"DeclarationList",loc:this.getLocationFromList(e),children:e}}function Pu(e){this.children(e,t=>{t.type==="Declaration"&&this.token(17,";");});}var An={};b(An,{generate:()=>Ou,name:()=>Iu,parse:()=>Cn,structure:()=>Du});var Iu="Dimension",Du={value:String,unit:String};function Cn(){let e=this.tokenStart,t=this.consumeNumber(12);return {type:"Dimension",loc:this.getLocation(e,this.tokenStart),value:t,unit:this.substring(e+t.length,this.tokenStart)}}function Ou(e){this.token(12,e.value+e.unit);}var En={};b(En,{generate:()=>Ru,name:()=>Nu,parse:()=>Tn,structure:()=>Mu,walkContext:()=>zu});var Nu="Function",zu="function",Mu={name:String,children:[[]]};function Tn(e,t){let r=this.tokenStart,n=this.consumeFunctionName(),o=n.toLowerCase(),i;return i=t.hasOwnProperty(o)?t[o].call(this,t):e.call(this,t),this.eof||this.eat(22),{type:"Function",loc:this.getLocation(r,this.tokenStart),name:n,children:i}}function Ru(e){this.token(2,e.name+"("),this.children(e),this.token(22,")");}var Pn={};b(Pn,{generate:()=>qu,name:()=>Bu,parse:()=>Ln,structure:()=>_u,xxx:()=>Fu});var Fu="XXX",Bu="Hash",_u={value:String};function Ln(){let e=this.tokenStart;return this.eat(4),{type:"Hash",loc:this.getLocation(e,this.tokenStart),value:this.substrToCursor(e+1)}}function qu(e){this.token(4,"#"+e.value);}var Dn={};b(Dn,{generate:()=>Wu,name:()=>Uu,parse:()=>In,structure:()=>ju});var Uu="Identifier",ju={name:String};function In(){return {type:"Identifier",loc:this.getLocation(this.tokenStart,this.tokenEnd),name:this.consume(1)}}function Wu(e){this.token(1,e.name);}var Nn={};b(Nn,{generate:()=>Gu,name:()=>Hu,parse:()=>On,structure:()=>Yu});var Hu="IdSelector",Yu={name:String};function On(){let e=this.tokenStart;return this.eat(4),{type:"IdSelector",loc:this.getLocation(e,this.tokenStart),name:this.substrToCursor(e+1)}}function Gu(e){this.token(9,"#"+e.name);}var Mn={};b(Mn,{generate:()=>Qu,name:()=>Vu,parse:()=>zn,structure:()=>Ku});var Vu="MediaFeature",Ku={name:String,value:["Identifier","Number","Dimension","Ratio",null]};function zn(){let e=this.tokenStart,t,r=null;if(this.eat(21),this.skipSC(),t=this.consume(1),this.skipSC(),this.tokenType!==22){switch(this.eat(16),this.skipSC(),this.tokenType){case 10:this.lookupNonWSType(1)===9?r=this.Ratio():r=this.Number();break;case 12:r=this.Dimension();break;case 1:r=this.Identifier();break;default:this.error("Number, dimension, ratio or identifier is expected");}this.skipSC();}return this.eat(22),{type:"MediaFeature",loc:this.getLocation(e,this.tokenStart),name:t,value:r}}function Qu(e){this.token(21,"("),this.token(1,e.name),e.value!==null&&(this.token(16,":"),this.node(e.value)),this.token(22,")");}var Fn={};b(Fn,{generate:()=>Zu,name:()=>Xu,parse:()=>Rn,structure:()=>$u});var Xu="MediaQuery",$u={children:[["Identifier","MediaFeature","WhiteSpace"]]};function Rn(){let e=this.createList(),t=null;this.skipSC();e:for(;!this.eof;){switch(this.tokenType){case 25:case 13:this.next();continue;case 1:t=this.Identifier();break;case 21:t=this.MediaFeature();break;default:break e}e.push(t);}return t===null&&this.error("Identifier or parenthesis is expected"),{type:"MediaQuery",loc:this.getLocationFromList(e),children:e}}function Zu(e){this.children(e);}var _n={};b(_n,{generate:()=>tp,name:()=>Ju,parse:()=>Bn,structure:()=>ep});var Ju="MediaQueryList",ep={children:[["MediaQuery"]]};function Bn(){let e=this.createList();for(this.skipSC();!this.eof&&(e.push(this.MediaQuery()),this.tokenType===18);)this.next();return {type:"MediaQueryList",loc:this.getLocationFromList(e),children:e}}function tp(e){this.children(e,()=>this.token(18,","));}var Un={};b(Un,{generate:()=>ip,name:()=>np,parse:()=>qn,structure:()=>op});var rp=38,np="NestingSelector",op={};function qn(){let e=this.tokenStart;return this.eatDelim(rp),{type:"NestingSelector",loc:this.getLocation(e,this.tokenStart)}}function ip(){this.token(9,"&");}var Wn={};b(Wn,{generate:()=>lp,name:()=>ap,parse:()=>jn,structure:()=>sp});var ap="Nth",sp={nth:["AnPlusB","Identifier"],selector:["SelectorList",null]};function jn(){this.skipSC();let e=this.tokenStart,t=e,r=null,n;return this.lookupValue(0,"odd")||this.lookupValue(0,"even")?n=this.Identifier():n=this.AnPlusB(),t=this.tokenStart,this.skipSC(),this.lookupValue(0,"of")&&(this.next(),r=this.SelectorList(),t=this.tokenStart),{type:"Nth",loc:this.getLocation(e,t),nth:n,selector:r}}function lp(e){this.node(e.nth),e.selector!==null&&(this.token(1,"of"),this.node(e.selector));}var Yn={};b(Yn,{generate:()=>pp,name:()=>cp,parse:()=>Hn,structure:()=>up});var cp="Number",up={value:String};function Hn(){return {type:"Number",loc:this.getLocation(this.tokenStart,this.tokenEnd),value:this.consume(10)}}function pp(e){this.token(10,e.value);}var Vn={};b(Vn,{generate:()=>fp,name:()=>hp,parse:()=>Gn,structure:()=>mp});var hp="Operator",mp={value:String};function Gn(){let e=this.tokenStart;return this.next(),{type:"Operator",loc:this.getLocation(e,this.tokenStart),value:this.substrToCursor(e)}}function fp(e){this.tokenize(e.value);}var Qn={};b(Qn,{generate:()=>bp,name:()=>dp,parse:()=>Kn,structure:()=>gp});var dp="Parentheses",gp={children:[[]]};function Kn(e,t){let r=this.tokenStart,n=null;return this.eat(21),n=e.call(this,t),this.eof||this.eat(22),{type:"Parentheses",loc:this.getLocation(r,this.tokenStart),children:n}}function bp(e){this.token(21,"("),this.children(e),this.token(22,")");}var $n={};b($n,{generate:()=>kp,name:()=>xp,parse:()=>Xn,structure:()=>yp});var xp="Percentage",yp={value:String};function Xn(){return {type:"Percentage",loc:this.getLocation(this.tokenStart,this.tokenEnd),value:this.consumeNumber(11)}}function kp(e){this.token(11,e.value+"%");}var Jn={};b(Jn,{generate:()=>Cp,name:()=>wp,parse:()=>Zn,structure:()=>Sp,walkContext:()=>vp});var wp="PseudoClassSelector",vp="function",Sp={name:String,children:[["Raw"],null]};function Zn(){let e=this.tokenStart,t=null,r,n;return this.eat(16),this.tokenType===2?(r=this.consumeFunctionName(),n=r.toLowerCase(),hasOwnProperty.call(this.pseudo,n)?(this.skipSC(),t=this.pseudo[n].call(this),this.skipSC()):(t=this.createList(),t.push(this.Raw(this.tokenIndex,null,!1))),this.eat(22)):r=this.consume(1),{type:"PseudoClassSelector",loc:this.getLocation(e,this.tokenStart),name:r,children:t}}function Cp(e){this.token(16,":"),e.children===null?this.token(1,e.name):(this.token(2,e.name+"("),this.children(e),this.token(22,")"));}var to={};b(to,{generate:()=>Lp,name:()=>Ap,parse:()=>eo,structure:()=>Ep,walkContext:()=>Tp});var Ap="PseudoElementSelector",Tp="function",Ep={name:String,children:[["Raw"],null]};function eo(){let e=this.tokenStart,t=null,r,n;return this.eat(16),this.eat(16),this.tokenType===2?(r=this.consumeFunctionName(),n=r.toLowerCase(),hasOwnProperty.call(this.pseudo,n)?(this.skipSC(),t=this.pseudo[n].call(this),this.skipSC()):(t=this.createList(),t.push(this.Raw(this.tokenIndex,null,!1))),this.eat(22)):r=this.consume(1),{type:"PseudoElementSelector",loc:this.getLocation(e,this.tokenStart),name:r,children:t}}function Lp(e){this.token(16,":"),this.token(16,":"),e.children===null?this.token(1,e.name):(this.token(2,e.name+"("),this.children(e),this.token(22,")"));}var no={};b(no,{generate:()=>Np,name:()=>Dp,parse:()=>ro,structure:()=>Op});var Pp=47,Ip=46;function Sa(){this.skipSC();let e=this.consume(10);for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);!B(r)&&r!==Ip&&this.error("Unsigned number is expected",this.tokenStart-e.length+t);}return Number(e)===0&&this.error("Zero number is not allowed",this.tokenStart-e.length),e}var Dp="Ratio",Op={left:String,right:String};function ro(){let e=this.tokenStart,t=Sa.call(this),r;return this.skipSC(),this.eatDelim(Pp),r=Sa.call(this),{type:"Ratio",loc:this.getLocation(e,this.tokenStart),left:t,right:r}}function Np(e){this.token(10,e.left),this.token(9,"/"),this.token(10,e.right);}var io={};b(io,{generate:()=>Fp,name:()=>Mp,parse:()=>oo,structure:()=>Rp});function zp(){return this.tokenIndex>0&&this.lookupType(-1)===13?this.tokenIndex>1?this.getTokenStart(this.tokenIndex-1):this.firstCharOffset:this.tokenStart}var Mp="Raw",Rp={value:String};function oo(e,t,r){let n=this.getTokenStart(e),o;return this.skipUntilBalanced(e,t||this.consumeUntilBalanceEnd),r&&this.tokenStart>n?o=zp.call(this):o=this.tokenStart,{type:"Raw",loc:this.getLocation(n,o),value:this.substring(n,o)}}function Fp(e){this.tokenize(e.value);}var so={};b(so,{generate:()=>jp,name:()=>_p,parse:()=>ao,structure:()=>Up,walkContext:()=>qp});function Ca(e){return this.Raw(e,this.consumeUntilLeftCurlyBracket,!0)}function Bp(){let e=this.SelectorList();return e.type!=="Raw"&&this.eof===!1&&this.tokenType!==23&&this.error(),e}var _p="Rule",qp="rule",Up={prelude:["SelectorList","Raw"],block:["Block"]};function ao(){let e=this.tokenIndex,t=this.tokenStart,r,n;return this.parseRulePrelude?r=this.parseWithFallback(Bp,Ca):r=Ca.call(this,e),n=this.Block(!0),{type:"Rule",loc:this.getLocation(t,this.tokenStart),prelude:r,block:n}}function jp(e){this.node(e.prelude),this.node(e.block);}var co={};b(co,{generate:()=>Yp,name:()=>Wp,parse:()=>lo,structure:()=>Hp});var Wp="Selector",Hp={children:[["TypeSelector","IdSelector","ClassSelector","AttributeSelector","PseudoClassSelector","PseudoElementSelector","Combinator","WhiteSpace"]]};function lo(){let e=this.readSequence(this.scope.Selector);return this.getFirstListNode(e)===null&&this.error("Selector is expected"),{type:"Selector",loc:this.getLocationFromList(e),children:e}}function Yp(e){this.children(e);}var po={};b(po,{generate:()=>Qp,name:()=>Gp,parse:()=>uo,structure:()=>Kp,walkContext:()=>Vp});var Gp="SelectorList",Vp="selector",Kp={children:[["Selector","Raw"]]};function uo(){let e=this.createList();for(;!this.eof;){if(e.push(this.Selector()),this.tokenType===18){this.next();continue}break}return {type:"SelectorList",loc:this.getLocationFromList(e),children:e}}function Qp(e){this.children(e,()=>this.token(18,","));}var bo={};b(bo,{generate:()=>Zp,name:()=>Xp,parse:()=>go,structure:()=>$p});var fo={};b(fo,{decode:()=>ft,encode:()=>mo});var ho=92,Aa=34,Ta=39;function ft(e){let t=e.length,r=e.charCodeAt(0),n=r===Aa||r===Ta?1:0,o=n===1&&t>1&&e.charCodeAt(t-1)===r?t-2:t-1,i="";for(let s=n;s<=o;s++){let u=e.charCodeAt(s);if(u===ho){if(s===o){s!==t-1&&(i=e.substr(s+1));break}if(u=e.charCodeAt(++s),$(ho,u)){let c=s-1,a=se(e,c);s=a-1,i+=Re(e.substring(c+1,a));}else u===13&&e.charCodeAt(s+1)===10&&s++;}else i+=e[s];}return i}function mo(e,t){let r=t?"'":'"',n=t?Ta:Aa,o="",i=!1;for(let s=0;s<e.length;s++){let u=e.charCodeAt(s);if(u===0){o+="\uFFFD";continue}if(u<=31||u===127){o+="\\"+u.toString(16),i=!0;continue}u===n||u===ho?(o+="\\"+e.charAt(s),i=!1):(i&&(ee(u)||pe(u))&&(o+=" "),o+=e.charAt(s),i=!1);}return r+o+r}var Xp="String",$p={value:String};function go(){return {type:"String",loc:this.getLocation(this.tokenStart,this.tokenEnd),value:ft(this.consume(5))}}function Zp(e){this.token(5,mo(e.value));}var yo={};b(yo,{generate:()=>nh,name:()=>eh,parse:()=>xo,structure:()=>rh,walkContext:()=>th});var Jp=33;function Ea(e){return this.Raw(e,null,!1)}var eh="StyleSheet",th="stylesheet",rh={children:[["Comment","CDO","CDC","Atrule","Rule","Raw"]]};function xo(){let e=this.tokenStart,t=this.createList(),r;for(;!this.eof;){switch(this.tokenType){case 13:this.next();continue;case 25:if(this.charCodeAt(this.tokenStart+2)!==Jp){this.next();continue}r=this.Comment();break;case 14:r=this.CDO();break;case 15:r=this.CDC();break;case 3:r=this.parseWithFallback(this.Atrule,Ea);break;default:r=this.parseWithFallback(this.Rule,Ea);}t.push(r);}return {type:"StyleSheet",loc:this.getLocation(e,this.tokenStart),children:t}}function nh(e){this.children(e);}var vo={};b(vo,{generate:()=>sh,name:()=>ih,parse:()=>wo,structure:()=>ah});var oh=42,La=124;function ko(){this.tokenType!==1&&this.isDelim(oh)===!1&&this.error("Identifier or asterisk is expected"),this.next();}var ih="TypeSelector",ah={name:String};function wo(){let e=this.tokenStart;return this.isDelim(La)?(this.next(),ko.call(this)):(ko.call(this),this.isDelim(La)&&(this.next(),ko.call(this))),{type:"TypeSelector",loc:this.getLocation(e,this.tokenStart),name:this.substrToCursor(e)}}function sh(e){this.tokenize(e.name);}var Ao={};b(Ao,{generate:()=>hh,name:()=>uh,parse:()=>Co,structure:()=>ph});var Pa=43,Ia=45,So=63;function dt(e,t){let r=0;for(let n=this.tokenStart+e;n<this.tokenEnd;n++){let o=this.charCodeAt(n);if(o===Ia&&t&&r!==0)return dt.call(this,e+r+1,!1),-1;ee(o)||this.error(t&&r!==0?"Hyphen minus"+(r<6?" or hex digit":"")+" is expected":r<6?"Hex digit is expected":"Unexpected input",n),++r>6&&this.error("Too many hex digits",n);}return this.next(),r}function Jt(e){let t=0;for(;this.isDelim(So);)++t>e&&this.error("Too many question marks"),this.next();}function lh(e){this.charCodeAt(this.tokenStart)!==e&&this.error((e===Pa?"Plus sign":"Hyphen minus")+" is expected");}function ch(){let e=0;switch(this.tokenType){case 10:if(e=dt.call(this,1,!0),this.isDelim(So)){Jt.call(this,6-e);break}if(this.tokenType===12||this.tokenType===10){lh.call(this,Ia),dt.call(this,1,!1);break}break;case 12:e=dt.call(this,1,!0),e>0&&Jt.call(this,6-e);break;default:if(this.eatDelim(Pa),this.tokenType===1){e=dt.call(this,0,!0),e>0&&Jt.call(this,6-e);break}if(this.isDelim(So)){this.next(),Jt.call(this,5);break}this.error("Hex digit or question mark is expected");}}var uh="UnicodeRange",ph={value:String};function Co(){let e=this.tokenStart;return this.eatIdent("u"),ch.call(this),{type:"UnicodeRange",loc:this.getLocation(e,this.tokenStart),value:this.substrToCursor(e)}}function hh(e){this.tokenize(e.value);}var Do={};b(Do,{generate:()=>yh,name:()=>bh,parse:()=>Io,structure:()=>xh});var Po={};b(Po,{decode:()=>Eo,encode:()=>Lo});var mh=32,To=92,fh=34,dh=39,gh=40,Da=41;function Eo(e){let t=e.length,r=4,n=e.charCodeAt(t-1)===Da?t-2:t-1,o="";for(;r<n&&pe(e.charCodeAt(r));)r++;for(;r<n&&pe(e.charCodeAt(n));)n--;for(let i=r;i<=n;i++){let s=e.charCodeAt(i);if(s===To){if(i===n){i!==t-1&&(o=e.substr(i+1));break}if(s=e.charCodeAt(++i),$(To,s)){let u=i-1,c=se(e,u);i=c-1,o+=Re(e.substring(u+1,c));}else s===13&&e.charCodeAt(i+1)===10&&i++;}else o+=e[i];}return o}function Lo(e){let t="",r=!1;for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);if(o===0){t+="\uFFFD";continue}if(o<=31||o===127){t+="\\"+o.toString(16),r=!0;continue}o===mh||o===To||o===fh||o===dh||o===gh||o===Da?(t+="\\"+e.charAt(n),r=!1):(r&&ee(o)&&(t+=" "),t+=e.charAt(n),r=!1);}return "url("+t+")"}var bh="Url",xh={value:String};function Io(){let e=this.tokenStart,t;switch(this.tokenType){case 7:t=Eo(this.consume(7));break;case 2:this.cmpStr(this.tokenStart,this.tokenEnd,"url(")||this.error("Function name must be `url`"),this.eat(2),this.skipSC(),t=ft(this.consume(5)),this.skipSC(),this.eof||this.eat(22);break;default:this.error("Url or Function is expected");}return {type:"Url",loc:this.getLocation(e,this.tokenStart),value:t}}function yh(e){this.token(7,Lo(e.value));}var No={};b(No,{generate:()=>vh,name:()=>kh,parse:()=>Oo,structure:()=>wh});var kh="Value",wh={children:[[]]};function Oo(){let e=this.tokenStart,t=this.readSequence(this.scope.Value);return {type:"Value",loc:this.getLocation(e,this.tokenStart),children:t}}function vh(e){this.children(e);}var Mo={};b(Mo,{generate:()=>Th,name:()=>Ch,parse:()=>zo,structure:()=>Ah});var Sh=Object.freeze({type:"WhiteSpace",loc:null,value:" "}),Ch="WhiteSpace",Ah={value:String};function zo(){return this.eat(13),Sh}function Th(e){this.token(13,e.value);}var Oa={generic:!0,...fa,node:gt};var Ro={};b(Ro,{AtrulePrelude:()=>za,Selector:()=>Ra,Value:()=>qa});var Eh=35,Lh=42,Na=43,Ph=45,Ih=47,Dh=117;function bt(e){switch(this.tokenType){case 4:return this.Hash();case 18:return this.Operator();case 21:return this.Parentheses(this.readSequence,e.recognizer);case 19:return this.Brackets(this.readSequence,e.recognizer);case 5:return this.String();case 12:return this.Dimension();case 11:return this.Percentage();case 10:return this.Number();case 2:return this.cmpStr(this.tokenStart,this.tokenEnd,"url(")?this.Url():this.Function(this.readSequence,e.recognizer);case 7:return this.Url();case 1:return this.cmpChar(this.tokenStart,Dh)&&this.cmpChar(this.tokenStart+1,Na)?this.UnicodeRange():this.Identifier();case 9:{let t=this.charCodeAt(this.tokenStart);if(t===Ih||t===Lh||t===Na||t===Ph)return this.Operator();t===Eh&&this.error("Hex or identifier is expected",this.tokenStart+1);break}}}var za={getNode:bt};var Oh=35,Nh=38,zh=42,Mh=43,Rh=47,Ma=46,Fh=62,Bh=124,_h=126;function qh(e,t){t.last!==null&&t.last.type!=="Combinator"&&e!==null&&e.type!=="Combinator"&&t.push({type:"Combinator",loc:null,name:" "});}function Uh(){switch(this.tokenType){case 19:return this.AttributeSelector();case 4:return this.IdSelector();case 16:return this.lookupType(1)===16?this.PseudoElementSelector():this.PseudoClassSelector();case 1:return this.TypeSelector();case 10:case 11:return this.Percentage();case 12:this.charCodeAt(this.tokenStart)===Ma&&this.error("Identifier is expected",this.tokenStart+1);break;case 9:{switch(this.charCodeAt(this.tokenStart)){case Mh:case Fh:case _h:case Rh:return this.Combinator();case Ma:return this.ClassSelector();case zh:case Bh:return this.TypeSelector();case Oh:return this.IdSelector();case Nh:return this.NestingSelector()}break}}}var Ra={onWhiteSpace:qh,getNode:Uh};function Fa(){return this.createSingleNodeList(this.Raw(this.tokenIndex,null,!1))}function Ba(){let e=this.createList();if(this.skipSC(),e.push(this.Identifier()),this.skipSC(),this.tokenType===18){e.push(this.Operator());let t=this.tokenIndex,r=this.parseCustomProperty?this.Value(null):this.Raw(this.tokenIndex,this.consumeUntilExclamationMarkOrSemicolon,!1);if(r.type==="Value"&&r.children.isEmpty){for(let n=t-this.tokenIndex;n<=0;n++)if(this.lookupType(n)===13){r.children.appendData({type:"WhiteSpace",loc:null,value:" "});break}}e.push(r);}return e}function _a(e){return e!==null&&e.type==="Operator"&&(e.value[e.value.length-1]==="-"||e.value[e.value.length-1]==="+")}var qa={getNode:bt,onWhiteSpace(e,t){_a(e)&&(e.value=" "+e.value),_a(t.last)&&(t.last.value+=" ");},expression:Fa,var:Ba};var Ua={parse:{prelude:null,block(){return this.Block(!0)}}};var ja={parse:{prelude(){let e=this.createList();switch(this.skipSC(),this.tokenType){case 5:e.push(this.String());break;case 7:case 2:e.push(this.Url());break;default:this.error("String or url() is expected");}return (this.lookupNonWSType(0)===1||this.lookupNonWSType(0)===21)&&e.push(this.MediaQueryList()),e},block:null}};var Wa={parse:{prelude(){return this.createSingleNodeList(this.MediaQueryList())},block(e=!1){return this.Block(e)}}};var Ha={parse:{prelude(){return this.createSingleNodeList(this.SelectorList())},block(){return this.Block(!0)}}};var Ya={parse:{prelude(){return this.createSingleNodeList(this.SelectorList())},block(){return this.Block(!0)}}};function jh(){return this.createSingleNodeList(this.Raw(this.tokenIndex,null,!1))}function Wh(){return this.skipSC(),this.tokenType===1&&this.lookupNonWSType(1)===16?this.createSingleNodeList(this.Declaration()):Ga.call(this)}function Ga(){let e=this.createList(),t;this.skipSC();e:for(;!this.eof;){switch(this.tokenType){case 25:case 13:this.next();continue;case 2:t=this.Function(jh,this.scope.AtrulePrelude);break;case 1:t=this.Identifier();break;case 21:t=this.Parentheses(Wh,this.scope.AtrulePrelude);break;default:break e}e.push(t);}return e}var Va={parse:{prelude(){let e=Ga.call(this);return this.getFirstListNode(e)===null&&this.error("Condition is expected"),e},block(e=!1){return this.Block(e)}}};var Ka={"font-face":Ua,import:ja,media:Wa,nest:Ha,page:Ya,supports:Va};var De={parse(){return this.createSingleNodeList(this.SelectorList())}},Fo={parse(){return this.createSingleNodeList(this.Selector())}},Qa={parse(){return this.createSingleNodeList(this.Identifier())}},er={parse(){return this.createSingleNodeList(this.Nth())}},Xa={dir:Qa,has:De,lang:Qa,matches:De,is:De,"-moz-any":De,"-webkit-any":De,where:De,not:De,"nth-child":er,"nth-last-child":er,"nth-last-of-type":er,"nth-of-type":er,slotted:Fo,host:Fo,"host-context":Fo};var Bo={};b(Bo,{AnPlusB:()=>Qr,Atrule:()=>$r,AtrulePrelude:()=>Jr,AttributeSelector:()=>rn,Block:()=>on,Brackets:()=>sn,CDC:()=>cn,CDO:()=>pn,ClassSelector:()=>mn,Combinator:()=>dn,Comment:()=>bn,Declaration:()=>yn,DeclarationList:()=>vn,Dimension:()=>Cn,Function:()=>Tn,Hash:()=>Ln,IdSelector:()=>On,Identifier:()=>In,MediaFeature:()=>zn,MediaQuery:()=>Rn,MediaQueryList:()=>Bn,NestingSelector:()=>qn,Nth:()=>jn,Number:()=>Hn,Operator:()=>Gn,Parentheses:()=>Kn,Percentage:()=>Xn,PseudoClassSelector:()=>Zn,PseudoElementSelector:()=>eo,Ratio:()=>ro,Raw:()=>oo,Rule:()=>ao,Selector:()=>lo,SelectorList:()=>uo,String:()=>go,StyleSheet:()=>xo,TypeSelector:()=>wo,UnicodeRange:()=>Co,Url:()=>Io,Value:()=>Oo,WhiteSpace:()=>zo});var $a={parseContext:{default:"StyleSheet",stylesheet:"StyleSheet",atrule:"Atrule",atrulePrelude(e){return this.AtrulePrelude(e.atrule?String(e.atrule):null)},mediaQueryList:"MediaQueryList",mediaQuery:"MediaQuery",rule:"Rule",selectorList:"SelectorList",selector:"Selector",block(){return this.Block(!0)},declarationList:"DeclarationList",declaration:"Declaration",value:"Value"},scope:Ro,atrule:Ka,pseudo:Xa,node:Bo};var Za={node:gt};var Ja=Vr({...Oa,...$a,...Za});var ts={};b(ts,{decode:()=>Hh,encode:()=>Yh});var es=92;function Hh(e){let t=e.length-1,r="";for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);if(o===es){if(n===t)break;if(o=e.charCodeAt(++n),$(es,o)){let i=n-1,s=se(e,i);n=s-1,r+=Re(e.substring(i+1,s));}else o===13&&e.charCodeAt(n+1)===10&&n++;}else r+=e[n];}return r}function Yh(e){let t="";if(e.length===1&&e.charCodeAt(0)===45)return "\\-";for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n===0){t+="\uFFFD";continue}if(n<=31||n===127||n>=48&&n<=57&&(r===0||r===1&&e.charCodeAt(0)===45)){t+="\\"+n.toString(16)+" ";continue}Ne(n)?t+=e.charAt(r):t+="\\"+e.charAt(r);}return t}var{tokenize:fb,parse:db,generate:gb,lexer:bb,createLexer:xb,walk:yb,find:kb,findLast:wb,findAll:vb,toPlainObject:Sb,fromPlainObject:Cb,fork:Ab}=Ja;

// CSS Syntax Module Level 3
// https://www.w3.org/TR/css-syntax-3/
const EOF = 0;                 // <EOF-token>
const Ident = 1;               // <ident-token>
const Function$1 = 2;            // <function-token>
const Delim = 9;               // <delim-token>
const Number$1 = 10;             // <number-token>
const Dimension = 12;          // <dimension-token>
const WhiteSpace = 13;         // <whitespace-token>
const Colon = 16;              // <colon-token>     :
const LeftParenthesis = 21;    // <(-token>
const RightParenthesis = 22;   // <)-token>
const LeftCurlyBracket = 23;   // <{-token>
const Comment$2 = 25;

// https://drafts.csswg.org/css-syntax-3/
// § 4.2. Definitions

// digit
// A code point between U+0030 DIGIT ZERO (0) and U+0039 DIGIT NINE (9).
function isDigit(code) {
    return code >= 0x0030 && code <= 0x0039;
}

// uppercase letter
// A code point between U+0041 LATIN CAPITAL LETTER A (A) and U+005A LATIN CAPITAL LETTER Z (Z).
function isUppercaseLetter(code) {
    return code >= 0x0041 && code <= 0x005A;
}

// lowercase letter
// A code point between U+0061 LATIN SMALL LETTER A (a) and U+007A LATIN SMALL LETTER Z (z).
function isLowercaseLetter(code) {
    return code >= 0x0061 && code <= 0x007A;
}

// letter
// An uppercase letter or a lowercase letter.
function isLetter(code) {
    return isUppercaseLetter(code) || isLowercaseLetter(code);
}

// non-ASCII code point
// A code point with a value equal to or greater than U+0080 <control>.
function isNonAscii(code) {
    return code >= 0x0080;
}

// name-start code point
// A letter, a non-ASCII code point, or U+005F LOW LINE (_).
function isNameStart(code) {
    return isLetter(code) || isNonAscii(code) || code === 0x005F;
}

// non-printable code point
// A code point between U+0000 NULL and U+0008 BACKSPACE, or U+000B LINE TABULATION,
// or a code point between U+000E SHIFT OUT and U+001F INFORMATION SEPARATOR ONE, or U+007F DELETE.
function isNonPrintable(code) {
    return (
        (code >= 0x0000 && code <= 0x0008) ||
        (code === 0x000B) ||
        (code >= 0x000E && code <= 0x001F) ||
        (code === 0x007F)
    );
}

// newline
// U+000A LINE FEED. Note that U+000D CARRIAGE RETURN and U+000C FORM FEED are not included in this definition,
// as they are converted to U+000A LINE FEED during preprocessing.
// TODO: we doesn't do a preprocessing, so check a code point for U+000D CARRIAGE RETURN and U+000C FORM FEED
function isNewline(code) {
    return code === 0x000A || code === 0x000D || code === 0x000C;
}

// whitespace
// A newline, U+0009 CHARACTER TABULATION, or U+0020 SPACE.
function isWhiteSpace(code) {
    return isNewline(code) || code === 0x0020 || code === 0x0009;
}

// Fast code category
// Only ASCII code points has a special meaning, that's why we define a maps for 0..127 codes only
const CATEGORY = new Array(0x80);
const EofCategory = 0x80;
const WhiteSpaceCategory = 0x82;
const DigitCategory = 0x83;
const NameStartCategory = 0x84;
const NonPrintableCategory = 0x85;

for (let i = 0; i < CATEGORY.length; i++) {
    CATEGORY[i] =
        isWhiteSpace(i) && WhiteSpaceCategory ||
        isDigit(i) && DigitCategory ||
        isNameStart(i) && NameStartCategory ||
        isNonPrintable(i) && NonPrintableCategory ||
        i || EofCategory;
}

// @ts-nocheck

const name$6 = 'Comparison';
const structure$6 = {
	value: String
};

function parse$8() {
	const start = this.tokenStart;

	const char1 = this.consume(Delim);

	// The first character in the comparison operator must match '<', '=', or '>'.
	if (char1 !== '<' && char1 !== '>' && char1 !== '=') {
		this.error('Malformed comparison operator');
	}

	let char2;

	if (this.tokenType === Delim) {
		char2 = this.consume(Delim);

		// The second character in the comparison operator must match '='.
		if (char2 !== '=') {
			this.error('Malformed comparison operator');
		}
	}

	// If the next token is also 'Delim' then it is malformed.
	if (this.tokenType === Delim) {
		this.error('Malformed comparison operator');
	}

	const value = char2 ? `${char1}${char2}` : char1;

	return {
		type: 'Comparison',
		loc: this.getLocation(start, this.tokenStart),
		value
	};
}

function generate$6(node) {
	for (let index = 0; index < node.value.length; index++) {
		this.token(Delim, node.value.charAt(index));
	}
}

var comparison = /*#__PURE__*/Object.freeze({
__proto__: null,
generate: generate$6,
name: name$6,
parse: parse$8,
structure: structure$6
});

// @ts-nocheck

const name$5 = 'ContainerFeatureStyle';
const structure$5 = {
	name: String,
	value: ['Function', 'Identifier', 'Number', 'Dimension', 'QueryCSSFunction', 'Ratio', null]
};

function parse$7() {
	const start = this.tokenStart;
	let value = null;

	const function_name = this.consumeFunctionName();
	if (function_name !== 'style') {
		this.error('Unknown container style query identifier; "style" is expected');
	}

	this.skipSC();

	const name = this.consume(Ident);
	this.skipSC();

	if (this.tokenType !== RightParenthesis) {
		this.eat(Colon);
		this.skipSC();

		switch (this.tokenType) {
			case Number$1:
				if (this.lookupNonWSType(1) === Delim) {
					value = this.Ratio();
				} else {
					value = this.Number();
				}
				break;

			case Dimension:
				value = this.Dimension();
				break;

			case Function$1:
				value = this.QueryCSSFunction();
				break;

			case Ident:
				value = this.Identifier();
				break;

			default:
				this.error('Number, dimension, ratio, function or identifier is expected');
				break;
		}

		this.skipSC();
	}

	this.eat(RightParenthesis);

	return {
		type: 'ContainerFeatureStyle',
		loc: this.getLocation(start, this.tokenStart),
		name,
		value
	};
}

function generate$5(node) {
	this.token(Function$1, 'style(');
	this.token(Ident, node.name);

	if (node.value !== null) {
		this.token(Colon, ':');
		this.node(node.value);
	}

	this.token(RightParenthesis, ')');
}

var container_feature_style = /*#__PURE__*/Object.freeze({
__proto__: null,
generate: generate$5,
name: name$5,
parse: parse$7,
structure: structure$5
});

// @ts-nocheck

/**
 * Looks ahead to determine if query feature is a range query. This involves locating at least one delimiter and no
 * colon tokens.
 *
 * @returns {boolean} Is potential range query.
 */
function lookahead_is_range() {
	let type;
	let offset = 0;

	let count = 0;
	let delim_found = false;
	let no_colon = true;

	// A range query has maximum 5 tokens when formatted as 'mf-range' /
	// '<mf-value> <mf-lt> <mf-name> <mf-lt> <mf-value>'. So only look ahead maximum of 6 non-whitespace tokens.
	do {
		type = this.lookupNonWSType(offset++);
		if (type !== WhiteSpace) {
			count++;
		}
		if (type === Delim) {
			delim_found = true;
		}
		if (type === Colon) {
			no_colon = false;
		}
		if (type === LeftCurlyBracket || type === RightParenthesis) {
			break;
		}
	} while (type !== EOF && count <= 6);

	return delim_found && no_colon;
}

// @ts-nocheck

const CONTAINER_QUERY_KEYWORDS = new Set(['none', 'and', 'not', 'or']);

const name$4 = 'ContainerQuery';
const structure$4 = {
	name: 'Identifier',
	children: [
		['Identifier', 'QueryFeature', 'QueryFeatureRange', 'ContainerFeatureStyle', 'WhiteSpace']
	]
};

function parse$6() {
	const start = this.tokenStart;
	const children = this.createList();
	let child = null;
	let name = null;

	// Parse potential container name.
	if (this.tokenType === Ident) {
		const container_name = this.substring(this.tokenStart, this.tokenEnd);

		// Container name doesn't match a query keyword, so assign it as container name.
		if (!CONTAINER_QUERY_KEYWORDS.has(container_name.toLowerCase())) {
			name = container_name;
			this.eatIdent(container_name);
		}
	}

	this.skipSC();

	scan: while (!this.eof) {
		switch (this.tokenType) {
			case Comment$2:
			case WhiteSpace:
				this.next();
				continue;

			case Ident:
				child = this.Identifier();
				break;

			case Function$1:
				child = this.ContainerFeatureStyle();
				break;

			case LeftParenthesis:
				// Lookahead to determine if range feature.
				child = lookahead_is_range.call(this) ? this.QueryFeatureRange() : this.QueryFeature();
				break;

			default:
				break scan;
		}

		children.push(child);
	}

	if (child === null) {
		this.error('Identifier or parenthesis is expected');
	}

	return {
		type: 'ContainerQuery',
		loc: this.getLocation(start, this.tokenStart - 1),
		name,
		children
	};
}

function generate$4(node) {
	if (typeof node.name === 'string') {
		this.token(Ident, node.name);
	}

	this.children(node);
}

var container_query = /*#__PURE__*/Object.freeze({
__proto__: null,
generate: generate$4,
name: name$4,
parse: parse$6,
structure: structure$4
});

// @ts-nocheck

const name$3 = 'MediaQuery';
const structure$3 = {
	children: [['Identifier', 'QueryFeature', 'QueryFeatureRange', 'WhiteSpace']]
};

function parse$5() {
	const children = this.createList();
	let child = null;

	this.skipSC();

	scan: while (!this.eof) {
		switch (this.tokenType) {
			case Comment$2:
			case WhiteSpace:
				this.next();
				continue;

			case Ident:
				child = this.Identifier();
				break;

			case LeftParenthesis:
				// Lookahead to determine if range feature.
				child = lookahead_is_range.call(this) ? this.QueryFeatureRange() : this.QueryFeature();
				break;

			default:
				break scan;
		}

		children.push(child);
	}

	if (child === null) {
		this.error('Identifier or parenthesis is expected');
	}

	return {
		type: 'MediaQuery',
		loc: this.getLocationFromList(children),
		children
	};
}

function generate$3(node) {
	this.children(node);
}

var media_query = /*#__PURE__*/Object.freeze({
__proto__: null,
generate: generate$3,
name: name$3,
parse: parse$5,
structure: structure$3
});

// @ts-nocheck

const name$2 = 'QueryFeature';
const structure$2 = {
	name: String,
	value: ['Identifier', 'Number', 'Dimension', 'QueryCSSFunction', 'Ratio', null]
};

function parse$4() {
	const start = this.tokenStart;
	let value = null;

	this.eat(LeftParenthesis);
	this.skipSC();

	const name = this.consume(Ident);
	this.skipSC();

	if (this.tokenType !== RightParenthesis) {
		this.eat(Colon);
		this.skipSC();

		switch (this.tokenType) {
			case Number$1:
				if (this.lookupNonWSType(1) === Delim) {
					value = this.Ratio();
				} else {
					value = this.Number();
				}
				break;

			case Dimension:
				value = this.Dimension();
				break;

			case Function$1:
				value = this.QueryCSSFunction();
				break;

			case Ident:
				value = this.Identifier();
				break;

			default:
				this.error('Number, dimension, ratio, function, or identifier is expected');
				break;
		}

		this.skipSC();
	}

	this.eat(RightParenthesis);

	return {
		type: 'QueryFeature',
		loc: this.getLocation(start, this.tokenStart),
		name,
		value
	};
}

function generate$2(node) {
	this.token(LeftParenthesis, '(');
	this.token(Ident, node.name);

	if (node.value !== null) {
		this.token(Colon, ':');
		this.node(node.value);
	}

	this.token(RightParenthesis, ')');
}

var query_feature = /*#__PURE__*/Object.freeze({
__proto__: null,
generate: generate$2,
name: name$2,
parse: parse$4,
structure: structure$2
});

// @ts-nocheck

const name$1 = 'QueryFeatureRange';
const structure$1 = {
	name: String,
	value: ['Identifier', 'Number', 'Comparison', 'Dimension', 'QueryCSSFunction', 'Ratio', null]
};

function lookup_non_WS_type_and_value(offset, type, referenceStr) {
	let current_type;

	do {
		current_type = this.lookupType(offset++);
		if (current_type !== WhiteSpace) {
			break;
		}
	} while (current_type !== 0); // NULL -> 0

	return current_type === type ? this.lookupValue(offset - 1, referenceStr) : false;
}

function parse$3() {
	const start = this.tokenStart;
	const children = this.createList();
	let child = null;

	this.eat(LeftParenthesis);
	this.skipSC();

	while (!this.eof && this.tokenType !== RightParenthesis) {
		switch (this.tokenType) {
			case Number$1:
				if (lookup_non_WS_type_and_value.call(this, 1, Delim, '/')) {
					child = this.Ratio();
				} else {
					child = this.Number();
				}
				break;

			case Delim:
				child = this.Comparison();
				break;

			case Dimension:
				child = this.Dimension();
				break;

			case Function$1:
				child = this.QueryCSSFunction();
				break;

			case Ident:
				child = this.Identifier();
				break;

			default:
				this.error('Number, dimension, comparison, ratio, function, or identifier is expected');
				break;
		}

		children.push(child);

		this.skipSC();
	}

	this.eat(RightParenthesis);

	return {
		type: 'QueryFeatureRange',
		loc: this.getLocation(start, this.tokenStart),
		children
	};
}

function generate$1(node) {
	this.children(node);
}

var query_feature_range = /*#__PURE__*/Object.freeze({
__proto__: null,
generate: generate$1,
name: name$1,
parse: parse$3,
structure: structure$1
});

// @ts-nocheck

const QUERY_CSS_FUNCTIONS = new Set(['calc', 'clamp', 'min', 'max']);

const name = 'QueryCSSFunction';
const structure = {
	name: String,
	expression: String
};

function parse$2() {
	const start = this.tokenStart;

	const name = this.consumeFunctionName();

	if (!QUERY_CSS_FUNCTIONS.has(name)) {
		this.error('Unknown query single value function; expected: "calc", "clamp", "max", min"');
	}

	const body = this.Raw(this.tokenIndex, null, false);

	this.eat(RightParenthesis);

	return {
		type: 'QueryCSSFunction',
		loc: this.getLocation(start, this.tokenStart),
		name,
		expression: body.value
	};
}

function generate(node) {
	this.token(Function, `${node.name}(`);

	this.node(node.expression);

	this.token(RightParenthesis, ')');
}

var query_css_function = /*#__PURE__*/Object.freeze({
__proto__: null,
generate: generate,
name: name,
parse: parse$2,
structure: structure
});

var node = /*#__PURE__*/Object.freeze({
__proto__: null,
Comparison: comparison,
ContainerFeatureStyle: container_feature_style,
ContainerQuery: container_query,
MediaQuery: media_query,
QueryCSSFunction: query_css_function,
QueryFeature: query_feature,
QueryFeatureRange: query_feature_range
});

// @ts-nocheck

/**
 * Extends `css-tree` for container query support by forking and adding new nodes and at-rule support for `@container`.
 *
 * The new nodes are located in `./node`.
 */
const cqSyntax = Ab({
	atrule: {
		// extend or override at-rule dictionary
		container: {
			parse: {
				prelude() {
					return this.createSingleNodeList(this.ContainerQuery());
				},
				block(isStyleBlock = false) {
					return this.Block(isStyleBlock);
				}
			}
		}
	},
	node
});

const parse$1 = cqSyntax.parse;

// @ts-ignore
// import parse from 'css-tree/parser'; // When css-tree supports container queries uncomment.

const regex_closing_style_tag = /<\/style\s*>/;
const regex_starts_with_closing_style_tag = /^<\/style\s*>/;

/**
 *
 * @param {import('../index.js').Parser} parser
 * @param {number} start
 * @param {import('estree').Node[]} attributes
 * @returns {import('../../interfaces.js').Style}
 */
function read_style(parser, start, attributes) {
	const content_start = parser.index;

	const styles = parser.read_until(regex_closing_style_tag, parser_errors.unclosed_style);

	if (parser.index >= parser.template.length) {
		parser.error(parser_errors.unclosed_style);
	}

	const content_end = parser.index;

	// discard styles when css is disabled
	if (parser.css_mode === 'none') {
		parser.read(regex_starts_with_closing_style_tag);
		return null;
	}

	let ast;

	try {
		ast = parse$1(styles, {
			positions: true,
			offset: content_start,
			onParseError(error) {
				throw error;
			}
		});
	} catch (err) {
		if (err.name === 'SyntaxError') {
			parser.error(parser_errors.css_syntax_error(err.message), err.offset);
		} else {
			throw err;
		}
	}

	ast = JSON.parse(JSON.stringify(ast));

	// tidy up AST
	walk(ast, {
		/** @param {any} node */
		enter: (node) => {
			// `any` because this isn't an ESTree node
			// replace `ref:a` nodes
			if (node.type === 'Selector') {
				for (let i = 0; i < node.children.length; i += 1) {
					const a = node.children[i];
					const b = node.children[i + 1];

					if (is_ref_selector(a, b)) {
						parser.error(parser_errors.invalid_ref_selector, a.loc.start.offset);
					}
				}
			}

			if (
				node.type === 'Declaration' &&
				node.value.type === 'Value' &&
				node.value.children.length === 0
			) {
				parser.error(parser_errors.invalid_declaration, node.start);
			}

			if (node.type === 'PseudoClassSelector' && node.name === 'global' && node.children === null) {
				parser.error(parser_errors.empty_global_selector, node.loc.start.offset);
			}

			if (node.loc) {
				node.start = node.loc.start.offset;
				node.end = node.loc.end.offset;
				delete node.loc;
			}
		}
	});

	parser.read(regex_starts_with_closing_style_tag);

	const end = parser.index;

	return {
		type: 'Style',
		start,
		end,
		attributes,
		children: ast.children,
		content: {
			start: content_start,
			end: content_end,
			styles
		}
	};
}

/**
 * @param {any} a
 * @param {any} b
 */
function is_ref_selector(a, b) {
	// TODO add CSS node types
	if (!b) return false;

	return a.type === 'TypeSelector' && a.name === 'ref' && b.type === 'PseudoClassSelector';
}

// https://html.spec.whatwg.org/entities.json from https://dev.w3.org/html5/html-author/charref
var entities = {
	'CounterClockwiseContourIntegral;': 8755,
	'ClockwiseContourIntegral;': 8754,
	'DoubleLongLeftRightArrow;': 10234,
	'NotNestedGreaterGreater;': 10914,
	'DiacriticalDoubleAcute;': 733,
	'NotSquareSupersetEqual;': 8931,
	'CloseCurlyDoubleQuote;': 8221,
	'DoubleContourIntegral;': 8751,
	'FilledVerySmallSquare;': 9642,
	'NegativeVeryThinSpace;': 8203,
	'NotPrecedesSlantEqual;': 8928,
	'NotRightTriangleEqual;': 8941,
	'NotSucceedsSlantEqual;': 8929,
	'CapitalDifferentialD;': 8517,
	'DoubleLeftRightArrow;': 8660,
	'DoubleLongRightArrow;': 10233,
	'EmptyVerySmallSquare;': 9643,
	'NestedGreaterGreater;': 8811,
	'NotDoubleVerticalBar;': 8742,
	'NotGreaterSlantEqual;': 10878,
	'NotLeftTriangleEqual;': 8940,
	'NotSquareSubsetEqual;': 8930,
	'OpenCurlyDoubleQuote;': 8220,
	'ReverseUpEquilibrium;': 10607,
	'DoubleLongLeftArrow;': 10232,
	'DownLeftRightVector;': 10576,
	'LeftArrowRightArrow;': 8646,
	'NegativeMediumSpace;': 8203,
	'NotGreaterFullEqual;': 8807,
	'NotRightTriangleBar;': 10704,
	'RightArrowLeftArrow;': 8644,
	'SquareSupersetEqual;': 8850,
	'leftrightsquigarrow;': 8621,
	'DownRightTeeVector;': 10591,
	'DownRightVectorBar;': 10583,
	'LongLeftRightArrow;': 10231,
	'Longleftrightarrow;': 10234,
	'NegativeThickSpace;': 8203,
	'NotLeftTriangleBar;': 10703,
	'PrecedesSlantEqual;': 8828,
	'ReverseEquilibrium;': 8651,
	'RightDoubleBracket;': 10215,
	'RightDownTeeVector;': 10589,
	'RightDownVectorBar;': 10581,
	'RightTriangleEqual;': 8885,
	'SquareIntersection;': 8851,
	'SucceedsSlantEqual;': 8829,
	'blacktriangleright;': 9656,
	'longleftrightarrow;': 10231,
	'DoubleUpDownArrow;': 8661,
	'DoubleVerticalBar;': 8741,
	'DownLeftTeeVector;': 10590,
	'DownLeftVectorBar;': 10582,
	'FilledSmallSquare;': 9724,
	'GreaterSlantEqual;': 10878,
	'LeftDoubleBracket;': 10214,
	'LeftDownTeeVector;': 10593,
	'LeftDownVectorBar;': 10585,
	'LeftTriangleEqual;': 8884,
	'NegativeThinSpace;': 8203,
	'NotGreaterGreater;': 8811,
	'NotLessSlantEqual;': 10877,
	'NotNestedLessLess;': 10913,
	'NotReverseElement;': 8716,
	'NotSquareSuperset;': 8848,
	'NotTildeFullEqual;': 8775,
	'RightAngleBracket;': 10217,
	'RightUpDownVector;': 10575,
	'SquareSubsetEqual;': 8849,
	'VerticalSeparator;': 10072,
	'blacktriangledown;': 9662,
	'blacktriangleleft;': 9666,
	'leftrightharpoons;': 8651,
	'rightleftharpoons;': 8652,
	'twoheadrightarrow;': 8608,
	'DiacriticalAcute;': 180,
	'DiacriticalGrave;': 96,
	'DiacriticalTilde;': 732,
	'DoubleRightArrow;': 8658,
	'DownArrowUpArrow;': 8693,
	'EmptySmallSquare;': 9723,
	'GreaterEqualLess;': 8923,
	'GreaterFullEqual;': 8807,
	'LeftAngleBracket;': 10216,
	'LeftUpDownVector;': 10577,
	'LessEqualGreater;': 8922,
	'NonBreakingSpace;': 160,
	'NotPrecedesEqual;': 10927,
	'NotRightTriangle;': 8939,
	'NotSucceedsEqual;': 10928,
	'NotSucceedsTilde;': 8831,
	'NotSupersetEqual;': 8841,
	'RightTriangleBar;': 10704,
	'RightUpTeeVector;': 10588,
	'RightUpVectorBar;': 10580,
	'UnderParenthesis;': 9181,
	'UpArrowDownArrow;': 8645,
	'circlearrowright;': 8635,
	'downharpoonright;': 8642,
	'ntrianglerighteq;': 8941,
	'rightharpoondown;': 8641,
	'rightrightarrows;': 8649,
	'twoheadleftarrow;': 8606,
	'vartriangleright;': 8883,
	'CloseCurlyQuote;': 8217,
	'ContourIntegral;': 8750,
	'DoubleDownArrow;': 8659,
	'DoubleLeftArrow;': 8656,
	'DownRightVector;': 8641,
	'LeftRightVector;': 10574,
	'LeftTriangleBar;': 10703,
	'LeftUpTeeVector;': 10592,
	'LeftUpVectorBar;': 10584,
	'LowerRightArrow;': 8600,
	'NotGreaterEqual;': 8817,
	'NotGreaterTilde;': 8821,
	'NotHumpDownHump;': 8782,
	'NotLeftTriangle;': 8938,
	'NotSquareSubset;': 8847,
	'OverParenthesis;': 9180,
	'RightDownVector;': 8642,
	'ShortRightArrow;': 8594,
	'UpperRightArrow;': 8599,
	'bigtriangledown;': 9661,
	'circlearrowleft;': 8634,
	'curvearrowright;': 8631,
	'downharpoonleft;': 8643,
	'leftharpoondown;': 8637,
	'leftrightarrows;': 8646,
	'nLeftrightarrow;': 8654,
	'nleftrightarrow;': 8622,
	'ntrianglelefteq;': 8940,
	'rightleftarrows;': 8644,
	'rightsquigarrow;': 8605,
	'rightthreetimes;': 8908,
	'straightepsilon;': 1013,
	'trianglerighteq;': 8885,
	'vartriangleleft;': 8882,
	'DiacriticalDot;': 729,
	'DoubleRightTee;': 8872,
	'DownLeftVector;': 8637,
	'GreaterGreater;': 10914,
	'HorizontalLine;': 9472,
	'InvisibleComma;': 8291,
	'InvisibleTimes;': 8290,
	'LeftDownVector;': 8643,
	'LeftRightArrow;': 8596,
	'Leftrightarrow;': 8660,
	'LessSlantEqual;': 10877,
	'LongRightArrow;': 10230,
	'Longrightarrow;': 10233,
	'LowerLeftArrow;': 8601,
	'NestedLessLess;': 8810,
	'NotGreaterLess;': 8825,
	'NotLessGreater;': 8824,
	'NotSubsetEqual;': 8840,
	'NotVerticalBar;': 8740,
	'OpenCurlyQuote;': 8216,
	'ReverseElement;': 8715,
	'RightTeeVector;': 10587,
	'RightVectorBar;': 10579,
	'ShortDownArrow;': 8595,
	'ShortLeftArrow;': 8592,
	'SquareSuperset;': 8848,
	'TildeFullEqual;': 8773,
	'UpperLeftArrow;': 8598,
	'ZeroWidthSpace;': 8203,
	'curvearrowleft;': 8630,
	'doublebarwedge;': 8966,
	'downdownarrows;': 8650,
	'hookrightarrow;': 8618,
	'leftleftarrows;': 8647,
	'leftrightarrow;': 8596,
	'leftthreetimes;': 8907,
	'longrightarrow;': 10230,
	'looparrowright;': 8620,
	'nshortparallel;': 8742,
	'ntriangleright;': 8939,
	'rightarrowtail;': 8611,
	'rightharpoonup;': 8640,
	'trianglelefteq;': 8884,
	'upharpoonright;': 8638,
	'ApplyFunction;': 8289,
	'DifferentialD;': 8518,
	'DoubleLeftTee;': 10980,
	'DoubleUpArrow;': 8657,
	'LeftTeeVector;': 10586,
	'LeftVectorBar;': 10578,
	'LessFullEqual;': 8806,
	'LongLeftArrow;': 10229,
	'Longleftarrow;': 10232,
	'NotEqualTilde;': 8770,
	'NotTildeEqual;': 8772,
	'NotTildeTilde;': 8777,
	'Poincareplane;': 8460,
	'PrecedesEqual;': 10927,
	'PrecedesTilde;': 8830,
	'RightArrowBar;': 8677,
	'RightTeeArrow;': 8614,
	'RightTriangle;': 8883,
	'RightUpVector;': 8638,
	'SucceedsEqual;': 10928,
	'SucceedsTilde;': 8831,
	'SupersetEqual;': 8839,
	'UpEquilibrium;': 10606,
	'VerticalTilde;': 8768,
	'VeryThinSpace;': 8202,
	'bigtriangleup;': 9651,
	'blacktriangle;': 9652,
	'divideontimes;': 8903,
	'fallingdotseq;': 8786,
	'hookleftarrow;': 8617,
	'leftarrowtail;': 8610,
	'leftharpoonup;': 8636,
	'longleftarrow;': 10229,
	'looparrowleft;': 8619,
	'measuredangle;': 8737,
	'ntriangleleft;': 8938,
	'shortparallel;': 8741,
	'smallsetminus;': 8726,
	'triangleright;': 9657,
	'upharpoonleft;': 8639,
	'varsubsetneqq;': 10955,
	'varsupsetneqq;': 10956,
	'DownArrowBar;': 10515,
	'DownTeeArrow;': 8615,
	'ExponentialE;': 8519,
	'GreaterEqual;': 8805,
	'GreaterTilde;': 8819,
	'HilbertSpace;': 8459,
	'HumpDownHump;': 8782,
	'Intersection;': 8898,
	'LeftArrowBar;': 8676,
	'LeftTeeArrow;': 8612,
	'LeftTriangle;': 8882,
	'LeftUpVector;': 8639,
	'NotCongruent;': 8802,
	'NotHumpEqual;': 8783,
	'NotLessEqual;': 8816,
	'NotLessTilde;': 8820,
	'Proportional;': 8733,
	'RightCeiling;': 8969,
	'RoundImplies;': 10608,
	'ShortUpArrow;': 8593,
	'SquareSubset;': 8847,
	'UnderBracket;': 9141,
	'VerticalLine;': 124,
	'blacklozenge;': 10731,
	'exponentiale;': 8519,
	'risingdotseq;': 8787,
	'triangledown;': 9663,
	'triangleleft;': 9667,
	'varsubsetneq;': 8842,
	'varsupsetneq;': 8843,
	'CircleMinus;': 8854,
	'CircleTimes;': 8855,
	'Equilibrium;': 8652,
	'GreaterLess;': 8823,
	'LeftCeiling;': 8968,
	'LessGreater;': 8822,
	'MediumSpace;': 8287,
	'NotLessLess;': 8810,
	'NotPrecedes;': 8832,
	'NotSucceeds;': 8833,
	'NotSuperset;': 8835,
	'OverBracket;': 9140,
	'RightVector;': 8640,
	'Rrightarrow;': 8667,
	'RuleDelayed;': 10740,
	'SmallCircle;': 8728,
	'SquareUnion;': 8852,
	'SubsetEqual;': 8838,
	'UpDownArrow;': 8597,
	'Updownarrow;': 8661,
	'VerticalBar;': 8739,
	'backepsilon;': 1014,
	'blacksquare;': 9642,
	'circledcirc;': 8858,
	'circleddash;': 8861,
	'curlyeqprec;': 8926,
	'curlyeqsucc;': 8927,
	'diamondsuit;': 9830,
	'eqslantless;': 10901,
	'expectation;': 8496,
	'nRightarrow;': 8655,
	'nrightarrow;': 8603,
	'preccurlyeq;': 8828,
	'precnapprox;': 10937,
	'quaternions;': 8461,
	'straightphi;': 981,
	'succcurlyeq;': 8829,
	'succnapprox;': 10938,
	'thickapprox;': 8776,
	'updownarrow;': 8597,
	'Bernoullis;': 8492,
	'CirclePlus;': 8853,
	'EqualTilde;': 8770,
	'Fouriertrf;': 8497,
	'ImaginaryI;': 8520,
	'Laplacetrf;': 8466,
	'LeftVector;': 8636,
	'Lleftarrow;': 8666,
	'NotElement;': 8713,
	'NotGreater;': 8815,
	'Proportion;': 8759,
	'RightArrow;': 8594,
	'RightFloor;': 8971,
	'Rightarrow;': 8658,
	'ThickSpace;': 8287,
	'TildeEqual;': 8771,
	'TildeTilde;': 8776,
	'UnderBrace;': 9183,
	'UpArrowBar;': 10514,
	'UpTeeArrow;': 8613,
	'circledast;': 8859,
	'complement;': 8705,
	'curlywedge;': 8911,
	'eqslantgtr;': 10902,
	'gtreqqless;': 10892,
	'lessapprox;': 10885,
	'lesseqqgtr;': 10891,
	'lmoustache;': 9136,
	'longmapsto;': 10236,
	'mapstodown;': 8615,
	'mapstoleft;': 8612,
	'nLeftarrow;': 8653,
	'nleftarrow;': 8602,
	'nsubseteqq;': 10949,
	'nsupseteqq;': 10950,
	'precapprox;': 10935,
	'rightarrow;': 8594,
	'rmoustache;': 9137,
	'sqsubseteq;': 8849,
	'sqsupseteq;': 8850,
	'subsetneqq;': 10955,
	'succapprox;': 10936,
	'supsetneqq;': 10956,
	'upuparrows;': 8648,
	'varepsilon;': 1013,
	'varnothing;': 8709,
	'Backslash;': 8726,
	'CenterDot;': 183,
	'CircleDot;': 8857,
	'Congruent;': 8801,
	'Coproduct;': 8720,
	'DoubleDot;': 168,
	'DownArrow;': 8595,
	'DownBreve;': 785,
	'Downarrow;': 8659,
	'HumpEqual;': 8783,
	'LeftArrow;': 8592,
	'LeftFloor;': 8970,
	'Leftarrow;': 8656,
	'LessTilde;': 8818,
	'Mellintrf;': 8499,
	'MinusPlus;': 8723,
	'NotCupCap;': 8813,
	'NotExists;': 8708,
	'NotSubset;': 8834,
	'OverBrace;': 9182,
	'PlusMinus;': 177,
	'Therefore;': 8756,
	'ThinSpace;': 8201,
	'TripleDot;': 8411,
	'UnionPlus;': 8846,
	'backprime;': 8245,
	'backsimeq;': 8909,
	'bigotimes;': 10754,
	'centerdot;': 183,
	'checkmark;': 10003,
	'complexes;': 8450,
	'dotsquare;': 8865,
	'downarrow;': 8595,
	'gtrapprox;': 10886,
	'gtreqless;': 8923,
	'gvertneqq;': 8809,
	'heartsuit;': 9829,
	'leftarrow;': 8592,
	'lesseqgtr;': 8922,
	'lvertneqq;': 8808,
	'ngeqslant;': 10878,
	'nleqslant;': 10877,
	'nparallel;': 8742,
	'nshortmid;': 8740,
	'nsubseteq;': 8840,
	'nsupseteq;': 8841,
	'pitchfork;': 8916,
	'rationals;': 8474,
	'spadesuit;': 9824,
	'subseteqq;': 10949,
	'subsetneq;': 8842,
	'supseteqq;': 10950,
	'supsetneq;': 8843,
	'therefore;': 8756,
	'triangleq;': 8796,
	'varpropto;': 8733,
	'DDotrahd;': 10513,
	'DotEqual;': 8784,
	'Integral;': 8747,
	'LessLess;': 10913,
	'NotEqual;': 8800,
	'NotTilde;': 8769,
	'PartialD;': 8706,
	'Precedes;': 8826,
	'RightTee;': 8866,
	'Succeeds;': 8827,
	'SuchThat;': 8715,
	'Superset;': 8835,
	'Uarrocir;': 10569,
	'UnderBar;': 95,
	'andslope;': 10840,
	'angmsdaa;': 10664,
	'angmsdab;': 10665,
	'angmsdac;': 10666,
	'angmsdad;': 10667,
	'angmsdae;': 10668,
	'angmsdaf;': 10669,
	'angmsdag;': 10670,
	'angmsdah;': 10671,
	'angrtvbd;': 10653,
	'approxeq;': 8778,
	'awconint;': 8755,
	'backcong;': 8780,
	'barwedge;': 8965,
	'bbrktbrk;': 9142,
	'bigoplus;': 10753,
	'bigsqcup;': 10758,
	'biguplus;': 10756,
	'bigwedge;': 8896,
	'boxminus;': 8863,
	'boxtimes;': 8864,
	'bsolhsub;': 10184,
	'capbrcup;': 10825,
	'circledR;': 174,
	'circledS;': 9416,
	'cirfnint;': 10768,
	'clubsuit;': 9827,
	'cupbrcap;': 10824,
	'curlyvee;': 8910,
	'cwconint;': 8754,
	'doteqdot;': 8785,
	'dotminus;': 8760,
	'drbkarow;': 10512,
	'dzigrarr;': 10239,
	'elinters;': 9191,
	'emptyset;': 8709,
	'eqvparsl;': 10725,
	'fpartint;': 10765,
	'geqslant;': 10878,
	'gesdotol;': 10884,
	'gnapprox;': 10890,
	'hksearow;': 10533,
	'hkswarow;': 10534,
	'imagline;': 8464,
	'imagpart;': 8465,
	'infintie;': 10717,
	'integers;': 8484,
	'intercal;': 8890,
	'intlarhk;': 10775,
	'laemptyv;': 10676,
	'ldrushar;': 10571,
	'leqslant;': 10877,
	'lesdotor;': 10883,
	'llcorner;': 8990,
	'lnapprox;': 10889,
	'lrcorner;': 8991,
	'lurdshar;': 10570,
	'mapstoup;': 8613,
	'multimap;': 8888,
	'naturals;': 8469,
	'ncongdot;': 10861,
	'notindot;': 8949,
	'otimesas;': 10806,
	'parallel;': 8741,
	'plusacir;': 10787,
	'pointint;': 10773,
	'precneqq;': 10933,
	'precnsim;': 8936,
	'profalar;': 9006,
	'profline;': 8978,
	'profsurf;': 8979,
	'raemptyv;': 10675,
	'realpart;': 8476,
	'rppolint;': 10770,
	'rtriltri;': 10702,
	'scpolint;': 10771,
	'setminus;': 8726,
	'shortmid;': 8739,
	'smeparsl;': 10724,
	'sqsubset;': 8847,
	'sqsupset;': 8848,
	'subseteq;': 8838,
	'succneqq;': 10934,
	'succnsim;': 8937,
	'supseteq;': 8839,
	'thetasym;': 977,
	'thicksim;': 8764,
	'timesbar;': 10801,
	'triangle;': 9653,
	'triminus;': 10810,
	'trpezium;': 9186,
	'ulcorner;': 8988,
	'urcorner;': 8989,
	'varkappa;': 1008,
	'varsigma;': 962,
	'vartheta;': 977,
	'Because;': 8757,
	'Cayleys;': 8493,
	'Cconint;': 8752,
	'Cedilla;': 184,
	'Diamond;': 8900,
	'DownTee;': 8868,
	'Element;': 8712,
	'Epsilon;': 917,
	'Implies;': 8658,
	'LeftTee;': 8867,
	'NewLine;': 10,
	'NoBreak;': 8288,
	'NotLess;': 8814,
	'Omicron;': 927,
	'OverBar;': 8254,
	'Product;': 8719,
	'UpArrow;': 8593,
	'Uparrow;': 8657,
	'Upsilon;': 933,
	'alefsym;': 8501,
	'angrtvb;': 8894,
	'angzarr;': 9084,
	'asympeq;': 8781,
	'backsim;': 8765,
	'because;': 8757,
	'bemptyv;': 10672,
	'between;': 8812,
	'bigcirc;': 9711,
	'bigodot;': 10752,
	'bigstar;': 9733,
	'bnequiv;': 8801,
	'boxplus;': 8862,
	'ccupssm;': 10832,
	'cemptyv;': 10674,
	'cirscir;': 10690,
	'coloneq;': 8788,
	'congdot;': 10861,
	'cudarrl;': 10552,
	'cudarrr;': 10549,
	'cularrp;': 10557,
	'curarrm;': 10556,
	'dbkarow;': 10511,
	'ddagger;': 8225,
	'ddotseq;': 10871,
	'demptyv;': 10673,
	'diamond;': 8900,
	'digamma;': 989,
	'dotplus;': 8724,
	'dwangle;': 10662,
	'epsilon;': 949,
	'eqcolon;': 8789,
	'equivDD;': 10872,
	'gesdoto;': 10882,
	'gtquest;': 10876,
	'gtrless;': 8823,
	'harrcir;': 10568,
	'intprod;': 10812,
	'isindot;': 8949,
	'larrbfs;': 10527,
	'larrsim;': 10611,
	'lbrksld;': 10639,
	'lbrkslu;': 10637,
	'ldrdhar;': 10599,
	'lesdoto;': 10881,
	'lessdot;': 8918,
	'lessgtr;': 8822,
	'lesssim;': 8818,
	'lotimes;': 10804,
	'lozenge;': 9674,
	'ltquest;': 10875,
	'luruhar;': 10598,
	'maltese;': 10016,
	'minusdu;': 10794,
	'napprox;': 8777,
	'natural;': 9838,
	'nearrow;': 8599,
	'nexists;': 8708,
	'notinva;': 8713,
	'notinvb;': 8951,
	'notinvc;': 8950,
	'notniva;': 8716,
	'notnivb;': 8958,
	'notnivc;': 8957,
	'npolint;': 10772,
	'npreceq;': 10927,
	'nsqsube;': 8930,
	'nsqsupe;': 8931,
	'nsubset;': 8834,
	'nsucceq;': 10928,
	'nsupset;': 8835,
	'nvinfin;': 10718,
	'nvltrie;': 8884,
	'nvrtrie;': 8885,
	'nwarrow;': 8598,
	'olcross;': 10683,
	'omicron;': 959,
	'orderof;': 8500,
	'orslope;': 10839,
	'pertenk;': 8241,
	'planckh;': 8462,
	'pluscir;': 10786,
	'plussim;': 10790,
	'plustwo;': 10791,
	'precsim;': 8830,
	'quatint;': 10774,
	'questeq;': 8799,
	'rarrbfs;': 10528,
	'rarrsim;': 10612,
	'rbrksld;': 10638,
	'rbrkslu;': 10640,
	'rdldhar;': 10601,
	'realine;': 8475,
	'rotimes;': 10805,
	'ruluhar;': 10600,
	'searrow;': 8600,
	'simplus;': 10788,
	'simrarr;': 10610,
	'subedot;': 10947,
	'submult;': 10945,
	'subplus;': 10943,
	'subrarr;': 10617,
	'succsim;': 8831,
	'supdsub;': 10968,
	'supedot;': 10948,
	'suphsol;': 10185,
	'suphsub;': 10967,
	'suplarr;': 10619,
	'supmult;': 10946,
	'supplus;': 10944,
	'swarrow;': 8601,
	'topfork;': 10970,
	'triplus;': 10809,
	'tritime;': 10811,
	'uparrow;': 8593,
	'upsilon;': 965,
	'uwangle;': 10663,
	'vzigzag;': 10650,
	'zigrarr;': 8669,
	'Aacute;': 193,
	'Abreve;': 258,
	'Agrave;': 192,
	'Assign;': 8788,
	'Atilde;': 195,
	'Barwed;': 8966,
	'Bumpeq;': 8782,
	'Cacute;': 262,
	'Ccaron;': 268,
	'Ccedil;': 199,
	'Colone;': 10868,
	'Conint;': 8751,
	'CupCap;': 8781,
	'Dagger;': 8225,
	'Dcaron;': 270,
	'DotDot;': 8412,
	'Dstrok;': 272,
	'Eacute;': 201,
	'Ecaron;': 282,
	'Egrave;': 200,
	'Exists;': 8707,
	'ForAll;': 8704,
	'Gammad;': 988,
	'Gbreve;': 286,
	'Gcedil;': 290,
	'HARDcy;': 1066,
	'Hstrok;': 294,
	'Iacute;': 205,
	'Igrave;': 204,
	'Itilde;': 296,
	'Jsercy;': 1032,
	'Kcedil;': 310,
	'Lacute;': 313,
	'Lambda;': 923,
	'Lcaron;': 317,
	'Lcedil;': 315,
	'Lmidot;': 319,
	'Lstrok;': 321,
	'Nacute;': 323,
	'Ncaron;': 327,
	'Ncedil;': 325,
	'Ntilde;': 209,
	'Oacute;': 211,
	'Odblac;': 336,
	'Ograve;': 210,
	'Oslash;': 216,
	'Otilde;': 213,
	'Otimes;': 10807,
	'Racute;': 340,
	'Rarrtl;': 10518,
	'Rcaron;': 344,
	'Rcedil;': 342,
	'SHCHcy;': 1065,
	'SOFTcy;': 1068,
	'Sacute;': 346,
	'Scaron;': 352,
	'Scedil;': 350,
	'Square;': 9633,
	'Subset;': 8912,
	'Supset;': 8913,
	'Tcaron;': 356,
	'Tcedil;': 354,
	'Tstrok;': 358,
	'Uacute;': 218,
	'Ubreve;': 364,
	'Udblac;': 368,
	'Ugrave;': 217,
	'Utilde;': 360,
	'Vdashl;': 10982,
	'Verbar;': 8214,
	'Vvdash;': 8874,
	'Yacute;': 221,
	'Zacute;': 377,
	'Zcaron;': 381,
	'aacute;': 225,
	'abreve;': 259,
	'agrave;': 224,
	'andand;': 10837,
	'angmsd;': 8737,
	'angsph;': 8738,
	'apacir;': 10863,
	'approx;': 8776,
	'atilde;': 227,
	'barvee;': 8893,
	'barwed;': 8965,
	'becaus;': 8757,
	'bernou;': 8492,
	'bigcap;': 8898,
	'bigcup;': 8899,
	'bigvee;': 8897,
	'bkarow;': 10509,
	'bottom;': 8869,
	'bowtie;': 8904,
	'boxbox;': 10697,
	'bprime;': 8245,
	'brvbar;': 166,
	'bullet;': 8226,
	'bumpeq;': 8783,
	'cacute;': 263,
	'capand;': 10820,
	'capcap;': 10827,
	'capcup;': 10823,
	'capdot;': 10816,
	'ccaron;': 269,
	'ccedil;': 231,
	'circeq;': 8791,
	'cirmid;': 10991,
	'colone;': 8788,
	'commat;': 64,
	'compfn;': 8728,
	'conint;': 8750,
	'coprod;': 8720,
	'copysr;': 8471,
	'cularr;': 8630,
	'cupcap;': 10822,
	'cupcup;': 10826,
	'cupdot;': 8845,
	'curarr;': 8631,
	'curren;': 164,
	'cylcty;': 9005,
	'dagger;': 8224,
	'daleth;': 8504,
	'dcaron;': 271,
	'dfisht;': 10623,
	'divide;': 247,
	'divonx;': 8903,
	'dlcorn;': 8990,
	'dlcrop;': 8973,
	'dollar;': 36,
	'drcorn;': 8991,
	'drcrop;': 8972,
	'dstrok;': 273,
	'eacute;': 233,
	'easter;': 10862,
	'ecaron;': 283,
	'ecolon;': 8789,
	'egrave;': 232,
	'egsdot;': 10904,
	'elsdot;': 10903,
	'emptyv;': 8709,
	'emsp13;': 8196,
	'emsp14;': 8197,
	'eparsl;': 10723,
	'eqcirc;': 8790,
	'equals;': 61,
	'equest;': 8799,
	'female;': 9792,
	'ffilig;': 64259,
	'ffllig;': 64260,
	'forall;': 8704,
	'frac12;': 189,
	'frac13;': 8531,
	'frac14;': 188,
	'frac15;': 8533,
	'frac16;': 8537,
	'frac18;': 8539,
	'frac23;': 8532,
	'frac25;': 8534,
	'frac34;': 190,
	'frac35;': 8535,
	'frac38;': 8540,
	'frac45;': 8536,
	'frac56;': 8538,
	'frac58;': 8541,
	'frac78;': 8542,
	'gacute;': 501,
	'gammad;': 989,
	'gbreve;': 287,
	'gesdot;': 10880,
	'gesles;': 10900,
	'gtlPar;': 10645,
	'gtrarr;': 10616,
	'gtrdot;': 8919,
	'gtrsim;': 8819,
	'hairsp;': 8202,
	'hamilt;': 8459,
	'hardcy;': 1098,
	'hearts;': 9829,
	'hellip;': 8230,
	'hercon;': 8889,
	'homtht;': 8763,
	'horbar;': 8213,
	'hslash;': 8463,
	'hstrok;': 295,
	'hybull;': 8259,
	'hyphen;': 8208,
	'iacute;': 237,
	'igrave;': 236,
	'iiiint;': 10764,
	'iinfin;': 10716,
	'incare;': 8453,
	'inodot;': 305,
	'intcal;': 8890,
	'iquest;': 191,
	'isinsv;': 8947,
	'itilde;': 297,
	'jsercy;': 1112,
	'kappav;': 1008,
	'kcedil;': 311,
	'kgreen;': 312,
	'lAtail;': 10523,
	'lacute;': 314,
	'lagran;': 8466,
	'lambda;': 955,
	'langle;': 10216,
	'larrfs;': 10525,
	'larrhk;': 8617,
	'larrlp;': 8619,
	'larrpl;': 10553,
	'larrtl;': 8610,
	'latail;': 10521,
	'lbrace;': 123,
	'lbrack;': 91,
	'lcaron;': 318,
	'lcedil;': 316,
	'ldquor;': 8222,
	'lesdot;': 10879,
	'lesges;': 10899,
	'lfisht;': 10620,
	'lfloor;': 8970,
	'lharul;': 10602,
	'llhard;': 10603,
	'lmidot;': 320,
	'lmoust;': 9136,
	'loplus;': 10797,
	'lowast;': 8727,
	'lowbar;': 95,
	'lparlt;': 10643,
	'lrhard;': 10605,
	'lsaquo;': 8249,
	'lsquor;': 8218,
	'lstrok;': 322,
	'lthree;': 8907,
	'ltimes;': 8905,
	'ltlarr;': 10614,
	'ltrPar;': 10646,
	'mapsto;': 8614,
	'marker;': 9646,
	'mcomma;': 10793,
	'midast;': 42,
	'midcir;': 10992,
	'middot;': 183,
	'minusb;': 8863,
	'minusd;': 8760,
	'mnplus;': 8723,
	'models;': 8871,
	'mstpos;': 8766,
	'nVDash;': 8879,
	'nVdash;': 8878,
	'nacute;': 324,
	'nbumpe;': 8783,
	'ncaron;': 328,
	'ncedil;': 326,
	'nearhk;': 10532,
	'nequiv;': 8802,
	'nesear;': 10536,
	'nexist;': 8708,
	'nltrie;': 8940,
	'notinE;': 8953,
	'nparsl;': 11005,
	'nprcue;': 8928,
	'nrarrc;': 10547,
	'nrarrw;': 8605,
	'nrtrie;': 8941,
	'nsccue;': 8929,
	'nsimeq;': 8772,
	'ntilde;': 241,
	'numero;': 8470,
	'nvDash;': 8877,
	'nvHarr;': 10500,
	'nvdash;': 8876,
	'nvlArr;': 10498,
	'nvrArr;': 10499,
	'nwarhk;': 10531,
	'nwnear;': 10535,
	'oacute;': 243,
	'odblac;': 337,
	'odsold;': 10684,
	'ograve;': 242,
	'ominus;': 8854,
	'origof;': 8886,
	'oslash;': 248,
	'otilde;': 245,
	'otimes;': 8855,
	'parsim;': 10995,
	'percnt;': 37,
	'period;': 46,
	'permil;': 8240,
	'phmmat;': 8499,
	'planck;': 8463,
	'plankv;': 8463,
	'plusdo;': 8724,
	'plusdu;': 10789,
	'plusmn;': 177,
	'preceq;': 10927,
	'primes;': 8473,
	'prnsim;': 8936,
	'propto;': 8733,
	'prurel;': 8880,
	'puncsp;': 8200,
	'qprime;': 8279,
	'rAtail;': 10524,
	'racute;': 341,
	'rangle;': 10217,
	'rarrap;': 10613,
	'rarrfs;': 10526,
	'rarrhk;': 8618,
	'rarrlp;': 8620,
	'rarrpl;': 10565,
	'rarrtl;': 8611,
	'ratail;': 10522,
	'rbrace;': 125,
	'rbrack;': 93,
	'rcaron;': 345,
	'rcedil;': 343,
	'rdquor;': 8221,
	'rfisht;': 10621,
	'rfloor;': 8971,
	'rharul;': 10604,
	'rmoust;': 9137,
	'roplus;': 10798,
	'rpargt;': 10644,
	'rsaquo;': 8250,
	'rsquor;': 8217,
	'rthree;': 8908,
	'rtimes;': 8906,
	'sacute;': 347,
	'scaron;': 353,
	'scedil;': 351,
	'scnsim;': 8937,
	'searhk;': 10533,
	'seswar;': 10537,
	'sfrown;': 8994,
	'shchcy;': 1097,
	'sigmaf;': 962,
	'sigmav;': 962,
	'simdot;': 10858,
	'smashp;': 10803,
	'softcy;': 1100,
	'solbar;': 9023,
	'spades;': 9824,
	'sqcaps;': 8851,
	'sqcups;': 8852,
	'sqsube;': 8849,
	'sqsupe;': 8850,
	'square;': 9633,
	'squarf;': 9642,
	'ssetmn;': 8726,
	'ssmile;': 8995,
	'sstarf;': 8902,
	'subdot;': 10941,
	'subset;': 8834,
	'subsim;': 10951,
	'subsub;': 10965,
	'subsup;': 10963,
	'succeq;': 10928,
	'supdot;': 10942,
	'supset;': 8835,
	'supsim;': 10952,
	'supsub;': 10964,
	'supsup;': 10966,
	'swarhk;': 10534,
	'swnwar;': 10538,
	'target;': 8982,
	'tcaron;': 357,
	'tcedil;': 355,
	'telrec;': 8981,
	'there4;': 8756,
	'thetav;': 977,
	'thinsp;': 8201,
	'thksim;': 8764,
	'timesb;': 8864,
	'timesd;': 10800,
	'topbot;': 9014,
	'topcir;': 10993,
	'tprime;': 8244,
	'tridot;': 9708,
	'tstrok;': 359,
	'uacute;': 250,
	'ubreve;': 365,
	'udblac;': 369,
	'ufisht;': 10622,
	'ugrave;': 249,
	'ulcorn;': 8988,
	'ulcrop;': 8975,
	'urcorn;': 8989,
	'urcrop;': 8974,
	'utilde;': 361,
	'vangrt;': 10652,
	'varphi;': 981,
	'varrho;': 1009,
	'veebar;': 8891,
	'vellip;': 8942,
	'verbar;': 124,
	'vsubnE;': 10955,
	'vsubne;': 8842,
	'vsupnE;': 10956,
	'vsupne;': 8843,
	'wedbar;': 10847,
	'wedgeq;': 8793,
	'weierp;': 8472,
	'wreath;': 8768,
	'xoplus;': 10753,
	'xotime;': 10754,
	'xsqcup;': 10758,
	'xuplus;': 10756,
	'xwedge;': 8896,
	'yacute;': 253,
	'zacute;': 378,
	'zcaron;': 382,
	'zeetrf;': 8488,
	'AElig;': 198,
	Aacute: 193,
	'Acirc;': 194,
	Agrave: 192,
	'Alpha;': 913,
	'Amacr;': 256,
	'Aogon;': 260,
	'Aring;': 197,
	Atilde: 195,
	'Breve;': 728,
	Ccedil: 199,
	'Ccirc;': 264,
	'Colon;': 8759,
	'Cross;': 10799,
	'Dashv;': 10980,
	'Delta;': 916,
	Eacute: 201,
	'Ecirc;': 202,
	Egrave: 200,
	'Emacr;': 274,
	'Eogon;': 280,
	'Equal;': 10869,
	'Gamma;': 915,
	'Gcirc;': 284,
	'Hacek;': 711,
	'Hcirc;': 292,
	'IJlig;': 306,
	Iacute: 205,
	'Icirc;': 206,
	Igrave: 204,
	'Imacr;': 298,
	'Iogon;': 302,
	'Iukcy;': 1030,
	'Jcirc;': 308,
	'Jukcy;': 1028,
	'Kappa;': 922,
	Ntilde: 209,
	'OElig;': 338,
	Oacute: 211,
	'Ocirc;': 212,
	Ograve: 210,
	'Omacr;': 332,
	'Omega;': 937,
	Oslash: 216,
	Otilde: 213,
	'Prime;': 8243,
	'RBarr;': 10512,
	'Scirc;': 348,
	'Sigma;': 931,
	'THORN;': 222,
	'TRADE;': 8482,
	'TSHcy;': 1035,
	'Theta;': 920,
	'Tilde;': 8764,
	Uacute: 218,
	'Ubrcy;': 1038,
	'Ucirc;': 219,
	Ugrave: 217,
	'Umacr;': 362,
	'Union;': 8899,
	'Uogon;': 370,
	'UpTee;': 8869,
	'Uring;': 366,
	'VDash;': 8875,
	'Vdash;': 8873,
	'Wcirc;': 372,
	'Wedge;': 8896,
	Yacute: 221,
	'Ycirc;': 374,
	aacute: 225,
	'acirc;': 226,
	'acute;': 180,
	'aelig;': 230,
	agrave: 224,
	'aleph;': 8501,
	'alpha;': 945,
	'amacr;': 257,
	'amalg;': 10815,
	'angle;': 8736,
	'angrt;': 8735,
	'angst;': 197,
	'aogon;': 261,
	'aring;': 229,
	'asymp;': 8776,
	atilde: 227,
	'awint;': 10769,
	'bcong;': 8780,
	'bdquo;': 8222,
	'bepsi;': 1014,
	'blank;': 9251,
	'blk12;': 9618,
	'blk14;': 9617,
	'blk34;': 9619,
	'block;': 9608,
	'boxDL;': 9559,
	'boxDR;': 9556,
	'boxDl;': 9558,
	'boxDr;': 9555,
	'boxHD;': 9574,
	'boxHU;': 9577,
	'boxHd;': 9572,
	'boxHu;': 9575,
	'boxUL;': 9565,
	'boxUR;': 9562,
	'boxUl;': 9564,
	'boxUr;': 9561,
	'boxVH;': 9580,
	'boxVL;': 9571,
	'boxVR;': 9568,
	'boxVh;': 9579,
	'boxVl;': 9570,
	'boxVr;': 9567,
	'boxdL;': 9557,
	'boxdR;': 9554,
	'boxdl;': 9488,
	'boxdr;': 9484,
	'boxhD;': 9573,
	'boxhU;': 9576,
	'boxhd;': 9516,
	'boxhu;': 9524,
	'boxuL;': 9563,
	'boxuR;': 9560,
	'boxul;': 9496,
	'boxur;': 9492,
	'boxvH;': 9578,
	'boxvL;': 9569,
	'boxvR;': 9566,
	'boxvh;': 9532,
	'boxvl;': 9508,
	'boxvr;': 9500,
	'breve;': 728,
	brvbar: 166,
	'bsemi;': 8271,
	'bsime;': 8909,
	'bsolb;': 10693,
	'bumpE;': 10926,
	'bumpe;': 8783,
	'caret;': 8257,
	'caron;': 711,
	'ccaps;': 10829,
	ccedil: 231,
	'ccirc;': 265,
	'ccups;': 10828,
	'cedil;': 184,
	'check;': 10003,
	'clubs;': 9827,
	'colon;': 58,
	'comma;': 44,
	'crarr;': 8629,
	'cross;': 10007,
	'csube;': 10961,
	'csupe;': 10962,
	'ctdot;': 8943,
	'cuepr;': 8926,
	'cuesc;': 8927,
	'cupor;': 10821,
	curren: 164,
	'cuvee;': 8910,
	'cuwed;': 8911,
	'cwint;': 8753,
	'dashv;': 8867,
	'dblac;': 733,
	'ddarr;': 8650,
	'delta;': 948,
	'dharl;': 8643,
	'dharr;': 8642,
	'diams;': 9830,
	'disin;': 8946,
	divide: 247,
	'doteq;': 8784,
	'dtdot;': 8945,
	'dtrif;': 9662,
	'duarr;': 8693,
	'duhar;': 10607,
	'eDDot;': 10871,
	eacute: 233,
	'ecirc;': 234,
	'efDot;': 8786,
	egrave: 232,
	'emacr;': 275,
	'empty;': 8709,
	'eogon;': 281,
	'eplus;': 10865,
	'epsiv;': 1013,
	'eqsim;': 8770,
	'equiv;': 8801,
	'erDot;': 8787,
	'erarr;': 10609,
	'esdot;': 8784,
	'exist;': 8707,
	'fflig;': 64256,
	'filig;': 64257,
	'fjlig;': 102,
	'fllig;': 64258,
	'fltns;': 9649,
	'forkv;': 10969,
	frac12: 189,
	frac14: 188,
	frac34: 190,
	'frasl;': 8260,
	'frown;': 8994,
	'gamma;': 947,
	'gcirc;': 285,
	'gescc;': 10921,
	'gimel;': 8503,
	'gneqq;': 8809,
	'gnsim;': 8935,
	'grave;': 96,
	'gsime;': 10894,
	'gsiml;': 10896,
	'gtcir;': 10874,
	'gtdot;': 8919,
	'harrw;': 8621,
	'hcirc;': 293,
	'hoarr;': 8703,
	iacute: 237,
	'icirc;': 238,
	'iexcl;': 161,
	igrave: 236,
	'iiint;': 8749,
	'iiota;': 8489,
	'ijlig;': 307,
	'imacr;': 299,
	'image;': 8465,
	'imath;': 305,
	'imped;': 437,
	'infin;': 8734,
	'iogon;': 303,
	'iprod;': 10812,
	iquest: 191,
	'isinE;': 8953,
	'isins;': 8948,
	'isinv;': 8712,
	'iukcy;': 1110,
	'jcirc;': 309,
	'jmath;': 567,
	'jukcy;': 1108,
	'kappa;': 954,
	'lAarr;': 8666,
	'lBarr;': 10510,
	'langd;': 10641,
	'laquo;': 171,
	'larrb;': 8676,
	'lates;': 10925,
	'lbarr;': 10508,
	'lbbrk;': 10098,
	'lbrke;': 10635,
	'lceil;': 8968,
	'ldquo;': 8220,
	'lescc;': 10920,
	'lhard;': 8637,
	'lharu;': 8636,
	'lhblk;': 9604,
	'llarr;': 8647,
	'lltri;': 9722,
	'lneqq;': 8808,
	'lnsim;': 8934,
	'loang;': 10220,
	'loarr;': 8701,
	'lobrk;': 10214,
	'lopar;': 10629,
	'lrarr;': 8646,
	'lrhar;': 8651,
	'lrtri;': 8895,
	'lsime;': 10893,
	'lsimg;': 10895,
	'lsquo;': 8216,
	'ltcir;': 10873,
	'ltdot;': 8918,
	'ltrie;': 8884,
	'ltrif;': 9666,
	'mDDot;': 8762,
	'mdash;': 8212,
	'micro;': 181,
	middot: 183,
	'minus;': 8722,
	'mumap;': 8888,
	'nabla;': 8711,
	'napid;': 8779,
	'napos;': 329,
	'natur;': 9838,
	'nbump;': 8782,
	'ncong;': 8775,
	'ndash;': 8211,
	'neArr;': 8663,
	'nearr;': 8599,
	'nedot;': 8784,
	'nesim;': 8770,
	'ngeqq;': 8807,
	'ngsim;': 8821,
	'nhArr;': 8654,
	'nharr;': 8622,
	'nhpar;': 10994,
	'nlArr;': 8653,
	'nlarr;': 8602,
	'nleqq;': 8806,
	'nless;': 8814,
	'nlsim;': 8820,
	'nltri;': 8938,
	'notin;': 8713,
	'notni;': 8716,
	'npart;': 8706,
	'nprec;': 8832,
	'nrArr;': 8655,
	'nrarr;': 8603,
	'nrtri;': 8939,
	'nsime;': 8772,
	'nsmid;': 8740,
	'nspar;': 8742,
	'nsubE;': 10949,
	'nsube;': 8840,
	'nsucc;': 8833,
	'nsupE;': 10950,
	'nsupe;': 8841,
	ntilde: 241,
	'numsp;': 8199,
	'nvsim;': 8764,
	'nwArr;': 8662,
	'nwarr;': 8598,
	oacute: 243,
	'ocirc;': 244,
	'odash;': 8861,
	'oelig;': 339,
	'ofcir;': 10687,
	ograve: 242,
	'ohbar;': 10677,
	'olarr;': 8634,
	'olcir;': 10686,
	'oline;': 8254,
	'omacr;': 333,
	'omega;': 969,
	'operp;': 10681,
	'oplus;': 8853,
	'orarr;': 8635,
	'order;': 8500,
	oslash: 248,
	otilde: 245,
	'ovbar;': 9021,
	'parsl;': 11005,
	'phone;': 9742,
	'plusb;': 8862,
	'pluse;': 10866,
	plusmn: 177,
	'pound;': 163,
	'prcue;': 8828,
	'prime;': 8242,
	'prnap;': 10937,
	'prsim;': 8830,
	'quest;': 63,
	'rAarr;': 8667,
	'rBarr;': 10511,
	'radic;': 8730,
	'rangd;': 10642,
	'range;': 10661,
	'raquo;': 187,
	'rarrb;': 8677,
	'rarrc;': 10547,
	'rarrw;': 8605,
	'ratio;': 8758,
	'rbarr;': 10509,
	'rbbrk;': 10099,
	'rbrke;': 10636,
	'rceil;': 8969,
	'rdquo;': 8221,
	'reals;': 8477,
	'rhard;': 8641,
	'rharu;': 8640,
	'rlarr;': 8644,
	'rlhar;': 8652,
	'rnmid;': 10990,
	'roang;': 10221,
	'roarr;': 8702,
	'robrk;': 10215,
	'ropar;': 10630,
	'rrarr;': 8649,
	'rsquo;': 8217,
	'rtrie;': 8885,
	'rtrif;': 9656,
	'sbquo;': 8218,
	'sccue;': 8829,
	'scirc;': 349,
	'scnap;': 10938,
	'scsim;': 8831,
	'sdotb;': 8865,
	'sdote;': 10854,
	'seArr;': 8664,
	'searr;': 8600,
	'setmn;': 8726,
	'sharp;': 9839,
	'sigma;': 963,
	'simeq;': 8771,
	'simgE;': 10912,
	'simlE;': 10911,
	'simne;': 8774,
	'slarr;': 8592,
	'smile;': 8995,
	'smtes;': 10924,
	'sqcap;': 8851,
	'sqcup;': 8852,
	'sqsub;': 8847,
	'sqsup;': 8848,
	'srarr;': 8594,
	'starf;': 9733,
	'strns;': 175,
	'subnE;': 10955,
	'subne;': 8842,
	'supnE;': 10956,
	'supne;': 8843,
	'swArr;': 8665,
	'swarr;': 8601,
	'szlig;': 223,
	'theta;': 952,
	'thkap;': 8776,
	'thorn;': 254,
	'tilde;': 732,
	'times;': 215,
	'trade;': 8482,
	'trisb;': 10701,
	'tshcy;': 1115,
	'twixt;': 8812,
	uacute: 250,
	'ubrcy;': 1118,
	'ucirc;': 251,
	'udarr;': 8645,
	'udhar;': 10606,
	ugrave: 249,
	'uharl;': 8639,
	'uharr;': 8638,
	'uhblk;': 9600,
	'ultri;': 9720,
	'umacr;': 363,
	'uogon;': 371,
	'uplus;': 8846,
	'upsih;': 978,
	'uring;': 367,
	'urtri;': 9721,
	'utdot;': 8944,
	'utrif;': 9652,
	'uuarr;': 8648,
	'vBarv;': 10985,
	'vDash;': 8872,
	'varpi;': 982,
	'vdash;': 8866,
	'veeeq;': 8794,
	'vltri;': 8882,
	'vnsub;': 8834,
	'vnsup;': 8835,
	'vprop;': 8733,
	'vrtri;': 8883,
	'wcirc;': 373,
	'wedge;': 8743,
	'xcirc;': 9711,
	'xdtri;': 9661,
	'xhArr;': 10234,
	'xharr;': 10231,
	'xlArr;': 10232,
	'xlarr;': 10229,
	'xodot;': 10752,
	'xrArr;': 10233,
	'xrarr;': 10230,
	'xutri;': 9651,
	yacute: 253,
	'ycirc;': 375,
	AElig: 198,
	Acirc: 194,
	'Aopf;': 120120,
	Aring: 197,
	'Ascr;': 119964,
	'Auml;': 196,
	'Barv;': 10983,
	'Beta;': 914,
	'Bopf;': 120121,
	'Bscr;': 8492,
	'CHcy;': 1063,
	'COPY;': 169,
	'Cdot;': 266,
	'Copf;': 8450,
	'Cscr;': 119966,
	'DJcy;': 1026,
	'DScy;': 1029,
	'DZcy;': 1039,
	'Darr;': 8609,
	'Dopf;': 120123,
	'Dscr;': 119967,
	Ecirc: 202,
	'Edot;': 278,
	'Eopf;': 120124,
	'Escr;': 8496,
	'Esim;': 10867,
	'Euml;': 203,
	'Fopf;': 120125,
	'Fscr;': 8497,
	'GJcy;': 1027,
	'Gdot;': 288,
	'Gopf;': 120126,
	'Gscr;': 119970,
	'Hopf;': 8461,
	'Hscr;': 8459,
	'IEcy;': 1045,
	'IOcy;': 1025,
	Icirc: 206,
	'Idot;': 304,
	'Iopf;': 120128,
	'Iota;': 921,
	'Iscr;': 8464,
	'Iuml;': 207,
	'Jopf;': 120129,
	'Jscr;': 119973,
	'KHcy;': 1061,
	'KJcy;': 1036,
	'Kopf;': 120130,
	'Kscr;': 119974,
	'LJcy;': 1033,
	'Lang;': 10218,
	'Larr;': 8606,
	'Lopf;': 120131,
	'Lscr;': 8466,
	'Mopf;': 120132,
	'Mscr;': 8499,
	'NJcy;': 1034,
	'Nopf;': 8469,
	'Nscr;': 119977,
	Ocirc: 212,
	'Oopf;': 120134,
	'Oscr;': 119978,
	'Ouml;': 214,
	'Popf;': 8473,
	'Pscr;': 119979,
	'QUOT;': 34,
	'Qopf;': 8474,
	'Qscr;': 119980,
	'Rang;': 10219,
	'Rarr;': 8608,
	'Ropf;': 8477,
	'Rscr;': 8475,
	'SHcy;': 1064,
	'Sopf;': 120138,
	'Sqrt;': 8730,
	'Sscr;': 119982,
	'Star;': 8902,
	THORN: 222,
	'TScy;': 1062,
	'Topf;': 120139,
	'Tscr;': 119983,
	'Uarr;': 8607,
	Ucirc: 219,
	'Uopf;': 120140,
	'Upsi;': 978,
	'Uscr;': 119984,
	'Uuml;': 220,
	'Vbar;': 10987,
	'Vert;': 8214,
	'Vopf;': 120141,
	'Vscr;': 119985,
	'Wopf;': 120142,
	'Wscr;': 119986,
	'Xopf;': 120143,
	'Xscr;': 119987,
	'YAcy;': 1071,
	'YIcy;': 1031,
	'YUcy;': 1070,
	'Yopf;': 120144,
	'Yscr;': 119988,
	'Yuml;': 376,
	'ZHcy;': 1046,
	'Zdot;': 379,
	'Zeta;': 918,
	'Zopf;': 8484,
	'Zscr;': 119989,
	acirc: 226,
	acute: 180,
	aelig: 230,
	'andd;': 10844,
	'andv;': 10842,
	'ange;': 10660,
	'aopf;': 120146,
	'apid;': 8779,
	'apos;': 39,
	aring: 229,
	'ascr;': 119990,
	'auml;': 228,
	'bNot;': 10989,
	'bbrk;': 9141,
	'beta;': 946,
	'beth;': 8502,
	'bnot;': 8976,
	'bopf;': 120147,
	'boxH;': 9552,
	'boxV;': 9553,
	'boxh;': 9472,
	'boxv;': 9474,
	'bscr;': 119991,
	'bsim;': 8765,
	'bsol;': 92,
	'bull;': 8226,
	'bump;': 8782,
	'caps;': 8745,
	'cdot;': 267,
	cedil: 184,
	'cent;': 162,
	'chcy;': 1095,
	'cirE;': 10691,
	'circ;': 710,
	'cire;': 8791,
	'comp;': 8705,
	'cong;': 8773,
	'copf;': 120148,
	'copy;': 169,
	'cscr;': 119992,
	'csub;': 10959,
	'csup;': 10960,
	'cups;': 8746,
	'dArr;': 8659,
	'dHar;': 10597,
	'darr;': 8595,
	'dash;': 8208,
	'diam;': 8900,
	'djcy;': 1106,
	'dopf;': 120149,
	'dscr;': 119993,
	'dscy;': 1109,
	'dsol;': 10742,
	'dtri;': 9663,
	'dzcy;': 1119,
	'eDot;': 8785,
	'ecir;': 8790,
	ecirc: 234,
	'edot;': 279,
	'emsp;': 8195,
	'ensp;': 8194,
	'eopf;': 120150,
	'epar;': 8917,
	'epsi;': 949,
	'escr;': 8495,
	'esim;': 8770,
	'euml;': 235,
	'euro;': 8364,
	'excl;': 33,
	'flat;': 9837,
	'fnof;': 402,
	'fopf;': 120151,
	'fork;': 8916,
	'fscr;': 119995,
	'gdot;': 289,
	'geqq;': 8807,
	'gesl;': 8923,
	'gjcy;': 1107,
	'gnap;': 10890,
	'gneq;': 10888,
	'gopf;': 120152,
	'gscr;': 8458,
	'gsim;': 8819,
	'gtcc;': 10919,
	'gvnE;': 8809,
	'hArr;': 8660,
	'half;': 189,
	'harr;': 8596,
	'hbar;': 8463,
	'hopf;': 120153,
	'hscr;': 119997,
	icirc: 238,
	'iecy;': 1077,
	iexcl: 161,
	'imof;': 8887,
	'iocy;': 1105,
	'iopf;': 120154,
	'iota;': 953,
	'iscr;': 119998,
	'isin;': 8712,
	'iuml;': 239,
	'jopf;': 120155,
	'jscr;': 119999,
	'khcy;': 1093,
	'kjcy;': 1116,
	'kopf;': 120156,
	'kscr;': 120000,
	'lArr;': 8656,
	'lHar;': 10594,
	'lang;': 10216,
	laquo: 171,
	'larr;': 8592,
	'late;': 10925,
	'lcub;': 123,
	'ldca;': 10550,
	'ldsh;': 8626,
	'leqq;': 8806,
	'lesg;': 8922,
	'ljcy;': 1113,
	'lnap;': 10889,
	'lneq;': 10887,
	'lopf;': 120157,
	'lozf;': 10731,
	'lpar;': 40,
	'lscr;': 120001,
	'lsim;': 8818,
	'lsqb;': 91,
	'ltcc;': 10918,
	'ltri;': 9667,
	'lvnE;': 8808,
	'macr;': 175,
	'male;': 9794,
	'malt;': 10016,
	micro: 181,
	'mlcp;': 10971,
	'mldr;': 8230,
	'mopf;': 120158,
	'mscr;': 120002,
	'nGtv;': 8811,
	'nLtv;': 8810,
	'nang;': 8736,
	'napE;': 10864,
	'nbsp;': 160,
	'ncap;': 10819,
	'ncup;': 10818,
	'ngeq;': 8817,
	'nges;': 10878,
	'ngtr;': 8815,
	'nisd;': 8954,
	'njcy;': 1114,
	'nldr;': 8229,
	'nleq;': 8816,
	'nles;': 10877,
	'nmid;': 8740,
	'nopf;': 120159,
	'npar;': 8742,
	'npre;': 10927,
	'nsce;': 10928,
	'nscr;': 120003,
	'nsim;': 8769,
	'nsub;': 8836,
	'nsup;': 8837,
	'ntgl;': 8825,
	'ntlg;': 8824,
	'nvap;': 8781,
	'nvge;': 8805,
	'nvgt;': 62,
	'nvle;': 8804,
	'nvlt;': 60,
	'oast;': 8859,
	'ocir;': 8858,
	ocirc: 244,
	'odiv;': 10808,
	'odot;': 8857,
	'ogon;': 731,
	'oint;': 8750,
	'omid;': 10678,
	'oopf;': 120160,
	'opar;': 10679,
	'ordf;': 170,
	'ordm;': 186,
	'oror;': 10838,
	'oscr;': 8500,
	'osol;': 8856,
	'ouml;': 246,
	'para;': 182,
	'part;': 8706,
	'perp;': 8869,
	'phiv;': 981,
	'plus;': 43,
	'popf;': 120161,
	pound: 163,
	'prap;': 10935,
	'prec;': 8826,
	'prnE;': 10933,
	'prod;': 8719,
	'prop;': 8733,
	'pscr;': 120005,
	'qint;': 10764,
	'qopf;': 120162,
	'qscr;': 120006,
	'quot;': 34,
	'rArr;': 8658,
	'rHar;': 10596,
	'race;': 8765,
	'rang;': 10217,
	raquo: 187,
	'rarr;': 8594,
	'rcub;': 125,
	'rdca;': 10551,
	'rdsh;': 8627,
	'real;': 8476,
	'rect;': 9645,
	'rhov;': 1009,
	'ring;': 730,
	'ropf;': 120163,
	'rpar;': 41,
	'rscr;': 120007,
	'rsqb;': 93,
	'rtri;': 9657,
	'scap;': 10936,
	'scnE;': 10934,
	'sdot;': 8901,
	'sect;': 167,
	'semi;': 59,
	'sext;': 10038,
	'shcy;': 1096,
	'sime;': 8771,
	'simg;': 10910,
	'siml;': 10909,
	'smid;': 8739,
	'smte;': 10924,
	'solb;': 10692,
	'sopf;': 120164,
	'spar;': 8741,
	'squf;': 9642,
	'sscr;': 120008,
	'star;': 9734,
	'subE;': 10949,
	'sube;': 8838,
	'succ;': 8827,
	'sung;': 9834,
	'sup1;': 185,
	'sup2;': 178,
	'sup3;': 179,
	'supE;': 10950,
	'supe;': 8839,
	szlig: 223,
	'tbrk;': 9140,
	'tdot;': 8411,
	thorn: 254,
	times: 215,
	'tint;': 8749,
	'toea;': 10536,
	'topf;': 120165,
	'tosa;': 10537,
	'trie;': 8796,
	'tscr;': 120009,
	'tscy;': 1094,
	'uArr;': 8657,
	'uHar;': 10595,
	'uarr;': 8593,
	ucirc: 251,
	'uopf;': 120166,
	'upsi;': 965,
	'uscr;': 120010,
	'utri;': 9653,
	'uuml;': 252,
	'vArr;': 8661,
	'vBar;': 10984,
	'varr;': 8597,
	'vert;': 124,
	'vopf;': 120167,
	'vscr;': 120011,
	'wopf;': 120168,
	'wscr;': 120012,
	'xcap;': 8898,
	'xcup;': 8899,
	'xmap;': 10236,
	'xnis;': 8955,
	'xopf;': 120169,
	'xscr;': 120013,
	'xvee;': 8897,
	'yacy;': 1103,
	'yicy;': 1111,
	'yopf;': 120170,
	'yscr;': 120014,
	'yucy;': 1102,
	'yuml;': 255,
	'zdot;': 380,
	'zeta;': 950,
	'zhcy;': 1078,
	'zopf;': 120171,
	'zscr;': 120015,
	'zwnj;': 8204,
	'AMP;': 38,
	'Acy;': 1040,
	'Afr;': 120068,
	'And;': 10835,
	Auml: 196,
	'Bcy;': 1041,
	'Bfr;': 120069,
	COPY: 169,
	'Cap;': 8914,
	'Cfr;': 8493,
	'Chi;': 935,
	'Cup;': 8915,
	'Dcy;': 1044,
	'Del;': 8711,
	'Dfr;': 120071,
	'Dot;': 168,
	'ENG;': 330,
	'ETH;': 208,
	'Ecy;': 1069,
	'Efr;': 120072,
	'Eta;': 919,
	Euml: 203,
	'Fcy;': 1060,
	'Ffr;': 120073,
	'Gcy;': 1043,
	'Gfr;': 120074,
	'Hat;': 94,
	'Hfr;': 8460,
	'Icy;': 1048,
	'Ifr;': 8465,
	'Int;': 8748,
	Iuml: 207,
	'Jcy;': 1049,
	'Jfr;': 120077,
	'Kcy;': 1050,
	'Kfr;': 120078,
	'Lcy;': 1051,
	'Lfr;': 120079,
	'Lsh;': 8624,
	'Map;': 10501,
	'Mcy;': 1052,
	'Mfr;': 120080,
	'Ncy;': 1053,
	'Nfr;': 120081,
	'Not;': 10988,
	'Ocy;': 1054,
	'Ofr;': 120082,
	Ouml: 214,
	'Pcy;': 1055,
	'Pfr;': 120083,
	'Phi;': 934,
	'Psi;': 936,
	QUOT: 34,
	'Qfr;': 120084,
	'REG;': 174,
	'Rcy;': 1056,
	'Rfr;': 8476,
	'Rho;': 929,
	'Rsh;': 8625,
	'Scy;': 1057,
	'Sfr;': 120086,
	'Sub;': 8912,
	'Sum;': 8721,
	'Sup;': 8913,
	'Tab;': 9,
	'Tau;': 932,
	'Tcy;': 1058,
	'Tfr;': 120087,
	'Ucy;': 1059,
	'Ufr;': 120088,
	Uuml: 220,
	'Vcy;': 1042,
	'Vee;': 8897,
	'Vfr;': 120089,
	'Wfr;': 120090,
	'Xfr;': 120091,
	'Ycy;': 1067,
	'Yfr;': 120092,
	'Zcy;': 1047,
	'Zfr;': 8488,
	'acE;': 8766,
	'acd;': 8767,
	'acy;': 1072,
	'afr;': 120094,
	'amp;': 38,
	'and;': 8743,
	'ang;': 8736,
	'apE;': 10864,
	'ape;': 8778,
	'ast;': 42,
	auml: 228,
	'bcy;': 1073,
	'bfr;': 120095,
	'bne;': 61,
	'bot;': 8869,
	'cap;': 8745,
	cent: 162,
	'cfr;': 120096,
	'chi;': 967,
	'cir;': 9675,
	copy: 169,
	'cup;': 8746,
	'dcy;': 1076,
	'deg;': 176,
	'dfr;': 120097,
	'die;': 168,
	'div;': 247,
	'dot;': 729,
	'ecy;': 1101,
	'efr;': 120098,
	'egs;': 10902,
	'ell;': 8467,
	'els;': 10901,
	'eng;': 331,
	'eta;': 951,
	'eth;': 240,
	euml: 235,
	'fcy;': 1092,
	'ffr;': 120099,
	'gEl;': 10892,
	'gap;': 10886,
	'gcy;': 1075,
	'gel;': 8923,
	'geq;': 8805,
	'ges;': 10878,
	'gfr;': 120100,
	'ggg;': 8921,
	'glE;': 10898,
	'gla;': 10917,
	'glj;': 10916,
	'gnE;': 8809,
	'gne;': 10888,
	'hfr;': 120101,
	'icy;': 1080,
	'iff;': 8660,
	'ifr;': 120102,
	'int;': 8747,
	iuml: 239,
	'jcy;': 1081,
	'jfr;': 120103,
	'kcy;': 1082,
	'kfr;': 120104,
	'lEg;': 10891,
	'lap;': 10885,
	'lat;': 10923,
	'lcy;': 1083,
	'leg;': 8922,
	'leq;': 8804,
	'les;': 10877,
	'lfr;': 120105,
	'lgE;': 10897,
	'lnE;': 8808,
	'lne;': 10887,
	'loz;': 9674,
	'lrm;': 8206,
	'lsh;': 8624,
	macr: 175,
	'map;': 8614,
	'mcy;': 1084,
	'mfr;': 120106,
	'mho;': 8487,
	'mid;': 8739,
	'nGg;': 8921,
	'nGt;': 8811,
	'nLl;': 8920,
	'nLt;': 8810,
	'nap;': 8777,
	nbsp: 160,
	'ncy;': 1085,
	'nfr;': 120107,
	'ngE;': 8807,
	'nge;': 8817,
	'ngt;': 8815,
	'nis;': 8956,
	'niv;': 8715,
	'nlE;': 8806,
	'nle;': 8816,
	'nlt;': 8814,
	'not;': 172,
	'npr;': 8832,
	'nsc;': 8833,
	'num;': 35,
	'ocy;': 1086,
	'ofr;': 120108,
	'ogt;': 10689,
	'ohm;': 937,
	'olt;': 10688,
	'ord;': 10845,
	ordf: 170,
	ordm: 186,
	'orv;': 10843,
	ouml: 246,
	'par;': 8741,
	para: 182,
	'pcy;': 1087,
	'pfr;': 120109,
	'phi;': 966,
	'piv;': 982,
	'prE;': 10931,
	'pre;': 10927,
	'psi;': 968,
	'qfr;': 120110,
	quot: 34,
	'rcy;': 1088,
	'reg;': 174,
	'rfr;': 120111,
	'rho;': 961,
	'rlm;': 8207,
	'rsh;': 8625,
	'scE;': 10932,
	'sce;': 10928,
	'scy;': 1089,
	sect: 167,
	'sfr;': 120112,
	'shy;': 173,
	'sim;': 8764,
	'smt;': 10922,
	'sol;': 47,
	'squ;': 9633,
	'sub;': 8834,
	'sum;': 8721,
	sup1: 185,
	sup2: 178,
	sup3: 179,
	'sup;': 8835,
	'tau;': 964,
	'tcy;': 1090,
	'tfr;': 120113,
	'top;': 8868,
	'ucy;': 1091,
	'ufr;': 120114,
	'uml;': 168,
	uuml: 252,
	'vcy;': 1074,
	'vee;': 8744,
	'vfr;': 120115,
	'wfr;': 120116,
	'xfr;': 120117,
	'ycy;': 1099,
	'yen;': 165,
	'yfr;': 120118,
	yuml: 255,
	'zcy;': 1079,
	'zfr;': 120119,
	'zwj;': 8205,
	AMP: 38,
	'DD;': 8517,
	ETH: 208,
	'GT;': 62,
	'Gg;': 8921,
	'Gt;': 8811,
	'Im;': 8465,
	'LT;': 60,
	'Ll;': 8920,
	'Lt;': 8810,
	'Mu;': 924,
	'Nu;': 925,
	'Or;': 10836,
	'Pi;': 928,
	'Pr;': 10939,
	REG: 174,
	'Re;': 8476,
	'Sc;': 10940,
	'Xi;': 926,
	'ac;': 8766,
	'af;': 8289,
	amp: 38,
	'ap;': 8776,
	'dd;': 8518,
	deg: 176,
	'ee;': 8519,
	'eg;': 10906,
	'el;': 10905,
	eth: 240,
	'gE;': 8807,
	'ge;': 8805,
	'gg;': 8811,
	'gl;': 8823,
	'gt;': 62,
	'ic;': 8291,
	'ii;': 8520,
	'in;': 8712,
	'it;': 8290,
	'lE;': 8806,
	'le;': 8804,
	'lg;': 8822,
	'll;': 8810,
	'lt;': 60,
	'mp;': 8723,
	'mu;': 956,
	'ne;': 8800,
	'ni;': 8715,
	not: 172,
	'nu;': 957,
	'oS;': 9416,
	'or;': 8744,
	'pi;': 960,
	'pm;': 177,
	'pr;': 8826,
	reg: 174,
	'rx;': 8478,
	'sc;': 8827,
	shy: 173,
	uml: 168,
	'wp;': 8472,
	'wr;': 8768,
	'xi;': 958,
	yen: 165,
	GT: 62,
	LT: 60,
	gt: 62,
	lt: 60
};

const windows_1252 = [
	8364, 129, 8218, 402, 8222, 8230, 8224, 8225, 710, 8240, 352, 8249, 338, 141, 381, 143, 144, 8216,
	8217, 8220, 8221, 8226, 8211, 8212, 732, 8482, 353, 8250, 339, 157, 382, 376
];

/**
 * @param {string} entity_name
 * @param {boolean} is_attribute_value
 */
function reg_exp_entity(entity_name, is_attribute_value) {
	// https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state
	// doesn't decode the html entity which not ends with ; and next character is =, number or alphabet in attribute value.
	if (is_attribute_value && !entity_name.endsWith(';')) {
		return `${entity_name}\\b(?!=)`;
	}
	return entity_name;
}

/**
 * @param {boolean} is_attribute_value
 */
function get_entity_pattern(is_attribute_value) {
	const reg_exp_num = '#(?:x[a-fA-F\\d]+|\\d+)(?:;)?';
	const reg_exp_entities = Object.keys(entities).map((entity_name) =>
		reg_exp_entity(entity_name, is_attribute_value)
	);
	const entity_pattern = new RegExp(`&(${reg_exp_num}|${reg_exp_entities.join('|')})`, 'g');
	return entity_pattern;
}
const entity_pattern_content = get_entity_pattern(false);
const entity_pattern_attr_value = get_entity_pattern(true);

/**
 * @param {string} html
 * @param {boolean} is_attribute_value
 */
function decode_character_references(html, is_attribute_value) {
	const entity_pattern = is_attribute_value ? entity_pattern_attr_value : entity_pattern_content;
	return html.replace(entity_pattern, (match, entity) => {
		let code;
		// Handle named entities
		if (entity[0] !== '#') {
			code = entities[entity];
		} else if (entity[1] === 'x') {
			code = parseInt(entity.substring(2), 16);
		} else {
			code = parseInt(entity.substring(1), 10);
		}
		if (!code) {
			return match;
		}
		return String.fromCodePoint(validate_code(code));
	});
}
const NUL = 0;
// some code points are verboten. If we were inserting HTML, the browser would replace the illegal
// code points with alternatives in some cases - since we're bypassing that mechanism, we need
// to replace them ourselves
//
// Source: http://en.wikipedia.org/wiki/Character_encodings_in_HTML#Illegal_characters

/**
 * @param {number} code
 */
function validate_code(code) {
	// line feed becomes generic whitespace
	if (code === 10) {
		return 32;
	}
	// ASCII range. (Why someone would use HTML entities for ASCII characters I don't know, but...)
	if (code < 128) {
		return code;
	}
	// code points 128-159 are dealt with leniently by browsers, but they're incorrect. We need
	// to correct the mistake or we'll end up with missing € signs and so on
	if (code <= 159) {
		return windows_1252[code - 128];
	}
	// basic multilingual plane
	if (code < 55296) {
		return code;
	}
	// UTF-16 surrogate halves
	if (code <= 57343) {
		return NUL;
	}
	// rest of the basic multilingual plane
	if (code <= 65535) {
		return code;
	}
	// supplementary multilingual plane 0x10000 - 0x1ffff
	if (code >= 65536 && code <= 131071) {
		return code;
	}
	// supplementary ideographic plane 0x20000 - 0x2ffff
	if (code >= 131072 && code <= 196607) {
		return code;
	}
	return NUL;
}
// based on http://developers.whatwg.org/syntax.html#syntax-tag-omission
const disallowed_contents = new Map([
	['li', new Set(['li'])],
	['dt', new Set(['dt', 'dd'])],
	['dd', new Set(['dt', 'dd'])],
	[
		'p',
		new Set(
			'address article aside blockquote div dl fieldset footer form h1 h2 h3 h4 h5 h6 header hgroup hr main menu nav ol p pre section table ul'.split(
				' '
			)
		)
	],
	['rt', new Set(['rt', 'rp'])],
	['rp', new Set(['rt', 'rp'])],
	['optgroup', new Set(['optgroup'])],
	['option', new Set(['option', 'optgroup'])],
	['thead', new Set(['tbody', 'tfoot'])],
	['tbody', new Set(['tbody', 'tfoot'])],
	['tfoot', new Set(['tbody'])],
	['tr', new Set(['tr', 'tbody'])],
	['td', new Set(['td', 'th', 'tr'])],
	['th', new Set(['td', 'th', 'tr'])]
]);
// can this be a child of the parent element, or does it implicitly
// close it, like `<li>one<li>two`?

/**
 * @param {string} current
 * @param {string} [next]
 */
function closing_tag_omitted(current, next) {
	if (disallowed_contents.has(current)) {
		if (!next || disallowed_contents.get(current).has(next)) {
			return true;
		}
	}
	return false;
}

// eslint-disable-next-line no-useless-escape
const valid_tag_name = /^\!?[a-zA-Z]{1,}:?[a-zA-Z0-9\-]*/;
/** Invalid attribute characters if the attribute is not surrounded by quotes */
const regex_starts_with_invalid_attr_value = /^(\/>|[\s"'=<>`])/;
const meta_tags = new Map([
	['svelte:head', 'Head'],
	['svelte:options', 'Options'],
	['svelte:window', 'Window'],
	['svelte:document', 'Document'],
	['svelte:body', 'Body']
]);
const valid_meta_tags = Array.from(meta_tags.keys()).concat(
	'svelte:self',
	'svelte:component',
	'svelte:fragment',
	'svelte:element'
);
const specials = new Map([
	[
		'script',
		{
			read: read_script,
			property: 'js'
		}
	],
	[
		'style',
		{
			read: read_style,
			property: 'css'
		}
	]
]);
const SELF = /^svelte:self(?=[\s/>])/;
const COMPONENT = /^svelte:component(?=[\s/>])/;
const SLOT = /^svelte:fragment(?=[\s/>])/;
const ELEMENT = /^svelte:element(?=[\s/>])/;
function parent_is_head(stack) {
	let i = stack.length;
	while (i--) {
		const { type } = stack[i];
		if (type === 'Head') return true;
		if (type === 'Element' || type === 'InlineComponent') return false;
	}
	return false;
}
const regex_closing_textarea_tag = /^<\/textarea(\s[^>]*)?>/i;
const regex_closing_comment = /-->/;
const regex_capital_letter = /[A-Z]/;

/**
 * @param {import('../index.js').Parser} parser
 */
function tag(parser) {
	const start = parser.index++;
	let parent = parser.current();
	if (parser.eat('!--')) {
		const data = parser.read_until(regex_closing_comment);
		parser.eat('-->', true, parser_errors.unclosed_comment);
		parser.current().children.push({
			start,
			end: parser.index,
			type: 'Comment',
			data,
			ignores: extract_svelte_ignore(data)
		});
		return;
	}
	const is_closing_tag = parser.eat('/');
	const name = read_tag_name(parser);
	if (meta_tags.has(name)) {
		const slug = meta_tags.get(name).toLowerCase();
		if (is_closing_tag) {
			if (
				(name === 'svelte:window' || name === 'svelte:body') &&
				parser.current().children.length
			) {
				parser.error(
					parser_errors.invalid_element_content(slug, name),
					parser.current().children[0].start
				);
			}
		} else {
			if (name in parser.meta_tags) {
				parser.error(parser_errors.duplicate_element(slug, name), start);
			}
			if (parser.stack.length > 1) {
				parser.error(parser_errors.invalid_element_placement(slug, name), start);
			}
			parser.meta_tags[name] = true;
		}
	}
	const type = meta_tags.has(name)
		? meta_tags.get(name)
		: regex_capital_letter.test(name[0]) || name === 'svelte:self' || name === 'svelte:component'
		? 'InlineComponent'
		: name === 'svelte:fragment'
		? 'SlotTemplate'
		: name === 'title' && parent_is_head(parser.stack)
		? 'Title'
		: name === 'slot'
		? 'Slot'
		: 'Element';

	/**
	 * @type {import('../../interfaces.js').TemplateNode}
	 */
	const element = {
		start,
		end: null,
		type,
		name,
		attributes: [],
		children: []
	};
	parser.allow_whitespace();
	if (is_closing_tag) {
		if (is_void(name)) {
			parser.error(parser_errors.invalid_void_content(name), start);
		}
		parser.eat('>', true);
		// close any elements that don't have their own closing tags, e.g. <div><p></div>
		while (parent.name !== name) {
			if (parent.type !== 'Element') {
				const error =
					parser.last_auto_closed_tag && parser.last_auto_closed_tag.tag === name
						? parser_errors.invalid_closing_tag_autoclosed(name, parser.last_auto_closed_tag.reason)
						: parser_errors.invalid_closing_tag_unopened(name);
				parser.error(error, start);
			}
			parent.end = start;
			parser.stack.pop();
			parent = parser.current();
		}
		parent.end = parser.index;
		parser.stack.pop();
		if (parser.last_auto_closed_tag && parser.stack.length < parser.last_auto_closed_tag.depth) {
			parser.last_auto_closed_tag = null;
		}
		return;
	} else if (closing_tag_omitted(parent.name, name)) {
		parent.end = start;
		parser.stack.pop();
		parser.last_auto_closed_tag = {
			tag: parent.name,
			reason: name,
			depth: parser.stack.length
		};
	}

	/**
	 * @type {Set<string>}
	 */
	const unique_names = new Set();
	let attribute;
	while ((attribute = read_attribute(parser, unique_names))) {
		element.attributes.push(attribute);
		parser.allow_whitespace();
	}
	if (name === 'svelte:component') {
		const index = element.attributes.findIndex(
			(attr) => attr.type === 'Attribute' && attr.name === 'this'
		);
		if (index === -1) {
			parser.error(parser_errors.missing_component_definition, start);
		}
		const definition = element.attributes.splice(index, 1)[0];
		if (
			definition.value === true ||
			definition.value.length !== 1 ||
			definition.value[0].type === 'Text'
		) {
			parser.error(parser_errors.invalid_component_definition, definition.start);
		}
		element.expression = definition.value[0].expression;
	}
	if (name === 'svelte:element') {
		const index = element.attributes.findIndex(
			(attr) => attr.type === 'Attribute' && attr.name === 'this'
		);
		if (index === -1) {
			parser.error(parser_errors.missing_element_definition, start);
		}
		const definition = element.attributes.splice(index, 1)[0];
		if (definition.value === true) {
			parser.error(parser_errors.invalid_element_definition, definition.start);
		}
		element.tag = definition.value[0].data || definition.value[0].expression;
	}
	// special cases – top-level <script> and <style>
	if (specials.has(name) && parser.stack.length === 1) {
		const special = specials.get(name);
		parser.eat('>', true);
		const content = special.read(parser, start, element.attributes);
		if (content) parser[special.property].push(content);
		return;
	}
	parser.current().children.push(element);
	const self_closing = parser.eat('/') || is_void(name);
	parser.eat('>', true);
	if (self_closing) {
		// don't push self-closing elements onto the stack
		element.end = parser.index;
	} else if (name === 'textarea') {
		// special case
		element.children = read_sequence(
			parser,
			() => regex_closing_textarea_tag.test(parser.template.slice(parser.index)),
			'inside <textarea>'
		);
		parser.read(regex_closing_textarea_tag);
		element.end = parser.index;
	} else if (name === 'script' || name === 'style') {
		// special case
		const start = parser.index;
		const data = parser.read_until(new RegExp(`</${name}>`));
		const end = parser.index;
		element.children.push({ start, end, type: 'Text', data });
		parser.eat(`</${name}>`, true);
		element.end = parser.index;
	} else {
		parser.stack.push(element);
	}
}
const regex_whitespace_or_slash_or_closing_tag = /(\s|\/|>)/;

/**
 * @param {import('../index.js').Parser} parser
 */
function read_tag_name(parser) {
	const start = parser.index;
	if (parser.read(SELF)) {
		// check we're inside a block, otherwise this
		// will cause infinite recursion
		let i = parser.stack.length;
		let legal = false;
		while (i--) {
			const fragment = parser.stack[i];
			if (
				fragment.type === 'IfBlock' ||
				fragment.type === 'EachBlock' ||
				fragment.type === 'InlineComponent'
			) {
				legal = true;
				break;
			}
		}
		if (!legal) {
			parser.error(parser_errors.invalid_self_placement, start);
		}
		return 'svelte:self';
	}
	if (parser.read(COMPONENT)) return 'svelte:component';
	if (parser.read(ELEMENT)) return 'svelte:element';
	if (parser.read(SLOT)) return 'svelte:fragment';
	const name = parser.read_until(regex_whitespace_or_slash_or_closing_tag);
	if (meta_tags.has(name)) return name;
	if (name.startsWith('svelte:')) {
		const match = fuzzymatch(name.slice(7), valid_meta_tags);
		parser.error(parser_errors.invalid_tag_name_svelte_element(valid_meta_tags, match), start);
	}
	if (!valid_tag_name.test(name)) {
		parser.error(parser_errors.invalid_tag_name, start);
	}
	return name;
}
// eslint-disable-next-line no-useless-escape
const regex_token_ending_character = /[\s=\/>"']/;
const regex_starts_with_quote_characters = /^["']/;

/**
 * @param {import('../index.js').Parser} parser
 * @param {Set<string>} unique_names
 */
function read_attribute(parser, unique_names) {
	const start = parser.index;

	/**
	 * @param {string} name
	 */
	function check_unique(name) {
		if (unique_names.has(name)) {
			parser.error(parser_errors.duplicate_attribute, start);
		}
		unique_names.add(name);
	}
	if (parser.eat('{')) {
		parser.allow_whitespace();
		if (parser.eat('...')) {
			const expression = read_expression(parser);
			parser.allow_whitespace();
			parser.eat('}', true);
			return {
				start,
				end: parser.index,
				type: 'Spread',
				expression
			};
		} else {
			const value_start = parser.index;
			const name = parser.read_identifier();
			parser.allow_whitespace();
			parser.eat('}', true);
			if (name === null) {
				parser.error(parser_errors.empty_attribute_shorthand, start);
			}
			check_unique(name);
			return {
				start,
				end: parser.index,
				type: 'Attribute',
				name,
				value: [
					{
						start: value_start,
						end: value_start + name.length,
						type: 'AttributeShorthand',
						expression: {
							start: value_start,
							end: value_start + name.length,
							type: 'Identifier',
							name
						}
					}
				]
			};
		}
	}
	const name = parser.read_until(regex_token_ending_character);
	if (!name) return null;
	let end = parser.index;
	parser.allow_whitespace();
	const colon_index = name.indexOf(':');
	const type = colon_index !== -1 && get_directive_type(name.slice(0, colon_index));

	/**
	 * @type {any[] | true}
	 */
	let value = true;
	if (parser.eat('=')) {
		parser.allow_whitespace();
		value = read_attribute_value(parser);
		end = parser.index;
	} else if (parser.match_regex(regex_starts_with_quote_characters)) {
		parser.error(parser_errors.unexpected_token('='), parser.index);
	}
	if (type) {
		const [directive_name, ...modifiers] = name.slice(colon_index + 1).split('|');
		if (directive_name === '') {
			parser.error(parser_errors.empty_directive_name(type), start + colon_index + 1);
		}
		if (type === 'Binding' && directive_name !== 'this') {
			check_unique(directive_name);
		} else if (type !== 'EventHandler' && type !== 'Action') {
			check_unique(name);
		}
		if (type === 'Ref') {
			parser.error(parser_errors.invalid_ref_directive(directive_name), start);
		}
		if (type === 'StyleDirective') {
			return {
				start,
				end,
				type,
				name: directive_name,
				modifiers,
				value
			};
		}
		const first_value = value[0];
		let expression = null;
		if (first_value) {
			const attribute_contains_text =
				/** @type {any[]} */ (value).length > 1 || first_value.type === 'Text';
			if (attribute_contains_text) {
				parser.error(parser_errors.invalid_directive_value, first_value.start);
			} else {
				expression = first_value.expression;
			}
		}
		const directive = {
			start,
			end,
			type,
			name: directive_name,
			modifiers,
			expression
		};
		if (type === 'Transition') {
			const direction = name.slice(0, colon_index);
			directive.intro = direction === 'in' || direction === 'transition';
			directive.outro = direction === 'out' || direction === 'transition';
		}
		// Directive name is expression, e.g. <p class:isRed />
		if (!directive.expression && (type === 'Binding' || type === 'Class')) {
			directive.expression = {
				start: directive.start + colon_index + 1,
				end: directive.end,
				type: 'Identifier',
				name: directive.name
			};
		}
		return directive;
	}
	check_unique(name);
	return {
		start,
		end,
		type: 'Attribute',
		name,
		value
	};
}

/**
 * @param {string} name
 * @returns {import('../../interfaces.js').DirectiveType}
 */
function get_directive_type(name) {
	if (name === 'use') return 'Action';
	if (name === 'animate') return 'Animation';
	if (name === 'bind') return 'Binding';
	if (name === 'class') return 'Class';
	if (name === 'style') return 'StyleDirective';
	if (name === 'on') return 'EventHandler';
	if (name === 'let') return 'Let';
	if (name === 'in' || name === 'out' || name === 'transition') return 'Transition';
}

/**
 * @param {import('../index.js').Parser} parser
 */
function read_attribute_value(parser) {
	const quote_mark = parser.eat("'") ? "'" : parser.eat('"') ? '"' : null;
	if (quote_mark && parser.eat(quote_mark)) {
		return [
			{
				start: parser.index - 1,
				end: parser.index - 1,
				type: 'Text',
				raw: '',
				data: ''
			}
		];
	}
	let value;
	try {
		value = read_sequence(
			parser,
			() => {
				// handle common case of quote marks existing outside of regex for performance reasons
				if (quote_mark) return parser.match(quote_mark);
				return !!parser.match_regex(regex_starts_with_invalid_attr_value);
			},
			'in attribute value'
		);
	} catch (error) {
		if (error.code === 'parse-error') {
			// if the attribute value didn't close + self-closing tag
			// eg: `<Component test={{a:1} />`
			// acorn may throw a `Unterminated regular expression` because of `/>`
			if (parser.template.slice(error.pos - 1, error.pos + 1) === '/>') {
				parser.index = error.pos;
				parser.error(parser_errors.unclosed_attribute_value(quote_mark || '}'));
			}
		}
		throw error;
	}
	if (value.length === 0 && !quote_mark) {
		parser.error(parser_errors.missing_attribute_value);
	}
	if (quote_mark) parser.index += 1;
	return value;
}

/**
 * @param {import('../index.js').Parser} parser
 * @param {() => boolean} done
 * @param {string} location
 * @returns {import('../../interfaces.js').TemplateNode[]}
 */
function read_sequence(parser, done, location) {
	/**
	 * @type {import('../../interfaces.js').Text}
	 */
	let current_chunk = {
		start: parser.index,
		end: null,
		type: 'Text',
		raw: '',
		data: null
	};

	/**
	 * @type {import('../../interfaces.js').TemplateNode[]}
	 */
	const chunks = [];

	/**
	 * @param {number} end
	 */
	function flush(end) {
		if (current_chunk.raw) {
			current_chunk.data = decode_character_references(current_chunk.raw, true);
			current_chunk.end = end;
			chunks.push(current_chunk);
		}
	}
	while (parser.index < parser.template.length) {
		const index = parser.index;
		if (done()) {
			flush(parser.index);
			return chunks;
		} else if (parser.eat('{')) {
			if (parser.match('#')) {
				const index = parser.index - 1;
				parser.eat('#');
				const name = parser.read_until(/[^a-z]/);
				parser.error(parser_errors.invalid_logic_block_placement(location, name), index);
			} else if (parser.match('@')) {
				const index = parser.index - 1;
				parser.eat('@');
				const name = parser.read_until(/[^a-z]/);
				parser.error(parser_errors.invalid_tag_placement(location, name), index);
			}
			flush(parser.index - 1);
			parser.allow_whitespace();
			const expression = read_expression(parser);
			parser.allow_whitespace();
			parser.eat('}', true);
			chunks.push({
				start: index,
				end: parser.index,
				type: 'MustacheTag',
				expression
			});
			current_chunk = {
				start: parser.index,
				end: null,
				type: 'Text',
				raw: '',
				data: null
			};
		} else {
			current_chunk.raw += parser.template[parser.index++];
		}
	}
	parser.error(parser_errors.unexpected_eof);
}

// Adapted from https://github.com/acornjs/acorn/blob/6584815dca7440e00de841d1dad152302fdd7ca5/src/tokenize.js
// Reproduced under MIT License https://github.com/acornjs/acorn/blob/master/LICENSE

/**
 * @param {string} str
 * @param {number} i
 * @returns {number}
 */
function full_char_code_at(str, i) {
	const code = str.charCodeAt(i);
	if (code <= 0xd7ff || code >= 0xe000) return code;

	const next = str.charCodeAt(i + 1);
	return (code << 10) + next - 0x35fdc00;
}

const SQUARE_BRACKET_OPEN = '['.charCodeAt(0);
const SQUARE_BRACKET_CLOSE = ']'.charCodeAt(0);
const CURLY_BRACKET_OPEN = '{'.charCodeAt(0);
const CURLY_BRACKET_CLOSE = '}'.charCodeAt(0);

function is_bracket_open(code) {
	return code === SQUARE_BRACKET_OPEN || code === CURLY_BRACKET_OPEN;
}

function is_bracket_close(code) {
	return code === SQUARE_BRACKET_CLOSE || code === CURLY_BRACKET_CLOSE;
}

function is_bracket_pair(open, close) {
	return (
		(open === SQUARE_BRACKET_OPEN && close === SQUARE_BRACKET_CLOSE) ||
		(open === CURLY_BRACKET_OPEN && close === CURLY_BRACKET_CLOSE)
	);
}

function get_bracket_close(open) {
	if (open === SQUARE_BRACKET_OPEN) {
		return SQUARE_BRACKET_CLOSE;
	}
	if (open === CURLY_BRACKET_OPEN) {
		return CURLY_BRACKET_CLOSE;
	}
}

/**
 * @param {import('../index.js').Parser} parser
 * @returns {import('estree').Pattern & { start: number; end: number }}
 */
function read_context(parser) {
	const start = parser.index;
	let i = parser.index;

	const code = full_char_code_at(parser.template, i);
	if (isIdentifierStart(code, true)) {
		return {
			type: 'Identifier',
			name: parser.read_identifier(),
			start,
			end: parser.index
		};
	}

	if (!is_bracket_open(code)) {
		parser.error(parser_errors.unexpected_token_destructure);
	}

	const bracket_stack = [code];
	i += code <= 0xffff ? 1 : 2;

	while (i < parser.template.length) {
		const code = full_char_code_at(parser.template, i);
		if (is_bracket_open(code)) {
			bracket_stack.push(code);
		} else if (is_bracket_close(code)) {
			if (!is_bracket_pair(bracket_stack[bracket_stack.length - 1], code)) {
				parser.error(
					parser_errors.unexpected_token(
						String.fromCharCode(get_bracket_close(bracket_stack[bracket_stack.length - 1]))
					)
				);
			}
			bracket_stack.pop();
			if (bracket_stack.length === 0) {
				i += code <= 0xffff ? 1 : 2;
				break;
			}
		}
		i += code <= 0xffff ? 1 : 2;
	}

	parser.index = i;

	const pattern_string = parser.template.slice(start, i);
	try {
		// the length of the `space_with_newline` has to be start - 1
		// because we added a `(` in front of the pattern_string,
		// which shifted the entire string to right by 1
		// so we offset it by removing 1 character in the `space_with_newline`
		// to achieve that, we remove the 1st space encountered,
		// so it will not affect the `column` of the node
		let space_with_newline = parser.template
			.slice(0, start)
			.replace(regex_not_newline_characters, ' ');
		const first_space = space_with_newline.indexOf(' ');
		space_with_newline =
			space_with_newline.slice(0, first_space) + space_with_newline.slice(first_space + 1);

		return /** @type {any} */ (
			parse_expression_at(`${space_with_newline}(${pattern_string} = 1)`, start - 1)
		).left;
	} catch (error) {
		parser.acorn_error(error);
	}
}

/**
 * @param {string} str
 */
function trim_start(str) {
	return str.replace(regex_starts_with_whitespaces, '');
}

/**
 * @param {string} str
 */
function trim_end(str) {
	return str.replace(regex_ends_with_whitespaces, '');
}

/**
 * @param {import("../../interfaces.js").TemplateNode} node
 */
function to_string$1(node) {
	switch (node.type) {
		case 'IfBlock':
			return '{#if} block';
		case 'ThenBlock':
			return '{:then} block';
		case 'ElseBlock':
			return '{:else} block';
		case 'PendingBlock':
		case 'AwaitBlock':
			return '{#await} block';
		case 'CatchBlock':
			return '{:catch} block';
		case 'EachBlock':
			return '{#each} block';
		case 'RawMustacheTag':
			return '{@html} block';
		case 'DebugTag':
			return '{@debug} block';
		case 'ConstTag':
			return '{@const} tag';
		case 'Element':
		case 'InlineComponent':
		case 'Slot':
		case 'Title':
			return `<${node.name}> tag`;
		default:
			return node.type;
	}
}

/**
 * @param {import('../../interfaces.js').TemplateNode} block
 * @param {boolean} trim_before
 * @param {boolean} trim_after
 */
function trim_whitespace(block, trim_before, trim_after) {
	if (!block.children || block.children.length === 0) return; // AwaitBlock
	const first_child = block.children[0];
	const last_child = block.children[block.children.length - 1];
	if (first_child.type === 'Text' && trim_before) {
		first_child.data = trim_start(first_child.data);
		if (!first_child.data) block.children.shift();
	}
	if (last_child.type === 'Text' && trim_after) {
		last_child.data = trim_end(last_child.data);
		if (!last_child.data) block.children.pop();
	}
	if (block.else) {
		trim_whitespace(block.else, trim_before, trim_after);
	}
	if (first_child.elseif) {
		trim_whitespace(first_child, trim_before, trim_after);
	}
}
const regex_whitespace_with_closing_curly_brace = /^\s*}/;

/**
 * @param {import('../index.js').Parser} parser
 */
function mustache(parser) {
	const start = parser.index;
	parser.index += 1;
	parser.allow_whitespace();
	// {/if}, {/each}, {/await} or {/key}
	if (parser.eat('/')) {
		let block = parser.current();
		let expected;
		if (closing_tag_omitted(block.name)) {
			block.end = start;
			parser.stack.pop();
			block = parser.current();
		}
		if (
			block.type === 'ElseBlock' ||
			block.type === 'PendingBlock' ||
			block.type === 'ThenBlock' ||
			block.type === 'CatchBlock'
		) {
			block.end = start;
			parser.stack.pop();
			block = parser.current();
			expected = 'await';
		}
		if (block.type === 'IfBlock') {
			expected = 'if';
		} else if (block.type === 'EachBlock') {
			expected = 'each';
		} else if (block.type === 'AwaitBlock') {
			expected = 'await';
		} else if (block.type === 'KeyBlock') {
			expected = 'key';
		} else {
			parser.error(parser_errors.unexpected_block_close);
		}
		parser.eat(expected, true);
		parser.allow_whitespace();
		parser.eat('}', true);
		while (block.elseif) {
			block.end = parser.index;
			parser.stack.pop();
			block = parser.current();
			if (block.else) {
				block.else.end = start;
			}
		}
		// strip leading/trailing whitespace as necessary
		const char_before = parser.template[block.start - 1];
		const char_after = parser.template[parser.index];
		const trim_before = !char_before || regex_whitespace.test(char_before);
		const trim_after = !char_after || regex_whitespace.test(char_after);
		trim_whitespace(block, trim_before, trim_after);
		block.end = parser.index;
		parser.stack.pop();
	} else if (parser.eat(':else')) {
		if (parser.eat('if')) {
			parser.error(parser_errors.invalid_elseif);
		}
		parser.allow_whitespace();
		// :else if
		if (parser.eat('if')) {
			const block = parser.current();
			if (block.type !== 'IfBlock') {
				parser.error(
					parser.stack.some((block) => block.type === 'IfBlock')
						? parser_errors.invalid_elseif_placement_unclosed_block(to_string$1(block))
						: parser_errors.invalid_elseif_placement_outside_if
				);
			}
			parser.require_whitespace();
			const expression = read_expression(parser);
			parser.allow_whitespace();
			parser.eat('}', true);
			block.else = {
				start: parser.index,
				end: null,
				type: 'ElseBlock',
				children: [
					{
						start: parser.index,
						end: null,
						type: 'IfBlock',
						elseif: true,
						expression,
						children: []
					}
				]
			};
			parser.stack.push(block.else.children[0]);
		} else {
			// :else
			const block = parser.current();
			if (block.type !== 'IfBlock' && block.type !== 'EachBlock') {
				parser.error(
					parser.stack.some((block) => block.type === 'IfBlock' || block.type === 'EachBlock')
						? parser_errors.invalid_else_placement_unclosed_block(to_string$1(block))
						: parser_errors.invalid_else_placement_outside_if
				);
			}
			parser.allow_whitespace();
			parser.eat('}', true);
			block.else = {
				start: parser.index,
				end: null,
				type: 'ElseBlock',
				children: []
			};
			parser.stack.push(block.else);
		}
	} else if (parser.match(':then') || parser.match(':catch')) {
		const block = parser.current();
		const is_then = parser.eat(':then') || !parser.eat(':catch');
		if (is_then) {
			if (block.type !== 'PendingBlock') {
				parser.error(
					parser.stack.some((block) => block.type === 'PendingBlock')
						? parser_errors.invalid_then_placement_unclosed_block(to_string$1(block))
						: parser_errors.invalid_then_placement_without_await
				);
			}
		} else {
			if (block.type !== 'ThenBlock' && block.type !== 'PendingBlock') {
				parser.error(
					parser.stack.some((block) => block.type === 'ThenBlock' || block.type === 'PendingBlock')
						? parser_errors.invalid_catch_placement_unclosed_block(to_string$1(block))
						: parser_errors.invalid_catch_placement_without_await
				);
			}
		}
		block.end = start;
		parser.stack.pop();
		const await_block = parser.current();
		if (!parser.eat('}')) {
			parser.require_whitespace();
			await_block[is_then ? 'value' : 'error'] = read_context(parser);
			parser.allow_whitespace();
			parser.eat('}', true);
		}
		const new_block = {
			start,
			end: null,
			type: is_then ? 'ThenBlock' : 'CatchBlock',
			children: [],
			skip: false
		};
		await_block[is_then ? 'then' : 'catch'] = new_block;
		parser.stack.push(new_block);
	} else if (parser.eat('#')) {
		// {#if foo}, {#each foo} or {#await foo}
		let type;
		if (parser.eat('if')) {
			type = 'IfBlock';
		} else if (parser.eat('each')) {
			type = 'EachBlock';
		} else if (parser.eat('await')) {
			type = 'AwaitBlock';
		} else if (parser.eat('key')) {
			type = 'KeyBlock';
		} else {
			parser.error(parser_errors.expected_block_type);
		}
		parser.require_whitespace();
		const expression = read_expression(parser);
		const block =
			type === 'AwaitBlock'
				? {
						start,
						end: null,
						type,
						expression,
						value: null,
						error: null,
						pending: {
							start: null,
							end: null,
							type: 'PendingBlock',
							children: [],
							skip: true
						},
						then: {
							start: null,
							end: null,
							type: 'ThenBlock',
							children: [],
							skip: true
						},
						catch: {
							start: null,
							end: null,
							type: 'CatchBlock',
							children: [],
							skip: true
						}
				  }
				: {
						start,
						end: null,
						type,
						expression,
						children: []
				  };
		parser.allow_whitespace();
		// {#each} blocks must declare a context – {#each list as item}
		if (type === 'EachBlock') {
			parser.eat('as', true);
			parser.require_whitespace();
			block.context = read_context(parser);
			parser.allow_whitespace();
			if (parser.eat(',')) {
				parser.allow_whitespace();
				block.index = parser.read_identifier();
				if (!block.index) parser.error(parser_errors.expected_name);
				parser.allow_whitespace();
			}
			if (parser.eat('(')) {
				parser.allow_whitespace();
				block.key = read_expression(parser);
				parser.allow_whitespace();
				parser.eat(')', true);
				parser.allow_whitespace();
			}
		}
		const await_block_shorthand = type === 'AwaitBlock' && parser.eat('then');
		if (await_block_shorthand) {
			if (parser.match_regex(regex_whitespace_with_closing_curly_brace)) {
				parser.allow_whitespace();
			} else {
				parser.require_whitespace();
				block.value = read_context(parser);
				parser.allow_whitespace();
			}
		}
		const await_block_catch_shorthand =
			!await_block_shorthand && type === 'AwaitBlock' && parser.eat('catch');
		if (await_block_catch_shorthand) {
			if (parser.match_regex(regex_whitespace_with_closing_curly_brace)) {
				parser.allow_whitespace();
			} else {
				parser.require_whitespace();
				block.error = read_context(parser);
				parser.allow_whitespace();
			}
		}
		parser.eat('}', true);
		parser.current().children.push(block);
		parser.stack.push(block);
		if (type === 'AwaitBlock') {
			let child_block;
			if (await_block_shorthand) {
				block.then.skip = false;
				child_block = block.then;
			} else if (await_block_catch_shorthand) {
				block.catch.skip = false;
				child_block = block.catch;
			} else {
				block.pending.skip = false;
				child_block = block.pending;
			}
			child_block.start = parser.index;
			parser.stack.push(child_block);
		}
	} else if (parser.eat('@html')) {
		// {@html content} tag
		parser.require_whitespace();
		const expression = read_expression(parser);
		parser.allow_whitespace();
		parser.eat('}', true);
		parser.current().children.push({
			start,
			end: parser.index,
			type: 'RawMustacheTag',
			expression
		});
	} else if (parser.eat('@debug')) {
		let identifiers;
		// Implies {@debug} which indicates "debug all"
		if (parser.read(regex_whitespace_with_closing_curly_brace)) {
			identifiers = [];
		} else {
			const expression = read_expression(parser);
			identifiers =
				expression.type === 'SequenceExpression' ? expression.expressions : [expression];
			identifiers.forEach((node) => {
				if (node.type !== 'Identifier') {
					parser.error(parser_errors.invalid_debug_args, node.start);
				}
			});
			parser.allow_whitespace();
			parser.eat('}', true);
		}
		parser.current().children.push({
			start,
			end: parser.index,
			type: 'DebugTag',
			identifiers
		});
	} else if (parser.eat('@const')) {
		// {@const a = b}
		parser.require_whitespace();
		const expression = read_expression(parser);
		if (!(expression.type === 'AssignmentExpression' && expression.operator === '=')) {
			parser.error(
				{
					code: 'invalid-const-args',
					message: '{@const ...} must be an assignment.'
				},
				start
			);
		}
		parser.allow_whitespace();
		parser.eat('}', true);
		parser.current().children.push({
			start,
			end: parser.index,
			type: 'ConstTag',
			expression
		});
	} else {
		const expression = read_expression(parser);
		parser.allow_whitespace();
		parser.eat('}', true);
		parser.current().children.push({
			start,
			end: parser.index,
			type: 'MustacheTag',
			expression
		});
	}
}

/**
 * @param {import('../index.js').Parser} parser
 */
function text(parser) {
	const start = parser.index;

	let data = '';

	while (parser.index < parser.template.length && !parser.match('<') && !parser.match('{')) {
		data += parser.template[parser.index++];
	}

	const node = {
		start,
		end: parser.index,
		type: 'Text',
		raw: data,
		data: decode_character_references(data, false)
	};

	parser.current().children.push(node);
}

/**
 * @param {import('../index.js').Parser} parser
 */
function fragment(parser) {
	if (parser.match('<')) {
		return tag;
	}

	if (parser.match('{')) {
		return mustache;
	}

	return text;
}

const reserved = new Set([
	'arguments',
	'await',
	'break',
	'case',
	'catch',
	'class',
	'const',
	'continue',
	'debugger',
	'default',
	'delete',
	'do',
	'else',
	'enum',
	'eval',
	'export',
	'extends',
	'false',
	'finally',
	'for',
	'function',
	'if',
	'implements',
	'import',
	'in',
	'instanceof',
	'interface',
	'let',
	'new',
	'null',
	'package',
	'private',
	'protected',
	'public',
	'return',
	'static',
	'super',
	'switch',
	'this',
	'throw',
	'true',
	'try',
	'typeof',
	'var',
	'void',
	'while',
	'with',
	'yield'
]);

/**
 * @param {string} str
 * @returns {boolean}
 */
function is_valid(str) {
	let i = 0;

	while (i < str.length) {
		const code = full_char_code_at(str, i);
		if (!(i === 0 ? isIdentifierStart : isIdentifierChar)(code, true)) return false;

		i += code <= 0xffff ? 1 : 2;
	}

	return true;
}

const regex_non_standard_characters = /[^a-zA-Z0-9_]+/g;
const regex_starts_with_number = /^[0-9]/;

/**
 * @param {string} name
 */
function sanitize(name) {
	return name
		.replace(regex_non_standard_characters, '_')
		.replace(regex_starts_with_underscore, '')
		.replace(regex_ends_with_underscore, '')
		.replace(regex_starts_with_number, '_$&');
}

/** @typedef {import('./types').Location} Location */

/**
 * @param {import('./types').Range} range
 * @param {number} index
 */
function rangeContains(range, index) {
	return range.start <= index && index < range.end;
}

/**
 * @param {string} source
 * @param {import('./types').Options} [options]
 */
function getLocator$1(source, options = {}) {
	const { offsetLine = 0, offsetColumn = 0 } = options;

	let start = 0;
	const ranges = source.split('\n').map((line, i) => {
		const end = start + line.length + 1;

		/** @type {import('./types').Range} */
		const range = { start, end, line: i };

		start = end;
		return range;
	});

	let i = 0;

	/**
	 * @param {string | number} search
	 * @param {number} [index]
	 * @returns {Location | undefined}
	 */
	function locator(search, index) {
		if (typeof search === 'string') {
			search = source.indexOf(search, index ?? 0);
		}

		if (search === -1) return undefined;

		let range = ranges[i];

		const d = search >= range.end ? 1 : -1;

		while (range) {
			if (rangeContains(range, search)) {
				return {
					line: offsetLine + range.line,
					column: offsetColumn + search - range.start,
					character: search
				};
			}

			i += d;
			range = ranges[i];
		}
	}

	return locator;
}

/**
 * @param {string} source
 * @param {string | number} search
 * @param {import('./types').Options} [options]
 * @returns {Location | undefined}
 */
function locate(source, search, options) {
	return getLocator$1(source, options)(search, options && options.startIndex);
}

const regex_tabs = /^\t+/;

/**
 * @param {string} str
 */
function tabs_to_spaces(str) {
	return str.replace(regex_tabs, (match) => match.split('\t').join('  '));
}

/**
 * @param {string} source
 * @param {number} line
 * @param {number} column
 */
function get_code_frame(source, line, column) {
	const lines = source.split('\n');
	const frame_start = Math.max(0, line - 2);
	const frame_end = Math.min(line + 3, lines.length);
	const digits = String(frame_end + 1).length;
	return lines
		.slice(frame_start, frame_end)
		.map((str, i) => {
			const is_error_line = frame_start + i === line;
			const line_num = String(i + frame_start + 1).padStart(digits, ' ');
			if (is_error_line) {
				const indicator =
					' '.repeat(digits + 2 + tabs_to_spaces(str.slice(0, column)).length) + '^';
				return `${line_num}: ${tabs_to_spaces(str)}\n${indicator}`;
			}
			return `${line_num}: ${tabs_to_spaces(str)}`;
		})
		.join('\n');
}

/**
 * @extends Error
 */
class CompileError extends Error {
	/**
	 * @type {string}
	 */
	code = undefined;

	/**
	 * @type {{ line: number; column: number }}
	 */
	start = undefined;

	/**
	 * @type {{ line: number; column: number }}
	 */
	end = undefined;

	/**
	 * @type {number}
	 */
	pos = undefined;

	/**
	 * @type {string}
	 */
	filename = undefined;

	/**
	 * @type {string}
	 */
	frame = undefined;

	toString() {
		return `${this.message} (${this.start.line}:${this.start.column})\n${this.frame}`;
	}
}

/**
 * @param {string} message
 * @param {{
 * 		name: string;
 * 		code: string;
 * 		source: string;
 * 		filename: string;
 * 		start: number;
 * 		end?: number;
 * 	}} props
 * @returns {never}
 */
function error(message, props) {
	const error = new CompileError(message);
	error.name = props.name;
	const start = locate(props.source, props.start, { offsetLine: 1 });
	const end = locate(props.source, props.end || props.start, { offsetLine: 1 });
	error.code = props.code;
	error.start = start;
	error.end = end;
	error.pos = props.start;
	error.filename = props.filename;
	error.frame = get_code_frame(props.source, start.line - 1, start.column);
	throw error;
}

const regex_position_indicator = / \(\d+:\d+\)$/;

class Parser {
	/**
	 * @readonly
	 * @type {string}
	 */
	template = undefined;

	/**
	 * @readonly
	 * @type {string}
	 */
	filename = undefined;

	/**
	 * @readonly
	 * @type {boolean}
	 */
	customElement = undefined;

	/**
	 * @readonly
	 * @type {'injected' | 'external' | 'none' | boolean}
	 */
	css_mode = undefined;

	index = 0;

	/**
	 * @type {import('../interfaces.js').TemplateNode[]}
	 */
	stack = [];

	/**
	 * @type {import('../interfaces.js').Fragment}
	 */
	html = undefined;

	/**
	 * @type {import('../interfaces.js').Style[]}
	 */
	css = [];

	/**
	 * @type {import('../interfaces.js').Script[]}
	 */
	js = [];

	meta_tags = {};

	/**
	 * @type {{tag: string; reason: string; depth: number;}}
	 */
	last_auto_closed_tag = undefined;

	/**
	 * @param {string} template
	 * @param {import('../interfaces.js').ParserOptions} options
	 */
	constructor(template, options) {
		if (typeof template !== 'string') {
			throw new TypeError('Template must be a string');
		}
		this.template = template.trimRight();
		this.filename = options.filename;
		this.customElement = options.customElement;
		this.css_mode = options.css;
		this.html = {
			start: null,
			end: null,
			type: 'Fragment',
			children: []
		};
		this.stack.push(this.html);

		/**
		 * @typedef {(parser: Parser) => ParserState | void} ParserState
		 */

		/** @type {ParserState} */
		let state = fragment;
		while (this.index < this.template.length) {
			state = state(this) || fragment;
		}
		if (this.stack.length > 1) {
			const current = this.current();
			const type = current.type === 'Element' ? `<${current.name}>` : 'Block';
			const slug = current.type === 'Element' ? 'element' : 'block';
			this.error(
				{
					code: `unclosed-${slug}`,
					message: `${type} was left open`
				},
				current.start
			);
		}
		if (state !== fragment) {
			this.error({
				code: 'unexpected-eof',
				message: 'Unexpected end of input'
			});
		}
		if (this.html.children.length) {
			let start = this.html.children[0].start;
			while (regex_whitespace.test(template[start])) start += 1;
			let end = this.html.children[this.html.children.length - 1].end;
			while (regex_whitespace.test(template[end - 1])) end -= 1;
			this.html.start = start;
			this.html.end = end;
		} else {
			this.html.start = this.html.end = null;
		}
	}
	current() {
		return this.stack[this.stack.length - 1];
	}

	/**
	 * @param {any} err
	 */
	acorn_error(err) {
		this.error(
			{
				code: 'parse-error',
				message: err.message.replace(regex_position_indicator, '')
			},
			err.pos
		);
	}

	/**
	 * @param {{ code: string; message: string }} err
	 */
	error({ code, message }, index = this.index) {
		error(message, {
			name: 'ParseError',
			code,
			source: this.template,
			start: index,
			filename: this.filename
		});
	}

	/**
	 * @param {string} str
	 * @param {boolean} [required]
	 * @param {{ code: string; message: string }} [error]
	 */
	eat(str, required, error) {
		if (this.match(str)) {
			this.index += str.length;
			return true;
		}
		if (required) {
			this.error(
				error ||
					(this.index === this.template.length
						? parser_errors.unexpected_eof_token(str)
						: parser_errors.unexpected_token(str))
			);
		}
		return false;
	}

	/**
	 * @param {string} str
	 */
	match(str) {
		return this.template.slice(this.index, this.index + str.length) === str;
	}
	/**
	 * Match a regex at the current index
	 * @param {RegExp} pattern  Should have a ^ anchor at the start so the regex doesn't search past the beginning, resulting in worse performance
	 */
	match_regex(pattern) {
		const match = pattern.exec(this.template.slice(this.index));
		if (!match || match.index !== 0) return null;
		return match[0];
	}
	allow_whitespace() {
		while (this.index < this.template.length && regex_whitespace.test(this.template[this.index])) {
			this.index++;
		}
	}
	/**
	 * Search for a regex starting at the current index and return the result if it matches
	 * @param {RegExp} pattern  Should have a ^ anchor at the start so the regex doesn't search past the beginning, resulting in worse performance
	 */
	read(pattern) {
		const result = this.match_regex(pattern);
		if (result) this.index += result.length;
		return result;
	}
	read_identifier(allow_reserved = false) {
		const start = this.index;
		let i = this.index;
		const code = full_char_code_at(this.template, i);
		if (!isIdentifierStart(code, true)) return null;
		i += code <= 0xffff ? 1 : 2;
		while (i < this.template.length) {
			const code = full_char_code_at(this.template, i);
			if (!isIdentifierChar(code, true)) break;
			i += code <= 0xffff ? 1 : 2;
		}
		const identifier = this.template.slice(this.index, (this.index = i));
		if (!allow_reserved && reserved.has(identifier)) {
			this.error(
				{
					code: 'unexpected-reserved-word',
					message: `'${identifier}' is a reserved word in JavaScript and cannot be used here`
				},
				start
			);
		}
		return identifier;
	}

	/**
	 * @param {RegExp} pattern
	 * @param {Parameters<Parser['error']>[0]} [error_message]
	 */
	read_until(pattern, error_message) {
		if (this.index >= this.template.length) {
			this.error(
				error_message || {
					code: 'unexpected-eof',
					message: 'Unexpected end of input'
				}
			);
		}
		const start = this.index;
		const match = pattern.exec(this.template.slice(start));
		if (match) {
			this.index = start + match.index;
			return this.template.slice(start, this.index);
		}
		this.index = this.template.length;
		return this.template.slice(start);
	}
	require_whitespace() {
		if (!regex_whitespace.test(this.template[this.index])) {
			this.error({
				code: 'missing-whitespace',
				message: 'Expected whitespace'
			});
		}
		this.allow_whitespace();
	}
}

/**
 * The parse function parses a component, returning only its abstract syntax tree.
 *
 * https://svelte.dev/docs/svelte-compiler#svelte-parse
 * @param {string} template
 * @param {import('../interfaces.js').ParserOptions} options
 * @returns {import('../interfaces.js').Ast}
 */
function parse(template, options = {}) {
	const parser = new Parser(template, options);
	// TODO we may want to allow multiple <style> tags —
	// one scoped, one global. for now, only allow one
	if (parser.css.length > 1) {
		parser.error(parser_errors.duplicate_style, parser.css[1].start);
	}
	const instance_scripts = parser.js.filter((script) => script.context === 'default');
	const module_scripts = parser.js.filter((script) => script.context === 'module');
	if (instance_scripts.length > 1) {
		parser.error(parser_errors.invalid_script_instance, instance_scripts[1].start);
	}
	if (module_scripts.length > 1) {
		parser.error(parser_errors.invalid_script_module, module_scripts[1].start);
	}
	return {
		html: parser.html,
		css: parser.css[0],
		instance: instance_scripts[0],
		module: module_scripts[0]
	};
}

/**
 * @param {import("estree").Node} node
 */
function is_head(node) {
	return (
		node &&
		node.type === 'MemberExpression' &&
		node.object['name'] === '@_document' &&
		node.property['name'] === 'head'
	);
}

let Block$1 = class Block {
	/**
	 * @typedef {Object} Bindings
	 * @property {import('estree').Identifier} object
	 * @property {import('estree').Identifier} property
	 * @property {import('estree').Node} snippet
	 * @property {string} store
	 * @property {(node:import('estree').Node) => import('estree').Node} modifier
	 */
	/**
	 * @typedef {Object} BlockOptions
	 * @property {Block} [parent]
	 * @property {import('estree').Identifier} name
	 * @property {string} type
	 * @property {import('./Renderer.js').default} [renderer]
	 * @property {string} [comment]
	 * @property {import('estree').Identifier} [key]
	 * @property {Map<string,Bindings>} [bindings]
	 * @property {Set<string>} [dependencies]
	 */

	/** @type {Block} */
	parent;

	/** @type {import('./Renderer.js').default} */
	renderer;

	/** @type {import('estree').Identifier} */
	name;

	/** @type {string} */
	type;

	/** @type {string} */
	comment;

	/** @type {import('./wrappers/shared/Wrapper.js').default[]} */
	wrappers;

	/** @type {import('estree').Identifier} */
	key;

	/** @type {import('estree').Identifier} */
	first;

	/** @type {Set<string>} */
	dependencies = new Set();

	/** @type {Map<string, Bindings>} */
	bindings;

	/** @type {Set<string>} */
	binding_group_initialised = new Set();

	/** @type {Set<import('./Renderer.js').BindingGroup>} */
	binding_groups = new Set();
	/**
	 * @type {{
	 * 		declarations: Array<import('estree').Node | import('estree').Node[]>;
	 * 		init: Array<import('estree').Node | import('estree').Node[]>;
	 * 		create: Array<import('estree').Node | import('estree').Node[]>;
	 * 		claim: Array<import('estree').Node | import('estree').Node[]>;
	 * 		hydrate: Array<import('estree').Node | import('estree').Node[]>;
	 * 		mount: Array<import('estree').Node | import('estree').Node[]>;
	 * 		measure: Array<import('estree').Node | import('estree').Node[]>;
	 * 		restore_measurements: Array<import('estree').Node | import('estree').Node[]>;
	 * 		fix: Array<import('estree').Node | import('estree').Node[]>;
	 * 		animate: Array<import('estree').Node | import('estree').Node[]>;
	 * 		intro: Array<import('estree').Node | import('estree').Node[]>;
	 * 		update: Array<import('estree').Node | import('estree').Node[]>;
	 * 		outro: Array<import('estree').Node | import('estree').Node[]>;
	 * 		destroy: Array<import('estree').Node | import('estree').Node[]>;
	 * 	}}
	 */
	chunks;

	/** @type {import('estree').Node[]} */
	event_listeners = [];

	/** @type {boolean} */
	maintain_context;

	/** @type {boolean} */
	has_animation;

	/** @type {boolean} */
	has_intros;

	/** @type {boolean} */
	has_outros;

	/** @type {boolean} */
	has_intro_method; // could have the method without the transition, due to siblings

	/** @type {boolean} */
	has_outro_method;

	/** @type {number} */
	outros;

	/** @type {Map<string, import('estree').Identifier>} */
	aliases;

	/** @type {Map<string, { id: import('estree').Identifier; init?: import('estree').Node }>} */
	variables = new Map();

	/** @type {(name: string) => import('estree').Identifier} */
	get_unique_name;
	/** */
	has_update_method = false;

	/** @type {{ element_var: string; condition_expression?: any }} */
	autofocus;

	/** @param {BlockOptions} options */
	constructor(options) {
		this.parent = options.parent;
		this.renderer = options.renderer;
		this.name = options.name;
		this.type = options.type;
		this.comment = options.comment;
		this.wrappers = [];
		// for keyed each blocks
		this.key = options.key;
		this.first = null;
		this.bindings = options.bindings;
		this.chunks = {
			declarations: [],
			init: [],
			create: [],
			claim: [],
			hydrate: [],
			mount: [],
			measure: [],
			restore_measurements: [],
			fix: [],
			animate: [],
			intro: [],
			update: [],
			outro: [],
			destroy: []
		};
		this.has_animation = false;
		this.has_intro_method = false; // a block could have an intro method but not intro transitions, e.g. if a sibling block has intros
		this.has_outro_method = false;
		this.outros = 0;
		this.get_unique_name = this.renderer.component.get_unique_name_maker();
		this.aliases = new Map();
		if (this.key) this.aliases.set('key', this.get_unique_name('key'));
	}

	assign_variable_names() {
		/** @type {Set<string>} */
		const seen = new Set();

		/** @type {Set<string>} */
		const dupes = new Set();
		let i = this.wrappers.length;
		while (i--) {
			const wrapper = this.wrappers[i];
			if (!wrapper.var) continue;
			if (seen.has(wrapper.var.name)) {
				dupes.add(wrapper.var.name);
			}
			seen.add(wrapper.var.name);
		}
		const counts = new Map();
		i = this.wrappers.length;
		while (i--) {
			const wrapper = this.wrappers[i];
			if (!wrapper.var) continue;
			let suffix = '';
			if (dupes.has(wrapper.var.name)) {
				const i = counts.get(wrapper.var.name) || 0;
				counts.set(wrapper.var.name, i + 1);
				suffix = i;
			}
			wrapper.var.name = this.get_unique_name(wrapper.var.name + suffix).name;
		}
	}

	/** @param {Set<string>} dependencies */
	add_dependencies(dependencies) {
		dependencies.forEach((dependency) => {
			this.dependencies.add(dependency);
		});
		this.has_update_method = true;
		if (this.parent) {
			this.parent.add_dependencies(dependencies);
		}
	}

	/**
	 * @param {import('estree').Identifier} id
	 * @param {import('estree').Node} render_statement
	 * @param {import('estree').Node} claim_statement
	 * @param {import('estree').Node} parent_node
	 * @param {boolean} [no_detach]
	 */
	add_element(id, render_statement, claim_statement, parent_node, no_detach) {
		this.add_variable(id);
		this.chunks.create.push(b$1`${id} = ${render_statement};`);
		if (this.renderer.options.hydratable) {
			this.chunks.claim.push(b$1`${id} = ${claim_statement || render_statement};`);
		}
		if (parent_node) {
			this.chunks.mount.push(b$1`@append(${parent_node}, ${id});`);
			if (is_head(parent_node) && !no_detach) this.chunks.destroy.push(b$1`@detach(${id});`);
		} else {
			this.chunks.mount.push(b$1`@insert(#target, ${id}, #anchor);`);
			if (!no_detach) this.chunks.destroy.push(b$1`if (detaching) @detach(${id});`);
		}
	}

	/** @param {boolean} [local] */
	add_intro(local) {
		this.has_intros = this.has_intro_method = true;
		if (!local && this.parent) this.parent.add_intro();
	}

	/** @param {boolean} [local] */
	add_outro(local) {
		this.has_outros = this.has_outro_method = true;
		this.outros += 1;
		if (!local && this.parent) this.parent.add_outro();
	}

	add_animation() {
		this.has_animation = true;
	}

	/**
	 * @param {import('estree').Identifier} id
	 * @param {import('estree').Node} [init]
	 */
	add_variable(id, init) {
		if (this.variables.has(id.name)) {
			throw new Error(`Variable '${id.name}' already initialised with a different value`);
		}
		this.variables.set(id.name, { id, init });
	}

	/** @param {string} name */
	alias(name) {
		if (!this.aliases.has(name)) {
			this.aliases.set(name, this.get_unique_name(name));
		}
		return this.aliases.get(name);
	}

	/** @param {BlockOptions} options */
	child(options) {
		return new Block(Object.assign({}, this, { key: null }, options, { parent: this }));
	}

	/** @param {any} [key] */
	get_contents(key) {
		const { dev } = this.renderer.options;
		if (this.has_outros) {
			this.add_variable({ type: 'Identifier', name: '#current' });
			if (this.chunks.intro.length > 0) {
				this.chunks.intro.push(b$1`#current = true;`);
				this.chunks.mount.push(b$1`#current = true;`);
			}
			if (this.chunks.outro.length > 0) {
				this.chunks.outro.push(b$1`#current = false;`);
			}
		}
		if (this.autofocus) {
			if (this.autofocus.condition_expression) {
				this.chunks.mount.push(
					b$1`if (${this.autofocus.condition_expression}) ${this.autofocus.element_var}.focus();`
				);
			} else {
				this.chunks.mount.push(b$1`${this.autofocus.element_var}.focus();`);
			}
		}
		this.render_binding_groups();
		this.render_listeners();

		/** @type {Record<string, any>} */
		const properties = {};
		const noop = x$1`@noop`;
		properties.key = key;
		if (this.first) {
			properties.first = x$1`null`;
			this.chunks.hydrate.push(b$1`this.first = ${this.first};`);
		}
		if (this.chunks.create.length === 0 && this.chunks.hydrate.length === 0) {
			properties.create = noop;
		} else {
			const hydrate =
				this.chunks.hydrate.length > 0 &&
				(this.renderer.options.hydratable ? b$1`this.h();` : this.chunks.hydrate);
			properties.create = x$1`function #create() {
				${this.chunks.create}
				${hydrate}
			}`;
		}
		if (this.renderer.options.hydratable || this.chunks.claim.length > 0) {
			if (this.chunks.claim.length === 0 && this.chunks.hydrate.length === 0) {
				properties.claim = noop;
			} else {
				properties.claim = x$1`function #claim(#nodes) {
					${this.chunks.claim}
					${this.renderer.options.hydratable && this.chunks.hydrate.length > 0 && b$1`this.h();`}
				}`;
			}
		}
		if (this.renderer.options.hydratable && this.chunks.hydrate.length > 0) {
			properties.hydrate = x$1`function #hydrate() {
				${this.chunks.hydrate}
			}`;
		}
		if (this.chunks.mount.length === 0) {
			properties.mount = noop;
		} else if (this.event_listeners.length === 0) {
			properties.mount = x$1`function #mount(#target, #anchor) {
				${this.chunks.mount}
			}`;
		} else {
			properties.mount = x$1`function #mount(#target, #anchor) {
				${this.chunks.mount}
			}`;
		}
		if (this.has_update_method || this.maintain_context) {
			if (this.chunks.update.length === 0 && !this.maintain_context) {
				properties.update = noop;
			} else {
				const ctx = this.maintain_context ? x$1`#new_ctx` : x$1`#ctx`;

				/** @type {import('estree').Identifier | import('estree').ArrayPattern} */
				let dirty = { type: 'Identifier', name: '#dirty' };
				if (!this.renderer.context_overflow && !this.parent) {
					dirty = { type: 'ArrayPattern', elements: [dirty] };
				}
				properties.update = x$1`function #update(${ctx}, ${dirty}) {
					${this.maintain_context && b$1`#ctx = ${ctx};`}
					${this.chunks.update}
				}`;
			}
		}
		if (this.has_animation) {
			properties.measure = x$1`function #measure() {
				${this.chunks.measure}
			}`;
			if (this.chunks.restore_measurements.length) {
				properties.restore_measurements = x$1`function #restore_measurements(#measurement) {
					${this.chunks.restore_measurements}
				}`;
			}
			properties.fix = x$1`function #fix() {
				${this.chunks.fix}
			}`;
			properties.animate = x$1`function #animate() {
				${this.chunks.animate}
			}`;
		}
		if (this.has_intro_method || this.has_outro_method) {
			if (this.chunks.intro.length === 0) {
				properties.intro = noop;
			} else {
				properties.intro = x$1`function #intro(#local) {
					${this.has_outros && b$1`if (#current) return;`}
					${this.chunks.intro}
				}`;
			}
			if (this.chunks.outro.length === 0) {
				properties.outro = noop;
			} else {
				properties.outro = x$1`function #outro(#local) {
					${this.chunks.outro}
				}`;
			}
		}
		if (this.chunks.destroy.length === 0) {
			properties.destroy = noop;
		} else {
			const dispose_elements = [];
			// Coalesce if blocks with the same condition
			const others = flatten$1(this.chunks.destroy).filter(
				/** @param {import('estree').Node} node */
				(node) => {
					if (
						node.type === 'IfStatement' &&
						node.test.type === 'Identifier' &&
						node.test.name === 'detaching'
					) {
						dispose_elements.push(node.consequent);
						return false;
					} else {
						return true;
					}
				}
			);

			properties.destroy = x$1`function #destroy(detaching) {
				${dispose_elements.length ? b$1`if (detaching) { ${dispose_elements} }` : null}
				${others}
			}`;
		}
		if (!this.renderer.component.compile_options.dev) {
			// allow shorthand names
			for (const name in properties) {
				const property = properties[name];
				if (property) property.id = null;
			}
		}

		/** @type {any} */
		const return_value = x$1`{
			key: ${properties.key},
			first: ${properties.first},
			c: ${properties.create},
			l: ${properties.claim},
			h: ${properties.hydrate},
			m: ${properties.mount},
			p: ${properties.update},
			r: ${properties.measure},
			s: ${properties.restore_measurements},
			f: ${properties.fix},
			a: ${properties.animate},
			i: ${properties.intro},
			o: ${properties.outro},
			d: ${properties.destroy}
		}`;
		const block = dev && this.get_unique_name('block');
		const body = b$1`
			${this.chunks.declarations}

			${Array.from(this.variables.values()).map(({ id, init }) => {
				return init ? b$1`let ${id} = ${init}` : b$1`let ${id}`;
			})}

			${this.chunks.init}

			${
				dev
					? b$1`
					const ${block} = ${return_value};
					@dispatch_dev("SvelteRegisterBlock", {
						block: ${block},
						id: ${this.name || 'create_fragment'}.name,
						type: "${this.type}",
						source: "${this.comment ? this.comment.replace(regex_double_quotes, '\\"') : ''}",
						ctx: #ctx
					});
					return ${block};`
					: b$1`
					return ${return_value};`
			}
		`;
		return body;
	}

	/** @returns {boolean} */
	has_content() {
		return (
			!!this.first ||
			this.event_listeners.length > 0 ||
			this.chunks.intro.length > 0 ||
			this.chunks.outro.length > 0 ||
			this.chunks.create.length > 0 ||
			this.chunks.hydrate.length > 0 ||
			this.chunks.claim.length > 0 ||
			this.chunks.mount.length > 0 ||
			this.chunks.update.length > 0 ||
			this.chunks.destroy.length > 0 ||
			this.has_animation
		);
	}

	render() {
		const key = this.key && this.get_unique_name('key');

		/** @type {any[]} */
		const args = [x$1`#ctx`];
		if (key) args.unshift(key);
		const fn = b$1`function ${this.name}(${args}) {
			${this.get_contents(key)}
		}`;
		return this.comment
			? b$1`
				// ${this.comment}
				${fn}`
			: fn;
	}

	/** @param {string} chunk */
	render_listeners(chunk = '') {
		if (this.event_listeners.length > 0) {
			this.add_variable({ type: 'Identifier', name: '#mounted' });
			this.chunks.destroy.push(b$1`#mounted = false`);

			/** @type {import('estree').Identifier} */
			const dispose = {
				type: 'Identifier',
				name: `#dispose${chunk}`
			};
			this.add_variable(dispose);
			if (this.event_listeners.length === 1) {
				this.chunks.mount.push(b$1`
						if (!#mounted) {
							${dispose} = ${this.event_listeners[0]};
							#mounted = true;
						}
					`);
				this.chunks.destroy.push(b$1`${dispose}();`);
			} else {
				this.chunks.mount.push(b$1`
					if (!#mounted) {
						${dispose} = [
							${this.event_listeners}
						];
						#mounted = true;
					}
				`);
				this.chunks.destroy.push(b$1`@run_all(${dispose});`);
			}
		}
	}
	render_binding_groups() {
		for (const binding_group of this.binding_groups) {
			binding_group.render(this);
		}
	}
};

/**
 * @template {import('../../../../interfaces.js').TemplateNode} [NodeType=import('../../../../interfaces.js').TemplateNode]
 */
class Wrapper {
	/** @type {import('../../Renderer.js').default} */
	renderer;

	/** @type {Wrapper} */
	parent;

	/** @type {NodeType} */
	node;

	/** @type {Wrapper | null} */
	prev;

	/** @type {Wrapper | null} */
	next;

	/** @type {import('estree').Identifier} */
	var;

	/**
	 * @param {import('../../Renderer.js').default} renderer
	 * @param {import('../../Block.js').default} block
	 * @param {Wrapper} parent
	 * @param {NodeType} node
	 */
	constructor(renderer, block, parent, node) {
		this.node = node;
		// make these non-enumerable so that they can be logged sensibly
		// (TODO in dev only?)
		Object.defineProperties(this, {
			renderer: {
				value: renderer
			},
			parent: {
				value: parent
			}
		});
		block.wrappers.push(this);
	}

	/**
	 * @param {import('../../Block.js').default} block
	 * @param {import('estree').Identifier} parent_node
	 * @param {import('estree').Identifier} parent_nodes
	 */
	get_or_create_anchor(block, parent_node, parent_nodes) {
		// TODO use this in EachBlock and IfBlock — tricky because
		// children need to be created first
		const needs_anchor = this.next
			? !this.next.is_dom_node()
			: !parent_node || !this.parent.is_dom_node();
		const anchor = needs_anchor
			? block.get_unique_name(`${this.var.name}_anchor`)
			: (this.next && this.next.var) || { type: 'Identifier', name: 'null' };
		if (needs_anchor) {
			block.add_element(
				anchor,
				x$1`@empty()`,
				parent_nodes && x$1`@empty()`,
				/** @type {import('estree').Identifier} */ (parent_node)
			);
		}
		return anchor;
	}

	/**
	 * @param {import('estree').Identifier} anchor
	 * @returns {import('estree').Identifier}
	 */
	get_update_mount_node(anchor) {
		return /** @type {import('estree').Identifier} */ (
			this.parent && this.parent.is_dom_node() ? this.parent.var : x$1`${anchor}.parentNode`
		);
	}
	is_dom_node() {
		return (
			this.node.type === 'Element' || this.node.type === 'Text' || this.node.type === 'MustacheTag'
		);
	}

	/**
	 * @param {import('../../Block.js').default} _block
	 * @param {import('estree').Identifier} _parent_node
	 * @param {import('estree').Identifier} _parent_nodes
	 * @param {Record<string, any>} _data
	 */
	render(_block, _parent_node, _parent_nodes, _data = undefined) {
		throw Error('Wrapper class is not renderable');
	}
}

/**
 * @param {import('../../../nodes/interfaces.js').INode} node
 * @param {import('../../../Component.js').default} component
 */
function create_debugging_comment(node, component) {
	const { locate, source } = component;
	let c = node.start;
	if (node.type === 'ElseBlock') {
		while (source[c - 1] !== '{') c -= 1;
		while (source[c - 1] === '{') c -= 1;
	}

	/** @type {number} */
	let d;
	if (node.type === 'InlineComponent' || node.type === 'Element' || node.type === 'SlotTemplate') {
		if (node.children.length) {
			d = node.children[0].start;
			while (source[d - 1] !== '>') d -= 1;
		} else {
			d = node.start;
			while (source[d] !== '>') d += 1;
			d += 1;
		}
	} else if (node.type === 'Text' || node.type === 'Comment') {
		d = node.end;
	} else {
		// @ts-ignore
		d = node.expression ? node.expression.node.end : c;
		while (source[d] !== '}' && d <= source.length) d += 1;
		while (source[d] === '}') d += 1;
	}
	const start = locate(c);
	const loc = `(${start.line}:${start.column})`;
	return `${loc} ${source.slice(c, d)}`.replace(regex_whitespace_characters, ' ');
}

/**
 * @template {string} Type
 * @template {import('../interfaces.js').INode} [Parent=import('../interfaces.js').INode]
 */
class Node {
	/**
	 * @readonly
	 * @type {number}
	 */
	start;

	/**
	 * @readonly
	 * @type {number}
	 */
	end;

	/**
	 * @readonly
	 * @type {import('../../Component.js').default}
	 */
	component;

	/**
	 * @readonly
	 * @type {Parent}
	 */
	parent;

	/**
	 * @readonly
	 * @type {Type}
	 */
	type;

	/** @type {import('../interfaces.js').INode} */
	prev;

	/** @type {import('../interfaces.js').INode} */
	next;

	/** @type {boolean} */
	can_use_innerhtml;

	/** @type {boolean} */
	is_static_content;

	/** @type {string} */
	var;

	/** @type {import('../Attribute.js').default[]} */
	attributes = [];

	/**
	 * @param {import('../../Component.js').default} component
	 * @param {Node} parent
	 * @param {any} _scope
	 * @param {import('../../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, _scope, info) {
		this.start = info.start;
		this.end = info.end;
		this.type = /** @type {Type} */ (info.type);
		// this makes properties non-enumerable, which makes logging
		// bearable. might have a performance cost. TODO remove in prod?
		Object.defineProperties(this, {
			component: {
				value: component
			},
			parent: {
				value: parent
			}
		});
		this.can_use_innerhtml = true;
		this.is_static_content = true;
	}
	cannot_use_innerhtml() {
		if (this.can_use_innerhtml !== false) {
			this.can_use_innerhtml = false;
			if (this.parent) this.parent.cannot_use_innerhtml();
		}
	}
	not_static_content() {
		this.is_static_content = false;
		if (this.parent) this.parent.not_static_content();
	}

	/** @param {RegExp} selector */
	find_nearest(selector) {
		if (selector.test(this.type)) return this;
		if (this.parent) return this.parent.find_nearest(selector);
	}

	/** @param {string} name */
	get_static_attribute_value(name) {
		const attribute = this.attributes.find(
			/** @param {import('../Attribute.js').default} attr */
			(attr) => attr.type === 'Attribute' && attr.name.toLowerCase() === name
		);
		if (!attribute) return null;
		if (attribute.is_true) return true;
		if (attribute.chunks.length === 0) return '';
		if (attribute.chunks.length === 1 && attribute.chunks[0].type === 'Text') {
			return /** @type {import('../Text.js').default} */ (attribute.chunks[0]).data;
		}
		return null;
	}

	/** @param {string} type */
	has_ancestor(type) {
		return this.parent ? this.parent.type === type || this.parent.has_ancestor(type) : false;
	}
}

/**
 * @internal
 */
var compiler_warnings = {
	tag_option_deprecated: {
		code: 'tag-option-deprecated',
		message: "'tag' option is deprecated — use 'customElement' instead"
	},
	unused_export_let: /**
	 * @param {string} component
	 * @param {string} property
	 */ (component, property) => ({
		code: 'unused-export-let',
		message: `${component} has unused export property '${property}'. If it is for external reference only, please consider using \`export const ${property}\``
	}),
	module_script_reactive_declaration: {
		code: 'module-script-reactive-declaration',
		message: '$: has no effect in a module script'
	},
	non_top_level_reactive_declaration: {
		code: 'non-top-level-reactive-declaration',
		message: '$: has no effect outside of the top-level'
	},
	module_script_variable_reactive_declaration: /** @param {string[]} names */ (names) => ({
		code: 'module-script-reactive-declaration',
		message: `${names.map(/** @param {any} name */ (name) => `"${name}"`).join(', ')} ${
			names.length > 1 ? 'are' : 'is'
		} declared in a module script and will not be reactive`
	}),
	missing_declaration: /**
	 * @param {string} name
	 * @param {boolean} has_script
	 */ (name, has_script) => ({
		code: 'missing-declaration',
		message:
			`'${name}' is not defined` +
			(has_script
				? ''
				: `. Consider adding a <script> block with 'export let ${name}' to declare a prop`)
	}),
	missing_custom_element_compile_options: {
		code: 'missing-custom-element-compile-options',
		message:
			"The 'customElement' option is used when generating a custom element. Did you forget the 'customElement: true' compile option?"
	},
	css_unused_selector: /** @param {string} selector */ (selector) => ({
		code: 'css-unused-selector',
		message: `Unused CSS selector "${selector}"`
	}),
	empty_block: {
		code: 'empty-block',
		message: 'Empty block'
	},
	reactive_component: /** @param {string} name */ (name) => ({
		code: 'reactive-component',
		message: `<${name}/> will not be reactive if ${name} changes. Use <svelte:component this={${name}}/> if you want this reactivity.`
	}),
	component_name_lowercase: /** @param {string} name */ (name) => ({
		code: 'component-name-lowercase',
		message: `<${name}> will be treated as an HTML element unless it begins with a capital letter`
	}),
	avoid_is: {
		code: 'avoid-is',
		message: "The 'is' attribute is not supported cross-browser and should be avoided"
	},
	invalid_html_attribute: /**
	 * @param {string} name
	 * @param {string} suggestion
	 */ (name, suggestion) => ({
		code: 'invalid-html-attribute',
		message: `'${name}' is not a valid HTML attribute. Did you mean '${suggestion}'?`
	}),
	a11y_aria_attributes: /** @param {string} name */ (name) => ({
		code: 'a11y-aria-attributes',
		message: `A11y: <${name}> should not have aria-* attributes`
	}),
	a11y_incorrect_attribute_type: /**
	 * @param {import('aria-query').ARIAPropertyDefinition} schema
	 * @param {string} attribute
	 */ (schema, attribute) => {
		let message;
		switch (schema.type) {
			case 'boolean':
				message = `The value of '${attribute}' must be exactly one of true or false`;
				break;
			case 'id':
				message = `The value of '${attribute}' must be a string that represents a DOM element ID`;
				break;
			case 'idlist':
				message = `The value of '${attribute}' must be a space-separated list of strings that represent DOM element IDs`;
				break;
			case 'tristate':
				message = `The value of '${attribute}' must be exactly one of true, false, or mixed`;
				break;
			case 'token':
				message = `The value of '${attribute}' must be exactly one of ${(schema.values || []).join(
					', '
				)}`;
				break;
			case 'tokenlist':
				message = `The value of '${attribute}' must be a space-separated list of one or more of ${(
					schema.values || []
				).join(', ')}`;
				break;
			default:
				message = `The value of '${attribute}' must be of type ${schema.type}`;
		}
		return {
			code: 'a11y-incorrect-aria-attribute-type',
			message: `A11y: ${message}`
		};
	},
	a11y_unknown_aria_attribute: /**
	 * @param {string} attribute
	 * @param {string} [suggestion]
	 */ (attribute, suggestion) => ({
		code: 'a11y-unknown-aria-attribute',
		message:
			`A11y: Unknown aria attribute 'aria-${attribute}'` +
			(suggestion ? ` (did you mean '${suggestion}'?)` : '')
	}),
	a11y_hidden: /** @param {string} name */ (name) => ({
		code: 'a11y-hidden',
		message: `A11y: <${name}> element should not be hidden`
	}),
	a11y_misplaced_role: /** @param {string} name */ (name) => ({
		code: 'a11y-misplaced-role',
		message: `A11y: <${name}> should not have role attribute`
	}),
	a11y_unknown_role: /**
	 * @param {string | boolean} role
	 * @param {string} [suggestion]
	 */ (role, suggestion) => ({
		code: 'a11y-unknown-role',
		message: `A11y: Unknown role '${role}'` + (suggestion ? ` (did you mean '${suggestion}'?)` : '')
	}),
	a11y_no_abstract_role: /** @param {string | boolean} role */ (role) => ({
		code: 'a11y-no-abstract-role',
		message: `A11y: Abstract role '${role}' is forbidden`
	}),
	a11y_no_redundant_roles: /** @param {string | boolean} role */ (role) => ({
		code: 'a11y-no-redundant-roles',
		message: `A11y: Redundant role '${role}'`
	}),
	a11y_no_static_element_interactions: /**
	 * @param {string} element
	 * @param {string[]} handlers
	 */ (element, handlers) => ({
		code: 'a11y-no-static-element-interactions',
		message: `A11y: <${element}> with ${handlers.join(', ')} ${
			handlers.length === 1 ? 'handler' : 'handlers'
		} must have an ARIA role`
	}),
	a11y_no_interactive_element_to_noninteractive_role: /**
	 * @param {string | boolean} role
	 * @param {string} element
	 */ (role, element) => ({
		code: 'a11y-no-interactive-element-to-noninteractive-role',
		message: `A11y: <${element}> cannot have role '${role}'`
	}),
	a11y_no_noninteractive_element_interactions: /** @param {string} element */ (element) => ({
		code: 'a11y-no-noninteractive-element-interactions',
		message: `A11y: Non-interactive element <${element}> should not be assigned mouse or keyboard event listeners.`
	}),
	a11y_no_noninteractive_element_to_interactive_role: /**
	 * @param {string | boolean} role
	 * @param {string} element
	 */ (role, element) => ({
		code: 'a11y-no-noninteractive-element-to-interactive-role',
		message: `A11y: Non-interactive element <${element}> cannot have interactive role '${role}'`
	}),
	a11y_role_has_required_aria_props: /**
	 * @param {string} role
	 * @param {string[]} props
	 */ (role, props) => ({
		code: 'a11y-role-has-required-aria-props',
		message: `A11y: Elements with the ARIA role "${role}" must have the following attributes defined: ${props
			.map(/** @param {any} name */ (name) => `"${name}"`)
			.join(', ')}`
	}),
	a11y_role_supports_aria_props: /**
	 * @param {string} attribute
	 * @param {string} role
	 * @param {boolean} is_implicit
	 * @param {string} name
	 */ (attribute, role, is_implicit, name) => {
		let message = `The attribute '${attribute}' is not supported by the role '${role}'.`;
		if (is_implicit) {
			message += ` This role is implicit on the element <${name}>.`;
		}
		return {
			code: 'a11y-role-supports-aria-props',
			message: `A11y: ${message}`
		};
	},
	a11y_accesskey: {
		code: 'a11y-accesskey',
		message: 'A11y: Avoid using accesskey'
	},
	a11y_autofocus: {
		code: 'a11y-autofocus',
		message: 'A11y: Avoid using autofocus'
	},
	a11y_misplaced_scope: {
		code: 'a11y-misplaced-scope',
		message: 'A11y: The scope attribute should only be used with <th> elements'
	},
	a11y_positive_tabindex: {
		code: 'a11y-positive-tabindex',
		message: 'A11y: avoid tabindex values above zero'
	},
	a11y_invalid_attribute: /**
	 * @param {string} href_attribute
	 * @param {string} href_value
	 */ (href_attribute, href_value) => ({
		code: 'a11y-invalid-attribute',
		message: `A11y: '${href_value}' is not a valid ${href_attribute} attribute`
	}),
	a11y_missing_attribute: /**
	 * @param {string} name
	 * @param {string} article
	 * @param {string} sequence
	 */ (name, article, sequence) => ({
		code: 'a11y-missing-attribute',
		message: `A11y: <${name}> element should have ${article} ${sequence} attribute`
	}),
	a11y_autocomplete_valid: /**
	 * @param {null | true | string} type
	 * @param {null | true | string} value
	 */ (type, value) => ({
		code: 'a11y-autocomplete-valid',
		message: `A11y: The value '${value}' is not supported by the attribute 'autocomplete' on element <input type="${
			type || '...'
		}">`
	}),
	a11y_img_redundant_alt: {
		code: 'a11y-img-redundant-alt',
		message: 'A11y: Screenreaders already announce <img> elements as an image.'
	},
	a11y_interactive_supports_focus: /** @param {string} role */ (role) => ({
		code: 'a11y-interactive-supports-focus',
		message: `A11y: Elements with the '${role}' interactive role must have a tabindex value.`
	}),
	a11y_label_has_associated_control: {
		code: 'a11y-label-has-associated-control',
		message: 'A11y: A form label must be associated with a control.'
	},
	a11y_media_has_caption: {
		code: 'a11y-media-has-caption',
		message: 'A11y: <video> elements must have a <track kind="captions">'
	},
	a11y_distracting_elements: /** @param {string} name */ (name) => ({
		code: 'a11y-distracting-elements',
		message: `A11y: Avoid <${name}> elements`
	}),
	a11y_structure_immediate: {
		code: 'a11y-structure',
		message: 'A11y: <figcaption> must be an immediate child of <figure>'
	},
	a11y_structure_first_or_last: {
		code: 'a11y-structure',
		message: 'A11y: <figcaption> must be first or last child of <figure>'
	},
	a11y_mouse_events_have_key_events: /**
	 * @param {string} event
	 * @param {string} accompanied_by
	 */ (event, accompanied_by) => ({
		code: 'a11y-mouse-events-have-key-events',
		message: `A11y: on:${event} must be accompanied by on:${accompanied_by}`
	}),
	a11y_click_events_have_key_events: {
		code: 'a11y-click-events-have-key-events',
		message:
			'A11y: visible, non-interactive elements with an on:click event must be accompanied by an on:keydown, on:keyup, or on:keypress event.'
	},
	a11y_missing_content: /** @param {string} name */ (name) => ({
		code: 'a11y-missing-content',
		message: `A11y: <${name}> element should have child content`
	}),
	a11y_no_noninteractive_tabindex: {
		code: 'a11y-no-noninteractive-tabindex',
		message: 'A11y: noninteractive element cannot have nonnegative tabIndex value'
	},
	a11y_aria_activedescendant_has_tabindex: {
		code: 'a11y-aria-activedescendant-has-tabindex',
		message: 'A11y: Elements with attribute aria-activedescendant should have tabindex value'
	},
	redundant_event_modifier_for_touch: {
		code: 'redundant-event-modifier',
		message: "Touch event handlers that don't use the 'event' object are passive by default"
	},
	redundant_event_modifier_passive: {
		code: 'redundant-event-modifier',
		message: 'The passive modifier only works with wheel and touch events'
	},
	invalid_rest_eachblock_binding: /** @param {string} rest_element_name */ (rest_element_name) => ({
		code: 'invalid-rest-eachblock-binding',
		message: `The rest operator (...) will create a new object and binding '${rest_element_name}' with the original object will not work`
	}),
	avoid_mouse_events_on_document: {
		code: 'avoid-mouse-events-on-document',
		message:
			'Mouse enter/leave events on the document are not supported in all browsers and should be avoided'
	},
	illegal_attribute_character: {
		code: 'illegal-attribute-character',
		message:
			"Attributes should not contain ':' characters to prevent ambiguity with Svelte directives"
	}
};

const regex_non_whitespace_characters$1 = /[^ \r\n\f\v\t]/;

/**
 * @template {string} Type
 * @extends Node<Type>
 */
class AbstractBlock extends Node {
	/** @type {import('../../render_dom/Block.js').default} */
	block;

	/** @type {import('../interfaces.js').INode[]} */
	children;

	/**
	 * @param {import('../../Component.js').default} component
	 * @param {any} parent
	 * @param {any} scope
	 * @param {any} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
	}
	warn_if_empty_block() {
		if (!this.children || this.children.length > 1) return;
		const child = this.children[0];
		if (!child || (child.type === 'Text' && !regex_non_whitespace_characters$1.test(child.data))) {
			this.component.warn(this, compiler_warnings.empty_block);
		}
	}
}

/**
 * @param {import('estree').Node} node
 */
function flatten_reference(node) {
	/** @type {any[]} */
	const nodes = [];
	/** @type {string[]} */
	const parts = [];

	while (node.type === 'MemberExpression') {
		nodes.unshift(node.property);

		if (!node.computed) {
			parts.unshift(/** @type {import('estree').Identifier} */ (node.property).name);
		} else {
			const computed_property = to_string(node.property);
			if (computed_property) {
				parts.unshift(`[${computed_property}]`);
			}
		}
		node = node.object;
	}

	const name =
		node.type === 'Identifier' ? node.name : node.type === 'ThisExpression' ? 'this' : null;

	nodes.unshift(node);

	parts.unshift(name);

	return { name, nodes, parts };
}

/**
 * @param {import('estree').Node} node
 */
function to_string(node) {
	switch (node.type) {
		case 'Literal':
			return String(node.value);
		case 'Identifier':
			return node.name;
	}
}

/**
 * @param {import('estree').Node} expression
 */
function create_scopes(expression) {
	return analyze(expression);
}

/**
 * @param {import('estree').Node} node
 */
function get_object(node) {
	while (node.type === 'MemberExpression') node = node.object;
	return /** @type {import('estree').Identifier} */ (node);
}

const reserved_keywords = new Set(['$$props', '$$restProps', '$$slots']);

/** @param {string} name */
function is_reserved_keyword(name) {
	return reserved_keywords.has(name);
}

/** @param {import('../../../../interfaces.js').Var} variable */
function is_dynamic$1(variable) {
	if (variable) {
		if (variable.mutated || variable.reassigned) return true; // dynamic internal state
		if (!variable.module && variable.writable && variable.export_name) return true; // writable props
		if (is_reserved_keyword(variable.name)) return true;
	}
	return false;
}

function nodes_match(a, b) {
	if (!!a !== !!b) return false;
	if (Array.isArray(a) !== Array.isArray(b)) return false;

	if (a && typeof a === 'object') {
		if (Array.isArray(a)) {
			if (a.length !== b.length) return false;
			return a.every((child, i) => nodes_match(child, b[i]));
		}

		const a_keys = Object.keys(a).sort();
		const b_keys = Object.keys(b).sort();

		if (a_keys.length !== b_keys.length) return false;

		let i = a_keys.length;
		while (i--) {
			const key = a_keys[i];
			if (b_keys[i] !== key) return false;

			if (key === 'start' || key === 'end') continue;

			if (!nodes_match(a[key], b[key])) {
				return false;
			}
		}

		return true;
	}

	return a === b;
}

/**
 * @param {import('./Renderer.js').default} renderer
 * @param {import('periscopic').Scope} scope
 * @param {import('estree').Node} node
 * @param {Set<string>} names
 * @param {boolean} main_execution_context
 * @returns {any}
 */
function invalidate(renderer, scope, node, names, main_execution_context = false) {
	const { component } = renderer;
	const [head, ...tail] = /** @type {import('../../interfaces.js').Var[]} */ (
		Array.from(names)
			.filter((name) => {
				const owner = scope.find_owner(name);
				return !owner || owner === component.instance_scope;
			})
			.map((name) => component.var_lookup.get(name))
			.filter((variable) => {
				return (
					variable &&
					!variable.hoistable &&
					!variable.global &&
					!variable.module &&
					(variable.referenced ||
						variable.subscribable ||
						variable.is_reactive_dependency ||
						variable.export_name ||
						variable.name[0] === '$')
				);
			})
	);

	/**
	 * @param {import('../../interfaces.js').Var} variable
	 * @param {import('estree').Expression} [node]
	 */
	function get_invalidated(variable, node) {
		if (main_execution_context && !variable.subscribable && variable.name[0] !== '$') {
			return node;
		}
		return renderer_invalidate(renderer, variable.name, undefined, main_execution_context);
	}
	if (!head) {
		return node;
	}
	component.has_reactive_assignments = true;
	if (
		node.type === 'AssignmentExpression' &&
		node.operator === '=' &&
		nodes_match(node.left, node.right) &&
		tail.length === 0
	) {
		return get_invalidated(head, node);
	}
	const is_store_value = head.name[0] === '$' && head.name[1] !== '$';
	const extra_args = tail.map((variable) => get_invalidated(variable)).filter(Boolean);
	if (is_store_value) {
		return x$1`@set_store_value(${head.name.slice(1)}, ${node}, ${head.name}, ${extra_args})`;
	}

	let invalidate;
	if (!main_execution_context) {
		const pass_value =
			extra_args.length > 0 ||
			(node.type === 'AssignmentExpression' && node.left.type !== 'Identifier') ||
			(node.type === 'UpdateExpression' && (!node.prefix || node.argument.type !== 'Identifier'));
		if (pass_value) {
			extra_args.unshift({
				type: 'Identifier',
				name: head.name
			});
		}
		invalidate = x$1`$$invalidate(${
			renderer.context_lookup.get(head.name).index
		}, ${node}, ${extra_args})`;
	} else {
		// skip `$$invalidate` if it is in the main execution context
		invalidate = extra_args.length ? [node, ...extra_args] : node;
	}
	if (head.subscribable && head.reassigned) {
		const subscribe = `$$subscribe_${head.name}`;
		invalidate = x$1`${subscribe}(${invalidate})`;
	}
	return invalidate;
}

/**
 * @param {import('./Renderer.js').default} renderer
 * @param {string} name
 * @param {any} [value]
 * @param {boolean} [main_execution_context]
 * @returns {import('estree').Node}
 */
function renderer_invalidate(renderer, name, value, main_execution_context = false) {
	const variable = renderer.component.var_lookup.get(name);
	if (variable && variable.subscribable && (variable.reassigned || variable.export_name)) {
		if (main_execution_context) {
			return x$1`${`$$subscribe_${name}`}(${value || name})`;
		} else {
			const member = renderer.context_lookup.get(name);
			return x$1`${`$$subscribe_${name}`}($$invalidate(${member.index}, ${value || name}))`;
		}
	}
	if (name[0] === '$' && name[1] !== '$') {
		return x$1`${name.slice(1)}.set(${value || name})`;
	}
	if (
		variable &&
		(variable.module ||
			(!variable.referenced &&
				!variable.is_reactive_dependency &&
				!variable.export_name &&
				!name.startsWith('$$')))
	) {
		return value || name;
	}
	if (value) {
		if (main_execution_context) {
			return x$1`${value}`;
		} else {
			const member = renderer.context_lookup.get(name);
			return x$1`$$invalidate(${member.index}, ${value})`;
		}
	}
	if (main_execution_context) return;
	// if this is a reactive declaration, invalidate dependencies recursively
	const deps = new Set([name]);
	deps.forEach((name) => {
		const reactive_declarations = renderer.component.reactive_declarations.filter((x) =>
			x.assignees.has(name)
		);
		reactive_declarations.forEach((declaration) => {
			declaration.dependencies.forEach((name) => {
				deps.add(name);
			});
		});
	});
	// TODO ideally globals etc wouldn't be here in the first place
	const filtered = Array.from(deps).filter((n) => renderer.context_lookup.has(n));
	if (!filtered.length) return null;
	return filtered
		.map((n) => x$1`$$invalidate(${renderer.context_lookup.get(n).index}, ${n})`)
		.reduce((lhs, rhs) => x$1`${lhs}, ${rhs}`);
}

/**
 * @param {import('estree').Node} node
 * @param {import('estree').Node} replacement
 */
function replace_object(node, replacement) {
	if (node.type === 'Identifier') return replacement;

	const ancestor = node;
	let parent;
	while (node.type === 'MemberExpression') {
		parent = node;
		node = node.object;
	}
	parent.object = /** @type {any} */ (replacement);
	return ancestor;
}

/**
 * @param {import('../../Component.js').default} component
 * @param {import('./TemplateScope.js').default} scope
 * @param {string} name
 */
function is_contextual(component, scope, name) {
	if (is_reserved_keyword(name)) return true;
	// if it's a name below root scope, it's contextual
	if (!scope.is_top_level(name)) return true;
	const variable = component.var_lookup.get(name);
	// hoistables, module declarations, and imports are non-contextual
	if (!variable || variable.hoistable) return false;
	// assume contextual
	return true;
}

// adapted from klona v2.0.4 - https://github.com/lukeed/klona
// (c) Luke Edwards, under MIT License

// The sole modification is to skip function values in objects when cloning, so we don't break tests.

function clone(val) {
	let k, out, tmp;

	if (Array.isArray(val)) {
		out = Array((k = val.length));
		while (k--) out[k] = (tmp = val[k]) && typeof tmp === 'object' ? clone(tmp) : tmp;
		return out;
	}

	if (Object.prototype.toString.call(val) === '[object Object]') {
		out = {}; // null
		for (k in val) {
			if (k === '__proto__') {
				Object.defineProperty(out, k, {
					value: clone(val[k]),
					configurable: true,
					enumerable: true,
					writable: true
				});
			} else if (typeof val[k] !== 'function') {
				// MODIFICATION: skip functions
				out[k] = (tmp = val[k]) && typeof tmp === 'object' ? clone(tmp) : tmp;
			}
		}
		return out;
	}

	return val;
}

// All compiler errors should be listed and accessed from here
/**
 * @internal
 */
var compiler_errors = {
	invalid_binding_elements: /**
	 * @param {string} element
	 * @param {string} binding
	 */ (element, binding) => ({
		code: 'invalid-binding',
		message: `'${binding}' is not a valid binding on <${element}> elements`
	}),
	invalid_binding_element_with: /**
	 * @param {string} elements
	 * @param {string} binding
	 */ (elements, binding) => ({
		code: 'invalid-binding',
		message: `'${binding}' binding can only be used with ${elements}`
	}),
	invalid_binding_on: /**
	 * @param {string} binding
	 * @param {string} element
	 * @param {string} [post]
	 */ (binding, element, post) => ({
		code: 'invalid-binding',
		message: `'${binding}' is not a valid binding on ${element}` + (post || '')
	}),
	invalid_binding_foreign: /** @param {string} binding */ (binding) => ({
		code: 'invalid-binding',
		message: `'${binding}' is not a valid binding. Foreign elements only support bind:this`
	}),
	invalid_binding_no_checkbox: /**
	 * @param {string} binding
	 * @param {boolean} is_radio
	 */ (binding, is_radio) => ({
		code: 'invalid-binding',
		message:
			`'${binding}' binding can only be used with <input type="checkbox">` +
			(is_radio ? ' — for <input type="radio">, use \'group\' binding' : '')
	}),
	invalid_binding: /** @param {string} binding */ (binding) => ({
		code: 'invalid-binding',
		message: `'${binding}' is not a valid binding`
	}),
	invalid_binding_window: /** @param {string[]} parts */ (parts) => ({
		code: 'invalid-binding',
		message: `Bindings on <svelte:window> must be to top-level properties, e.g. '${
			parts[parts.length - 1]
		}' rather than '${parts.join('.')}'`
	}),
	invalid_binding_let: {
		code: 'invalid-binding',
		message: 'Cannot bind to a variable declared with the let: directive'
	},
	invalid_binding_await: {
		code: 'invalid-binding',
		message: 'Cannot bind to a variable declared with {#await ... then} or {:catch} blocks'
	},
	invalid_binding_const: {
		code: 'invalid-binding',
		message: 'Cannot bind to a variable declared with {@const ...}'
	},
	invalid_binding_writable: {
		code: 'invalid-binding',
		message: 'Cannot bind to a variable which is not writable'
	},
	binding_undeclared: /** @param {string} name */ (name) => ({
		code: 'binding-undeclared',
		message: `${name} is not declared`
	}),
	invalid_type: {
		code: 'invalid-type',
		message: "'type' attribute cannot be dynamic if input uses two-way binding"
	},
	missing_type: {
		code: 'missing-type',
		message: "'type' attribute must be specified"
	},
	dynamic_multiple_attribute: {
		code: 'dynamic-multiple-attribute',
		message: "'multiple' attribute cannot be dynamic if select uses two-way binding"
	},
	missing_contenteditable_attribute: {
		code: 'missing-contenteditable-attribute',
		message:
			"'contenteditable' attribute is required for textContent, innerHTML and innerText two-way bindings"
	},
	dynamic_contenteditable_attribute: {
		code: 'dynamic-contenteditable-attribute',
		message: "'contenteditable' attribute cannot be dynamic if element uses two-way binding"
	},
	invalid_event_modifier_combination: /**
	 * @param {string} modifier1
	 * @param {string} modifier2
	 */ (modifier1, modifier2) => ({
		code: 'invalid-event-modifier',
		message: `The '${modifier1}' and '${modifier2}' modifiers cannot be used together`
	}),
	invalid_event_modifier_legacy: /** @param {string} modifier */ (modifier) => ({
		code: 'invalid-event-modifier',
		message: `The '${modifier}' modifier cannot be used in legacy mode`
	}),
	invalid_event_modifier: /** @param {string} valid */ (valid) => ({
		code: 'invalid-event-modifier',
		message: `Valid event modifiers are ${valid}`
	}),
	invalid_event_modifier_component: {
		code: 'invalid-event-modifier',
		message: "Event modifiers other than 'once' can only be used on DOM elements"
	},
	textarea_duplicate_value: {
		code: 'textarea-duplicate-value',
		message:
			'A <textarea> can have either a value attribute or (equivalently) child content, but not both'
	},
	illegal_attribute: /** @param {string} name */ (name) => ({
		code: 'illegal-attribute',
		message: `'${name}' is not a valid attribute name`
	}),
	invalid_slot_attribute: {
		code: 'invalid-slot-attribute',
		message: 'slot attribute cannot have a dynamic value'
	},
	duplicate_slot_attribute: /** @param {string} name */ (name) => ({
		code: 'duplicate-slot-attribute',
		message: `Duplicate '${name}' slot`
	}),
	invalid_slotted_content: {
		code: 'invalid-slotted-content',
		message:
			"Element with a slot='...' attribute must be a child of a component or a descendant of a custom element"
	},
	invalid_attribute_head: {
		code: 'invalid-attribute',
		message: '<svelte:head> should not have any attributes or directives'
	},
	invalid_action: {
		code: 'invalid-action',
		message: 'Actions can only be applied to DOM elements, not components'
	},
	invalid_animation: {
		code: 'invalid-animation',
		message: 'Animations can only be applied to DOM elements, not components'
	},
	invalid_class: {
		code: 'invalid-class',
		message: 'Classes can only be applied to DOM elements, not components'
	},
	invalid_transition: {
		code: 'invalid-transition',
		message: 'Transitions can only be applied to DOM elements, not components'
	},
	invalid_let: {
		code: 'invalid-let',
		message: 'let directive value must be an identifier or an object/array pattern'
	},
	invalid_slot_directive: {
		code: 'invalid-slot-directive',
		message: '<slot> cannot have directives'
	},
	dynamic_slot_name: {
		code: 'dynamic-slot-name',
		message: '<slot> name cannot be dynamic'
	},
	invalid_slot_name: {
		code: 'invalid-slot-name',
		message: 'default is a reserved word — it cannot be used as a slot name'
	},
	invalid_slot_attribute_value_missing: {
		code: 'invalid-slot-attribute',
		message: 'slot attribute value is missing'
	},
	invalid_slotted_content_fragment: {
		code: 'invalid-slotted-content',
		message: '<svelte:fragment> must be a child of a component'
	},
	illegal_attribute_title: {
		code: 'illegal-attribute',
		message: '<title> cannot have attributes'
	},
	illegal_structure_title: {
		code: 'illegal-structure',
		message: '<title> can only contain text and {tags}'
	},
	duplicate_transition: /**
	 * @param {string} directive
	 * @param {string} parent_directive
	 */ (directive, parent_directive) => {
		/** @param {string} _directive */
		function describe(_directive) {
			return _directive === 'transition' ? "a 'transition'" : `an '${_directive}'`;
		}
		const message =
			directive === parent_directive
				? `An element can only have one '${directive}' directive`
				: `An element cannot have both ${describe(parent_directive)} directive and ${describe(
						directive
				  )} directive`;
		return {
			code: 'duplicate-transition',
			message
		};
	},
	contextual_store: {
		code: 'contextual-store',
		message:
			'Stores must be declared at the top level of the component (this may change in a future version of Svelte)'
	},
	default_export: {
		code: 'default-export',
		message: 'A component cannot have a default export'
	},
	illegal_declaration: {
		code: 'illegal-declaration',
		message: 'The $ prefix is reserved, and cannot be used for variable and import names'
	},
	illegal_subscription: {
		code: 'illegal-subscription',
		message: 'Cannot reference store value inside <script context="module">'
	},
	illegal_global: /** @param {string} name */ (name) => ({
		code: 'illegal-global',
		message: `${name} is an illegal variable name`
	}),
	illegal_variable_declaration: {
		code: 'illegal-variable-declaration',
		message: 'Cannot declare same variable name which is imported inside <script context="module">'
	},
	cyclical_reactive_declaration: /** @param {string[]} cycle */ (cycle) => ({
		code: 'cyclical-reactive-declaration',
		message: `Cyclical dependency detected: ${cycle.join(' → ')}`
	}),
	invalid_tag_property: {
		code: 'invalid-tag-property',
		message: "tag name must be two or more words joined by the '-' character"
	},
	invalid_customElement_attribute: {
		code: 'invalid-customElement-attribute',
		message:
			"'customElement' must be a string literal defining a valid custom element name or an object of the form " +
			"{ tag: string; shadow?: 'open' | 'none'; props?: { [key: string]: { attribute?: string; reflect?: boolean; type: .. } } }"
	},
	invalid_tag_attribute: {
		code: 'invalid-tag-attribute',
		message: "'tag' must be a string literal"
	},
	invalid_shadow_attribute: {
		code: 'invalid-shadow-attribute',
		message: "'shadow' must be either 'open' or 'none'"
	},
	invalid_props_attribute: {
		code: 'invalid-props-attribute',
		message:
			"'props' must be a statically analyzable object literal of the form " +
			"'{ [key: string]: { attribute?: string; reflect?: boolean; type?: 'String' | 'Boolean' | 'Number' | 'Array' | 'Object' }'"
	},
	invalid_namespace_property: /**
	 * @param {string} namespace
	 * @param {string} [suggestion]
	 */ (namespace, suggestion) => ({
		code: 'invalid-namespace-property',
		message:
			`Invalid namespace '${namespace}'` + (suggestion ? ` (did you mean '${suggestion}'?)` : '')
	}),
	invalid_namespace_attribute: {
		code: 'invalid-namespace-attribute',
		message: "The 'namespace' attribute must be a string literal representing a valid namespace"
	},
	invalid_attribute_value: /** @param {string} name */ (name) => ({
		code: `invalid-${name}-value`,
		message: `${name} attribute must be true or false`
	}),
	invalid_options_attribute_unknown: /** @param {string} name */ (name) => ({
		code: 'invalid-options-attribute',
		message: `<svelte:options> unknown attribute '${name}'`
	}),
	invalid_options_attribute: {
		code: 'invalid-options-attribute',
		message:
			"<svelte:options> can only have static 'tag', 'namespace', 'accessors', 'immutable' and 'preserveWhitespace' attributes"
	},
	css_invalid_global: {
		code: 'css-invalid-global',
		message: ':global(...) can be at the start or end of a selector sequence, but not in the middle'
	},
	css_invalid_global_selector: {
		code: 'css-invalid-global-selector',
		message: ':global(...) must contain a single selector'
	},
	css_invalid_global_selector_position: {
		code: 'css-invalid-global-selector-position',
		message:
			':global(...) not at the start of a selector sequence should not contain type or universal selectors'
	},
	css_invalid_selector: /** @param {string} selector */ (selector) => ({
		code: 'css-invalid-selector',
		message: `Invalid selector "${selector}"`
	}),
	duplicate_animation: {
		code: 'duplicate-animation',
		message: "An element can only have one 'animate' directive"
	},
	invalid_animation_immediate: {
		code: 'invalid-animation',
		message:
			'An element that uses the animate directive must be the immediate child of a keyed each block'
	},
	invalid_animation_key: {
		code: 'invalid-animation',
		message:
			'An element that uses the animate directive must be used inside a keyed each block. Did you forget to add a key to your each block?'
	},
	invalid_animation_sole: {
		code: 'invalid-animation',
		message:
			'An element that uses the animate directive must be the sole child of a keyed each block'
	},
	invalid_animation_dynamic_element: {
		code: 'invalid-animation',
		message: '<svelte:element> cannot have a animate directive'
	},
	invalid_directive_value: {
		code: 'invalid-directive-value',
		message:
			'Can only bind to an identifier (e.g. `foo`) or a member expression (e.g. `foo.bar` or `foo[baz]`)'
	},
	invalid_const_placement: {
		code: 'invalid-const-placement',
		message:
			'{@const} must be the immediate child of {#if}, {:else if}, {:else}, {#each}, {:then}, {:catch}, <svelte:fragment> or <Component>'
	},
	invalid_const_declaration: /** @param {string} name */ (name) => ({
		code: 'invalid-const-declaration',
		message: `'${name}' has already been declared`
	}),
	invalid_const_update: /** @param {string} name */ (name) => ({
		code: 'invalid-const-update',
		message: `'${name}' is declared using {@const ...} and is read-only`
	}),
	cyclical_const_tags: /** @param {string[]} cycle */ (cycle) => ({
		code: 'cyclical-const-tags',
		message: `Cyclical dependency detected: ${cycle.join(' → ')}`
	}),
	invalid_component_style_directive: {
		code: 'invalid-component-style-directive',
		message: 'Style directives cannot be used on components'
	},
	invalid_var_declaration: {
		code: 'invalid_var_declaration',
		message: '"var" scope should not extend outside the reactive block'
	},
	invalid_style_directive_modifier: /** @param {string} valid */ (valid) => ({
		code: 'invalid-style-directive-modifier',
		message: `Valid modifiers for style directives are: ${valid}`
	})
};

const regex_contains_term_function_expression$1 = /FunctionExpression/;

class Expression {
	/** @type {'Expression'} */
	type = 'Expression';

	/** @type {import('../../Component.js').default} */
	component;

	/** @type {import('../interfaces.js').INode} */
	owner;

	/** @type {import('estree').Node} */
	node;

	/** @type {Set<string>} */
	references = new Set();

	/** @type {Set<string>} */
	dependencies = new Set();

	/** @type {Set<string>} */
	contextual_dependencies = new Set();

	/** @type {import('./TemplateScope.js').default} */
	template_scope;

	/** @type {import('../../utils/scope.js').Scope} */
	scope;

	/** @type {WeakMap<import('estree').Node, import('../../utils/scope.js').Scope>} */
	scope_map;

	/** @type {Array<import('estree').Node | import('estree').Node[]>} */
	declarations = [];
	/** */
	uses_context = false;

	/** @type {import('estree').Node} */
	manipulated;

	/**
	 * @param {import('../../Component.js').default} component  *
	 * @param {import('../interfaces.js').INode} owner  *
	 * @param {import('./TemplateScope.js').default} template_scope  *
	 * @param {import('estree').Node} info  *
	 * @param {boolean} [lazy]  undefined
	 */
	constructor(component, owner, template_scope, info, lazy) {
		// TODO revert to direct property access in prod?
		Object.defineProperties(this, {
			component: {
				value: component
			}
		});
		this.node = info;
		this.template_scope = template_scope;
		this.owner = owner;
		const { dependencies, contextual_dependencies, references } = this;
		let { map, scope } = create_scopes(info);
		this.scope = scope;
		this.scope_map = map;
		const expression = this;
		let function_expression;

		// discover dependencies, but don't change the code yet
		walk(info, {
			/**
			 * @param {any} node
			 * @param {any} parent
			 * @param {string} key
			 */
			enter(node, parent, key) {
				// don't manipulate shorthand props twice
				if (key === 'key' && parent.shorthand) return;
				// don't manipulate `import.meta`, `new.target`
				if (node.type === 'MetaProperty') return this.skip();
				if (map.has(node)) {
					scope = map.get(node);
				}
				if (!function_expression && regex_contains_term_function_expression$1.test(node.type)) {
					function_expression = node;
				}
				if (is_reference(node, parent)) {
					const { name, nodes } = flatten_reference(node);
					references.add(name);
					if (scope.has(name)) return;
					if (name[0] === '$') {
						const store_name = name.slice(1);
						if (template_scope.names.has(store_name) || scope.has(store_name)) {
							return component.error(node, compiler_errors.contextual_store);
						}
					}
					if (template_scope.is_let(name)) {
						if (!lazy) {
							contextual_dependencies.add(name);
							dependencies.add(name);
						}
					} else if (template_scope.names.has(name)) {
						expression.uses_context = true;
						contextual_dependencies.add(name);
						const owner = template_scope.get_owner(name);
						const is_index = owner.type === 'EachBlock' && owner.key && name === owner.index;
						if (!lazy || is_index) {
							template_scope.dependencies_for_name
								.get(name)
								.forEach(/** @param {any} name */ (name) => dependencies.add(name));
						}
					} else {
						if (!lazy) {
							dependencies.add(name);
						}
						component.add_reference(node, name);
						component.warn_if_undefined(name, nodes[0], template_scope, owner);
					}
					this.skip();
				}
				// track any assignments from template expressions as mutable
				let names;
				let deep = false;
				if (function_expression) {
					if (node.type === 'AssignmentExpression') {
						deep = node.left.type === 'MemberExpression';
						names = extract_names(deep ? get_object(node.left) : node.left);
					} else if (node.type === 'UpdateExpression') {
						deep = node.argument.type === 'MemberExpression';
						names = extract_names(get_object(node.argument));
					}
				}
				if (names) {
					names.forEach(
						/** @param {any} name */ (name) => {
							if (template_scope.names.has(name)) {
								if (template_scope.is_const(name)) {
									component.error(node, compiler_errors.invalid_const_update(name));
								}
								template_scope.dependencies_for_name.get(name).forEach(
									/** @param {any} name */ (name) => {
										const variable = component.var_lookup.get(name);
										if (variable) variable[deep ? 'mutated' : 'reassigned'] = true;
									}
								);
								const each_block = template_scope.get_owner(name);
								/** @type {import('../EachBlock.js').default} */ (each_block).has_binding = true;
							} else {
								component.add_reference(node, name);
								const variable = component.var_lookup.get(name);
								if (variable) {
									variable[deep ? 'mutated' : 'reassigned'] = true;
								}

								/** @type {any} */
								const declaration = scope.find_owner(name)?.declarations.get(name);
								if (declaration) {
									if (declaration.kind === 'const' && !deep) {
										component.error(node, {
											code: 'assignment-to-const',
											message: 'You are assigning to a const'
										});
									}
								} else if (variable && variable.writable === false && !deep) {
									component.error(node, {
										code: 'assignment-to-const',
										message: 'You are assigning to a const'
									});
								}
							}
						}
					);
				}
			},

			/** @param {import('estree').Node} node */
			leave(node) {
				if (map.has(node)) {
					scope = scope.parent;
				}
				if (node === function_expression) {
					function_expression = null;
				}
			}
		});
	}
	dynamic_dependencies() {
		return Array.from(this.dependencies).filter(
			/** @param {any} name */ (name) => {
				if (this.template_scope.is_let(name)) return true;
				if (is_reserved_keyword(name)) return true;
				const variable = this.component.var_lookup.get(name);
				return is_dynamic$1(variable);
			}
		);
	}
	dynamic_contextual_dependencies() {
		return Array.from(this.contextual_dependencies).filter(
			/** @param {any} name */ (name) => {
				return Array.from(this.template_scope.dependencies_for_name.get(name)).some(
					/** @param {any} variable_name */
					(variable_name) => {
						const variable = this.component.var_lookup.get(variable_name);
						return is_dynamic$1(variable);
					}
				);
			}
		);
	}
	// TODO move this into a render-dom wrapper?

	/**
	 * @param {import('../../render_dom/Block.js').default} [block]
	 * @param {string | void} [ctx]
	 */
	manipulate(block, ctx) {
		// TODO ideally we wouldn't end up calling this method
		// multiple times
		if (this.manipulated) return this.manipulated;
		const { component, declarations, scope_map: map, template_scope, owner } = this;
		let scope = this.scope;
		let function_expression;

		/** @type {Set<string>} */
		let dependencies;

		/** @type {Set<string>} */
		let contextual_dependencies;
		const node = walk(this.node, {
			/**
			 * @param {any} node
			 * @param {any} parent
			 */
			enter(node, parent) {
				if (node.type === 'Property' && node.shorthand) {
					node.value = clone(node.value);
					node.shorthand = false;
				}
				if (map.has(node)) {
					scope = map.get(node);
				}
				if (node.type === 'Identifier' && is_reference(node, parent)) {
					const { name } = flatten_reference(node);
					if (scope.has(name)) return;
					if (function_expression) {
						if (template_scope.names.has(name)) {
							contextual_dependencies.add(name);
							template_scope.dependencies_for_name.get(name).forEach(
								/** @param {any} dependency */ (dependency) => {
									dependencies.add(dependency);
								}
							);
						} else {
							dependencies.add(name);
							component.add_reference(node, name); // TODO is this redundant/misplaced?
						}
					} else if (is_contextual(component, template_scope, name)) {
						const reference = block.renderer.reference(node, ctx);
						this.replace(reference);
					}
					this.skip();
				}
				if (!function_expression) {
					if (node.type === 'AssignmentExpression') ;
					if (node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') {
						function_expression = node;
						dependencies = new Set();
						contextual_dependencies = new Set();
					}
				}
			},

			/**
			 * @param {import('estree').Node} node
			 * @param {import('estree').Node} parent
			 */
			leave(node, parent) {
				if (map.has(node)) scope = scope.parent;
				if (node === function_expression) {
					const id = component.get_unique_name(sanitize(get_function_name(node, owner)));
					const declaration = b$1`const ${id} = ${node}`;
					const extract_functions = () => {
						const deps = Array.from(contextual_dependencies);
						const function_expression = /** @type {import('estree').FunctionExpression} */ (node);
						const has_args = function_expression.params.length > 0;
						function_expression.params = [
							...deps.map(
								/** @param {any} name */ (name) =>
									/** @type {import('estree').Identifier} */ ({ type: 'Identifier', name })
							),
							...function_expression.params
						];
						const context_args = deps.map(
							/** @param {any} name */ (name) => block.renderer.reference(name, ctx)
						);
						component.partly_hoisted.push(declaration);
						block.renderer.add_to_context(id.name);
						const callee = block.renderer.reference(id);
						this.replace(/** @type {any} */ (id));
						const func_declaration = has_args
							? b$1`function ${id}(...args) {
								return ${callee}(${context_args}, ...args);
							}`
							: b$1`function ${id}() {
								return ${callee}(${context_args});
							}`;
						return { deps, func_declaration };
					};
					if (owner.type === 'ConstTag') {
						// we need a combo block/init recipe
						if (contextual_dependencies.size === 0) {
							let child_scope = scope;
							walk(node, {
								/**
								 * @param {import('estree').Node} node
								 * @param {any} parent
								 */
								enter(node, parent) {
									if (map.has(node)) child_scope = map.get(node);
									if (node.type === 'Identifier' && is_reference(node, parent)) {
										if (child_scope.has(node.name)) return;
										this.replace(block.renderer.reference(node, ctx));
									}
								},

								/** @param {import('estree').Node} node */
								leave(node) {
									if (map.has(node)) child_scope = child_scope.parent;
								}
							});
						} else {
							const { func_declaration } = extract_functions();
							this.replace(func_declaration[0]);
						}
					} else if (dependencies.size === 0 && contextual_dependencies.size === 0) {
						// we can hoist this out of the component completely
						component.fully_hoisted.push(declaration);
						this.replace(/** @type {any} */ (id));
						component.add_var(node, {
							name: id.name,
							internal: true,
							hoistable: true,
							referenced: true
						});
					} else if (contextual_dependencies.size === 0) {
						// function can be hoisted inside the component init
						component.partly_hoisted.push(declaration);
						block.renderer.add_to_context(id.name);
						this.replace(block.renderer.reference(id));
					} else {
						// we need a combo block/init recipe
						const { deps, func_declaration } = extract_functions();
						if (owner.type === 'Attribute' && owner.parent.name === 'slot') {
							/** @type {Set<import('../interfaces.js').INode>} */
							const dep_scopes = new Set(
								deps.map(/** @param {any} name */ (name) => template_scope.get_owner(name))
							);
							// find the nearest scopes

							/** @type {import('../interfaces.js').INode} */
							let node = owner.parent;
							while (node && !dep_scopes.has(node)) {
								node = node.parent;
							}
							const func_expression = func_declaration[0];

							if (node.type === 'SlotTemplate') {
								// <svelte:fragment let:data />
								this.replace(func_expression);
							} else {
								// {#each}, {#await}
								const func_id = component.get_unique_name(id.name + '_func');
								block.renderer.add_to_context(func_id.name, true);
								// rename #ctx -> child_ctx;
								walk(func_expression, {
									/** @param {import('estree').Node} node */
									enter(node) {
										if (node.type === 'Identifier' && node.name === '#ctx') {
											node.name = 'child_ctx';
										}
									}
								});
								// add to get_xxx_context
								// child_ctx[x] = function () { ... }
								/** @type {import('../EachBlock.js').default} */ (
									template_scope.get_owner(deps[0])
								).contexts.push({
									type: 'DestructuredVariable',
									key: func_id,
									modifier: () => func_expression,
									default_modifier: /** @param {any} node */ (node) => node
								});
								this.replace(block.renderer.reference(func_id));
							}
						} else {
							declarations.push(func_declaration);
						}
					}
					function_expression = null;
					dependencies = null;
					contextual_dependencies = null;
					if (parent && parent.type === 'Property') {
						parent.method = false;
					}
				}
				if (node.type === 'AssignmentExpression' || node.type === 'UpdateExpression') {
					const assignee = node.type === 'AssignmentExpression' ? node.left : node.argument;
					const object_name = get_object(assignee).name;
					if (scope.has(object_name)) return;
					// normally (`a = 1`, `b.c = 2`), there'll be a single name
					// (a or b). In destructuring cases (`[d, e] = [e, d]`) there
					// may be more, in which case we need to tack the extra ones
					// onto the initial function call
					const names = new Set(extract_names(/** @type {import('estree').Node} */ (assignee)));

					/** @type {Set<string>} */
					const traced = new Set();
					names.forEach(
						/** @param {any} name */ (name) => {
							const dependencies = template_scope.dependencies_for_name.get(name);
							if (dependencies) {
								dependencies.forEach(/** @param {any} name */ (name) => traced.add(name));
							} else {
								traced.add(name);
							}
						}
					);
					const context = block.bindings.get(object_name);
					if (context) {
						// for `{#each array as item}`
						// replace `item = 1` to `each_array[each_index] = 1`, this allow us to mutate the array
						// rather than mutating the local `item` variable
						const { snippet, object, property } = context;

						/** @type {any} */
						const replaced = replace_object(assignee, snippet);
						if (node.type === 'AssignmentExpression') {
							node.left = replaced;
						} else {
							node.argument = replaced;
						}
						contextual_dependencies.add(object.name);
						contextual_dependencies.add(property.name);
					}
					this.replace(invalidate(block.renderer, scope, node, traced));
				}
			}
		});

		if (declarations.length > 0) {
			block.maintain_context = true;
			declarations.forEach(
				/** @param {any} declaration */ (declaration) => {
					block.chunks.init.push(declaration);
				}
			);
		}
		return (this.manipulated = /** @type {import('estree').Node} */ (node));
	}
}

/**
 * @param {any} _node
 * @param {any} parent
 */
function get_function_name(_node, parent) {
	if (parent.type === 'EventHandler') {
		return `${parent.name}_handler`;
	}
	if (parent.type === 'Action') {
		return `${parent.name}_function`;
	}
	return 'func';
}

/**
 * @param {{
 * 	contexts: Context[];
 * 	node: import('estree').Pattern;
 * 	modifier?: DestructuredVariable['modifier'];
 * 	default_modifier?: DestructuredVariable['default_modifier'];
 * 	scope: import('./TemplateScope.js').default;
 * 	component: import('../../Component.js').default;
 * 	context_rest_properties: Map<string, import('estree').Node>;
 * 	in_rest_element?: boolean;
 * }} params
 */
function unpack_destructuring({
	contexts,
	node,
	modifier = (node) => node,
	default_modifier = (node) => node,
	scope,
	component,
	context_rest_properties,
	in_rest_element = false
}) {
	if (!node) return;
	if (node.type === 'Identifier') {
		contexts.push({
			type: 'DestructuredVariable',
			key: /** @type {import('estree').Identifier} */ (node),
			modifier,
			default_modifier
		});
		if (in_rest_element) {
			context_rest_properties.set(node.name, node);
		}
		component.used_names.add(node.name);
	} else if (node.type === 'ArrayPattern') {
		node.elements.forEach((element, i) => {
			if (!element) {
				return;
			} else if (element.type === 'RestElement') {
				unpack_destructuring({
					contexts,
					node: element.argument,
					modifier: (node) =>
						/** @type {import('estree').Node} */ (x$1`${modifier(node)}.slice(${i})`),
					default_modifier,
					scope,
					component,
					context_rest_properties,
					in_rest_element: true
				});
			} else if (element.type === 'AssignmentPattern') {
				const n = contexts.length;
				mark_referenced(element.right, scope, component);
				unpack_destructuring({
					contexts,
					node: element.left,
					modifier: (node) => x$1`${modifier(node)}[${i}]`,
					default_modifier: (node, to_ctx) =>
						/** @type {import('estree').Node} */ (
							x$1`${node} !== undefined ? ${node} : ${update_reference(
								contexts,
								n,
								element.right,
								to_ctx
							)}`
						),
					scope,
					component,
					context_rest_properties,
					in_rest_element
				});
			} else {
				unpack_destructuring({
					contexts,
					node: element,
					modifier: (node) => /** @type {import('estree').Node} */ (x$1`${modifier(node)}[${i}]`),
					default_modifier,
					scope,
					component,
					context_rest_properties,
					in_rest_element
				});
			}
		});
	} else if (node.type === 'ObjectPattern') {
		const used_properties = [];
		node.properties.forEach((property) => {
			if (property.type === 'RestElement') {
				unpack_destructuring({
					contexts,
					node: property.argument,
					modifier: (node) =>
						/** @type {import('estree').Node} */ (
							x$1`@object_without_properties(${modifier(node)}, [${used_properties}])`
						),
					default_modifier,
					scope,
					component,
					context_rest_properties,
					in_rest_element: true
				});
			} else if (property.type === 'Property') {
				const key = property.key;
				const value = property.value;

				/** @type {(node: import('estree').Node) => import('estree').Node} */
				let new_modifier;
				if (property.computed) {
					// e.g { [computedProperty]: ... }
					const property_name = component.get_unique_name('computed_property');
					contexts.push({
						type: 'ComputedProperty',
						property_name,
						key
					});
					new_modifier = (node) => x$1`${modifier(node)}[${property_name}]`;
					used_properties.push(x$1`${property_name}`);
				} else if (key.type === 'Identifier') {
					// e.g. { someProperty: ... }
					const property_name = key.name;
					new_modifier = (node) => x$1`${modifier(node)}.${property_name}`;
					used_properties.push(x$1`"${property_name}"`);
				} else if (key.type === 'Literal') {
					// e.g. { "property-in-quotes": ... } or { 14: ... }
					const property_name = key.value;
					new_modifier = (node) => x$1`${modifier(node)}["${property_name}"]`;
					used_properties.push(x$1`"${property_name}"`);
				}
				if (value.type === 'AssignmentPattern') {
					// e.g. { property = default } or { property: newName = default }
					const n = contexts.length;
					mark_referenced(value.right, scope, component);
					unpack_destructuring({
						contexts,
						node: value.left,
						modifier: new_modifier,
						default_modifier: (node, to_ctx) =>
							/** @type {import('estree').Node} */ (
								x$1`${node} !== undefined ? ${node} : ${update_reference(
									contexts,
									n,
									value.right,
									to_ctx
								)}`
							),
						scope,
						component,
						context_rest_properties,
						in_rest_element
					});
				} else {
					// e.g. { property } or { property: newName }
					unpack_destructuring({
						contexts,
						node: value,
						modifier: new_modifier,
						default_modifier,
						scope,
						component,
						context_rest_properties,
						in_rest_element
					});
				}
			}
		});
	}
}

/**
 * @param {Context[]} contexts
 * @param {number} n
 * @param {import('estree').Expression} expression
 * @param {(name: string) => import('estree').Node} to_ctx
 * @returns {import('estree').Node}
 */
function update_reference(contexts, n, expression, to_ctx) {
	/** @param {import('estree').Identifier} node */
	const find_from_context = (node) => {
		for (let i = n; i < contexts.length; i++) {
			const cur_context = contexts[i];
			if (cur_context.type !== 'DestructuredVariable') continue;
			const { key } = cur_context;
			if (node.name === key.name) {
				throw new Error(`Cannot access '${node.name}' before initialization`);
			}
		}
		return to_ctx(node.name);
	};
	if (expression.type === 'Identifier') {
		return find_from_context(expression);
	}
	// NOTE: avoid unnecessary deep clone?
	expression = /** @type {import('estree').Expression} */ (clone(expression));
	walk(expression, {
		enter(node, parent) {
			if (
				is_reference(
					/** @type {import('is-reference').NodeWithPropertyDefinition} */ (node),
					/** @type {import('is-reference').NodeWithPropertyDefinition} */ (parent)
				)
			) {
				this.replace(find_from_context(/** @type {import('estree').Identifier} */ (node)));
				this.skip();
			}
		}
	});
	return expression;
}

/**
 * @param {import('estree').Node} node
 * @param {import('./TemplateScope.js').default} scope
 * @param {import('../../Component.js').default} component
 */
function mark_referenced(node, scope, component) {
	walk(node, {
		enter(node, parent) {
			if (is_reference(node, parent)) {
				const { name } = flatten_reference(node);
				if (!scope.is_let(name) && !scope.names.has(name)) {
					component.add_reference(node, name);
				}
			}
		}
	});
}

/** @typedef {DestructuredVariable | ComputedProperty} Context */

/**
 * @typedef {Object} ComputedProperty
 * @property {'ComputedProperty'} type
 * @property {import('estree').Identifier} property_name
 * @property {import('estree').Expression|import('estree').PrivateIdentifier} key
 */

/**
 * @typedef {Object} DestructuredVariable
 * @property {'DestructuredVariable'} type
 * @property {import('estree').Identifier} key
 * @property {string} [name]
 * @property {(node:import('estree').Node)=>import('estree').Node} modifier
 * @property {(node:import('estree').Node,to_ctx:(name:string)=>import('estree').Node)=>import('estree').Node} default_modifier
 */

const allowed_parents = new Set([
	'EachBlock',
	'CatchBlock',
	'ThenBlock',
	'InlineComponent',
	'SlotTemplate',
	'IfBlock',
	'ElseBlock'
]);

/** @extends Node<'ConstTag'> */
class ConstTag extends Node {
	/** @type {import('./shared/Expression.js').default} */
	expression;

	/** @type {import('./shared/Context.js').Context[]} */
	contexts = [];

	/** @type {import('../../interfaces.js').ConstTag} */
	node;

	/** @type {import('./shared/TemplateScope.js').default} */
	scope;

	/** @type {Map<string, import('estree').Node>} */
	context_rest_properties = new Map();

	/** @type {Set<string>} */
	assignees = new Set();

	/** @type {Set<string>} */
	dependencies = new Set();

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./interfaces.js').INodeAllowConstTag} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').ConstTag} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		if (!allowed_parents.has(parent.type)) {
			component.error(info, compiler_errors.invalid_const_placement);
		}
		this.node = info;
		this.scope = scope;
		const { assignees, dependencies } = this;
		extract_identifiers(info.expression.left).forEach(
			/** @param {any}params_0 */ ({ name }) => {
				assignees.add(name);
				const owner = this.scope.get_owner(name);
				if (owner === parent) {
					component.error(info, compiler_errors.invalid_const_declaration(name));
				}
			}
		);
		walk(info.expression.right, {
			/**
			 * @param {any} node
			 * @param {any} parent
			 */
			enter(node, parent) {
				if (
					is_reference(
						/** @type {import('is-reference').NodeWithPropertyDefinition} */ (node),
						/** @type {import('is-reference').NodeWithPropertyDefinition} */ (parent)
					)
				) {
					const identifier = get_object(/** @type {any} */ (node));
					const { name } = identifier;
					dependencies.add(name);
				}
			}
		});
	}

	parse_expression() {
		unpack_destructuring({
			contexts: this.contexts,
			node: this.node.expression.left,
			scope: this.scope,
			component: this.component,
			context_rest_properties: this.context_rest_properties
		});
		this.expression = new Expression(this.component, this, this.scope, this.node.expression.right);
		this.contexts.forEach(
			/** @param {any} context */ (context) => {
				if (context.type !== 'DestructuredVariable') return;
				const owner = this.scope.get_owner(context.key.name);
				if (owner && owner.type === 'ConstTag' && owner.parent === this.parent) {
					this.component.error(
						this.node,
						compiler_errors.invalid_const_declaration(context.key.name)
					);
				}
				this.scope.add(context.key.name, this.expression.dependencies, this);
			}
		);
	}
}

/** @extends AbstractBlock<'PendingBlock'> */
class PendingBlock extends AbstractBlock {
	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./shared/Node.js').default} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		this.children = map_children(component, parent, scope, info.children);
		if (!info.skip) {
			this.warn_if_empty_block();
		}
	}
}

/** @extends AbstractBlock<'CatchBlock'> */
class CatchBlock extends AbstractBlock {
	/** @type {import('./shared/TemplateScope.js').default} */
	scope;

	/** @type {import('./ConstTag.js').default[]} */
	const_tags;

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./AwaitBlock.js').default} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		this.scope = scope.child();
		if (parent.catch_node) {
			parent.catch_contexts.forEach(
				/** @param {any} context */ (context) => {
					if (context.type !== 'DestructuredVariable') return;
					this.scope.add(context.key.name, parent.expression.dependencies, this);
				}
			);
		}
		[this.const_tags, this.children] = get_const_tags$1(info.children, component, this, parent);
		if (!info.skip) {
			this.warn_if_empty_block();
		}
	}
}

/** @extends Node<'AwaitBlock'> */
let AwaitBlock$1 = class AwaitBlock extends Node {
	/** @type {import('./shared/Expression.js').default} */
	expression;

	/** @type {import('./shared/Context.js').Context[]} */
	then_contexts;

	/** @type {import('./shared/Context.js').Context[]} */
	catch_contexts;

	/** @type {import('estree').Node | null} */
	then_node;

	/** @type {import('estree').Node | null} */
	catch_node;

	/** @type {import('./PendingBlock.js').default} */
	pending;

	/** @type {import('./ThenBlock.js').default} */
	then;

	/** @type {import('./CatchBlock.js').default} */
	catch;

	/** @type {Map<string, import('estree').Node>} */
	context_rest_properties = new Map();

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./shared/Node.js').default} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		this.cannot_use_innerhtml();
		this.not_static_content();
		this.expression = new Expression(component, this, scope, info.expression);
		this.then_node = info.value;
		this.catch_node = info.error;
		if (this.then_node) {
			this.then_contexts = [];
			unpack_destructuring({
				contexts: this.then_contexts,
				node: info.value,
				scope,
				component,
				context_rest_properties: this.context_rest_properties
			});
		}
		if (this.catch_node) {
			this.catch_contexts = [];
			unpack_destructuring({
				contexts: this.catch_contexts,
				node: info.error,
				scope,
				component,
				context_rest_properties: this.context_rest_properties
			});
		}
		this.pending = new PendingBlock(component, this, scope, info.pending);
		this.then = new ThenBlock(component, this, scope, info.then);
		this.catch = new CatchBlock(component, this, scope, info.catch);
	}
};

const regex_contains_term_function_expression = /FunctionExpression/;

/** @extends Node<'EventHandler'> */
class EventHandler extends Node {
	/** @type {string} */
	name;

	/** @type {Set<string>} */
	modifiers;

	/** @type {import('./shared/Expression.js').default} */
	expression;

	/** @type {import('estree').Identifier} */
	handler_name;
	/** */
	uses_context = false;
	/** */
	can_make_passive = false;

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./shared/Node.js').default} parent
	 * @param {import('./shared/TemplateScope.js').default} template_scope
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, template_scope, info) {
		super(component, parent, template_scope, info);
		this.name = info.name;
		this.modifiers = new Set(info.modifiers);
		if (info.expression) {
			this.expression = new Expression(component, this, template_scope, info.expression);
			this.uses_context = this.expression.uses_context;
			if (
				regex_contains_term_function_expression.test(info.expression.type) &&
				info.expression.params.length === 0
			) {
				// TODO make this detection more accurate — if `event.preventDefault` isn't called, and
				// `event` is passed to another function, we can make it passive
				this.can_make_passive = true;
			} else if (info.expression.type === 'Identifier') {
				let node = component.node_for_declaration.get(info.expression.name);
				if (node) {
					if (node.type === 'VariableDeclaration') {
						// for `const handleClick = () => {...}`, we want the [arrow] function expression node
						const declarator = node.declarations.find(
							/** @param {any} d */
							(d) => /** @type {import('estree').Identifier} */ (d.id).name === info.expression.name
						);
						node = declarator && declarator.init;
					}
					if (
						node &&
						(node.type === 'FunctionExpression' ||
							node.type === 'FunctionDeclaration' ||
							node.type === 'ArrowFunctionExpression') &&
						node.params.length === 0
					) {
						this.can_make_passive = true;
					}
				}
			}
		} else {
			this.handler_name = component.get_unique_name(`${sanitize(this.name)}_handler`);
		}
	}

	/** @returns {boolean} */
	get reassigned() {
		if (!this.expression) {
			return false;
		}
		const node = this.expression.node;
		if (regex_contains_term_function_expression.test(node.type)) {
			return false;
		}
		return this.expression.dynamic_dependencies().length > 0;
	}
}

/** @extends Node<'Action'> */
class Action extends Node {
	/** @type {string} */
	name;

	/** @type {import('./shared/Expression.js').default} */
	expression;

	/** @type {boolean} */
	uses_context;

	/** @type {import('./shared/TemplateScope.js').default} */
	template_scope;

	/**
	 * @param {import('../Component.js').default} component  *
	 * @param {import('./shared/Node.js').default} parent  *
	 * @param {import('./shared/TemplateScope.js').default} scope  *
	 * @param {import('../../interfaces.js').Directive} info  undefined
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		const object = info.name.split('.')[0];
		component.warn_if_undefined(object, info, scope);
		this.name = info.name;
		component.add_reference(/** @type {any} */ (this), object);
		this.expression = info.expression
			? new Expression(component, this, scope, info.expression)
			: null;
		this.template_scope = scope;
		this.uses_context = this.expression && this.expression.uses_context;
	}
}

/** @extends Node<'Body'> */
class Body extends Node {
	/** @type {import('./EventHandler.js').default[]} */
	handlers = [];

	/** @type {import('./Action.js').default[]} */
	actions = [];

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./shared/Node.js').default} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').Element} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		info.attributes.forEach(
			/** @param {any} node */ (node) => {
				if (node.type === 'EventHandler') {
					this.handlers.push(new EventHandler(component, this, scope, node));
				} else if (node.type === 'Action') {
					this.actions.push(new Action(component, this, scope, node));
				} else ;
			}
		);
	}
}

/** @extends Node<'Comment'> */
let Comment$1 = class Comment extends Node {
	/** @type {string} */
	data;

	/** @type {string[]} */
	ignores;

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./shared/Node.js').default} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		this.data = info.data;
		this.ignores = info.ignores;
	}
};

/** @extends AbstractBlock<'ElseBlock'> */
class ElseBlock extends AbstractBlock {
	/** @type {import('./shared/TemplateScope.js').default} */
	scope;

	/** @type {import('./ConstTag.js').default[]} */
	const_tags;

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./shared/Node.js').default} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		this.scope = scope.child();
		[this.const_tags, this.children] = get_const_tags$1(info.children, component, this, this);
		this.warn_if_empty_block();
	}
}

/** @extends AbstractBlock<'EachBlock'> */
let EachBlock$1 = class EachBlock extends AbstractBlock {
	/** @type {import('./shared/Expression.js').default} */
	expression;

	/** @type {import('estree').Node} */
	context_node;

	/** @type {string} */
	iterations;

	/** @type {string} */
	index;

	/** @type {string} */
	context;

	/** @type {import('./shared/Expression.js').default} */
	key;

	/** @type {import('./shared/TemplateScope.js').default} */
	scope;

	/** @type {import('./shared/Context.js').Context[]} */
	contexts;

	/** @type {import('./ConstTag.js').default[]} */
	const_tags;

	/** @type {boolean} */
	has_animation;
	/** */
	has_binding = false;
	/** */
	has_index_binding = false;

	/** @type {Map<string, import('estree').Node>} */
	context_rest_properties;

	/** @type {import('./ElseBlock.js').default} */
	else;

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('estree').Node} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		this.cannot_use_innerhtml();
		this.not_static_content();
		this.expression = new Expression(component, this, scope, info.expression);
		this.context = info.context.name || 'each'; // TODO this is used to facilitate binding; currently fails with destructuring
		this.context_node = info.context;
		this.index = info.index;
		this.scope = scope.child();
		this.context_rest_properties = new Map();
		this.contexts = [];
		unpack_destructuring({
			contexts: this.contexts,
			node: info.context,
			scope,
			component,
			context_rest_properties: this.context_rest_properties
		});
		this.contexts.forEach(
			/** @param {any} context */ (context) => {
				if (context.type !== 'DestructuredVariable') return;
				this.scope.add(context.key.name, this.expression.dependencies, this);
			}
		);
		if (this.index) {
			// index can only change if this is a keyed each block
			const dependencies = info.key ? this.expression.dependencies : new Set([]);
			this.scope.add(this.index, dependencies, this);
		}
		this.key = info.key ? new Expression(component, this, this.scope, info.key) : null;
		this.has_animation = false;
		[this.const_tags, this.children] = get_const_tags$1(info.children, component, this, this);
		if (this.has_animation) {
			this.children = this.children.filter(
				/** @param {any} child */ (child) => !isEmptyNode(child) && !isCommentNode(child)
			);
			if (this.children.length !== 1) {
				const child = this.children.find(
					/** @param {any} child */ (child) =>
						!!(/** @type {import('./Element.js').default} */ (child).animation)
				);
				component.error(
					/** @type {import('./Element.js').default} */ (child).animation,
					compiler_errors.invalid_animation_sole
				);
				return;
			}
		}
		this.warn_if_empty_block();
		this.else = info.else ? new ElseBlock(component, this, this.scope, info.else) : null;
	}
};

/** @param {import('./interfaces.js').INode} node */
function isEmptyNode(node) {
	return node.type === 'Text' && node.data.trim() === '';
}

/** @param {import('./interfaces.js').INode} node */
function isCommentNode(node) {
	return node.type === 'Comment';
}

// TODO this should live in a specific binding
const read_only_media_attributes = new Set([
	'duration',
	'buffered',
	'seekable',
	'played',
	'seeking',
	'ended',
	'videoHeight',
	'videoWidth',
	'naturalWidth',
	'naturalHeight',
	'readyState'
]);

/** @extends Node<'Binding'> */
class Binding extends Node {
	/** @type {string} */
	name;

	/** @type {import('./shared/Expression.js').default} */
	expression;

	/** @type {import('estree').Node} */
	raw_expression; // TODO exists only for bind:this — is there a more elegant solution?

	/** @type {boolean} */
	is_contextual;

	/** @type {boolean} */
	is_readonly;

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./Element.js').default | import('./InlineComponent.js').default | import('./Window.js').default | import('./Document.js').default} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		if (info.expression.type !== 'Identifier' && info.expression.type !== 'MemberExpression') {
			component.error(info, compiler_errors.invalid_directive_value);
			return;
		}
		this.name = info.name;
		this.expression = new Expression(component, this, scope, info.expression);
		this.raw_expression = clone(info.expression);
		const { name } = get_object(this.expression.node);
		this.is_contextual = Array.from(this.expression.references).some(
			/** @param {any} name */ (name) => scope.names.has(name)
		);
		if (this.is_contextual) this.validate_binding_rest_properties(scope);
		// make sure we track this as a mutable ref
		if (scope.is_let(name)) {
			component.error(this, compiler_errors.invalid_binding_let);
			return;
		} else if (scope.names.has(name)) {
			if (scope.is_await(name)) {
				component.error(this, compiler_errors.invalid_binding_await);
				return;
			}
			if (scope.is_const(name)) {
				component.error(this, compiler_errors.invalid_binding_const);
			}
			scope.dependencies_for_name.get(name).forEach(
				/** @param {any} name */ (name) => {
					const variable = component.var_lookup.get(name);
					if (variable) {
						variable.mutated = true;
					}
				}
			);
		} else {
			const variable = component.var_lookup.get(name);
			if (!variable || variable.global) {
				component.error(
					/** @type {any} */ (this.expression.node),
					compiler_errors.binding_undeclared(name)
				);
				return;
			}
			variable[this.expression.node.type === 'MemberExpression' ? 'mutated' : 'reassigned'] = true;
			if (info.expression.type === 'Identifier' && !variable.writable) {
				component.error(
					/** @type {any} */ (this.expression.node),
					compiler_errors.invalid_binding_writable
				);
				return;
			}
		}
		const type = parent.get_static_attribute_value('type');
		this.is_readonly =
			regex_dimensions.test(this.name) ||
			regex_box_size.test(this.name) ||
			(isElement(parent) &&
				((parent.is_media_node() && read_only_media_attributes.has(this.name)) ||
					(parent.name === 'input' && type === 'file'))) /* TODO others? */;
	}
	is_readonly_media_attribute() {
		return read_only_media_attributes.has(this.name);
	}

	/** @param {import('./shared/TemplateScope.js').default} scope */
	validate_binding_rest_properties(scope) {
		this.expression.references.forEach(
			/** @param {any} name */ (name) => {
				const each_block = scope.get_owner(name);
				if (each_block && each_block.type === 'EachBlock') {
					const rest_node = each_block.context_rest_properties.get(name);
					if (rest_node) {
						this.component.warn(
							/** @type {any} */ (rest_node),
							compiler_warnings.invalid_rest_eachblock_binding(name)
						);
					}
				}
			}
		);
	}
}

/**
 * @param {import('./shared/Node.js').default} node
 * @returns {node is import('./Element.js').default}
 */
function isElement(node) {
	return !!(/** @type {any} */ (node).is_media_node);
}

const valid_bindings$1 = ['fullscreenElement', 'visibilityState'];

/** @extends Node<'Document'> */
class Document extends Node {
	/** @type {import('./EventHandler.js').default[]} */
	handlers = [];

	/** @type {import('./Binding.js').default[]} */
	bindings = [];

	/** @type {import('./Action.js').default[]} */
	actions = [];

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./shared/Node.js').default} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').Element} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		info.attributes.forEach(
			/** @param {any} node */ (node) => {
				if (node.type === 'EventHandler') {
					this.handlers.push(new EventHandler(component, this, scope, node));
				} else if (node.type === 'Binding') {
					if (!~valid_bindings$1.indexOf(node.name)) {
						const match = fuzzymatch(node.name, valid_bindings$1);
						if (match) {
							return component.error(
								node,
								compiler_errors.invalid_binding_on(
									node.name,
									'<svelte:document>',
									` (did you mean '${match}'?)`
								)
							);
						} else {
							return component.error(
								node,
								compiler_errors.invalid_binding_on(
									node.name,
									'<svelte:document>',
									` — valid bindings are ${list(valid_bindings$1)}`
								)
							);
						}
					}
					this.bindings.push(new Binding(component, this, scope, node));
				} else if (node.type === 'Action') {
					this.actions.push(new Action(component, this, scope, node));
				} else ;
			}
		);
		this.validate();
	}

	/** @private */
	validate() {
		const handlers_map = new Set();
		this.handlers.forEach(/** @param {any} handler */ (handler) => handlers_map.add(handler.name));
		if (handlers_map.has('mouseenter') || handlers_map.has('mouseleave')) {
			this.component.warn(this, compiler_warnings.avoid_mouse_events_on_document);
		}
	}
}

/**
 * @param {string} data
 * @returns {import('estree').Literal}
 */
function string_literal(data) {
	return {
		type: 'Literal',
		value: data
	};
}

const escaped = {
	'"': '&quot;',
	"'": '&#39;',
	'&': '&amp;',
	'<': '&lt;',
	'>': '&gt;'
};

const regex_html_characters_to_escape = /["'&<>]/g;

function escape_html(html) {
	return String(html).replace(regex_html_characters_to_escape, (match) => escaped[match]);
}

const regex_template_characters_to_escape = /(\${|`|\\)/g;

function escape_template(str) {
	return str.replace(regex_template_characters_to_escape, '\\$1');
}

/**
 * @template T
 * @param {Set<T>} a
 * @param {Set<T> | T[]} b
 */
function add_to_set(a, b) {
	// @ts-ignore
	b.forEach((item) => {
		a.add(item);
	});
}

/** @extends Node<'Attribute' | 'Spread', import('./Element.js').default> */
class Attribute extends Node {
	/** @type {import('./shared/TemplateScope.js').default} */
	scope;

	/** @type {string} */
	name;

	/** @type {boolean} */
	is_spread;

	/** @type {boolean} */
	is_true;

	/** @type {boolean} */
	is_static;

	/** @type {import('./shared/Expression.js').default} */
	expression;

	/** @type {Array<import('./Text.js').default | import('./shared/Expression.js').default>} */
	chunks;

	/** @type {Set<string>} */
	dependencies;

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./shared/Node.js').default} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		this.scope = scope;

		if (info.type === 'Spread') {
			this.name = null;
			this.is_spread = true;
			this.is_true = false;
			this.expression = new Expression(component, this, scope, info.expression);
			this.dependencies = this.expression.dependencies;
			this.chunks = null;
			this.is_static = false;
		} else {
			this.name = info.name;
			this.is_true = info.value === true;
			this.is_static = true;
			this.dependencies = new Set();
			this.chunks = this.is_true
				? []
				: info.value.map(
						/** @param {any} node */ (node) => {
							if (node.type === 'Text') return node;
							this.is_static = false;
							const expression = new Expression(component, this, scope, node.expression);
							add_to_set(this.dependencies, expression.dependencies);
							return expression;
						}
				  );
		}

		if (this.dependencies.size > 0) {
			parent.cannot_use_innerhtml();
			parent.not_static_content();
		}

		// TODO Svelte 5: Think about moving this into the parser and make it an error
		if (
			this.name &&
			this.name.includes(':') &&
			!this.name.startsWith('xmlns:') &&
			!this.name.startsWith('xlink:') &&
			!this.name.startsWith('xml:')
		) {
			component.warn(this, compiler_warnings.illegal_attribute_character);
		}
	}
	get_dependencies() {
		if (this.is_spread) return this.expression.dynamic_dependencies();

		/** @type {Set<string>} */
		const dependencies = new Set();
		this.chunks.forEach(
			/** @param {any} chunk */ (chunk) => {
				if (chunk.type === 'Expression') {
					add_to_set(dependencies, chunk.dynamic_dependencies());
				}
			}
		);
		return Array.from(dependencies);
	}

	/** @param {any} block */
	get_value(block) {
		if (this.is_true) return x$1`true`;
		if (this.chunks.length === 0) return x$1`""`;
		if (this.chunks.length === 1) {
			return this.chunks[0].type === 'Text'
				? string_literal(/** @type {import('./Text.js').default} */ (this.chunks[0]).data)
				: /** @type {import('./shared/Expression.js').default} */ (this.chunks[0]).manipulate(
						block
				  );
		}
		let expression = this.chunks
			.map(
				/** @param {any} chunk */ (chunk) =>
					chunk.type === 'Text' ? string_literal(chunk.data) : chunk.manipulate(block)
			)
			.reduce(
				/**
				 * @param {any} lhs
				 * @param {any} rhs
				 */ (lhs, rhs) => x$1`${lhs} + ${rhs}`
			);
		if (this.chunks[0].type !== 'Text') {
			expression = x$1`"" + ${expression}`;
		}
		return expression;
	}
	get_static_value() {
		if (!this.is_static) return null;
		return this.is_true
			? true
			: this.chunks[0]
			? // method should be called only when `is_static = true`
			  /** @type {import('./Text.js').default} */ (this.chunks[0]).data
			: '';
	}
	should_cache() {
		return this.is_static
			? false
			: this.chunks.length === 1
			? // @ts-ignore todo: probably error
			  this.chunks[0].node.type !== 'Identifier' || this.scope.names.has(this.chunks[0].node.name)
			: true;
	}
}

/** @extends Node<'Transition'> */
class Transition extends Node {
	/** @type {string} */
	name;

	/** @type {string} */
	directive;

	/** @type {import('./shared/Expression.js').default} */
	expression;

	/** @type {boolean} */
	is_local;

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./Element.js').default} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		component.warn_if_undefined(info.name, info, scope);
		this.name = info.name;
		component.add_reference(/** @type {any} */ (this), info.name.split('.')[0]);
		this.directive = info.intro && info.outro ? 'transition' : info.intro ? 'in' : 'out';
		this.is_local = !info.modifiers.includes('global');
		if ((info.intro && parent.intro) || (info.outro && parent.outro)) {
			const parent_transition = parent.intro || parent.outro;
			component.error(
				info,
				compiler_errors.duplicate_transition(this.directive, parent_transition.directive)
			);
			return;
		}
		this.expression = info.expression
			? new Expression(component, this, scope, info.expression)
			: null;
	}
}

/** @extends Node<'Animation'> */
class Animation extends Node {
	/** @type {string} */
	name;

	/** @type {import('./shared/Expression.js').default} */
	expression;

	/**
	 * @param {import('../Component.js').default} component  *
	 * @param {import('./Element.js').default} parent  *
	 * @param {import('./shared/TemplateScope.js').default} scope  *
	 * @param {import('../../interfaces.js').TemplateNode} info  undefined
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		component.warn_if_undefined(info.name, info, scope);
		this.name = info.name;
		component.add_reference(/** @type {any} */ (this), info.name.split('.')[0]);
		if (parent.animation) {
			component.error(this, compiler_errors.duplicate_animation);
			return;
		}
		const block = parent.parent;
		if (!block || block.type !== 'EachBlock') {
			// TODO can we relax the 'immediate child' rule?
			component.error(this, compiler_errors.invalid_animation_immediate);
			return;
		}
		if (!block.key) {
			component.error(this, compiler_errors.invalid_animation_key);
			return;
		}
		/** @type {import('./EachBlock.js').default} */ (block).has_animation = true;
		this.expression = info.expression
			? new Expression(component, this, scope, info.expression, true)
			: null;
	}
}

/** @extends Node<'Class'> */
class Class extends Node {
	/** @type {string} */
	name;

	/** @type {import('./shared/Expression.js').default} */
	expression;

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./shared/Node.js').default} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		this.name = info.name;
		this.expression = info.expression
			? new Expression(component, this, scope, info.expression)
			: null;
	}
}

/**
 * Transforms a list of Text and MustacheTags into a TemplateLiteral expression.
 * Start/End positions on the elements of the expression are not set.
 * @param {Array<import('../../interfaces.js').Text | import('../../interfaces.js').MustacheTag>} value
 * @returns {import('estree').TemplateLiteral}
 */
function nodes_to_template_literal(value) {
	/**
	 * @type {import('estree').TemplateLiteral}
	 */
	const literal = {
		type: 'TemplateLiteral',
		expressions: [],
		quasis: []
	};

	/**
	 * @type {import('estree').TemplateElement}
	 */
	let quasi = {
		type: 'TemplateElement',
		value: { raw: '', cooked: null },
		tail: false
	};
	value.forEach((node) => {
		if (node.type === 'Text') {
			quasi.value.raw += node.raw;
		} else if (node.type === 'MustacheTag') {
			literal.quasis.push(quasi);
			literal.expressions.push(/** @type {any} */ (node.expression));
			quasi = {
				type: 'TemplateElement',
				value: { raw: '', cooked: null },
				tail: false
			};
		}
	});
	quasi.tail = true;
	literal.quasis.push(quasi);
	return literal;
}

const valid_modifiers$1 = new Set(['important']);

/** @extends Node<'StyleDirective'> */
class StyleDirective extends Node {
	/** @type {string} */
	name;

	/** @type {Set<string>} */
	modifiers;

	/** @type {import('./shared/Expression.js').default} */
	expression;

	/** @type {boolean} */
	should_cache;

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./shared/Node.js').default} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		this.name = info.name;
		this.modifiers = new Set(info.modifiers);
		for (const modifier of this.modifiers) {
			if (!valid_modifiers$1.has(modifier)) {
				component.error(
					this,
					compiler_errors.invalid_style_directive_modifier(list([...valid_modifiers$1]))
				);
			}
		}
		// Convert the value array to an expression so it's easier to handle
		// the StyleDirective going forward.
		if (info.value === true || (info.value.length === 1 && info.value[0].type === 'MustacheTag')) {
			const identifier =
				info.value === true
					? /** @type {any} */ ({
							type: 'Identifier',
							start: info.end - info.name.length,
							end: info.end,
							name: info.name
					  })
					: info.value[0].expression;
			this.expression = new Expression(component, this, scope, identifier);
			this.should_cache = false;
		} else {
			const raw_expression = nodes_to_template_literal(info.value);
			this.expression = new Expression(component, this, scope, raw_expression);
			this.should_cache = raw_expression.expressions.length > 0;
		}
	}
	get important() {
		return this.modifiers.has('important');
	}
}

// Whitespace inside one of these elements will not result in
// a whitespace node being created in any circumstances. (This
// list is almost certainly very incomplete)
const elements_without_text = new Set(['audio', 'datalist', 'dl', 'optgroup', 'select', 'video']);
const regex_ends_with_svg = /svg$/;
const regex_non_whitespace_characters = /[\S\u00A0]/;

/** @extends Node<'Text'> */
let Text$1 = class Text extends Node {
	/** @type {string} */
	data;

	/** @type {boolean} */
	synthetic;

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./interfaces.js').INode} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		this.data = info.data;
		this.synthetic = info.synthetic || false;
	}
	should_skip() {
		if (regex_non_whitespace_character.test(this.data)) return false;
		const parent_element = this.find_nearest(/(?:Element|InlineComponent|SlotTemplate|Head)/);
		if (!parent_element) return false;
		if (parent_element.type === 'Head') return true;
		if (parent_element.type === 'InlineComponent')
			return parent_element.children.length === 1 && this === parent_element.children[0];
		// svg namespace exclusions
		if (regex_ends_with_svg.test(parent_element.namespace)) {
			if (this.prev && this.prev.type === 'Element' && this.prev.name === 'tspan') return false;
		}
		return parent_element.namespace || elements_without_text.has(parent_element.name);
	}

	/** @returns {boolean} */
	keep_space() {
		if (this.component.component_options.preserveWhitespace) return true;
		return this.within_pre();
	}

	/** @returns {boolean} */
	within_pre() {
		let node = this.parent;
		while (node) {
			if (node.type === 'Element' && node.name === 'pre') {
				return true;
			}
			node = node.parent;
		}
		return false;
	}

	/** @returns {boolean} */
	use_space() {
		if (this.component.compile_options.preserveWhitespace) return false;
		if (regex_non_whitespace_characters.test(this.data)) return false;
		return !this.within_pre();
	}
};

// The `foreign` namespace covers all DOM implementations that aren't HTML5.
// It opts out of HTML5-specific a11y checks and case-insensitive attribute names.
const foreign = 'https://svelte.dev/docs/special-elements#svelte-options';
const html = 'http://www.w3.org/1999/xhtml';
const mathml = 'http://www.w3.org/1998/Math/MathML';
const svg = 'http://www.w3.org/2000/svg';
const xlink = 'http://www.w3.org/1999/xlink';
const xml = 'http://www.w3.org/XML/1998/namespace';
const xmlns = 'http://www.w3.org/2000/xmlns';

const valid_namespaces = [
	'foreign',
	'html',
	'mathml',
	'svg',
	'xlink',
	'xml',
	'xmlns',
	foreign,
	html,
	mathml,
	svg,
	xlink,
	xml,
	xmlns
];

const namespaces = /** @type {const} */ ({ foreign, html, mathml, svg, xlink, xml, xmlns });

// Utilities for managing contenteditable nodes

/** @typedef {import('../nodes/Attribute.js').default} Attribute */
/** @typedef {import('../nodes/Element.js').default} Element */

const CONTENTEDITABLE_BINDINGS = ['textContent', 'innerHTML', 'innerText'];

/**
 * Returns true if node is an 'input' or 'textarea'.
 * @param {Element} node The element to be checked
 */
function is_input_or_textarea(node) {
	return node.name === 'textarea' || node.name === 'input';
}

/**
 * Check if a given attribute is 'contenteditable'.
 * @param {Attribute} attribute A node.attribute
 */
function is_attr_contenteditable(attribute) {
	return attribute.name === 'contenteditable';
}

/**
 * Check if any of a node's attributes are 'contentenditable'.
 * @param {Element} node The element to be checked
 */
function has_contenteditable_attr(node) {
	return node.attributes.some(is_attr_contenteditable);
}

/**
 * Returns true if node is not textarea or input, but has 'contenteditable' attribute.
 * @param {Element} node The element to be tested
 */
function is_contenteditable(node) {
	return !is_input_or_textarea(node) && has_contenteditable_attr(node);
}

/**
 * Returns true if a given binding/node is contenteditable.
 * @param {string} name A binding or node name to be checked
 */
function is_name_contenteditable(name) {
	return CONTENTEDITABLE_BINDINGS.includes(name);
}

/**
 * Returns the contenteditable attribute from the node (if it exists).
 * @param {Element} node The element to get the attribute from
 */
function get_contenteditable_attr(node) {
	return node.attributes.find(is_attr_contenteditable);
}

// https://github.com/darkskyapp/string-hash/blob/master/index.js

const regex_return_characters = /\r/g;

/**
 * @param {string} str
 * @returns {string}
 */
function hash(str) {
	str = str.replace(regex_return_characters, '');
	let hash = 5381;
	let i = str.length;

	while (i--) hash = ((hash << 5) - hash) ^ str.charCodeAt(i);
	return (hash >>> 0).toString(36);
}

const applicable = new Set(['Identifier', 'ObjectExpression', 'ArrayExpression', 'Property']);

/** @extends Node<'Let'> */
class Let extends Node {
	/** @type {import('estree').Identifier} */
	name;

	/** @type {import('estree').Identifier} */
	value;

	/** @type {string[]} */
	names = [];

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./shared/Node.js').default} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		this.name = { type: 'Identifier', name: info.name };
		const { names } = this;
		if (info.expression) {
			this.value = info.expression;
			walk(info.expression, {
				/** @param {import('estree').Identifier | import('estree').BasePattern} node */
				enter(node) {
					if (!applicable.has(node.type)) {
						return component.error(/** @type {any} */ (node), compiler_errors.invalid_let);
					}
					if (node.type === 'Identifier') {
						names.push(/** @type {import('estree').Identifier} */ (node).name);
					}
					// slightly unfortunate hack
					if (node.type === 'ArrayExpression') {
						node.type = 'ArrayPattern';
					}
					if (node.type === 'ObjectExpression') {
						node.type = 'ObjectPattern';
					}
				}
			});
		} else {
			names.push(this.name.name);
		}
	}
}

var lib$1 = {};

var ariaPropsMap$1 = {};

var iterationDecorator$3 = {};

var iteratorProxy$3 = {};

Object.defineProperty(iteratorProxy$3, "__esModule", {
  value: true
});
iteratorProxy$3.default = void 0;

// eslint-disable-next-line no-unused-vars
function iteratorProxy$2() {
  var values = this;
  var index = 0;
  var iter = {
    '@@iterator': function iterator() {
      return iter;
    },
    next: function next() {
      if (index < values.length) {
        var value = values[index];
        index = index + 1;
        return {
          done: false,
          value: value
        };
      } else {
        return {
          done: true
        };
      }
    }
  };
  return iter;
}
var _default$4j = iteratorProxy$2;
iteratorProxy$3.default = _default$4j;

Object.defineProperty(iterationDecorator$3, "__esModule", {
  value: true
});
iterationDecorator$3.default = iterationDecorator$2;
var _iteratorProxy$1 = _interopRequireDefault$g(iteratorProxy$3);
function _interopRequireDefault$g(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _typeof$1(obj) { "@babel/helpers - typeof"; return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof$1(obj); }
function iterationDecorator$2(collection, entries) {
  if (typeof Symbol === 'function' && _typeof$1(Symbol.iterator) === 'symbol') {
    Object.defineProperty(collection, Symbol.iterator, {
      value: _iteratorProxy$1.default.bind(entries)
    });
  }
  return collection;
}

Object.defineProperty(ariaPropsMap$1, "__esModule", {
  value: true
});
ariaPropsMap$1.default = void 0;
var _iterationDecorator$8 = _interopRequireDefault$f(iterationDecorator$3);
function _interopRequireDefault$f(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _slicedToArray$8(arr, i) { return _arrayWithHoles$8(arr) || _iterableToArrayLimit$8(arr, i) || _unsupportedIterableToArray$8(arr, i) || _nonIterableRest$8(); }
function _nonIterableRest$8() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit$8(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles$8(arr) { if (Array.isArray(arr)) return arr; }
function _createForOfIteratorHelper$8(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$8(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray$8(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$8(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$8(o, minLen); }
function _arrayLikeToArray$8(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
var properties$1 = [['aria-activedescendant', {
  'type': 'id'
}], ['aria-atomic', {
  'type': 'boolean'
}], ['aria-autocomplete', {
  'type': 'token',
  'values': ['inline', 'list', 'both', 'none']
}], ['aria-braillelabel', {
  'type': 'string'
}], ['aria-brailleroledescription', {
  'type': 'string'
}], ['aria-busy', {
  'type': 'boolean'
}], ['aria-checked', {
  'type': 'tristate'
}], ['aria-colcount', {
  type: 'integer'
}], ['aria-colindex', {
  type: 'integer'
}], ['aria-colspan', {
  type: 'integer'
}], ['aria-controls', {
  'type': 'idlist'
}], ['aria-current', {
  type: 'token',
  values: ['page', 'step', 'location', 'date', 'time', true, false]
}], ['aria-describedby', {
  'type': 'idlist'
}], ['aria-description', {
  'type': 'string'
}], ['aria-details', {
  'type': 'id'
}], ['aria-disabled', {
  'type': 'boolean'
}], ['aria-dropeffect', {
  'type': 'tokenlist',
  'values': ['copy', 'execute', 'link', 'move', 'none', 'popup']
}], ['aria-errormessage', {
  'type': 'id'
}], ['aria-expanded', {
  'type': 'boolean',
  'allowundefined': true
}], ['aria-flowto', {
  'type': 'idlist'
}], ['aria-grabbed', {
  'type': 'boolean',
  'allowundefined': true
}], ['aria-haspopup', {
  'type': 'token',
  'values': [false, true, 'menu', 'listbox', 'tree', 'grid', 'dialog']
}], ['aria-hidden', {
  'type': 'boolean',
  'allowundefined': true
}], ['aria-invalid', {
  'type': 'token',
  'values': ['grammar', false, 'spelling', true]
}], ['aria-keyshortcuts', {
  type: 'string'
}], ['aria-label', {
  'type': 'string'
}], ['aria-labelledby', {
  'type': 'idlist'
}], ['aria-level', {
  'type': 'integer'
}], ['aria-live', {
  'type': 'token',
  'values': ['assertive', 'off', 'polite']
}], ['aria-modal', {
  type: 'boolean'
}], ['aria-multiline', {
  'type': 'boolean'
}], ['aria-multiselectable', {
  'type': 'boolean'
}], ['aria-orientation', {
  'type': 'token',
  'values': ['vertical', 'undefined', 'horizontal']
}], ['aria-owns', {
  'type': 'idlist'
}], ['aria-placeholder', {
  type: 'string'
}], ['aria-posinset', {
  'type': 'integer'
}], ['aria-pressed', {
  'type': 'tristate'
}], ['aria-readonly', {
  'type': 'boolean'
}], ['aria-relevant', {
  'type': 'tokenlist',
  'values': ['additions', 'all', 'removals', 'text']
}], ['aria-required', {
  'type': 'boolean'
}], ['aria-roledescription', {
  type: 'string'
}], ['aria-rowcount', {
  type: 'integer'
}], ['aria-rowindex', {
  type: 'integer'
}], ['aria-rowspan', {
  type: 'integer'
}], ['aria-selected', {
  'type': 'boolean',
  'allowundefined': true
}], ['aria-setsize', {
  'type': 'integer'
}], ['aria-sort', {
  'type': 'token',
  'values': ['ascending', 'descending', 'none', 'other']
}], ['aria-valuemax', {
  'type': 'number'
}], ['aria-valuemin', {
  'type': 'number'
}], ['aria-valuenow', {
  'type': 'number'
}], ['aria-valuetext', {
  'type': 'string'
}]];
var ariaPropsMap = {
  entries: function entries() {
    return properties$1;
  },
  forEach: function forEach(fn) {
    var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
    var _iterator = _createForOfIteratorHelper$8(properties$1),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var _step$value = _slicedToArray$8(_step.value, 2),
          key = _step$value[0],
          values = _step$value[1];
        fn.call(thisArg, values, key, properties$1);
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
  },
  get: function get(key) {
    var item = properties$1.find(function (tuple) {
      return tuple[0] === key ? true : false;
    });
    return item && item[1];
  },
  has: function has(key) {
    return !!ariaPropsMap.get(key);
  },
  keys: function keys() {
    return properties$1.map(function (_ref) {
      var _ref2 = _slicedToArray$8(_ref, 1),
        key = _ref2[0];
      return key;
    });
  },
  values: function values() {
    return properties$1.map(function (_ref3) {
      var _ref4 = _slicedToArray$8(_ref3, 2),
        values = _ref4[1];
      return values;
    });
  }
};
var _default$4i = (0, _iterationDecorator$8.default)(ariaPropsMap, ariaPropsMap.entries());
ariaPropsMap$1.default = _default$4i;

var domMap$1 = {};

Object.defineProperty(domMap$1, "__esModule", {
  value: true
});
domMap$1.default = void 0;
var _iterationDecorator$7 = _interopRequireDefault$e(iterationDecorator$3);
function _interopRequireDefault$e(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _slicedToArray$7(arr, i) { return _arrayWithHoles$7(arr) || _iterableToArrayLimit$7(arr, i) || _unsupportedIterableToArray$7(arr, i) || _nonIterableRest$7(); }
function _nonIterableRest$7() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit$7(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles$7(arr) { if (Array.isArray(arr)) return arr; }
function _createForOfIteratorHelper$7(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$7(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray$7(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$7(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$7(o, minLen); }
function _arrayLikeToArray$7(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
var dom$2 = [['a', {
  reserved: false
}], ['abbr', {
  reserved: false
}], ['acronym', {
  reserved: false
}], ['address', {
  reserved: false
}], ['applet', {
  reserved: false
}], ['area', {
  reserved: false
}], ['article', {
  reserved: false
}], ['aside', {
  reserved: false
}], ['audio', {
  reserved: false
}], ['b', {
  reserved: false
}], ['base', {
  reserved: true
}], ['bdi', {
  reserved: false
}], ['bdo', {
  reserved: false
}], ['big', {
  reserved: false
}], ['blink', {
  reserved: false
}], ['blockquote', {
  reserved: false
}], ['body', {
  reserved: false
}], ['br', {
  reserved: false
}], ['button', {
  reserved: false
}], ['canvas', {
  reserved: false
}], ['caption', {
  reserved: false
}], ['center', {
  reserved: false
}], ['cite', {
  reserved: false
}], ['code', {
  reserved: false
}], ['col', {
  reserved: true
}], ['colgroup', {
  reserved: true
}], ['content', {
  reserved: false
}], ['data', {
  reserved: false
}], ['datalist', {
  reserved: false
}], ['dd', {
  reserved: false
}], ['del', {
  reserved: false
}], ['details', {
  reserved: false
}], ['dfn', {
  reserved: false
}], ['dialog', {
  reserved: false
}], ['dir', {
  reserved: false
}], ['div', {
  reserved: false
}], ['dl', {
  reserved: false
}], ['dt', {
  reserved: false
}], ['em', {
  reserved: false
}], ['embed', {
  reserved: false
}], ['fieldset', {
  reserved: false
}], ['figcaption', {
  reserved: false
}], ['figure', {
  reserved: false
}], ['font', {
  reserved: false
}], ['footer', {
  reserved: false
}], ['form', {
  reserved: false
}], ['frame', {
  reserved: false
}], ['frameset', {
  reserved: false
}], ['h1', {
  reserved: false
}], ['h2', {
  reserved: false
}], ['h3', {
  reserved: false
}], ['h4', {
  reserved: false
}], ['h5', {
  reserved: false
}], ['h6', {
  reserved: false
}], ['head', {
  reserved: true
}], ['header', {
  reserved: false
}], ['hgroup', {
  reserved: false
}], ['hr', {
  reserved: false
}], ['html', {
  reserved: true
}], ['i', {
  reserved: false
}], ['iframe', {
  reserved: false
}], ['img', {
  reserved: false
}], ['input', {
  reserved: false
}], ['ins', {
  reserved: false
}], ['kbd', {
  reserved: false
}], ['keygen', {
  reserved: false
}], ['label', {
  reserved: false
}], ['legend', {
  reserved: false
}], ['li', {
  reserved: false
}], ['link', {
  reserved: true
}], ['main', {
  reserved: false
}], ['map', {
  reserved: false
}], ['mark', {
  reserved: false
}], ['marquee', {
  reserved: false
}], ['menu', {
  reserved: false
}], ['menuitem', {
  reserved: false
}], ['meta', {
  reserved: true
}], ['meter', {
  reserved: false
}], ['nav', {
  reserved: false
}], ['noembed', {
  reserved: true
}], ['noscript', {
  reserved: true
}], ['object', {
  reserved: false
}], ['ol', {
  reserved: false
}], ['optgroup', {
  reserved: false
}], ['option', {
  reserved: false
}], ['output', {
  reserved: false
}], ['p', {
  reserved: false
}], ['param', {
  reserved: true
}], ['picture', {
  reserved: true
}], ['pre', {
  reserved: false
}], ['progress', {
  reserved: false
}], ['q', {
  reserved: false
}], ['rp', {
  reserved: false
}], ['rt', {
  reserved: false
}], ['rtc', {
  reserved: false
}], ['ruby', {
  reserved: false
}], ['s', {
  reserved: false
}], ['samp', {
  reserved: false
}], ['script', {
  reserved: true
}], ['section', {
  reserved: false
}], ['select', {
  reserved: false
}], ['small', {
  reserved: false
}], ['source', {
  reserved: true
}], ['spacer', {
  reserved: false
}], ['span', {
  reserved: false
}], ['strike', {
  reserved: false
}], ['strong', {
  reserved: false
}], ['style', {
  reserved: true
}], ['sub', {
  reserved: false
}], ['summary', {
  reserved: false
}], ['sup', {
  reserved: false
}], ['table', {
  reserved: false
}], ['tbody', {
  reserved: false
}], ['td', {
  reserved: false
}], ['textarea', {
  reserved: false
}], ['tfoot', {
  reserved: false
}], ['th', {
  reserved: false
}], ['thead', {
  reserved: false
}], ['time', {
  reserved: false
}], ['title', {
  reserved: true
}], ['tr', {
  reserved: false
}], ['track', {
  reserved: true
}], ['tt', {
  reserved: false
}], ['u', {
  reserved: false
}], ['ul', {
  reserved: false
}], ['var', {
  reserved: false
}], ['video', {
  reserved: false
}], ['wbr', {
  reserved: false
}], ['xmp', {
  reserved: false
}]];
var domMap = {
  entries: function entries() {
    return dom$2;
  },
  forEach: function forEach(fn) {
    var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
    var _iterator = _createForOfIteratorHelper$7(dom$2),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var _step$value = _slicedToArray$7(_step.value, 2),
          key = _step$value[0],
          values = _step$value[1];
        fn.call(thisArg, values, key, dom$2);
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
  },
  get: function get(key) {
    var item = dom$2.find(function (tuple) {
      return tuple[0] === key ? true : false;
    });
    return item && item[1];
  },
  has: function has(key) {
    return !!domMap.get(key);
  },
  keys: function keys() {
    return dom$2.map(function (_ref) {
      var _ref2 = _slicedToArray$7(_ref, 1),
        key = _ref2[0];
      return key;
    });
  },
  values: function values() {
    return dom$2.map(function (_ref3) {
      var _ref4 = _slicedToArray$7(_ref3, 2),
        values = _ref4[1];
      return values;
    });
  }
};
var _default$4h = (0, _iterationDecorator$7.default)(domMap, domMap.entries());
domMap$1.default = _default$4h;

var rolesMap$1 = {};

var ariaAbstractRoles$1 = {};

var commandRole$1 = {};

Object.defineProperty(commandRole$1, "__esModule", {
  value: true
});
commandRole$1.default = void 0;
var commandRole = {
  abstract: true,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'widget']]
};
var _default$4g = commandRole;
commandRole$1.default = _default$4g;

var compositeRole$1 = {};

Object.defineProperty(compositeRole$1, "__esModule", {
  value: true
});
compositeRole$1.default = void 0;
var compositeRole = {
  abstract: true,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-activedescendant': null,
    'aria-disabled': null
  },
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'widget']]
};
var _default$4f = compositeRole;
compositeRole$1.default = _default$4f;

var inputRole$1 = {};

Object.defineProperty(inputRole$1, "__esModule", {
  value: true
});
inputRole$1.default = void 0;
var inputRole = {
  abstract: true,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null
  },
  relatedConcepts: [{
    concept: {
      name: 'input'
    },
    module: 'XForms'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'widget']]
};
var _default$4e = inputRole;
inputRole$1.default = _default$4e;

var landmarkRole$1 = {};

Object.defineProperty(landmarkRole$1, "__esModule", {
  value: true
});
landmarkRole$1.default = void 0;
var landmarkRole = {
  abstract: true,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$4d = landmarkRole;
landmarkRole$1.default = _default$4d;

var rangeRole$1 = {};

Object.defineProperty(rangeRole$1, "__esModule", {
  value: true
});
rangeRole$1.default = void 0;
var rangeRole = {
  abstract: true,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-valuemax': null,
    'aria-valuemin': null,
    'aria-valuenow': null
  },
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure']]
};
var _default$4c = rangeRole;
rangeRole$1.default = _default$4c;

var roletypeRole$1 = {};

Object.defineProperty(roletypeRole$1, "__esModule", {
  value: true
});
roletypeRole$1.default = void 0;
var roletypeRole = {
  abstract: true,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: [],
  prohibitedProps: [],
  props: {
    'aria-atomic': null,
    'aria-busy': null,
    'aria-controls': null,
    'aria-current': null,
    'aria-describedby': null,
    'aria-details': null,
    'aria-dropeffect': null,
    'aria-flowto': null,
    'aria-grabbed': null,
    'aria-hidden': null,
    'aria-keyshortcuts': null,
    'aria-label': null,
    'aria-labelledby': null,
    'aria-live': null,
    'aria-owns': null,
    'aria-relevant': null,
    'aria-roledescription': null
  },
  relatedConcepts: [{
    concept: {
      name: 'role'
    },
    module: 'XHTML'
  }, {
    concept: {
      name: 'type'
    },
    module: 'Dublin Core'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: []
};
var _default$4b = roletypeRole;
roletypeRole$1.default = _default$4b;

var sectionRole$1 = {};

Object.defineProperty(sectionRole$1, "__esModule", {
  value: true
});
sectionRole$1.default = void 0;
var sectionRole = {
  abstract: true,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: [],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'frontmatter'
    },
    module: 'DTB'
  }, {
    concept: {
      name: 'level'
    },
    module: 'DTB'
  }, {
    concept: {
      name: 'level'
    },
    module: 'SMIL'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure']]
};
var _default$4a = sectionRole;
sectionRole$1.default = _default$4a;

var sectionheadRole$1 = {};

Object.defineProperty(sectionheadRole$1, "__esModule", {
  value: true
});
sectionheadRole$1.default = void 0;
var sectionheadRole = {
  abstract: true,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure']]
};
var _default$49 = sectionheadRole;
sectionheadRole$1.default = _default$49;

var selectRole$1 = {};

Object.defineProperty(selectRole$1, "__esModule", {
  value: true
});
selectRole$1.default = void 0;
var selectRole = {
  abstract: true,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-orientation': null
  },
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'widget', 'composite'], ['roletype', 'structure', 'section', 'group']]
};
var _default$48 = selectRole;
selectRole$1.default = _default$48;

var structureRole$1 = {};

Object.defineProperty(structureRole$1, "__esModule", {
  value: true
});
structureRole$1.default = void 0;
var structureRole = {
  abstract: true,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: [],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype']]
};
var _default$47 = structureRole;
structureRole$1.default = _default$47;

var widgetRole$1 = {};

Object.defineProperty(widgetRole$1, "__esModule", {
  value: true
});
widgetRole$1.default = void 0;
var widgetRole = {
  abstract: true,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: [],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype']]
};
var _default$46 = widgetRole;
widgetRole$1.default = _default$46;

var windowRole$1 = {};

Object.defineProperty(windowRole$1, "__esModule", {
  value: true
});
windowRole$1.default = void 0;
var windowRole = {
  abstract: true,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-modal': null
  },
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype']]
};
var _default$45 = windowRole;
windowRole$1.default = _default$45;

Object.defineProperty(ariaAbstractRoles$1, "__esModule", {
  value: true
});
ariaAbstractRoles$1.default = void 0;
var _commandRole = _interopRequireDefault$d(commandRole$1);
var _compositeRole = _interopRequireDefault$d(compositeRole$1);
var _inputRole = _interopRequireDefault$d(inputRole$1);
var _landmarkRole = _interopRequireDefault$d(landmarkRole$1);
var _rangeRole = _interopRequireDefault$d(rangeRole$1);
var _roletypeRole = _interopRequireDefault$d(roletypeRole$1);
var _sectionRole = _interopRequireDefault$d(sectionRole$1);
var _sectionheadRole = _interopRequireDefault$d(sectionheadRole$1);
var _selectRole = _interopRequireDefault$d(selectRole$1);
var _structureRole = _interopRequireDefault$d(structureRole$1);
var _widgetRole = _interopRequireDefault$d(widgetRole$1);
var _windowRole = _interopRequireDefault$d(windowRole$1);
function _interopRequireDefault$d(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var ariaAbstractRoles = [['command', _commandRole.default], ['composite', _compositeRole.default], ['input', _inputRole.default], ['landmark', _landmarkRole.default], ['range', _rangeRole.default], ['roletype', _roletypeRole.default], ['section', _sectionRole.default], ['sectionhead', _sectionheadRole.default], ['select', _selectRole.default], ['structure', _structureRole.default], ['widget', _widgetRole.default], ['window', _windowRole.default]];
var _default$44 = ariaAbstractRoles;
ariaAbstractRoles$1.default = _default$44;

var ariaLiteralRoles$1 = {};

var alertRole$1 = {};

Object.defineProperty(alertRole$1, "__esModule", {
  value: true
});
alertRole$1.default = void 0;
var alertRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-atomic': 'true',
    'aria-live': 'assertive'
  },
  relatedConcepts: [{
    concept: {
      name: 'alert'
    },
    module: 'XForms'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$43 = alertRole;
alertRole$1.default = _default$43;

var alertdialogRole$1 = {};

Object.defineProperty(alertdialogRole$1, "__esModule", {
  value: true
});
alertdialogRole$1.default = void 0;
var alertdialogRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'alert'
    },
    module: 'XForms'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'alert'], ['roletype', 'window', 'dialog']]
};
var _default$42 = alertdialogRole;
alertdialogRole$1.default = _default$42;

var applicationRole$1 = {};

Object.defineProperty(applicationRole$1, "__esModule", {
  value: true
});
applicationRole$1.default = void 0;
var applicationRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-activedescendant': null,
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'Device Independence Delivery Unit'
    }
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure']]
};
var _default$41 = applicationRole;
applicationRole$1.default = _default$41;

var articleRole$1 = {};

Object.defineProperty(articleRole$1, "__esModule", {
  value: true
});
articleRole$1.default = void 0;
var articleRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-posinset': null,
    'aria-setsize': null
  },
  relatedConcepts: [{
    concept: {
      name: 'article'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'document']]
};
var _default$40 = articleRole;
articleRole$1.default = _default$40;

var bannerRole$1 = {};

Object.defineProperty(bannerRole$1, "__esModule", {
  value: true
});
bannerRole$1.default = void 0;
var bannerRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      constraints: ['scoped to the body element'],
      name: 'header'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$3$ = bannerRole;
bannerRole$1.default = _default$3$;

var blockquoteRole$1 = {};

Object.defineProperty(blockquoteRole$1, "__esModule", {
  value: true
});
blockquoteRole$1.default = void 0;
var blockquoteRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'blockquote'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$3_ = blockquoteRole;
blockquoteRole$1.default = _default$3_;

var buttonRole$1 = {};

Object.defineProperty(buttonRole$1, "__esModule", {
  value: true
});
buttonRole$1.default = void 0;
var buttonRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: true,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-pressed': null
  },
  relatedConcepts: [{
    concept: {
      attributes: [{
        name: 'type',
        value: 'button'
      }],
      name: 'input'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        name: 'type',
        value: 'image'
      }],
      name: 'input'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        name: 'type',
        value: 'reset'
      }],
      name: 'input'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        name: 'type',
        value: 'submit'
      }],
      name: 'input'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'button'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'trigger'
    },
    module: 'XForms'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'widget', 'command']]
};
var _default$3Z = buttonRole;
buttonRole$1.default = _default$3Z;

var captionRole$1 = {};

Object.defineProperty(captionRole$1, "__esModule", {
  value: true
});
captionRole$1.default = void 0;
var captionRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['prohibited'],
  prohibitedProps: ['aria-label', 'aria-labelledby'],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'caption'
    },
    module: 'HTML'
  }],
  requireContextRole: ['figure', 'grid', 'table'],
  requiredContextRole: ['figure', 'grid', 'table'],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$3Y = captionRole;
captionRole$1.default = _default$3Y;

var cellRole$1 = {};

Object.defineProperty(cellRole$1, "__esModule", {
  value: true
});
cellRole$1.default = void 0;
var cellRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {
    'aria-colindex': null,
    'aria-colspan': null,
    'aria-rowindex': null,
    'aria-rowspan': null
  },
  relatedConcepts: [{
    concept: {
      constraints: ['ancestor table element has table role'],
      name: 'td'
    },
    module: 'HTML'
  }],
  requireContextRole: ['row'],
  requiredContextRole: ['row'],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$3X = cellRole;
cellRole$1.default = _default$3X;

var checkboxRole$1 = {};

Object.defineProperty(checkboxRole$1, "__esModule", {
  value: true
});
checkboxRole$1.default = void 0;
var checkboxRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: true,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {
    'aria-checked': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-invalid': null,
    'aria-readonly': null,
    'aria-required': null
  },
  relatedConcepts: [{
    concept: {
      attributes: [{
        name: 'type',
        value: 'checkbox'
      }],
      name: 'input'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'option'
    },
    module: 'ARIA'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {
    'aria-checked': null
  },
  superClass: [['roletype', 'widget', 'input']]
};
var _default$3W = checkboxRole;
checkboxRole$1.default = _default$3W;

var codeRole$1 = {};

Object.defineProperty(codeRole$1, "__esModule", {
  value: true
});
codeRole$1.default = void 0;
var codeRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['prohibited'],
  prohibitedProps: ['aria-label', 'aria-labelledby'],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'code'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$3V = codeRole;
codeRole$1.default = _default$3V;

var columnheaderRole$1 = {};

Object.defineProperty(columnheaderRole$1, "__esModule", {
  value: true
});
columnheaderRole$1.default = void 0;
var columnheaderRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {
    'aria-sort': null
  },
  relatedConcepts: [{
    concept: {
      name: 'th'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        name: 'scope',
        value: 'col'
      }],
      name: 'th'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        name: 'scope',
        value: 'colgroup'
      }],
      name: 'th'
    },
    module: 'HTML'
  }],
  requireContextRole: ['row'],
  requiredContextRole: ['row'],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'cell'], ['roletype', 'structure', 'section', 'cell', 'gridcell'], ['roletype', 'widget', 'gridcell'], ['roletype', 'structure', 'sectionhead']]
};
var _default$3U = columnheaderRole;
columnheaderRole$1.default = _default$3U;

var comboboxRole$1 = {};

Object.defineProperty(comboboxRole$1, "__esModule", {
  value: true
});
comboboxRole$1.default = void 0;
var comboboxRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-activedescendant': null,
    'aria-autocomplete': null,
    'aria-errormessage': null,
    'aria-invalid': null,
    'aria-readonly': null,
    'aria-required': null,
    'aria-expanded': 'false',
    'aria-haspopup': 'listbox'
  },
  relatedConcepts: [{
    concept: {
      attributes: [{
        constraints: ['set'],
        name: 'list'
      }, {
        name: 'type',
        value: 'email'
      }],
      name: 'input'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        constraints: ['set'],
        name: 'list'
      }, {
        name: 'type',
        value: 'search'
      }],
      name: 'input'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        constraints: ['set'],
        name: 'list'
      }, {
        name: 'type',
        value: 'tel'
      }],
      name: 'input'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        constraints: ['set'],
        name: 'list'
      }, {
        name: 'type',
        value: 'text'
      }],
      name: 'input'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        constraints: ['set'],
        name: 'list'
      }, {
        name: 'type',
        value: 'url'
      }],
      name: 'input'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        constraints: ['set'],
        name: 'list'
      }, {
        name: 'type',
        value: 'url'
      }],
      name: 'input'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        constraints: ['undefined'],
        name: 'multiple'
      }, {
        constraints: ['undefined'],
        name: 'size'
      }],
      constraints: ['the multiple attribute is not set and the size attribute does not have a value greater than 1'],
      name: 'select'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'select'
    },
    module: 'XForms'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {
    'aria-controls': null,
    'aria-expanded': 'false'
  },
  superClass: [['roletype', 'widget', 'input']]
};
var _default$3T = comboboxRole;
comboboxRole$1.default = _default$3T;

var complementaryRole$1 = {};

Object.defineProperty(complementaryRole$1, "__esModule", {
  value: true
});
complementaryRole$1.default = void 0;
var complementaryRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'aside'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        constraints: ['set'],
        name: 'aria-label'
      }],
      constraints: ['scoped to a sectioning content element', 'scoped to a sectioning root element other than body'],
      name: 'aside'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        constraints: ['set'],
        name: 'aria-labelledby'
      }],
      constraints: ['scoped to a sectioning content element', 'scoped to a sectioning root element other than body'],
      name: 'aside'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$3S = complementaryRole;
complementaryRole$1.default = _default$3S;

var contentinfoRole$1 = {};

Object.defineProperty(contentinfoRole$1, "__esModule", {
  value: true
});
contentinfoRole$1.default = void 0;
var contentinfoRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      constraints: ['scoped to the body element'],
      name: 'footer'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$3R = contentinfoRole;
contentinfoRole$1.default = _default$3R;

var definitionRole$1 = {};

Object.defineProperty(definitionRole$1, "__esModule", {
  value: true
});
definitionRole$1.default = void 0;
var definitionRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'dd'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$3Q = definitionRole;
definitionRole$1.default = _default$3Q;

var deletionRole$1 = {};

Object.defineProperty(deletionRole$1, "__esModule", {
  value: true
});
deletionRole$1.default = void 0;
var deletionRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['prohibited'],
  prohibitedProps: ['aria-label', 'aria-labelledby'],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'del'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$3P = deletionRole;
deletionRole$1.default = _default$3P;

var dialogRole$1 = {};

Object.defineProperty(dialogRole$1, "__esModule", {
  value: true
});
dialogRole$1.default = void 0;
var dialogRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'dialog'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'window']]
};
var _default$3O = dialogRole;
dialogRole$1.default = _default$3O;

var directoryRole$1 = {};

Object.defineProperty(directoryRole$1, "__esModule", {
  value: true
});
directoryRole$1.default = void 0;
var directoryRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    module: 'DAISY Guide'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'list']]
};
var _default$3N = directoryRole;
directoryRole$1.default = _default$3N;

var documentRole$1 = {};

Object.defineProperty(documentRole$1, "__esModule", {
  value: true
});
documentRole$1.default = void 0;
var documentRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'Device Independence Delivery Unit'
    }
  }, {
    concept: {
      name: 'html'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure']]
};
var _default$3M = documentRole;
documentRole$1.default = _default$3M;

var emphasisRole$1 = {};

Object.defineProperty(emphasisRole$1, "__esModule", {
  value: true
});
emphasisRole$1.default = void 0;
var emphasisRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['prohibited'],
  prohibitedProps: ['aria-label', 'aria-labelledby'],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'em'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$3L = emphasisRole;
emphasisRole$1.default = _default$3L;

var feedRole$1 = {};

Object.defineProperty(feedRole$1, "__esModule", {
  value: true
});
feedRole$1.default = void 0;
var feedRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [['article']],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'list']]
};
var _default$3K = feedRole;
feedRole$1.default = _default$3K;

var figureRole$1 = {};

Object.defineProperty(figureRole$1, "__esModule", {
  value: true
});
figureRole$1.default = void 0;
var figureRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'figure'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$3J = figureRole;
figureRole$1.default = _default$3J;

var formRole$1 = {};

Object.defineProperty(formRole$1, "__esModule", {
  value: true
});
formRole$1.default = void 0;
var formRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      attributes: [{
        constraints: ['set'],
        name: 'aria-label'
      }],
      name: 'form'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        constraints: ['set'],
        name: 'aria-labelledby'
      }],
      name: 'form'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        constraints: ['set'],
        name: 'name'
      }],
      name: 'form'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$3I = formRole;
formRole$1.default = _default$3I;

var genericRole$1 = {};

Object.defineProperty(genericRole$1, "__esModule", {
  value: true
});
genericRole$1.default = void 0;
var genericRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['prohibited'],
  prohibitedProps: ['aria-label', 'aria-labelledby'],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'a'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'area'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'aside'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'b'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'bdo'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'body'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'data'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'div'
    },
    module: 'HTML'
  }, {
    concept: {
      constraints: ['scoped to the main element', 'scoped to a sectioning content element', 'scoped to a sectioning root element other than body'],
      name: 'footer'
    },
    module: 'HTML'
  }, {
    concept: {
      constraints: ['scoped to the main element', 'scoped to a sectioning content element', 'scoped to a sectioning root element other than body'],
      name: 'header'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'hgroup'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'i'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'pre'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'q'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'samp'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'section'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'small'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'span'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'u'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure']]
};
var _default$3H = genericRole;
genericRole$1.default = _default$3H;

var gridRole$1 = {};

Object.defineProperty(gridRole$1, "__esModule", {
  value: true
});
gridRole$1.default = void 0;
var gridRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-multiselectable': null,
    'aria-readonly': null
  },
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [['row'], ['row', 'rowgroup']],
  requiredProps: {},
  superClass: [['roletype', 'widget', 'composite'], ['roletype', 'structure', 'section', 'table']]
};
var _default$3G = gridRole;
gridRole$1.default = _default$3G;

var gridcellRole$1 = {};

Object.defineProperty(gridcellRole$1, "__esModule", {
  value: true
});
gridcellRole$1.default = void 0;
var gridcellRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null,
    'aria-readonly': null,
    'aria-required': null,
    'aria-selected': null
  },
  relatedConcepts: [{
    concept: {
      constraints: ['ancestor table element has grid role', 'ancestor table element has treegrid role'],
      name: 'td'
    },
    module: 'HTML'
  }],
  requireContextRole: ['row'],
  requiredContextRole: ['row'],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'cell'], ['roletype', 'widget']]
};
var _default$3F = gridcellRole;
gridcellRole$1.default = _default$3F;

var groupRole$1 = {};

Object.defineProperty(groupRole$1, "__esModule", {
  value: true
});
groupRole$1.default = void 0;
var groupRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-activedescendant': null,
    'aria-disabled': null
  },
  relatedConcepts: [{
    concept: {
      name: 'details'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'fieldset'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'optgroup'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'address'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$3E = groupRole;
groupRole$1.default = _default$3E;

var headingRole$1 = {};

Object.defineProperty(headingRole$1, "__esModule", {
  value: true
});
headingRole$1.default = void 0;
var headingRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {
    'aria-level': '2'
  },
  relatedConcepts: [{
    concept: {
      name: 'h1'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'h2'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'h3'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'h4'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'h5'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'h6'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {
    'aria-level': '2'
  },
  superClass: [['roletype', 'structure', 'sectionhead']]
};
var _default$3D = headingRole;
headingRole$1.default = _default$3D;

var imgRole$1 = {};

Object.defineProperty(imgRole$1, "__esModule", {
  value: true
});
imgRole$1.default = void 0;
var imgRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: true,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      attributes: [{
        constraints: ['set'],
        name: 'alt'
      }],
      name: 'img'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        constraints: ['undefined'],
        name: 'alt'
      }],
      name: 'img'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'imggroup'
    },
    module: 'DTB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$3C = imgRole;
imgRole$1.default = _default$3C;

var insertionRole$1 = {};

Object.defineProperty(insertionRole$1, "__esModule", {
  value: true
});
insertionRole$1.default = void 0;
var insertionRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['prohibited'],
  prohibitedProps: ['aria-label', 'aria-labelledby'],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'ins'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$3B = insertionRole;
insertionRole$1.default = _default$3B;

var linkRole$1 = {};

Object.defineProperty(linkRole$1, "__esModule", {
  value: true
});
linkRole$1.default = void 0;
var linkRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-expanded': null,
    'aria-haspopup': null
  },
  relatedConcepts: [{
    concept: {
      attributes: [{
        constraints: ['set'],
        name: 'href'
      }],
      name: 'a'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        constraints: ['set'],
        name: 'href'
      }],
      name: 'area'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'widget', 'command']]
};
var _default$3A = linkRole;
linkRole$1.default = _default$3A;

var listRole$1 = {};

Object.defineProperty(listRole$1, "__esModule", {
  value: true
});
listRole$1.default = void 0;
var listRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'menu'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'ol'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'ul'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [['listitem']],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$3z = listRole;
listRole$1.default = _default$3z;

var listboxRole$1 = {};

Object.defineProperty(listboxRole$1, "__esModule", {
  value: true
});
listboxRole$1.default = void 0;
var listboxRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-invalid': null,
    'aria-multiselectable': null,
    'aria-readonly': null,
    'aria-required': null,
    'aria-orientation': 'vertical'
  },
  relatedConcepts: [{
    concept: {
      attributes: [{
        constraints: ['>1'],
        name: 'size'
      }],
      constraints: ['the size attribute value is greater than 1'],
      name: 'select'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        name: 'multiple'
      }],
      name: 'select'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'datalist'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'list'
    },
    module: 'ARIA'
  }, {
    concept: {
      name: 'select'
    },
    module: 'XForms'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [['option', 'group'], ['option']],
  requiredProps: {},
  superClass: [['roletype', 'widget', 'composite', 'select'], ['roletype', 'structure', 'section', 'group', 'select']]
};
var _default$3y = listboxRole;
listboxRole$1.default = _default$3y;

var listitemRole$1 = {};

Object.defineProperty(listitemRole$1, "__esModule", {
  value: true
});
listitemRole$1.default = void 0;
var listitemRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-level': null,
    'aria-posinset': null,
    'aria-setsize': null
  },
  relatedConcepts: [{
    concept: {
      constraints: ['direct descendant of ol', 'direct descendant of ul', 'direct descendant of menu'],
      name: 'li'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'item'
    },
    module: 'XForms'
  }],
  requireContextRole: ['directory', 'list'],
  requiredContextRole: ['directory', 'list'],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$3x = listitemRole;
listitemRole$1.default = _default$3x;

var logRole$1 = {};

Object.defineProperty(logRole$1, "__esModule", {
  value: true
});
logRole$1.default = void 0;
var logRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-live': 'polite'
  },
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$3w = logRole;
logRole$1.default = _default$3w;

var mainRole$1 = {};

Object.defineProperty(mainRole$1, "__esModule", {
  value: true
});
mainRole$1.default = void 0;
var mainRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'main'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$3v = mainRole;
mainRole$1.default = _default$3v;

var markRole$1 = {};

Object.defineProperty(markRole$1, "__esModule", {
  value: true
});
markRole$1.default = void 0;
var markRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['prohibited'],
  prohibitedProps: [],
  props: {
    'aria-braillelabel': null,
    'aria-brailleroledescription': null,
    'aria-description': null
  },
  relatedConcepts: [{
    concept: {
      name: 'mark'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$3u = markRole;
markRole$1.default = _default$3u;

var marqueeRole$1 = {};

Object.defineProperty(marqueeRole$1, "__esModule", {
  value: true
});
marqueeRole$1.default = void 0;
var marqueeRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$3t = marqueeRole;
marqueeRole$1.default = _default$3t;

var mathRole$1 = {};

Object.defineProperty(mathRole$1, "__esModule", {
  value: true
});
mathRole$1.default = void 0;
var mathRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'math'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$3s = mathRole;
mathRole$1.default = _default$3s;

var menuRole$1 = {};

Object.defineProperty(menuRole$1, "__esModule", {
  value: true
});
menuRole$1.default = void 0;
var menuRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-orientation': 'vertical'
  },
  relatedConcepts: [{
    concept: {
      name: 'MENU'
    },
    module: 'JAPI'
  }, {
    concept: {
      name: 'list'
    },
    module: 'ARIA'
  }, {
    concept: {
      name: 'select'
    },
    module: 'XForms'
  }, {
    concept: {
      name: 'sidebar'
    },
    module: 'DTB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [['menuitem', 'group'], ['menuitemradio', 'group'], ['menuitemcheckbox', 'group'], ['menuitem'], ['menuitemcheckbox'], ['menuitemradio']],
  requiredProps: {},
  superClass: [['roletype', 'widget', 'composite', 'select'], ['roletype', 'structure', 'section', 'group', 'select']]
};
var _default$3r = menuRole;
menuRole$1.default = _default$3r;

var menubarRole$1 = {};

Object.defineProperty(menubarRole$1, "__esModule", {
  value: true
});
menubarRole$1.default = void 0;
var menubarRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-orientation': 'horizontal'
  },
  relatedConcepts: [{
    concept: {
      name: 'toolbar'
    },
    module: 'ARIA'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [['menuitem', 'group'], ['menuitemradio', 'group'], ['menuitemcheckbox', 'group'], ['menuitem'], ['menuitemcheckbox'], ['menuitemradio']],
  requiredProps: {},
  superClass: [['roletype', 'widget', 'composite', 'select', 'menu'], ['roletype', 'structure', 'section', 'group', 'select', 'menu']]
};
var _default$3q = menubarRole;
menubarRole$1.default = _default$3q;

var menuitemRole$1 = {};

Object.defineProperty(menuitemRole$1, "__esModule", {
  value: true
});
menuitemRole$1.default = void 0;
var menuitemRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-posinset': null,
    'aria-setsize': null
  },
  relatedConcepts: [{
    concept: {
      name: 'MENU_ITEM'
    },
    module: 'JAPI'
  }, {
    concept: {
      name: 'listitem'
    },
    module: 'ARIA'
  }, {
    concept: {
      name: 'option'
    },
    module: 'ARIA'
  }],
  requireContextRole: ['group', 'menu', 'menubar'],
  requiredContextRole: ['group', 'menu', 'menubar'],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'widget', 'command']]
};
var _default$3p = menuitemRole;
menuitemRole$1.default = _default$3p;

var menuitemcheckboxRole$1 = {};

Object.defineProperty(menuitemcheckboxRole$1, "__esModule", {
  value: true
});
menuitemcheckboxRole$1.default = void 0;
var menuitemcheckboxRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: true,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'menuitem'
    },
    module: 'ARIA'
  }],
  requireContextRole: ['group', 'menu', 'menubar'],
  requiredContextRole: ['group', 'menu', 'menubar'],
  requiredOwnedElements: [],
  requiredProps: {
    'aria-checked': null
  },
  superClass: [['roletype', 'widget', 'input', 'checkbox'], ['roletype', 'widget', 'command', 'menuitem']]
};
var _default$3o = menuitemcheckboxRole;
menuitemcheckboxRole$1.default = _default$3o;

var menuitemradioRole$1 = {};

Object.defineProperty(menuitemradioRole$1, "__esModule", {
  value: true
});
menuitemradioRole$1.default = void 0;
var menuitemradioRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: true,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'menuitem'
    },
    module: 'ARIA'
  }],
  requireContextRole: ['group', 'menu', 'menubar'],
  requiredContextRole: ['group', 'menu', 'menubar'],
  requiredOwnedElements: [],
  requiredProps: {
    'aria-checked': null
  },
  superClass: [['roletype', 'widget', 'input', 'checkbox', 'menuitemcheckbox'], ['roletype', 'widget', 'command', 'menuitem', 'menuitemcheckbox'], ['roletype', 'widget', 'input', 'radio']]
};
var _default$3n = menuitemradioRole;
menuitemradioRole$1.default = _default$3n;

var meterRole$1 = {};

Object.defineProperty(meterRole$1, "__esModule", {
  value: true
});
meterRole$1.default = void 0;
var meterRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: true,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-valuetext': null,
    'aria-valuemax': '100',
    'aria-valuemin': '0'
  },
  relatedConcepts: [{
    concept: {
      name: 'meter'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {
    'aria-valuenow': null
  },
  superClass: [['roletype', 'structure', 'range']]
};
var _default$3m = meterRole;
meterRole$1.default = _default$3m;

var navigationRole$1 = {};

Object.defineProperty(navigationRole$1, "__esModule", {
  value: true
});
navigationRole$1.default = void 0;
var navigationRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'nav'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$3l = navigationRole;
navigationRole$1.default = _default$3l;

var noneRole$1 = {};

Object.defineProperty(noneRole$1, "__esModule", {
  value: true
});
noneRole$1.default = void 0;
var noneRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: [],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: []
};
var _default$3k = noneRole;
noneRole$1.default = _default$3k;

var noteRole$1 = {};

Object.defineProperty(noteRole$1, "__esModule", {
  value: true
});
noteRole$1.default = void 0;
var noteRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$3j = noteRole;
noteRole$1.default = _default$3j;

var optionRole$1 = {};

Object.defineProperty(optionRole$1, "__esModule", {
  value: true
});
optionRole$1.default = void 0;
var optionRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: true,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {
    'aria-checked': null,
    'aria-posinset': null,
    'aria-setsize': null,
    'aria-selected': 'false'
  },
  relatedConcepts: [{
    concept: {
      name: 'item'
    },
    module: 'XForms'
  }, {
    concept: {
      name: 'listitem'
    },
    module: 'ARIA'
  }, {
    concept: {
      name: 'option'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {
    'aria-selected': 'false'
  },
  superClass: [['roletype', 'widget', 'input']]
};
var _default$3i = optionRole;
optionRole$1.default = _default$3i;

var paragraphRole$1 = {};

Object.defineProperty(paragraphRole$1, "__esModule", {
  value: true
});
paragraphRole$1.default = void 0;
var paragraphRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['prohibited'],
  prohibitedProps: ['aria-label', 'aria-labelledby'],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'p'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$3h = paragraphRole;
paragraphRole$1.default = _default$3h;

var presentationRole$1 = {};

Object.defineProperty(presentationRole$1, "__esModule", {
  value: true
});
presentationRole$1.default = void 0;
var presentationRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['prohibited'],
  prohibitedProps: ['aria-label', 'aria-labelledby'],
  props: {},
  relatedConcepts: [{
    concept: {
      attributes: [{
        name: 'alt',
        value: ''
      }],
      name: 'img'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure']]
};
var _default$3g = presentationRole;
presentationRole$1.default = _default$3g;

var progressbarRole$1 = {};

Object.defineProperty(progressbarRole$1, "__esModule", {
  value: true
});
progressbarRole$1.default = void 0;
var progressbarRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: true,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-valuetext': null
  },
  relatedConcepts: [{
    concept: {
      name: 'progress'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'status'
    },
    module: 'ARIA'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'range'], ['roletype', 'widget']]
};
var _default$3f = progressbarRole;
progressbarRole$1.default = _default$3f;

var radioRole$1 = {};

Object.defineProperty(radioRole$1, "__esModule", {
  value: true
});
radioRole$1.default = void 0;
var radioRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: true,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {
    'aria-checked': null,
    'aria-posinset': null,
    'aria-setsize': null
  },
  relatedConcepts: [{
    concept: {
      attributes: [{
        name: 'type',
        value: 'radio'
      }],
      name: 'input'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {
    'aria-checked': null
  },
  superClass: [['roletype', 'widget', 'input']]
};
var _default$3e = radioRole;
radioRole$1.default = _default$3e;

var radiogroupRole$1 = {};

Object.defineProperty(radiogroupRole$1, "__esModule", {
  value: true
});
radiogroupRole$1.default = void 0;
var radiogroupRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-errormessage': null,
    'aria-invalid': null,
    'aria-readonly': null,
    'aria-required': null
  },
  relatedConcepts: [{
    concept: {
      name: 'list'
    },
    module: 'ARIA'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [['radio']],
  requiredProps: {},
  superClass: [['roletype', 'widget', 'composite', 'select'], ['roletype', 'structure', 'section', 'group', 'select']]
};
var _default$3d = radiogroupRole;
radiogroupRole$1.default = _default$3d;

var regionRole$1 = {};

Object.defineProperty(regionRole$1, "__esModule", {
  value: true
});
regionRole$1.default = void 0;
var regionRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      attributes: [{
        constraints: ['set'],
        name: 'aria-label'
      }],
      name: 'section'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        constraints: ['set'],
        name: 'aria-labelledby'
      }],
      name: 'section'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'Device Independence Glossart perceivable unit'
    }
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$3c = regionRole;
regionRole$1.default = _default$3c;

var rowRole$1 = {};

Object.defineProperty(rowRole$1, "__esModule", {
  value: true
});
rowRole$1.default = void 0;
var rowRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {
    'aria-colindex': null,
    'aria-expanded': null,
    'aria-level': null,
    'aria-posinset': null,
    'aria-rowindex': null,
    'aria-selected': null,
    'aria-setsize': null
  },
  relatedConcepts: [{
    concept: {
      name: 'tr'
    },
    module: 'HTML'
  }],
  requireContextRole: ['grid', 'rowgroup', 'table', 'treegrid'],
  requiredContextRole: ['grid', 'rowgroup', 'table', 'treegrid'],
  requiredOwnedElements: [['cell'], ['columnheader'], ['gridcell'], ['rowheader']],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'group'], ['roletype', 'widget']]
};
var _default$3b = rowRole;
rowRole$1.default = _default$3b;

var rowgroupRole$1 = {};

Object.defineProperty(rowgroupRole$1, "__esModule", {
  value: true
});
rowgroupRole$1.default = void 0;
var rowgroupRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'tbody'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'tfoot'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'thead'
    },
    module: 'HTML'
  }],
  requireContextRole: ['grid', 'table', 'treegrid'],
  requiredContextRole: ['grid', 'table', 'treegrid'],
  requiredOwnedElements: [['row']],
  requiredProps: {},
  superClass: [['roletype', 'structure']]
};
var _default$3a = rowgroupRole;
rowgroupRole$1.default = _default$3a;

var rowheaderRole$1 = {};

Object.defineProperty(rowheaderRole$1, "__esModule", {
  value: true
});
rowheaderRole$1.default = void 0;
var rowheaderRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {
    'aria-sort': null
  },
  relatedConcepts: [{
    concept: {
      attributes: [{
        name: 'scope',
        value: 'row'
      }],
      name: 'th'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        name: 'scope',
        value: 'rowgroup'
      }],
      name: 'th'
    },
    module: 'HTML'
  }],
  requireContextRole: ['row', 'rowgroup'],
  requiredContextRole: ['row', 'rowgroup'],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'cell'], ['roletype', 'structure', 'section', 'cell', 'gridcell'], ['roletype', 'widget', 'gridcell'], ['roletype', 'structure', 'sectionhead']]
};
var _default$39 = rowheaderRole;
rowheaderRole$1.default = _default$39;

var scrollbarRole$1 = {};

Object.defineProperty(scrollbarRole$1, "__esModule", {
  value: true
});
scrollbarRole$1.default = void 0;
var scrollbarRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: true,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-valuetext': null,
    'aria-orientation': 'vertical',
    'aria-valuemax': '100',
    'aria-valuemin': '0'
  },
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {
    'aria-controls': null,
    'aria-valuenow': null
  },
  superClass: [['roletype', 'structure', 'range'], ['roletype', 'widget']]
};
var _default$38 = scrollbarRole;
scrollbarRole$1.default = _default$38;

var searchRole$1 = {};

Object.defineProperty(searchRole$1, "__esModule", {
  value: true
});
searchRole$1.default = void 0;
var searchRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$37 = searchRole;
searchRole$1.default = _default$37;

var searchboxRole$1 = {};

Object.defineProperty(searchboxRole$1, "__esModule", {
  value: true
});
searchboxRole$1.default = void 0;
var searchboxRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      attributes: [{
        constraints: ['undefined'],
        name: 'list'
      }, {
        name: 'type',
        value: 'search'
      }],
      constraints: ['the list attribute is not set'],
      name: 'input'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'widget', 'input', 'textbox']]
};
var _default$36 = searchboxRole;
searchboxRole$1.default = _default$36;

var separatorRole$1 = {};

Object.defineProperty(separatorRole$1, "__esModule", {
  value: true
});
separatorRole$1.default = void 0;
var separatorRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: true,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-orientation': 'horizontal',
    'aria-valuemax': '100',
    'aria-valuemin': '0',
    'aria-valuenow': null,
    'aria-valuetext': null
  },
  relatedConcepts: [{
    concept: {
      name: 'hr'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure']]
};
var _default$35 = separatorRole;
separatorRole$1.default = _default$35;

var sliderRole$1 = {};

Object.defineProperty(sliderRole$1, "__esModule", {
  value: true
});
sliderRole$1.default = void 0;
var sliderRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: true,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-errormessage': null,
    'aria-haspopup': null,
    'aria-invalid': null,
    'aria-readonly': null,
    'aria-valuetext': null,
    'aria-orientation': 'horizontal',
    'aria-valuemax': '100',
    'aria-valuemin': '0'
  },
  relatedConcepts: [{
    concept: {
      attributes: [{
        name: 'type',
        value: 'range'
      }],
      name: 'input'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {
    'aria-valuenow': null
  },
  superClass: [['roletype', 'widget', 'input'], ['roletype', 'structure', 'range']]
};
var _default$34 = sliderRole;
sliderRole$1.default = _default$34;

var spinbuttonRole$1 = {};

Object.defineProperty(spinbuttonRole$1, "__esModule", {
  value: true
});
spinbuttonRole$1.default = void 0;
var spinbuttonRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-errormessage': null,
    'aria-invalid': null,
    'aria-readonly': null,
    'aria-required': null,
    'aria-valuetext': null,
    'aria-valuenow': '0'
  },
  relatedConcepts: [{
    concept: {
      attributes: [{
        name: 'type',
        value: 'number'
      }],
      name: 'input'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'widget', 'composite'], ['roletype', 'widget', 'input'], ['roletype', 'structure', 'range']]
};
var _default$33 = spinbuttonRole;
spinbuttonRole$1.default = _default$33;

var statusRole$1 = {};

Object.defineProperty(statusRole$1, "__esModule", {
  value: true
});
statusRole$1.default = void 0;
var statusRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-atomic': 'true',
    'aria-live': 'polite'
  },
  relatedConcepts: [{
    concept: {
      name: 'output'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$32 = statusRole;
statusRole$1.default = _default$32;

var strongRole$1 = {};

Object.defineProperty(strongRole$1, "__esModule", {
  value: true
});
strongRole$1.default = void 0;
var strongRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['prohibited'],
  prohibitedProps: ['aria-label', 'aria-labelledby'],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'strong'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$31 = strongRole;
strongRole$1.default = _default$31;

var subscriptRole$1 = {};

Object.defineProperty(subscriptRole$1, "__esModule", {
  value: true
});
subscriptRole$1.default = void 0;
var subscriptRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['prohibited'],
  prohibitedProps: ['aria-label', 'aria-labelledby'],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'sub'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$30 = subscriptRole;
subscriptRole$1.default = _default$30;

var superscriptRole$1 = {};

Object.defineProperty(superscriptRole$1, "__esModule", {
  value: true
});
superscriptRole$1.default = void 0;
var superscriptRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['prohibited'],
  prohibitedProps: ['aria-label', 'aria-labelledby'],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'sup'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$2$ = superscriptRole;
superscriptRole$1.default = _default$2$;

var switchRole$1 = {};

Object.defineProperty(switchRole$1, "__esModule", {
  value: true
});
switchRole$1.default = void 0;
var switchRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: true,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'button'
    },
    module: 'ARIA'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {
    'aria-checked': null
  },
  superClass: [['roletype', 'widget', 'input', 'checkbox']]
};
var _default$2_ = switchRole;
switchRole$1.default = _default$2_;

var tabRole$1 = {};

Object.defineProperty(tabRole$1, "__esModule", {
  value: true
});
tabRole$1.default = void 0;
var tabRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: true,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-posinset': null,
    'aria-setsize': null,
    'aria-selected': 'false'
  },
  relatedConcepts: [],
  requireContextRole: ['tablist'],
  requiredContextRole: ['tablist'],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'sectionhead'], ['roletype', 'widget']]
};
var _default$2Z = tabRole;
tabRole$1.default = _default$2Z;

var tableRole$1 = {};

Object.defineProperty(tableRole$1, "__esModule", {
  value: true
});
tableRole$1.default = void 0;
var tableRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-colcount': null,
    'aria-rowcount': null
  },
  relatedConcepts: [{
    concept: {
      name: 'table'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [['row'], ['row', 'rowgroup']],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$2Y = tableRole;
tableRole$1.default = _default$2Y;

var tablistRole$1 = {};

Object.defineProperty(tablistRole$1, "__esModule", {
  value: true
});
tablistRole$1.default = void 0;
var tablistRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-level': null,
    'aria-multiselectable': null,
    'aria-orientation': 'horizontal'
  },
  relatedConcepts: [{
    module: 'DAISY',
    concept: {
      name: 'guide'
    }
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [['tab']],
  requiredProps: {},
  superClass: [['roletype', 'widget', 'composite']]
};
var _default$2X = tablistRole;
tablistRole$1.default = _default$2X;

var tabpanelRole$1 = {};

Object.defineProperty(tabpanelRole$1, "__esModule", {
  value: true
});
tabpanelRole$1.default = void 0;
var tabpanelRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$2W = tabpanelRole;
tabpanelRole$1.default = _default$2W;

var termRole$1 = {};

Object.defineProperty(termRole$1, "__esModule", {
  value: true
});
termRole$1.default = void 0;
var termRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'dfn'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'dt'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$2V = termRole;
termRole$1.default = _default$2V;

var textboxRole$1 = {};

Object.defineProperty(textboxRole$1, "__esModule", {
  value: true
});
textboxRole$1.default = void 0;
var textboxRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-activedescendant': null,
    'aria-autocomplete': null,
    'aria-errormessage': null,
    'aria-haspopup': null,
    'aria-invalid': null,
    'aria-multiline': null,
    'aria-placeholder': null,
    'aria-readonly': null,
    'aria-required': null
  },
  relatedConcepts: [{
    concept: {
      attributes: [{
        constraints: ['undefined'],
        name: 'type'
      }, {
        constraints: ['undefined'],
        name: 'list'
      }],
      constraints: ['the list attribute is not set'],
      name: 'input'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        constraints: ['undefined'],
        name: 'list'
      }, {
        name: 'type',
        value: 'email'
      }],
      constraints: ['the list attribute is not set'],
      name: 'input'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        constraints: ['undefined'],
        name: 'list'
      }, {
        name: 'type',
        value: 'tel'
      }],
      constraints: ['the list attribute is not set'],
      name: 'input'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        constraints: ['undefined'],
        name: 'list'
      }, {
        name: 'type',
        value: 'text'
      }],
      constraints: ['the list attribute is not set'],
      name: 'input'
    },
    module: 'HTML'
  }, {
    concept: {
      attributes: [{
        constraints: ['undefined'],
        name: 'list'
      }, {
        name: 'type',
        value: 'url'
      }],
      constraints: ['the list attribute is not set'],
      name: 'input'
    },
    module: 'HTML'
  }, {
    concept: {
      name: 'input'
    },
    module: 'XForms'
  }, {
    concept: {
      name: 'textarea'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'widget', 'input']]
};
var _default$2U = textboxRole;
textboxRole$1.default = _default$2U;

var timeRole$1 = {};

Object.defineProperty(timeRole$1, "__esModule", {
  value: true
});
timeRole$1.default = void 0;
var timeRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'time'
    },
    module: 'HTML'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$2T = timeRole;
timeRole$1.default = _default$2T;

var timerRole$1 = {};

Object.defineProperty(timerRole$1, "__esModule", {
  value: true
});
timerRole$1.default = void 0;
var timerRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'status']]
};
var _default$2S = timerRole;
timerRole$1.default = _default$2S;

var toolbarRole$1 = {};

Object.defineProperty(toolbarRole$1, "__esModule", {
  value: true
});
toolbarRole$1.default = void 0;
var toolbarRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-orientation': 'horizontal'
  },
  relatedConcepts: [{
    concept: {
      name: 'menubar'
    },
    module: 'ARIA'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'group']]
};
var _default$2R = toolbarRole;
toolbarRole$1.default = _default$2R;

var tooltipRole$1 = {};

Object.defineProperty(tooltipRole$1, "__esModule", {
  value: true
});
tooltipRole$1.default = void 0;
var tooltipRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$2Q = tooltipRole;
tooltipRole$1.default = _default$2Q;

var treeRole$1 = {};

Object.defineProperty(treeRole$1, "__esModule", {
  value: true
});
treeRole$1.default = void 0;
var treeRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-errormessage': null,
    'aria-invalid': null,
    'aria-multiselectable': null,
    'aria-required': null,
    'aria-orientation': 'vertical'
  },
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [['treeitem', 'group'], ['treeitem']],
  requiredProps: {},
  superClass: [['roletype', 'widget', 'composite', 'select'], ['roletype', 'structure', 'section', 'group', 'select']]
};
var _default$2P = treeRole;
treeRole$1.default = _default$2P;

var treegridRole$1 = {};

Object.defineProperty(treegridRole$1, "__esModule", {
  value: true
});
treegridRole$1.default = void 0;
var treegridRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [['row'], ['row', 'rowgroup']],
  requiredProps: {},
  superClass: [['roletype', 'widget', 'composite', 'grid'], ['roletype', 'structure', 'section', 'table', 'grid'], ['roletype', 'widget', 'composite', 'select', 'tree'], ['roletype', 'structure', 'section', 'group', 'select', 'tree']]
};
var _default$2O = treegridRole;
treegridRole$1.default = _default$2O;

var treeitemRole$1 = {};

Object.defineProperty(treeitemRole$1, "__esModule", {
  value: true
});
treeitemRole$1.default = void 0;
var treeitemRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {
    'aria-expanded': null,
    'aria-haspopup': null
  },
  relatedConcepts: [],
  requireContextRole: ['group', 'tree'],
  requiredContextRole: ['group', 'tree'],
  requiredOwnedElements: [],
  requiredProps: {
    'aria-selected': null
  },
  superClass: [['roletype', 'structure', 'section', 'listitem'], ['roletype', 'widget', 'input', 'option']]
};
var _default$2N = treeitemRole;
treeitemRole$1.default = _default$2N;

Object.defineProperty(ariaLiteralRoles$1, "__esModule", {
  value: true
});
ariaLiteralRoles$1.default = void 0;
var _alertRole = _interopRequireDefault$c(alertRole$1);
var _alertdialogRole = _interopRequireDefault$c(alertdialogRole$1);
var _applicationRole = _interopRequireDefault$c(applicationRole$1);
var _articleRole = _interopRequireDefault$c(articleRole$1);
var _bannerRole = _interopRequireDefault$c(bannerRole$1);
var _blockquoteRole = _interopRequireDefault$c(blockquoteRole$1);
var _buttonRole = _interopRequireDefault$c(buttonRole$1);
var _captionRole = _interopRequireDefault$c(captionRole$1);
var _cellRole = _interopRequireDefault$c(cellRole$1);
var _checkboxRole = _interopRequireDefault$c(checkboxRole$1);
var _codeRole = _interopRequireDefault$c(codeRole$1);
var _columnheaderRole = _interopRequireDefault$c(columnheaderRole$1);
var _comboboxRole = _interopRequireDefault$c(comboboxRole$1);
var _complementaryRole = _interopRequireDefault$c(complementaryRole$1);
var _contentinfoRole = _interopRequireDefault$c(contentinfoRole$1);
var _definitionRole = _interopRequireDefault$c(definitionRole$1);
var _deletionRole = _interopRequireDefault$c(deletionRole$1);
var _dialogRole = _interopRequireDefault$c(dialogRole$1);
var _directoryRole = _interopRequireDefault$c(directoryRole$1);
var _documentRole = _interopRequireDefault$c(documentRole$1);
var _emphasisRole = _interopRequireDefault$c(emphasisRole$1);
var _feedRole = _interopRequireDefault$c(feedRole$1);
var _figureRole = _interopRequireDefault$c(figureRole$1);
var _formRole = _interopRequireDefault$c(formRole$1);
var _genericRole = _interopRequireDefault$c(genericRole$1);
var _gridRole = _interopRequireDefault$c(gridRole$1);
var _gridcellRole = _interopRequireDefault$c(gridcellRole$1);
var _groupRole = _interopRequireDefault$c(groupRole$1);
var _headingRole = _interopRequireDefault$c(headingRole$1);
var _imgRole = _interopRequireDefault$c(imgRole$1);
var _insertionRole = _interopRequireDefault$c(insertionRole$1);
var _linkRole = _interopRequireDefault$c(linkRole$1);
var _listRole = _interopRequireDefault$c(listRole$1);
var _listboxRole = _interopRequireDefault$c(listboxRole$1);
var _listitemRole = _interopRequireDefault$c(listitemRole$1);
var _logRole = _interopRequireDefault$c(logRole$1);
var _mainRole = _interopRequireDefault$c(mainRole$1);
var _markRole = _interopRequireDefault$c(markRole$1);
var _marqueeRole = _interopRequireDefault$c(marqueeRole$1);
var _mathRole = _interopRequireDefault$c(mathRole$1);
var _menuRole = _interopRequireDefault$c(menuRole$1);
var _menubarRole = _interopRequireDefault$c(menubarRole$1);
var _menuitemRole = _interopRequireDefault$c(menuitemRole$1);
var _menuitemcheckboxRole = _interopRequireDefault$c(menuitemcheckboxRole$1);
var _menuitemradioRole = _interopRequireDefault$c(menuitemradioRole$1);
var _meterRole = _interopRequireDefault$c(meterRole$1);
var _navigationRole = _interopRequireDefault$c(navigationRole$1);
var _noneRole = _interopRequireDefault$c(noneRole$1);
var _noteRole = _interopRequireDefault$c(noteRole$1);
var _optionRole = _interopRequireDefault$c(optionRole$1);
var _paragraphRole = _interopRequireDefault$c(paragraphRole$1);
var _presentationRole = _interopRequireDefault$c(presentationRole$1);
var _progressbarRole = _interopRequireDefault$c(progressbarRole$1);
var _radioRole = _interopRequireDefault$c(radioRole$1);
var _radiogroupRole = _interopRequireDefault$c(radiogroupRole$1);
var _regionRole = _interopRequireDefault$c(regionRole$1);
var _rowRole = _interopRequireDefault$c(rowRole$1);
var _rowgroupRole = _interopRequireDefault$c(rowgroupRole$1);
var _rowheaderRole = _interopRequireDefault$c(rowheaderRole$1);
var _scrollbarRole = _interopRequireDefault$c(scrollbarRole$1);
var _searchRole = _interopRequireDefault$c(searchRole$1);
var _searchboxRole = _interopRequireDefault$c(searchboxRole$1);
var _separatorRole = _interopRequireDefault$c(separatorRole$1);
var _sliderRole = _interopRequireDefault$c(sliderRole$1);
var _spinbuttonRole = _interopRequireDefault$c(spinbuttonRole$1);
var _statusRole = _interopRequireDefault$c(statusRole$1);
var _strongRole = _interopRequireDefault$c(strongRole$1);
var _subscriptRole = _interopRequireDefault$c(subscriptRole$1);
var _superscriptRole = _interopRequireDefault$c(superscriptRole$1);
var _switchRole = _interopRequireDefault$c(switchRole$1);
var _tabRole = _interopRequireDefault$c(tabRole$1);
var _tableRole = _interopRequireDefault$c(tableRole$1);
var _tablistRole = _interopRequireDefault$c(tablistRole$1);
var _tabpanelRole = _interopRequireDefault$c(tabpanelRole$1);
var _termRole = _interopRequireDefault$c(termRole$1);
var _textboxRole = _interopRequireDefault$c(textboxRole$1);
var _timeRole = _interopRequireDefault$c(timeRole$1);
var _timerRole = _interopRequireDefault$c(timerRole$1);
var _toolbarRole = _interopRequireDefault$c(toolbarRole$1);
var _tooltipRole = _interopRequireDefault$c(tooltipRole$1);
var _treeRole = _interopRequireDefault$c(treeRole$1);
var _treegridRole = _interopRequireDefault$c(treegridRole$1);
var _treeitemRole = _interopRequireDefault$c(treeitemRole$1);
function _interopRequireDefault$c(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var ariaLiteralRoles = [['alert', _alertRole.default], ['alertdialog', _alertdialogRole.default], ['application', _applicationRole.default], ['article', _articleRole.default], ['banner', _bannerRole.default], ['blockquote', _blockquoteRole.default], ['button', _buttonRole.default], ['caption', _captionRole.default], ['cell', _cellRole.default], ['checkbox', _checkboxRole.default], ['code', _codeRole.default], ['columnheader', _columnheaderRole.default], ['combobox', _comboboxRole.default], ['complementary', _complementaryRole.default], ['contentinfo', _contentinfoRole.default], ['definition', _definitionRole.default], ['deletion', _deletionRole.default], ['dialog', _dialogRole.default], ['directory', _directoryRole.default], ['document', _documentRole.default], ['emphasis', _emphasisRole.default], ['feed', _feedRole.default], ['figure', _figureRole.default], ['form', _formRole.default], ['generic', _genericRole.default], ['grid', _gridRole.default], ['gridcell', _gridcellRole.default], ['group', _groupRole.default], ['heading', _headingRole.default], ['img', _imgRole.default], ['insertion', _insertionRole.default], ['link', _linkRole.default], ['list', _listRole.default], ['listbox', _listboxRole.default], ['listitem', _listitemRole.default], ['log', _logRole.default], ['main', _mainRole.default], ['mark', _markRole.default], ['marquee', _marqueeRole.default], ['math', _mathRole.default], ['menu', _menuRole.default], ['menubar', _menubarRole.default], ['menuitem', _menuitemRole.default], ['menuitemcheckbox', _menuitemcheckboxRole.default], ['menuitemradio', _menuitemradioRole.default], ['meter', _meterRole.default], ['navigation', _navigationRole.default], ['none', _noneRole.default], ['note', _noteRole.default], ['option', _optionRole.default], ['paragraph', _paragraphRole.default], ['presentation', _presentationRole.default], ['progressbar', _progressbarRole.default], ['radio', _radioRole.default], ['radiogroup', _radiogroupRole.default], ['region', _regionRole.default], ['row', _rowRole.default], ['rowgroup', _rowgroupRole.default], ['rowheader', _rowheaderRole.default], ['scrollbar', _scrollbarRole.default], ['search', _searchRole.default], ['searchbox', _searchboxRole.default], ['separator', _separatorRole.default], ['slider', _sliderRole.default], ['spinbutton', _spinbuttonRole.default], ['status', _statusRole.default], ['strong', _strongRole.default], ['subscript', _subscriptRole.default], ['superscript', _superscriptRole.default], ['switch', _switchRole.default], ['tab', _tabRole.default], ['table', _tableRole.default], ['tablist', _tablistRole.default], ['tabpanel', _tabpanelRole.default], ['term', _termRole.default], ['textbox', _textboxRole.default], ['time', _timeRole.default], ['timer', _timerRole.default], ['toolbar', _toolbarRole.default], ['tooltip', _tooltipRole.default], ['tree', _treeRole.default], ['treegrid', _treegridRole.default], ['treeitem', _treeitemRole.default]];
var _default$2M = ariaLiteralRoles;
ariaLiteralRoles$1.default = _default$2M;

var ariaDpubRoles$1 = {};

var docAbstractRole$1 = {};

Object.defineProperty(docAbstractRole$1, "__esModule", {
  value: true
});
docAbstractRole$1.default = void 0;
var docAbstractRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'abstract [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$2L = docAbstractRole;
docAbstractRole$1.default = _default$2L;

var docAcknowledgmentsRole$1 = {};

Object.defineProperty(docAcknowledgmentsRole$1, "__esModule", {
  value: true
});
docAcknowledgmentsRole$1.default = void 0;
var docAcknowledgmentsRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'acknowledgments [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$2K = docAcknowledgmentsRole;
docAcknowledgmentsRole$1.default = _default$2K;

var docAfterwordRole$1 = {};

Object.defineProperty(docAfterwordRole$1, "__esModule", {
  value: true
});
docAfterwordRole$1.default = void 0;
var docAfterwordRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'afterword [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$2J = docAfterwordRole;
docAfterwordRole$1.default = _default$2J;

var docAppendixRole$1 = {};

Object.defineProperty(docAppendixRole$1, "__esModule", {
  value: true
});
docAppendixRole$1.default = void 0;
var docAppendixRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'appendix [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$2I = docAppendixRole;
docAppendixRole$1.default = _default$2I;

var docBacklinkRole$1 = {};

Object.defineProperty(docBacklinkRole$1, "__esModule", {
  value: true
});
docBacklinkRole$1.default = void 0;
var docBacklinkRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {
    'aria-errormessage': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'referrer [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'widget', 'command', 'link']]
};
var _default$2H = docBacklinkRole;
docBacklinkRole$1.default = _default$2H;

var docBiblioentryRole$1 = {};

Object.defineProperty(docBiblioentryRole$1, "__esModule", {
  value: true
});
docBiblioentryRole$1.default = void 0;
var docBiblioentryRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'EPUB biblioentry [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: ['doc-bibliography'],
  requiredContextRole: ['doc-bibliography'],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'listitem']]
};
var _default$2G = docBiblioentryRole;
docBiblioentryRole$1.default = _default$2G;

var docBibliographyRole$1 = {};

Object.defineProperty(docBibliographyRole$1, "__esModule", {
  value: true
});
docBibliographyRole$1.default = void 0;
var docBibliographyRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'bibliography [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [['doc-biblioentry']],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$2F = docBibliographyRole;
docBibliographyRole$1.default = _default$2F;

var docBibliorefRole$1 = {};

Object.defineProperty(docBibliorefRole$1, "__esModule", {
  value: true
});
docBibliorefRole$1.default = void 0;
var docBibliorefRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {
    'aria-errormessage': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'biblioref [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'widget', 'command', 'link']]
};
var _default$2E = docBibliorefRole;
docBibliorefRole$1.default = _default$2E;

var docChapterRole$1 = {};

Object.defineProperty(docChapterRole$1, "__esModule", {
  value: true
});
docChapterRole$1.default = void 0;
var docChapterRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'chapter [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$2D = docChapterRole;
docChapterRole$1.default = _default$2D;

var docColophonRole$1 = {};

Object.defineProperty(docColophonRole$1, "__esModule", {
  value: true
});
docColophonRole$1.default = void 0;
var docColophonRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'colophon [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$2C = docColophonRole;
docColophonRole$1.default = _default$2C;

var docConclusionRole$1 = {};

Object.defineProperty(docConclusionRole$1, "__esModule", {
  value: true
});
docConclusionRole$1.default = void 0;
var docConclusionRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'conclusion [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$2B = docConclusionRole;
docConclusionRole$1.default = _default$2B;

var docCoverRole$1 = {};

Object.defineProperty(docCoverRole$1, "__esModule", {
  value: true
});
docCoverRole$1.default = void 0;
var docCoverRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'cover [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'img']]
};
var _default$2A = docCoverRole;
docCoverRole$1.default = _default$2A;

var docCreditRole$1 = {};

Object.defineProperty(docCreditRole$1, "__esModule", {
  value: true
});
docCreditRole$1.default = void 0;
var docCreditRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'credit [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$2z = docCreditRole;
docCreditRole$1.default = _default$2z;

var docCreditsRole$1 = {};

Object.defineProperty(docCreditsRole$1, "__esModule", {
  value: true
});
docCreditsRole$1.default = void 0;
var docCreditsRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'credits [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$2y = docCreditsRole;
docCreditsRole$1.default = _default$2y;

var docDedicationRole$1 = {};

Object.defineProperty(docDedicationRole$1, "__esModule", {
  value: true
});
docDedicationRole$1.default = void 0;
var docDedicationRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'dedication [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$2x = docDedicationRole;
docDedicationRole$1.default = _default$2x;

var docEndnoteRole$1 = {};

Object.defineProperty(docEndnoteRole$1, "__esModule", {
  value: true
});
docEndnoteRole$1.default = void 0;
var docEndnoteRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'rearnote [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: ['doc-endnotes'],
  requiredContextRole: ['doc-endnotes'],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'listitem']]
};
var _default$2w = docEndnoteRole;
docEndnoteRole$1.default = _default$2w;

var docEndnotesRole$1 = {};

Object.defineProperty(docEndnotesRole$1, "__esModule", {
  value: true
});
docEndnotesRole$1.default = void 0;
var docEndnotesRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'rearnotes [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [['doc-endnote']],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$2v = docEndnotesRole;
docEndnotesRole$1.default = _default$2v;

var docEpigraphRole$1 = {};

Object.defineProperty(docEpigraphRole$1, "__esModule", {
  value: true
});
docEpigraphRole$1.default = void 0;
var docEpigraphRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'epigraph [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$2u = docEpigraphRole;
docEpigraphRole$1.default = _default$2u;

var docEpilogueRole$1 = {};

Object.defineProperty(docEpilogueRole$1, "__esModule", {
  value: true
});
docEpilogueRole$1.default = void 0;
var docEpilogueRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'epilogue [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$2t = docEpilogueRole;
docEpilogueRole$1.default = _default$2t;

var docErrataRole$1 = {};

Object.defineProperty(docErrataRole$1, "__esModule", {
  value: true
});
docErrataRole$1.default = void 0;
var docErrataRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'errata [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$2s = docErrataRole;
docErrataRole$1.default = _default$2s;

var docExampleRole$1 = {};

Object.defineProperty(docExampleRole$1, "__esModule", {
  value: true
});
docExampleRole$1.default = void 0;
var docExampleRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$2r = docExampleRole;
docExampleRole$1.default = _default$2r;

var docFootnoteRole$1 = {};

Object.defineProperty(docFootnoteRole$1, "__esModule", {
  value: true
});
docFootnoteRole$1.default = void 0;
var docFootnoteRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'footnote [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$2q = docFootnoteRole;
docFootnoteRole$1.default = _default$2q;

var docForewordRole$1 = {};

Object.defineProperty(docForewordRole$1, "__esModule", {
  value: true
});
docForewordRole$1.default = void 0;
var docForewordRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'foreword [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$2p = docForewordRole;
docForewordRole$1.default = _default$2p;

var docGlossaryRole$1 = {};

Object.defineProperty(docGlossaryRole$1, "__esModule", {
  value: true
});
docGlossaryRole$1.default = void 0;
var docGlossaryRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'glossary [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [['definition'], ['term']],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$2o = docGlossaryRole;
docGlossaryRole$1.default = _default$2o;

var docGlossrefRole$1 = {};

Object.defineProperty(docGlossrefRole$1, "__esModule", {
  value: true
});
docGlossrefRole$1.default = void 0;
var docGlossrefRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {
    'aria-errormessage': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'glossref [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'widget', 'command', 'link']]
};
var _default$2n = docGlossrefRole;
docGlossrefRole$1.default = _default$2n;

var docIndexRole$1 = {};

Object.defineProperty(docIndexRole$1, "__esModule", {
  value: true
});
docIndexRole$1.default = void 0;
var docIndexRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'index [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark', 'navigation']]
};
var _default$2m = docIndexRole;
docIndexRole$1.default = _default$2m;

var docIntroductionRole$1 = {};

Object.defineProperty(docIntroductionRole$1, "__esModule", {
  value: true
});
docIntroductionRole$1.default = void 0;
var docIntroductionRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'introduction [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$2l = docIntroductionRole;
docIntroductionRole$1.default = _default$2l;

var docNoterefRole$1 = {};

Object.defineProperty(docNoterefRole$1, "__esModule", {
  value: true
});
docNoterefRole$1.default = void 0;
var docNoterefRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {
    'aria-errormessage': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'noteref [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'widget', 'command', 'link']]
};
var _default$2k = docNoterefRole;
docNoterefRole$1.default = _default$2k;

var docNoticeRole$1 = {};

Object.defineProperty(docNoticeRole$1, "__esModule", {
  value: true
});
docNoticeRole$1.default = void 0;
var docNoticeRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'notice [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'note']]
};
var _default$2j = docNoticeRole;
docNoticeRole$1.default = _default$2j;

var docPagebreakRole$1 = {};

Object.defineProperty(docPagebreakRole$1, "__esModule", {
  value: true
});
docPagebreakRole$1.default = void 0;
var docPagebreakRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: true,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'pagebreak [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'separator']]
};
var _default$2i = docPagebreakRole;
docPagebreakRole$1.default = _default$2i;

var docPagelistRole$1 = {};

Object.defineProperty(docPagelistRole$1, "__esModule", {
  value: true
});
docPagelistRole$1.default = void 0;
var docPagelistRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'page-list [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark', 'navigation']]
};
var _default$2h = docPagelistRole;
docPagelistRole$1.default = _default$2h;

var docPartRole$1 = {};

Object.defineProperty(docPartRole$1, "__esModule", {
  value: true
});
docPartRole$1.default = void 0;
var docPartRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'part [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$2g = docPartRole;
docPartRole$1.default = _default$2g;

var docPrefaceRole$1 = {};

Object.defineProperty(docPrefaceRole$1, "__esModule", {
  value: true
});
docPrefaceRole$1.default = void 0;
var docPrefaceRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'preface [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$2f = docPrefaceRole;
docPrefaceRole$1.default = _default$2f;

var docPrologueRole$1 = {};

Object.defineProperty(docPrologueRole$1, "__esModule", {
  value: true
});
docPrologueRole$1.default = void 0;
var docPrologueRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'prologue [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default$2e = docPrologueRole;
docPrologueRole$1.default = _default$2e;

var docPullquoteRole$1 = {};

Object.defineProperty(docPullquoteRole$1, "__esModule", {
  value: true
});
docPullquoteRole$1.default = void 0;
var docPullquoteRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {},
  relatedConcepts: [{
    concept: {
      name: 'pullquote [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['none']]
};
var _default$2d = docPullquoteRole;
docPullquoteRole$1.default = _default$2d;

var docQnaRole$1 = {};

Object.defineProperty(docQnaRole$1, "__esModule", {
  value: true
});
docQnaRole$1.default = void 0;
var docQnaRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'qna [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section']]
};
var _default$2c = docQnaRole;
docQnaRole$1.default = _default$2c;

var docSubtitleRole$1 = {};

Object.defineProperty(docSubtitleRole$1, "__esModule", {
  value: true
});
docSubtitleRole$1.default = void 0;
var docSubtitleRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'subtitle [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'sectionhead']]
};
var _default$2b = docSubtitleRole;
docSubtitleRole$1.default = _default$2b;

var docTipRole$1 = {};

Object.defineProperty(docTipRole$1, "__esModule", {
  value: true
});
docTipRole$1.default = void 0;
var docTipRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'help [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'note']]
};
var _default$2a = docTipRole;
docTipRole$1.default = _default$2a;

var docTocRole$1 = {};

Object.defineProperty(docTocRole$1, "__esModule", {
  value: true
});
docTocRole$1.default = void 0;
var docTocRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    concept: {
      name: 'toc [EPUB-SSV]'
    },
    module: 'EPUB'
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'landmark', 'navigation']]
};
var _default$29 = docTocRole;
docTocRole$1.default = _default$29;

Object.defineProperty(ariaDpubRoles$1, "__esModule", {
  value: true
});
ariaDpubRoles$1.default = void 0;
var _docAbstractRole = _interopRequireDefault$b(docAbstractRole$1);
var _docAcknowledgmentsRole = _interopRequireDefault$b(docAcknowledgmentsRole$1);
var _docAfterwordRole = _interopRequireDefault$b(docAfterwordRole$1);
var _docAppendixRole = _interopRequireDefault$b(docAppendixRole$1);
var _docBacklinkRole = _interopRequireDefault$b(docBacklinkRole$1);
var _docBiblioentryRole = _interopRequireDefault$b(docBiblioentryRole$1);
var _docBibliographyRole = _interopRequireDefault$b(docBibliographyRole$1);
var _docBibliorefRole = _interopRequireDefault$b(docBibliorefRole$1);
var _docChapterRole = _interopRequireDefault$b(docChapterRole$1);
var _docColophonRole = _interopRequireDefault$b(docColophonRole$1);
var _docConclusionRole = _interopRequireDefault$b(docConclusionRole$1);
var _docCoverRole = _interopRequireDefault$b(docCoverRole$1);
var _docCreditRole = _interopRequireDefault$b(docCreditRole$1);
var _docCreditsRole = _interopRequireDefault$b(docCreditsRole$1);
var _docDedicationRole = _interopRequireDefault$b(docDedicationRole$1);
var _docEndnoteRole = _interopRequireDefault$b(docEndnoteRole$1);
var _docEndnotesRole = _interopRequireDefault$b(docEndnotesRole$1);
var _docEpigraphRole = _interopRequireDefault$b(docEpigraphRole$1);
var _docEpilogueRole = _interopRequireDefault$b(docEpilogueRole$1);
var _docErrataRole = _interopRequireDefault$b(docErrataRole$1);
var _docExampleRole = _interopRequireDefault$b(docExampleRole$1);
var _docFootnoteRole = _interopRequireDefault$b(docFootnoteRole$1);
var _docForewordRole = _interopRequireDefault$b(docForewordRole$1);
var _docGlossaryRole = _interopRequireDefault$b(docGlossaryRole$1);
var _docGlossrefRole = _interopRequireDefault$b(docGlossrefRole$1);
var _docIndexRole = _interopRequireDefault$b(docIndexRole$1);
var _docIntroductionRole = _interopRequireDefault$b(docIntroductionRole$1);
var _docNoterefRole = _interopRequireDefault$b(docNoterefRole$1);
var _docNoticeRole = _interopRequireDefault$b(docNoticeRole$1);
var _docPagebreakRole = _interopRequireDefault$b(docPagebreakRole$1);
var _docPagelistRole = _interopRequireDefault$b(docPagelistRole$1);
var _docPartRole = _interopRequireDefault$b(docPartRole$1);
var _docPrefaceRole = _interopRequireDefault$b(docPrefaceRole$1);
var _docPrologueRole = _interopRequireDefault$b(docPrologueRole$1);
var _docPullquoteRole = _interopRequireDefault$b(docPullquoteRole$1);
var _docQnaRole = _interopRequireDefault$b(docQnaRole$1);
var _docSubtitleRole = _interopRequireDefault$b(docSubtitleRole$1);
var _docTipRole = _interopRequireDefault$b(docTipRole$1);
var _docTocRole = _interopRequireDefault$b(docTocRole$1);
function _interopRequireDefault$b(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var ariaDpubRoles = [['doc-abstract', _docAbstractRole.default], ['doc-acknowledgments', _docAcknowledgmentsRole.default], ['doc-afterword', _docAfterwordRole.default], ['doc-appendix', _docAppendixRole.default], ['doc-backlink', _docBacklinkRole.default], ['doc-biblioentry', _docBiblioentryRole.default], ['doc-bibliography', _docBibliographyRole.default], ['doc-biblioref', _docBibliorefRole.default], ['doc-chapter', _docChapterRole.default], ['doc-colophon', _docColophonRole.default], ['doc-conclusion', _docConclusionRole.default], ['doc-cover', _docCoverRole.default], ['doc-credit', _docCreditRole.default], ['doc-credits', _docCreditsRole.default], ['doc-dedication', _docDedicationRole.default], ['doc-endnote', _docEndnoteRole.default], ['doc-endnotes', _docEndnotesRole.default], ['doc-epigraph', _docEpigraphRole.default], ['doc-epilogue', _docEpilogueRole.default], ['doc-errata', _docErrataRole.default], ['doc-example', _docExampleRole.default], ['doc-footnote', _docFootnoteRole.default], ['doc-foreword', _docForewordRole.default], ['doc-glossary', _docGlossaryRole.default], ['doc-glossref', _docGlossrefRole.default], ['doc-index', _docIndexRole.default], ['doc-introduction', _docIntroductionRole.default], ['doc-noteref', _docNoterefRole.default], ['doc-notice', _docNoticeRole.default], ['doc-pagebreak', _docPagebreakRole.default], ['doc-pagelist', _docPagelistRole.default], ['doc-part', _docPartRole.default], ['doc-preface', _docPrefaceRole.default], ['doc-prologue', _docPrologueRole.default], ['doc-pullquote', _docPullquoteRole.default], ['doc-qna', _docQnaRole.default], ['doc-subtitle', _docSubtitleRole.default], ['doc-tip', _docTipRole.default], ['doc-toc', _docTocRole.default]];
var _default$28 = ariaDpubRoles;
ariaDpubRoles$1.default = _default$28;

var ariaGraphicsRoles$1 = {};

var graphicsDocumentRole$1 = {};

Object.defineProperty(graphicsDocumentRole$1, "__esModule", {
  value: true
});
graphicsDocumentRole$1.default = void 0;
var graphicsDocumentRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    module: 'GRAPHICS',
    concept: {
      name: 'graphics-object'
    }
  }, {
    module: 'ARIA',
    concept: {
      name: 'img'
    }
  }, {
    module: 'ARIA',
    concept: {
      name: 'article'
    }
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'document']]
};
var _default$27 = graphicsDocumentRole;
graphicsDocumentRole$1.default = _default$27;

var graphicsObjectRole$1 = {};

Object.defineProperty(graphicsObjectRole$1, "__esModule", {
  value: true
});
graphicsObjectRole$1.default = void 0;
var graphicsObjectRole = {
  abstract: false,
  accessibleNameRequired: false,
  baseConcepts: [],
  childrenPresentational: false,
  nameFrom: ['author', 'contents'],
  prohibitedProps: [],
  props: {
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [{
    module: 'GRAPHICS',
    concept: {
      name: 'graphics-document'
    }
  }, {
    module: 'ARIA',
    concept: {
      name: 'group'
    }
  }, {
    module: 'ARIA',
    concept: {
      name: 'img'
    }
  }, {
    module: 'GRAPHICS',
    concept: {
      name: 'graphics-symbol'
    }
  }],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'group']]
};
var _default$26 = graphicsObjectRole;
graphicsObjectRole$1.default = _default$26;

var graphicsSymbolRole$1 = {};

Object.defineProperty(graphicsSymbolRole$1, "__esModule", {
  value: true
});
graphicsSymbolRole$1.default = void 0;
var graphicsSymbolRole = {
  abstract: false,
  accessibleNameRequired: true,
  baseConcepts: [],
  childrenPresentational: true,
  nameFrom: ['author'],
  prohibitedProps: [],
  props: {
    'aria-disabled': null,
    'aria-errormessage': null,
    'aria-expanded': null,
    'aria-haspopup': null,
    'aria-invalid': null
  },
  relatedConcepts: [],
  requireContextRole: [],
  requiredContextRole: [],
  requiredOwnedElements: [],
  requiredProps: {},
  superClass: [['roletype', 'structure', 'section', 'img']]
};
var _default$25 = graphicsSymbolRole;
graphicsSymbolRole$1.default = _default$25;

Object.defineProperty(ariaGraphicsRoles$1, "__esModule", {
  value: true
});
ariaGraphicsRoles$1.default = void 0;
var _graphicsDocumentRole = _interopRequireDefault$a(graphicsDocumentRole$1);
var _graphicsObjectRole = _interopRequireDefault$a(graphicsObjectRole$1);
var _graphicsSymbolRole = _interopRequireDefault$a(graphicsSymbolRole$1);
function _interopRequireDefault$a(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var ariaGraphicsRoles = [['graphics-document', _graphicsDocumentRole.default], ['graphics-object', _graphicsObjectRole.default], ['graphics-symbol', _graphicsSymbolRole.default]];
var _default$24 = ariaGraphicsRoles;
ariaGraphicsRoles$1.default = _default$24;

Object.defineProperty(rolesMap$1, "__esModule", {
  value: true
});
rolesMap$1.default = void 0;
var _ariaAbstractRoles = _interopRequireDefault$9(ariaAbstractRoles$1);
var _ariaLiteralRoles = _interopRequireDefault$9(ariaLiteralRoles$1);
var _ariaDpubRoles = _interopRequireDefault$9(ariaDpubRoles$1);
var _ariaGraphicsRoles = _interopRequireDefault$9(ariaGraphicsRoles$1);
var _iterationDecorator$6 = _interopRequireDefault$9(iterationDecorator$3);
function _interopRequireDefault$9(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _createForOfIteratorHelper$6(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$6(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _slicedToArray$6(arr, i) { return _arrayWithHoles$6(arr) || _iterableToArrayLimit$6(arr, i) || _unsupportedIterableToArray$6(arr, i) || _nonIterableRest$6(); }
function _nonIterableRest$6() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray$6(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$6(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$6(o, minLen); }
function _arrayLikeToArray$6(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _iterableToArrayLimit$6(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles$6(arr) { if (Array.isArray(arr)) return arr; }
var roles$1 = [].concat(_ariaAbstractRoles.default, _ariaLiteralRoles.default, _ariaDpubRoles.default, _ariaGraphicsRoles.default);
roles$1.forEach(function (_ref) {
  var _ref2 = _slicedToArray$6(_ref, 2),
    roleDefinition = _ref2[1];
  // Conglomerate the properties
  var _iterator = _createForOfIteratorHelper$6(roleDefinition.superClass),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var superClassIter = _step.value;
      var _iterator2 = _createForOfIteratorHelper$6(superClassIter),
        _step2;
      try {
        var _loop = function _loop() {
          var superClassName = _step2.value;
          var superClassRoleTuple = roles$1.find(function (_ref3) {
            var _ref4 = _slicedToArray$6(_ref3, 1),
              name = _ref4[0];
            return name === superClassName;
          });
          if (superClassRoleTuple) {
            var superClassDefinition = superClassRoleTuple[1];
            for (var _i2 = 0, _Object$keys = Object.keys(superClassDefinition.props); _i2 < _Object$keys.length; _i2++) {
              var prop = _Object$keys[_i2];
              if (
              // $FlowIssue Accessing the hasOwnProperty on the Object prototype is fine.
              !Object.prototype.hasOwnProperty.call(roleDefinition.props, prop)) {
                Object.assign(roleDefinition.props, _defineProperty({}, prop, superClassDefinition.props[prop]));
              }
            }
          }
        };
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          _loop();
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
});
var rolesMap = {
  entries: function entries() {
    return roles$1;
  },
  forEach: function forEach(fn) {
    var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
    var _iterator3 = _createForOfIteratorHelper$6(roles$1),
      _step3;
    try {
      for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
        var _step3$value = _slicedToArray$6(_step3.value, 2),
          key = _step3$value[0],
          values = _step3$value[1];
        fn.call(thisArg, values, key, roles$1);
      }
    } catch (err) {
      _iterator3.e(err);
    } finally {
      _iterator3.f();
    }
  },
  get: function get(key) {
    var item = roles$1.find(function (tuple) {
      return tuple[0] === key ? true : false;
    });
    return item && item[1];
  },
  has: function has(key) {
    return !!rolesMap.get(key);
  },
  keys: function keys() {
    return roles$1.map(function (_ref5) {
      var _ref6 = _slicedToArray$6(_ref5, 1),
        key = _ref6[0];
      return key;
    });
  },
  values: function values() {
    return roles$1.map(function (_ref7) {
      var _ref8 = _slicedToArray$6(_ref7, 2),
        values = _ref8[1];
      return values;
    });
  }
};
var _default$23 = (0, _iterationDecorator$6.default)(rolesMap, rolesMap.entries());
rolesMap$1.default = _default$23;

var elementRoleMap$1 = {};

var lite = {};

var has = Object.prototype.hasOwnProperty;

function dequal(foo, bar) {
	var ctor, len;
	if (foo === bar) return true;

	if (foo && bar && (ctor=foo.constructor) === bar.constructor) {
		if (ctor === Date) return foo.getTime() === bar.getTime();
		if (ctor === RegExp) return foo.toString() === bar.toString();

		if (ctor === Array) {
			if ((len=foo.length) === bar.length) {
				while (len-- && dequal(foo[len], bar[len]));
			}
			return len === -1;
		}

		if (!ctor || typeof foo === 'object') {
			len = 0;
			for (ctor in foo) {
				if (has.call(foo, ctor) && ++len && !has.call(bar, ctor)) return false;
				if (!(ctor in bar) || !dequal(foo[ctor], bar[ctor])) return false;
			}
			return Object.keys(bar).length === len;
		}
	}

	return foo !== foo && bar !== bar;
}

lite.dequal = dequal;

Object.defineProperty(elementRoleMap$1, "__esModule", {
  value: true
});
elementRoleMap$1.default = void 0;
var _lite$1 = lite;
var _iterationDecorator$5 = _interopRequireDefault$8(iterationDecorator$3);
var _rolesMap$2 = _interopRequireDefault$8(rolesMap$1);
function _interopRequireDefault$8(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _slicedToArray$5(arr, i) { return _arrayWithHoles$5(arr) || _iterableToArrayLimit$5(arr, i) || _unsupportedIterableToArray$5(arr, i) || _nonIterableRest$5(); }
function _nonIterableRest$5() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit$5(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles$5(arr) { if (Array.isArray(arr)) return arr; }
function _createForOfIteratorHelper$5(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$5(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray$5(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$5(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$5(o, minLen); }
function _arrayLikeToArray$5(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
var elementRoles$1 = [];
var keys$1 = _rolesMap$2.default.keys();
for (var i$1 = 0; i$1 < keys$1.length; i$1++) {
  var key$1 = keys$1[i$1];
  var role$1 = _rolesMap$2.default.get(key$1);
  if (role$1) {
    var concepts$1 = [].concat(role$1.baseConcepts, role$1.relatedConcepts);
    for (var k$1 = 0; k$1 < concepts$1.length; k$1++) {
      var relation$1 = concepts$1[k$1];
      if (relation$1.module === 'HTML') {
        (function () {
          var concept = relation$1.concept;
          if (concept) {
            var elementRoleRelation = elementRoles$1.find(function (relation) {
              return (0, _lite$1.dequal)(relation, concept);
            });
            var roles;
            if (elementRoleRelation) {
              roles = elementRoleRelation[1];
            } else {
              roles = [];
            }
            var isUnique = true;
            for (var _i = 0; _i < roles.length; _i++) {
              if (roles[_i] === key$1) {
                isUnique = false;
                break;
              }
            }
            if (isUnique) {
              roles.push(key$1);
            }
            elementRoles$1.push([concept, roles]);
          }
        })();
      }
    }
  }
}
var elementRoleMap = {
  entries: function entries() {
    return elementRoles$1;
  },
  forEach: function forEach(fn) {
    var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
    var _iterator = _createForOfIteratorHelper$5(elementRoles$1),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var _step$value = _slicedToArray$5(_step.value, 2),
          _key = _step$value[0],
          values = _step$value[1];
        fn.call(thisArg, values, _key, elementRoles$1);
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
  },
  get: function get(key) {
    var item = elementRoles$1.find(function (tuple) {
      return key.name === tuple[0].name && (0, _lite$1.dequal)(key.attributes, tuple[0].attributes);
    });
    return item && item[1];
  },
  has: function has(key) {
    return !!elementRoleMap.get(key);
  },
  keys: function keys() {
    return elementRoles$1.map(function (_ref) {
      var _ref2 = _slicedToArray$5(_ref, 1),
        key = _ref2[0];
      return key;
    });
  },
  values: function values() {
    return elementRoles$1.map(function (_ref3) {
      var _ref4 = _slicedToArray$5(_ref3, 2),
        values = _ref4[1];
      return values;
    });
  }
};
var _default$22 = (0, _iterationDecorator$5.default)(elementRoleMap, elementRoleMap.entries());
elementRoleMap$1.default = _default$22;

var roleElementMap$1 = {};

Object.defineProperty(roleElementMap$1, "__esModule", {
  value: true
});
roleElementMap$1.default = void 0;
var _iterationDecorator$4 = _interopRequireDefault$7(iterationDecorator$3);
var _rolesMap$1 = _interopRequireDefault$7(rolesMap$1);
function _interopRequireDefault$7(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _slicedToArray$4(arr, i) { return _arrayWithHoles$4(arr) || _iterableToArrayLimit$4(arr, i) || _unsupportedIterableToArray$4(arr, i) || _nonIterableRest$4(); }
function _nonIterableRest$4() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit$4(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles$4(arr) { if (Array.isArray(arr)) return arr; }
function _createForOfIteratorHelper$4(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$4(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray$4(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$4(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$4(o, minLen); }
function _arrayLikeToArray$4(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
var roleElement = [];
var keys = _rolesMap$1.default.keys();
for (var i = 0; i < keys.length; i++) {
  var key = keys[i];
  var role = _rolesMap$1.default.get(key);
  var relationConcepts = [];
  if (role) {
    var concepts = [].concat(role.baseConcepts, role.relatedConcepts);
    for (var k = 0; k < concepts.length; k++) {
      var relation = concepts[k];
      if (relation.module === 'HTML') {
        var concept = relation.concept;
        if (concept != null) {
          relationConcepts.push(concept);
        }
      }
    }
    if (relationConcepts.length > 0) {
      roleElement.push([key, relationConcepts]);
    }
  }
}
var roleElementMap = {
  entries: function entries() {
    return roleElement;
  },
  forEach: function forEach(fn) {
    var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
    var _iterator = _createForOfIteratorHelper$4(roleElement),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var _step$value = _slicedToArray$4(_step.value, 2),
          _key = _step$value[0],
          values = _step$value[1];
        fn.call(thisArg, values, _key, roleElement);
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
  },
  get: function get(key) {
    var item = roleElement.find(function (tuple) {
      return tuple[0] === key ? true : false;
    });
    return item && item[1];
  },
  has: function has(key) {
    return !!roleElementMap.get(key);
  },
  keys: function keys() {
    return roleElement.map(function (_ref) {
      var _ref2 = _slicedToArray$4(_ref, 1),
        key = _ref2[0];
      return key;
    });
  },
  values: function values() {
    return roleElement.map(function (_ref3) {
      var _ref4 = _slicedToArray$4(_ref3, 2),
        values = _ref4[1];
      return values;
    });
  }
};
var _default$21 = (0, _iterationDecorator$4.default)(roleElementMap, roleElementMap.entries());
roleElementMap$1.default = _default$21;

Object.defineProperty(lib$1, "__esModule", {
  value: true
});
var roles_1 = lib$1.roles = lib$1.roleElements = elementRoles_1 = lib$1.elementRoles = lib$1.dom = aria_1 = lib$1.aria = void 0;
var _ariaPropsMap = _interopRequireDefault$6(ariaPropsMap$1);
var _domMap = _interopRequireDefault$6(domMap$1);
var _rolesMap = _interopRequireDefault$6(rolesMap$1);
var _elementRoleMap = _interopRequireDefault$6(elementRoleMap$1);
var _roleElementMap = _interopRequireDefault$6(roleElementMap$1);
function _interopRequireDefault$6(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var aria = _ariaPropsMap.default;
var aria_1 = lib$1.aria = aria;
var dom$1 = _domMap.default;
lib$1.dom = dom$1;
var roles = _rolesMap.default;
roles_1 = lib$1.roles = roles;
var elementRoles = _elementRoleMap.default;
var elementRoles_1 = lib$1.elementRoles = elementRoles;
var roleElements = _roleElementMap.default;
lib$1.roleElements = roleElements;

var lib = {};

var AXObjectElementMap$1 = {};

var iterationDecorator$1 = {};

var iteratorProxy$1 = {};

Object.defineProperty(iteratorProxy$1, "__esModule", {
  value: true
});
iteratorProxy$1.default = void 0;

// eslint-disable-next-line no-unused-vars
function iteratorProxy() {
  var values = this;
  var index = 0;
  var iter = {
    '@@iterator': function iterator() {
      return iter;
    },
    next: function next() {
      if (index < values.length) {
        var value = values[index];
        index = index + 1;
        return {
          done: false,
          value: value
        };
      } else {
        return {
          done: true
        };
      }
    }
  };
  return iter;
}
var _default$20 = iteratorProxy;
iteratorProxy$1.default = _default$20;

Object.defineProperty(iterationDecorator$1, "__esModule", {
  value: true
});
iterationDecorator$1.default = iterationDecorator;
var _iteratorProxy = _interopRequireDefault$5(iteratorProxy$1);
function _interopRequireDefault$5(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function iterationDecorator(collection, entries) {
  if (typeof Symbol === 'function' && _typeof(Symbol.iterator) === 'symbol') {
    Object.defineProperty(collection, Symbol.iterator, {
      value: _iteratorProxy.default.bind(entries)
    });
  }
  return collection;
}

var AXObjectsMap$1 = {};

var AbbrRole$1 = {};

Object.defineProperty(AbbrRole$1, "__esModule", {
  value: true
});
AbbrRole$1.default = void 0;
var AbbrRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'abbr'
    }
  }],
  type: 'structure'
};
var _default$1$ = AbbrRole;
AbbrRole$1.default = _default$1$;

var AlertDialogRole$1 = {};

Object.defineProperty(AlertDialogRole$1, "__esModule", {
  value: true
});
AlertDialogRole$1.default = void 0;
var AlertDialogRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'alertdialog'
    }
  }],
  type: 'window'
};
var _default$1_ = AlertDialogRole;
AlertDialogRole$1.default = _default$1_;

var AlertRole$1 = {};

Object.defineProperty(AlertRole$1, "__esModule", {
  value: true
});
AlertRole$1.default = void 0;
var AlertRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'alert'
    }
  }],
  type: 'structure'
};
var _default$1Z = AlertRole;
AlertRole$1.default = _default$1Z;

var AnnotationRole$1 = {};

Object.defineProperty(AnnotationRole$1, "__esModule", {
  value: true
});
AnnotationRole$1.default = void 0;
var AnnotationRole = {
  relatedConcepts: [],
  type: 'structure'
};
var _default$1Y = AnnotationRole;
AnnotationRole$1.default = _default$1Y;

var ApplicationRole$1 = {};

Object.defineProperty(ApplicationRole$1, "__esModule", {
  value: true
});
ApplicationRole$1.default = void 0;
var ApplicationRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'application'
    }
  }],
  type: 'window'
};
var _default$1X = ApplicationRole;
ApplicationRole$1.default = _default$1X;

var ArticleRole$1 = {};

Object.defineProperty(ArticleRole$1, "__esModule", {
  value: true
});
ArticleRole$1.default = void 0;
var ArticleRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'article'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'article'
    }
  }],
  type: 'structure'
};
var _default$1W = ArticleRole;
ArticleRole$1.default = _default$1W;

var AudioRole$1 = {};

Object.defineProperty(AudioRole$1, "__esModule", {
  value: true
});
AudioRole$1.default = void 0;
var AudioRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'audio'
    }
  }],
  type: 'widget'
};
var _default$1V = AudioRole;
AudioRole$1.default = _default$1V;

var BannerRole$1 = {};

Object.defineProperty(BannerRole$1, "__esModule", {
  value: true
});
BannerRole$1.default = void 0;
var BannerRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'banner'
    }
  }],
  type: 'structure'
};
var _default$1U = BannerRole;
BannerRole$1.default = _default$1U;

var BlockquoteRole$1 = {};

Object.defineProperty(BlockquoteRole$1, "__esModule", {
  value: true
});
BlockquoteRole$1.default = void 0;
var BlockquoteRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'blockquote'
    }
  }],
  type: 'structure'
};
var _default$1T = BlockquoteRole;
BlockquoteRole$1.default = _default$1T;

var BusyIndicatorRole$1 = {};

Object.defineProperty(BusyIndicatorRole$1, "__esModule", {
  value: true
});
BusyIndicatorRole$1.default = void 0;
var BusyIndicatorRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      attributes: [{
        name: 'aria-busy',
        value: 'true'
      }]
    }
  }],
  type: 'widget'
};
var _default$1S = BusyIndicatorRole;
BusyIndicatorRole$1.default = _default$1S;

var ButtonRole$1 = {};

Object.defineProperty(ButtonRole$1, "__esModule", {
  value: true
});
ButtonRole$1.default = void 0;
var ButtonRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'button'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'button'
    }
  }],
  type: 'widget'
};
var _default$1R = ButtonRole;
ButtonRole$1.default = _default$1R;

var CanvasRole$1 = {};

Object.defineProperty(CanvasRole$1, "__esModule", {
  value: true
});
CanvasRole$1.default = void 0;
var CanvasRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'canvas'
    }
  }],
  type: 'widget'
};
var _default$1Q = CanvasRole;
CanvasRole$1.default = _default$1Q;

var CaptionRole$1 = {};

Object.defineProperty(CaptionRole$1, "__esModule", {
  value: true
});
CaptionRole$1.default = void 0;
var CaptionRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'caption'
    }
  }],
  type: 'structure'
};
var _default$1P = CaptionRole;
CaptionRole$1.default = _default$1P;

var CellRole$1 = {};

Object.defineProperty(CellRole$1, "__esModule", {
  value: true
});
CellRole$1.default = void 0;
var CellRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'cell'
    }
  }, {
    module: 'ARIA',
    concept: {
      name: 'gridcell'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'td'
    }
  }],
  type: 'widget'
};
var _default$1O = CellRole;
CellRole$1.default = _default$1O;

var CheckBoxRole$1 = {};

Object.defineProperty(CheckBoxRole$1, "__esModule", {
  value: true
});
CheckBoxRole$1.default = void 0;
var CheckBoxRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'checkbox'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'input',
      attributes: [{
        name: 'type',
        value: 'checkbox'
      }]
    }
  }],
  type: 'widget'
};
var _default$1N = CheckBoxRole;
CheckBoxRole$1.default = _default$1N;

var ColorWellRole$1 = {};

Object.defineProperty(ColorWellRole$1, "__esModule", {
  value: true
});
ColorWellRole$1.default = void 0;
var ColorWellRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'input',
      attributes: [{
        name: 'type',
        value: 'color'
      }]
    }
  }],
  type: 'widget'
};
var _default$1M = ColorWellRole;
ColorWellRole$1.default = _default$1M;

var ColumnHeaderRole$1 = {};

Object.defineProperty(ColumnHeaderRole$1, "__esModule", {
  value: true
});
ColumnHeaderRole$1.default = void 0;
var ColumnHeaderRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'columnheader'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'th'
    }
  }],
  type: 'widget'
};
var _default$1L = ColumnHeaderRole;
ColumnHeaderRole$1.default = _default$1L;

var ColumnRole$1 = {};

Object.defineProperty(ColumnRole$1, "__esModule", {
  value: true
});
ColumnRole$1.default = void 0;
var ColumnRole = {
  relatedConcepts: [],
  type: 'structure'
};
var _default$1K = ColumnRole;
ColumnRole$1.default = _default$1K;

var ComboBoxRole$1 = {};

Object.defineProperty(ComboBoxRole$1, "__esModule", {
  value: true
});
ComboBoxRole$1.default = void 0;
var ComboBoxRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'combobox'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'select'
    }
  }],
  type: 'widget'
};
var _default$1J = ComboBoxRole;
ComboBoxRole$1.default = _default$1J;

var ComplementaryRole$1 = {};

Object.defineProperty(ComplementaryRole$1, "__esModule", {
  value: true
});
ComplementaryRole$1.default = void 0;
var ComplementaryRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'complementary'
    }
  }],
  type: 'structure'
};
var _default$1I = ComplementaryRole;
ComplementaryRole$1.default = _default$1I;

var ContentInfoRole$1 = {};

Object.defineProperty(ContentInfoRole$1, "__esModule", {
  value: true
});
ContentInfoRole$1.default = void 0;
var ContentInfoRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'structureinfo'
    }
  }],
  type: 'structure'
};
var _default$1H = ContentInfoRole;
ContentInfoRole$1.default = _default$1H;

var DateRole$1 = {};

Object.defineProperty(DateRole$1, "__esModule", {
  value: true
});
DateRole$1.default = void 0;
var DateRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'input',
      attributes: [{
        name: 'type',
        value: 'date'
      }]
    }
  }],
  type: 'widget'
};
var _default$1G = DateRole;
DateRole$1.default = _default$1G;

var DateTimeRole$1 = {};

Object.defineProperty(DateTimeRole$1, "__esModule", {
  value: true
});
DateTimeRole$1.default = void 0;
var DateTimeRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'input',
      attributes: [{
        name: 'type',
        value: 'datetime'
      }]
    }
  }],
  type: 'widget'
};
var _default$1F = DateTimeRole;
DateTimeRole$1.default = _default$1F;

var DefinitionRole$1 = {};

Object.defineProperty(DefinitionRole$1, "__esModule", {
  value: true
});
DefinitionRole$1.default = void 0;
var DefinitionRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'dfn'
    }
  }],
  type: 'structure'
};
var _default$1E = DefinitionRole;
DefinitionRole$1.default = _default$1E;

var DescriptionListDetailRole$1 = {};

Object.defineProperty(DescriptionListDetailRole$1, "__esModule", {
  value: true
});
DescriptionListDetailRole$1.default = void 0;
var DescriptionListDetailRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'dd'
    }
  }],
  type: 'structure'
};
var _default$1D = DescriptionListDetailRole;
DescriptionListDetailRole$1.default = _default$1D;

var DescriptionListRole$1 = {};

Object.defineProperty(DescriptionListRole$1, "__esModule", {
  value: true
});
DescriptionListRole$1.default = void 0;
var DescriptionListRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'dl'
    }
  }],
  type: 'structure'
};
var _default$1C = DescriptionListRole;
DescriptionListRole$1.default = _default$1C;

var DescriptionListTermRole$1 = {};

Object.defineProperty(DescriptionListTermRole$1, "__esModule", {
  value: true
});
DescriptionListTermRole$1.default = void 0;
var DescriptionListTermRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'dt'
    }
  }],
  type: 'structure'
};
var _default$1B = DescriptionListTermRole;
DescriptionListTermRole$1.default = _default$1B;

var DetailsRole$1 = {};

Object.defineProperty(DetailsRole$1, "__esModule", {
  value: true
});
DetailsRole$1.default = void 0;
var DetailsRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'details'
    }
  }],
  type: 'structure'
};
var _default$1A = DetailsRole;
DetailsRole$1.default = _default$1A;

var DialogRole$1 = {};

Object.defineProperty(DialogRole$1, "__esModule", {
  value: true
});
DialogRole$1.default = void 0;
var DialogRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'dialog'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'dialog'
    }
  }],
  type: 'window'
};
var _default$1z = DialogRole;
DialogRole$1.default = _default$1z;

var DirectoryRole$1 = {};

Object.defineProperty(DirectoryRole$1, "__esModule", {
  value: true
});
DirectoryRole$1.default = void 0;
var DirectoryRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'directory'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'dir'
    }
  }],
  type: 'structure'
};
var _default$1y = DirectoryRole;
DirectoryRole$1.default = _default$1y;

var DisclosureTriangleRole$1 = {};

Object.defineProperty(DisclosureTriangleRole$1, "__esModule", {
  value: true
});
DisclosureTriangleRole$1.default = void 0;
var DisclosureTriangleRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      attributes: [{
        name: 'open',
        value: 'open'
      }],
      constraints: ['scoped to a details element'],
      name: 'summary'
    }
  }, {
    module: 'HTML',
    concept: {
      attributes: [{
        name: 'aria-expanded'
      }],
      constraints: ['scoped to a details element'],
      name: 'summary'
    }
  }],
  type: 'widget'
};
var _default$1x = DisclosureTriangleRole;
DisclosureTriangleRole$1.default = _default$1x;

var DivRole$1 = {};

Object.defineProperty(DivRole$1, "__esModule", {
  value: true
});
DivRole$1.default = void 0;
var DivRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'div'
    }
  }],
  type: 'generic'
};
var _default$1w = DivRole;
DivRole$1.default = _default$1w;

var DocumentRole$1 = {};

Object.defineProperty(DocumentRole$1, "__esModule", {
  value: true
});
DocumentRole$1.default = void 0;
var DocumentRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'document'
    }
  }],
  type: 'structure'
};
var _default$1v = DocumentRole;
DocumentRole$1.default = _default$1v;

var EmbeddedObjectRole$1 = {};

Object.defineProperty(EmbeddedObjectRole$1, "__esModule", {
  value: true
});
EmbeddedObjectRole$1.default = void 0;
var EmbeddedObjectRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'embed'
    }
  }],
  type: 'widget'
};
var _default$1u = EmbeddedObjectRole;
EmbeddedObjectRole$1.default = _default$1u;

var FeedRole$1 = {};

Object.defineProperty(FeedRole$1, "__esModule", {
  value: true
});
FeedRole$1.default = void 0;
var FeedRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'feed'
    }
  }],
  type: 'structure'
};
var _default$1t = FeedRole;
FeedRole$1.default = _default$1t;

var FigcaptionRole$1 = {};

Object.defineProperty(FigcaptionRole$1, "__esModule", {
  value: true
});
FigcaptionRole$1.default = void 0;
var FigcaptionRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'figcaption'
    }
  }],
  type: 'structure'
};
var _default$1s = FigcaptionRole;
FigcaptionRole$1.default = _default$1s;

var FigureRole$1 = {};

Object.defineProperty(FigureRole$1, "__esModule", {
  value: true
});
FigureRole$1.default = void 0;
var FigureRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'figure'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'figure'
    }
  }],
  type: 'structure'
};
var _default$1r = FigureRole;
FigureRole$1.default = _default$1r;

var FooterRole$1 = {};

Object.defineProperty(FooterRole$1, "__esModule", {
  value: true
});
FooterRole$1.default = void 0;
var FooterRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'footer'
    }
  }],
  type: 'structure'
};
var _default$1q = FooterRole;
FooterRole$1.default = _default$1q;

var FormRole$1 = {};

Object.defineProperty(FormRole$1, "__esModule", {
  value: true
});
FormRole$1.default = void 0;
var FormRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'form'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'form'
    }
  }],
  type: 'structure'
};
var _default$1p = FormRole;
FormRole$1.default = _default$1p;

var GridRole$1 = {};

Object.defineProperty(GridRole$1, "__esModule", {
  value: true
});
GridRole$1.default = void 0;
var GridRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'grid'
    }
  }],
  type: 'widget'
};
var _default$1o = GridRole;
GridRole$1.default = _default$1o;

var GroupRole$1 = {};

Object.defineProperty(GroupRole$1, "__esModule", {
  value: true
});
GroupRole$1.default = void 0;
var GroupRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'group'
    }
  }],
  type: 'structure'
};
var _default$1n = GroupRole;
GroupRole$1.default = _default$1n;

var HeadingRole$1 = {};

Object.defineProperty(HeadingRole$1, "__esModule", {
  value: true
});
HeadingRole$1.default = void 0;
var HeadingRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'heading'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'h1'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'h2'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'h3'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'h4'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'h5'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'h6'
    }
  }],
  type: 'structure'
};
var _default$1m = HeadingRole;
HeadingRole$1.default = _default$1m;

var IframePresentationalRole$1 = {};

Object.defineProperty(IframePresentationalRole$1, "__esModule", {
  value: true
});
IframePresentationalRole$1.default = void 0;
var IframePresentationalRole = {
  relatedConcepts: [],
  type: 'window'
};
var _default$1l = IframePresentationalRole;
IframePresentationalRole$1.default = _default$1l;

var IframeRole$1 = {};

Object.defineProperty(IframeRole$1, "__esModule", {
  value: true
});
IframeRole$1.default = void 0;
var IframeRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'iframe'
    }
  }],
  type: 'window'
};
var _default$1k = IframeRole;
IframeRole$1.default = _default$1k;

var IgnoredRole$1 = {};

Object.defineProperty(IgnoredRole$1, "__esModule", {
  value: true
});
IgnoredRole$1.default = void 0;
var IgnoredRole = {
  relatedConcepts: [],
  type: 'structure'
};
var _default$1j = IgnoredRole;
IgnoredRole$1.default = _default$1j;

var ImageMapLinkRole$1 = {};

Object.defineProperty(ImageMapLinkRole$1, "__esModule", {
  value: true
});
ImageMapLinkRole$1.default = void 0;
var ImageMapLinkRole = {
  relatedConcepts: [],
  type: 'widget'
};
var _default$1i = ImageMapLinkRole;
ImageMapLinkRole$1.default = _default$1i;

var ImageMapRole$1 = {};

Object.defineProperty(ImageMapRole$1, "__esModule", {
  value: true
});
ImageMapRole$1.default = void 0;
var ImageMapRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'img',
      attributes: [{
        name: 'usemap'
      }]
    }
  }],
  type: 'structure'
};
var _default$1h = ImageMapRole;
ImageMapRole$1.default = _default$1h;

var ImageRole$1 = {};

Object.defineProperty(ImageRole$1, "__esModule", {
  value: true
});
ImageRole$1.default = void 0;
var ImageRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'img'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'img'
    }
  }],
  type: 'structure'
};
var _default$1g = ImageRole;
ImageRole$1.default = _default$1g;

var InlineTextBoxRole$1 = {};

Object.defineProperty(InlineTextBoxRole$1, "__esModule", {
  value: true
});
InlineTextBoxRole$1.default = void 0;
var InlineTextBoxRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'input'
    }
  }],
  type: 'widget'
};
var _default$1f = InlineTextBoxRole;
InlineTextBoxRole$1.default = _default$1f;

var InputTimeRole$1 = {};

Object.defineProperty(InputTimeRole$1, "__esModule", {
  value: true
});
InputTimeRole$1.default = void 0;
var InputTimeRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'input',
      attributes: [{
        name: 'type',
        value: 'time'
      }]
    }
  }],
  type: 'widget'
};
var _default$1e = InputTimeRole;
InputTimeRole$1.default = _default$1e;

var LabelRole$1 = {};

Object.defineProperty(LabelRole$1, "__esModule", {
  value: true
});
LabelRole$1.default = void 0;
var LabelRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'label'
    }
  }],
  type: 'structure'
};
var _default$1d = LabelRole;
LabelRole$1.default = _default$1d;

var LegendRole$1 = {};

Object.defineProperty(LegendRole$1, "__esModule", {
  value: true
});
LegendRole$1.default = void 0;
var LegendRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'legend'
    }
  }],
  type: 'structure'
};
var _default$1c = LegendRole;
LegendRole$1.default = _default$1c;

var LineBreakRole$1 = {};

Object.defineProperty(LineBreakRole$1, "__esModule", {
  value: true
});
LineBreakRole$1.default = void 0;
var LineBreakRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'br'
    }
  }],
  type: 'structure'
};
var _default$1b = LineBreakRole;
LineBreakRole$1.default = _default$1b;

var LinkRole$1 = {};

Object.defineProperty(LinkRole$1, "__esModule", {
  value: true
});
LinkRole$1.default = void 0;
var LinkRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'link'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'a',
      attributes: [{
        name: 'href'
      }]
    }
  }],
  type: 'widget'
};
var _default$1a = LinkRole;
LinkRole$1.default = _default$1a;

var ListBoxOptionRole$1 = {};

Object.defineProperty(ListBoxOptionRole$1, "__esModule", {
  value: true
});
ListBoxOptionRole$1.default = void 0;
var ListBoxOptionRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'option'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'option'
    }
  }],
  type: 'widget'
};
var _default$19 = ListBoxOptionRole;
ListBoxOptionRole$1.default = _default$19;

var ListBoxRole$1 = {};

Object.defineProperty(ListBoxRole$1, "__esModule", {
  value: true
});
ListBoxRole$1.default = void 0;
var ListBoxRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'listbox'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'datalist'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'select'
    }
  }],
  type: 'widget'
};
var _default$18 = ListBoxRole;
ListBoxRole$1.default = _default$18;

var ListItemRole$1 = {};

Object.defineProperty(ListItemRole$1, "__esModule", {
  value: true
});
ListItemRole$1.default = void 0;
var ListItemRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'listitem'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'li'
    }
  }],
  type: 'structure'
};
var _default$17 = ListItemRole;
ListItemRole$1.default = _default$17;

var ListMarkerRole$1 = {};

Object.defineProperty(ListMarkerRole$1, "__esModule", {
  value: true
});
ListMarkerRole$1.default = void 0;
var ListMarkerRole = {
  relatedConcepts: [],
  type: 'structure'
};
var _default$16 = ListMarkerRole;
ListMarkerRole$1.default = _default$16;

var ListRole$1 = {};

Object.defineProperty(ListRole$1, "__esModule", {
  value: true
});
ListRole$1.default = void 0;
var ListRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'list'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'ul'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'ol'
    }
  }],
  type: 'structure'
};
var _default$15 = ListRole;
ListRole$1.default = _default$15;

var LogRole$1 = {};

Object.defineProperty(LogRole$1, "__esModule", {
  value: true
});
LogRole$1.default = void 0;
var LogRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'log'
    }
  }],
  type: 'structure'
};
var _default$14 = LogRole;
LogRole$1.default = _default$14;

var MainRole$1 = {};

Object.defineProperty(MainRole$1, "__esModule", {
  value: true
});
MainRole$1.default = void 0;
var MainRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'main'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'main'
    }
  }],
  type: 'structure'
};
var _default$13 = MainRole;
MainRole$1.default = _default$13;

var MarkRole$1 = {};

Object.defineProperty(MarkRole$1, "__esModule", {
  value: true
});
MarkRole$1.default = void 0;
var MarkRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'mark'
    }
  }],
  type: 'structure'
};
var _default$12 = MarkRole;
MarkRole$1.default = _default$12;

var MarqueeRole$1 = {};

Object.defineProperty(MarqueeRole$1, "__esModule", {
  value: true
});
MarqueeRole$1.default = void 0;
var MarqueeRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'marquee'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'marquee'
    }
  }],
  type: 'structure'
};
var _default$11 = MarqueeRole;
MarqueeRole$1.default = _default$11;

var MathRole$1 = {};

Object.defineProperty(MathRole$1, "__esModule", {
  value: true
});
MathRole$1.default = void 0;
var MathRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'math'
    }
  }],
  type: 'structure'
};
var _default$10 = MathRole;
MathRole$1.default = _default$10;

var MenuBarRole$1 = {};

Object.defineProperty(MenuBarRole$1, "__esModule", {
  value: true
});
MenuBarRole$1.default = void 0;
var MenuBarRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'menubar'
    }
  }],
  type: 'structure'
};
var _default$$ = MenuBarRole;
MenuBarRole$1.default = _default$$;

var MenuButtonRole$1 = {};

Object.defineProperty(MenuButtonRole$1, "__esModule", {
  value: true
});
MenuButtonRole$1.default = void 0;
var MenuButtonRole = {
  relatedConcepts: [],
  type: 'widget'
};
var _default$_ = MenuButtonRole;
MenuButtonRole$1.default = _default$_;

var MenuItemRole$1 = {};

Object.defineProperty(MenuItemRole$1, "__esModule", {
  value: true
});
MenuItemRole$1.default = void 0;
var MenuItemRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'menuitem'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'menuitem'
    }
  }],
  type: 'widget'
};
var _default$Z = MenuItemRole;
MenuItemRole$1.default = _default$Z;

var MenuItemCheckBoxRole$1 = {};

Object.defineProperty(MenuItemCheckBoxRole$1, "__esModule", {
  value: true
});
MenuItemCheckBoxRole$1.default = void 0;
var MenuItemCheckBoxRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'menuitemcheckbox'
    }
  }],
  type: 'widget'
};
var _default$Y = MenuItemCheckBoxRole;
MenuItemCheckBoxRole$1.default = _default$Y;

var MenuItemRadioRole$1 = {};

Object.defineProperty(MenuItemRadioRole$1, "__esModule", {
  value: true
});
MenuItemRadioRole$1.default = void 0;
var MenuItemRadioRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'menuitemradio'
    }
  }],
  type: 'widget'
};
var _default$X = MenuItemRadioRole;
MenuItemRadioRole$1.default = _default$X;

var MenuListOptionRole$1 = {};

Object.defineProperty(MenuListOptionRole$1, "__esModule", {
  value: true
});
MenuListOptionRole$1.default = void 0;
var MenuListOptionRole = {
  relatedConcepts: [],
  type: 'widget'
};
var _default$W = MenuListOptionRole;
MenuListOptionRole$1.default = _default$W;

var MenuListPopupRole$1 = {};

Object.defineProperty(MenuListPopupRole$1, "__esModule", {
  value: true
});
MenuListPopupRole$1.default = void 0;
var MenuListPopupRole = {
  relatedConcepts: [],
  type: 'widget'
};
var _default$V = MenuListPopupRole;
MenuListPopupRole$1.default = _default$V;

var MenuRole$1 = {};

Object.defineProperty(MenuRole$1, "__esModule", {
  value: true
});
MenuRole$1.default = void 0;
var MenuRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'menu'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'menu'
    }
  }],
  type: 'structure'
};
var _default$U = MenuRole;
MenuRole$1.default = _default$U;

var MeterRole$1 = {};

Object.defineProperty(MeterRole$1, "__esModule", {
  value: true
});
MeterRole$1.default = void 0;
var MeterRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'meter'
    }
  }],
  type: 'structure'
};
var _default$T = MeterRole;
MeterRole$1.default = _default$T;

var NavigationRole$1 = {};

Object.defineProperty(NavigationRole$1, "__esModule", {
  value: true
});
NavigationRole$1.default = void 0;
var NavigationRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'navigation'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'nav'
    }
  }],
  type: 'structure'
};
var _default$S = NavigationRole;
NavigationRole$1.default = _default$S;

var NoneRole$1 = {};

Object.defineProperty(NoneRole$1, "__esModule", {
  value: true
});
NoneRole$1.default = void 0;
var NoneRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'none'
    }
  }],
  type: 'structure'
};
var _default$R = NoneRole;
NoneRole$1.default = _default$R;

var NoteRole$1 = {};

Object.defineProperty(NoteRole$1, "__esModule", {
  value: true
});
NoteRole$1.default = void 0;
var NoteRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'note'
    }
  }],
  type: 'structure'
};
var _default$Q = NoteRole;
NoteRole$1.default = _default$Q;

var OutlineRole$1 = {};

Object.defineProperty(OutlineRole$1, "__esModule", {
  value: true
});
OutlineRole$1.default = void 0;
var OutlineRole = {
  relatedConcepts: [],
  type: 'structure'
};
var _default$P = OutlineRole;
OutlineRole$1.default = _default$P;

var ParagraphRole$1 = {};

Object.defineProperty(ParagraphRole$1, "__esModule", {
  value: true
});
ParagraphRole$1.default = void 0;
var ParagraphRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'p'
    }
  }],
  type: 'structure'
};
var _default$O = ParagraphRole;
ParagraphRole$1.default = _default$O;

var PopUpButtonRole$1 = {};

Object.defineProperty(PopUpButtonRole$1, "__esModule", {
  value: true
});
PopUpButtonRole$1.default = void 0;
var PopUpButtonRole = {
  relatedConcepts: [],
  type: 'widget'
};
var _default$N = PopUpButtonRole;
PopUpButtonRole$1.default = _default$N;

var PreRole$1 = {};

Object.defineProperty(PreRole$1, "__esModule", {
  value: true
});
PreRole$1.default = void 0;
var PreRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'pre'
    }
  }],
  type: 'structure'
};
var _default$M = PreRole;
PreRole$1.default = _default$M;

var PresentationalRole$1 = {};

Object.defineProperty(PresentationalRole$1, "__esModule", {
  value: true
});
PresentationalRole$1.default = void 0;
var PresentationalRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'presentation'
    }
  }],
  type: 'structure'
};
var _default$L = PresentationalRole;
PresentationalRole$1.default = _default$L;

var ProgressIndicatorRole$1 = {};

Object.defineProperty(ProgressIndicatorRole$1, "__esModule", {
  value: true
});
ProgressIndicatorRole$1.default = void 0;
var ProgressIndicatorRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'progressbar'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'progress'
    }
  }],
  type: 'structure'
};
var _default$K = ProgressIndicatorRole;
ProgressIndicatorRole$1.default = _default$K;

var RadioButtonRole$1 = {};

Object.defineProperty(RadioButtonRole$1, "__esModule", {
  value: true
});
RadioButtonRole$1.default = void 0;
var RadioButtonRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'radio'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'input',
      attributes: [{
        name: 'type',
        value: 'radio'
      }]
    }
  }],
  type: 'widget'
};
var _default$J = RadioButtonRole;
RadioButtonRole$1.default = _default$J;

var RadioGroupRole$1 = {};

Object.defineProperty(RadioGroupRole$1, "__esModule", {
  value: true
});
RadioGroupRole$1.default = void 0;
var RadioGroupRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'radiogroup'
    }
  }],
  type: 'structure'
};
var _default$I = RadioGroupRole;
RadioGroupRole$1.default = _default$I;

var RegionRole$1 = {};

Object.defineProperty(RegionRole$1, "__esModule", {
  value: true
});
RegionRole$1.default = void 0;
var RegionRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'region'
    }
  }],
  type: 'structure'
};
var _default$H = RegionRole;
RegionRole$1.default = _default$H;

var RootWebAreaRole$1 = {};

Object.defineProperty(RootWebAreaRole$1, "__esModule", {
  value: true
});
RootWebAreaRole$1.default = void 0;
var RootWebAreaRole = {
  relatedConcepts: [],
  type: 'structure'
};
var _default$G = RootWebAreaRole;
RootWebAreaRole$1.default = _default$G;

var RowHeaderRole$1 = {};

Object.defineProperty(RowHeaderRole$1, "__esModule", {
  value: true
});
RowHeaderRole$1.default = void 0;
var RowHeaderRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'rowheader'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'th',
      attributes: [{
        name: 'scope',
        value: 'row'
      }]
    }
  }],
  type: 'widget'
};
var _default$F = RowHeaderRole;
RowHeaderRole$1.default = _default$F;

var RowRole$1 = {};

Object.defineProperty(RowRole$1, "__esModule", {
  value: true
});
RowRole$1.default = void 0;
var RowRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'row'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'tr'
    }
  }],
  type: 'structure'
};
var _default$E = RowRole;
RowRole$1.default = _default$E;

var RubyRole$1 = {};

Object.defineProperty(RubyRole$1, "__esModule", {
  value: true
});
RubyRole$1.default = void 0;
var RubyRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'ruby'
    }
  }],
  type: 'structure'
};
var _default$D = RubyRole;
RubyRole$1.default = _default$D;

var RulerRole$1 = {};

Object.defineProperty(RulerRole$1, "__esModule", {
  value: true
});
RulerRole$1.default = void 0;
var RulerRole = {
  relatedConcepts: [],
  type: 'structure'
};
var _default$C = RulerRole;
RulerRole$1.default = _default$C;

var ScrollAreaRole$1 = {};

Object.defineProperty(ScrollAreaRole$1, "__esModule", {
  value: true
});
ScrollAreaRole$1.default = void 0;
var ScrollAreaRole = {
  relatedConcepts: [],
  type: 'structure'
};
var _default$B = ScrollAreaRole;
ScrollAreaRole$1.default = _default$B;

var ScrollBarRole$1 = {};

Object.defineProperty(ScrollBarRole$1, "__esModule", {
  value: true
});
ScrollBarRole$1.default = void 0;
var ScrollBarRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'scrollbar'
    }
  }],
  type: 'widget'
};
var _default$A = ScrollBarRole;
ScrollBarRole$1.default = _default$A;

var SeamlessWebAreaRole$1 = {};

Object.defineProperty(SeamlessWebAreaRole$1, "__esModule", {
  value: true
});
SeamlessWebAreaRole$1.default = void 0;
var SeamlessWebAreaRole = {
  relatedConcepts: [],
  type: 'structure'
};
var _default$z = SeamlessWebAreaRole;
SeamlessWebAreaRole$1.default = _default$z;

var SearchRole$1 = {};

Object.defineProperty(SearchRole$1, "__esModule", {
  value: true
});
SearchRole$1.default = void 0;
var SearchRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'search'
    }
  }],
  type: 'structure'
};
var _default$y = SearchRole;
SearchRole$1.default = _default$y;

var SearchBoxRole$1 = {};

Object.defineProperty(SearchBoxRole$1, "__esModule", {
  value: true
});
SearchBoxRole$1.default = void 0;
var SearchBoxRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'searchbox'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'input',
      attributes: [{
        name: 'type',
        value: 'search'
      }]
    }
  }],
  type: 'widget'
};
var _default$x = SearchBoxRole;
SearchBoxRole$1.default = _default$x;

var SliderRole$1 = {};

Object.defineProperty(SliderRole$1, "__esModule", {
  value: true
});
SliderRole$1.default = void 0;
var SliderRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'slider'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'input',
      attributes: [{
        name: 'type',
        value: 'range'
      }]
    }
  }],
  type: 'widget'
};
var _default$w = SliderRole;
SliderRole$1.default = _default$w;

var SliderThumbRole$1 = {};

Object.defineProperty(SliderThumbRole$1, "__esModule", {
  value: true
});
SliderThumbRole$1.default = void 0;
var SliderThumbRole = {
  relatedConcepts: [],
  type: 'structure'
};
var _default$v = SliderThumbRole;
SliderThumbRole$1.default = _default$v;

var SpinButtonRole$1 = {};

Object.defineProperty(SpinButtonRole$1, "__esModule", {
  value: true
});
SpinButtonRole$1.default = void 0;
var SpinButtonRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'spinbutton'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'input',
      attributes: [{
        name: 'type',
        value: 'number'
      }]
    }
  }],
  type: 'widget'
};
var _default$u = SpinButtonRole;
SpinButtonRole$1.default = _default$u;

var SpinButtonPartRole$1 = {};

Object.defineProperty(SpinButtonPartRole$1, "__esModule", {
  value: true
});
SpinButtonPartRole$1.default = void 0;
var SpinButtonPartRole = {
  relatedConcepts: [],
  type: 'structure'
};
var _default$t = SpinButtonPartRole;
SpinButtonPartRole$1.default = _default$t;

var SplitterRole$1 = {};

Object.defineProperty(SplitterRole$1, "__esModule", {
  value: true
});
SplitterRole$1.default = void 0;
var SplitterRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'separator'
    }
  }],
  type: 'widget'
};
var _default$s = SplitterRole;
SplitterRole$1.default = _default$s;

var StaticTextRole$1 = {};

Object.defineProperty(StaticTextRole$1, "__esModule", {
  value: true
});
StaticTextRole$1.default = void 0;
var StaticTextRole = {
  relatedConcepts: [],
  type: 'structure'
};
var _default$r = StaticTextRole;
StaticTextRole$1.default = _default$r;

var StatusRole$1 = {};

Object.defineProperty(StatusRole$1, "__esModule", {
  value: true
});
StatusRole$1.default = void 0;
var StatusRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'status'
    }
  }],
  type: 'structure'
};
var _default$q = StatusRole;
StatusRole$1.default = _default$q;

var SVGRootRole$1 = {};

Object.defineProperty(SVGRootRole$1, "__esModule", {
  value: true
});
SVGRootRole$1.default = void 0;
var SVGRootRole = {
  relatedConcepts: [],
  type: 'structure'
};
var _default$p = SVGRootRole;
SVGRootRole$1.default = _default$p;

var SwitchRole$1 = {};

Object.defineProperty(SwitchRole$1, "__esModule", {
  value: true
});
SwitchRole$1.default = void 0;
var SwitchRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'switch'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'input',
      attributes: [{
        name: 'type',
        value: 'checkbox'
      }]
    }
  }],
  type: 'widget'
};
var _default$o = SwitchRole;
SwitchRole$1.default = _default$o;

var TabGroupRole$1 = {};

Object.defineProperty(TabGroupRole$1, "__esModule", {
  value: true
});
TabGroupRole$1.default = void 0;
var TabGroupRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'tablist'
    }
  }],
  type: 'structure'
};
var _default$n = TabGroupRole;
TabGroupRole$1.default = _default$n;

var TabRole$1 = {};

Object.defineProperty(TabRole$1, "__esModule", {
  value: true
});
TabRole$1.default = void 0;
var TabRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'tab'
    }
  }],
  type: 'widget'
};
var _default$m = TabRole;
TabRole$1.default = _default$m;

var TableHeaderContainerRole$1 = {};

Object.defineProperty(TableHeaderContainerRole$1, "__esModule", {
  value: true
});
TableHeaderContainerRole$1.default = void 0;
var TableHeaderContainerRole = {
  relatedConcepts: [],
  type: 'structure'
};
var _default$l = TableHeaderContainerRole;
TableHeaderContainerRole$1.default = _default$l;

var TableRole$1 = {};

Object.defineProperty(TableRole$1, "__esModule", {
  value: true
});
TableRole$1.default = void 0;
var TableRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'table'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'table'
    }
  }],
  type: 'structure'
};
var _default$k = TableRole;
TableRole$1.default = _default$k;

var TabListRole$1 = {};

Object.defineProperty(TabListRole$1, "__esModule", {
  value: true
});
TabListRole$1.default = void 0;
var TabListRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'tablist'
    }
  }],
  type: 'structure'
};
var _default$j = TabListRole;
TabListRole$1.default = _default$j;

var TabPanelRole$1 = {};

Object.defineProperty(TabPanelRole$1, "__esModule", {
  value: true
});
TabPanelRole$1.default = void 0;
var TabPanelRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'tabpanel'
    }
  }],
  type: 'structure'
};
var _default$i = TabPanelRole;
TabPanelRole$1.default = _default$i;

var TermRole$1 = {};

Object.defineProperty(TermRole$1, "__esModule", {
  value: true
});
TermRole$1.default = void 0;
var TermRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'term'
    }
  }],
  type: 'structure'
};
var _default$h = TermRole;
TermRole$1.default = _default$h;

var TextAreaRole$1 = {};

Object.defineProperty(TextAreaRole$1, "__esModule", {
  value: true
});
TextAreaRole$1.default = void 0;
var TextAreaRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      attributes: [{
        name: 'aria-multiline',
        value: 'true'
      }],
      name: 'textbox'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'textarea'
    }
  }],
  type: 'widget'
};
var _default$g = TextAreaRole;
TextAreaRole$1.default = _default$g;

var TextFieldRole$1 = {};

Object.defineProperty(TextFieldRole$1, "__esModule", {
  value: true
});
TextFieldRole$1.default = void 0;
var TextFieldRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'textbox'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'input'
    }
  }, {
    module: 'HTML',
    concept: {
      name: 'input',
      attributes: [{
        name: 'type',
        value: 'text'
      }]
    }
  }],
  type: 'widget'
};
var _default$f = TextFieldRole;
TextFieldRole$1.default = _default$f;

var TimeRole$1 = {};

Object.defineProperty(TimeRole$1, "__esModule", {
  value: true
});
TimeRole$1.default = void 0;
var TimeRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'time'
    }
  }],
  type: 'structure'
};
var _default$e = TimeRole;
TimeRole$1.default = _default$e;

var TimerRole$1 = {};

Object.defineProperty(TimerRole$1, "__esModule", {
  value: true
});
TimerRole$1.default = void 0;
var TimerRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'timer'
    }
  }],
  type: 'structure'
};
var _default$d = TimerRole;
TimerRole$1.default = _default$d;

var ToggleButtonRole$1 = {};

Object.defineProperty(ToggleButtonRole$1, "__esModule", {
  value: true
});
ToggleButtonRole$1.default = void 0;
var ToggleButtonRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      attributes: [{
        name: 'aria-pressed'
      }]
    }
  }],
  type: 'widget'
};
var _default$c = ToggleButtonRole;
ToggleButtonRole$1.default = _default$c;

var ToolbarRole$1 = {};

Object.defineProperty(ToolbarRole$1, "__esModule", {
  value: true
});
ToolbarRole$1.default = void 0;
var ToolbarRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'toolbar'
    }
  }],
  type: 'structure'
};
var _default$b = ToolbarRole;
ToolbarRole$1.default = _default$b;

var TreeRole$1 = {};

Object.defineProperty(TreeRole$1, "__esModule", {
  value: true
});
TreeRole$1.default = void 0;
var TreeRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'tree'
    }
  }],
  type: 'widget'
};
var _default$a = TreeRole;
TreeRole$1.default = _default$a;

var TreeGridRole$1 = {};

Object.defineProperty(TreeGridRole$1, "__esModule", {
  value: true
});
TreeGridRole$1.default = void 0;
var TreeGridRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'treegrid'
    }
  }],
  type: 'widget'
};
var _default$9 = TreeGridRole;
TreeGridRole$1.default = _default$9;

var TreeItemRole$1 = {};

Object.defineProperty(TreeItemRole$1, "__esModule", {
  value: true
});
TreeItemRole$1.default = void 0;
var TreeItemRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'treeitem'
    }
  }],
  type: 'widget'
};
var _default$8 = TreeItemRole;
TreeItemRole$1.default = _default$8;

var UserInterfaceTooltipRole$1 = {};

Object.defineProperty(UserInterfaceTooltipRole$1, "__esModule", {
  value: true
});
UserInterfaceTooltipRole$1.default = void 0;
var UserInterfaceTooltipRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'tooltip'
    }
  }],
  type: 'structure'
};
var _default$7 = UserInterfaceTooltipRole;
UserInterfaceTooltipRole$1.default = _default$7;

var VideoRole$1 = {};

Object.defineProperty(VideoRole$1, "__esModule", {
  value: true
});
VideoRole$1.default = void 0;
var VideoRole = {
  relatedConcepts: [{
    module: 'HTML',
    concept: {
      name: 'video'
    }
  }],
  type: 'widget'
};
var _default$6 = VideoRole;
VideoRole$1.default = _default$6;

var WebAreaRole$1 = {};

Object.defineProperty(WebAreaRole$1, "__esModule", {
  value: true
});
WebAreaRole$1.default = void 0;
var WebAreaRole = {
  relatedConcepts: [],
  type: 'structure'
};
var _default$5 = WebAreaRole;
WebAreaRole$1.default = _default$5;

var WindowRole$1 = {};

Object.defineProperty(WindowRole$1, "__esModule", {
  value: true
});
WindowRole$1.default = void 0;
var WindowRole = {
  relatedConcepts: [],
  type: 'window'
};
var _default$4 = WindowRole;
WindowRole$1.default = _default$4;

Object.defineProperty(AXObjectsMap$1, "__esModule", {
  value: true
});
AXObjectsMap$1.default = void 0;
var _iterationDecorator$3 = _interopRequireDefault$4(iterationDecorator$1);
var _AbbrRole = _interopRequireDefault$4(AbbrRole$1);
var _AlertDialogRole = _interopRequireDefault$4(AlertDialogRole$1);
var _AlertRole = _interopRequireDefault$4(AlertRole$1);
var _AnnotationRole = _interopRequireDefault$4(AnnotationRole$1);
var _ApplicationRole = _interopRequireDefault$4(ApplicationRole$1);
var _ArticleRole = _interopRequireDefault$4(ArticleRole$1);
var _AudioRole = _interopRequireDefault$4(AudioRole$1);
var _BannerRole = _interopRequireDefault$4(BannerRole$1);
var _BlockquoteRole = _interopRequireDefault$4(BlockquoteRole$1);
var _BusyIndicatorRole = _interopRequireDefault$4(BusyIndicatorRole$1);
var _ButtonRole = _interopRequireDefault$4(ButtonRole$1);
var _CanvasRole = _interopRequireDefault$4(CanvasRole$1);
var _CaptionRole = _interopRequireDefault$4(CaptionRole$1);
var _CellRole = _interopRequireDefault$4(CellRole$1);
var _CheckBoxRole = _interopRequireDefault$4(CheckBoxRole$1);
var _ColorWellRole = _interopRequireDefault$4(ColorWellRole$1);
var _ColumnHeaderRole = _interopRequireDefault$4(ColumnHeaderRole$1);
var _ColumnRole = _interopRequireDefault$4(ColumnRole$1);
var _ComboBoxRole = _interopRequireDefault$4(ComboBoxRole$1);
var _ComplementaryRole = _interopRequireDefault$4(ComplementaryRole$1);
var _ContentInfoRole = _interopRequireDefault$4(ContentInfoRole$1);
var _DateRole = _interopRequireDefault$4(DateRole$1);
var _DateTimeRole = _interopRequireDefault$4(DateTimeRole$1);
var _DefinitionRole = _interopRequireDefault$4(DefinitionRole$1);
var _DescriptionListDetailRole = _interopRequireDefault$4(DescriptionListDetailRole$1);
var _DescriptionListRole = _interopRequireDefault$4(DescriptionListRole$1);
var _DescriptionListTermRole = _interopRequireDefault$4(DescriptionListTermRole$1);
var _DetailsRole = _interopRequireDefault$4(DetailsRole$1);
var _DialogRole = _interopRequireDefault$4(DialogRole$1);
var _DirectoryRole = _interopRequireDefault$4(DirectoryRole$1);
var _DisclosureTriangleRole = _interopRequireDefault$4(DisclosureTriangleRole$1);
var _DivRole = _interopRequireDefault$4(DivRole$1);
var _DocumentRole = _interopRequireDefault$4(DocumentRole$1);
var _EmbeddedObjectRole = _interopRequireDefault$4(EmbeddedObjectRole$1);
var _FeedRole = _interopRequireDefault$4(FeedRole$1);
var _FigcaptionRole = _interopRequireDefault$4(FigcaptionRole$1);
var _FigureRole = _interopRequireDefault$4(FigureRole$1);
var _FooterRole = _interopRequireDefault$4(FooterRole$1);
var _FormRole = _interopRequireDefault$4(FormRole$1);
var _GridRole = _interopRequireDefault$4(GridRole$1);
var _GroupRole = _interopRequireDefault$4(GroupRole$1);
var _HeadingRole = _interopRequireDefault$4(HeadingRole$1);
var _IframePresentationalRole = _interopRequireDefault$4(IframePresentationalRole$1);
var _IframeRole = _interopRequireDefault$4(IframeRole$1);
var _IgnoredRole = _interopRequireDefault$4(IgnoredRole$1);
var _ImageMapLinkRole = _interopRequireDefault$4(ImageMapLinkRole$1);
var _ImageMapRole = _interopRequireDefault$4(ImageMapRole$1);
var _ImageRole = _interopRequireDefault$4(ImageRole$1);
var _InlineTextBoxRole = _interopRequireDefault$4(InlineTextBoxRole$1);
var _InputTimeRole = _interopRequireDefault$4(InputTimeRole$1);
var _LabelRole = _interopRequireDefault$4(LabelRole$1);
var _LegendRole = _interopRequireDefault$4(LegendRole$1);
var _LineBreakRole = _interopRequireDefault$4(LineBreakRole$1);
var _LinkRole = _interopRequireDefault$4(LinkRole$1);
var _ListBoxOptionRole = _interopRequireDefault$4(ListBoxOptionRole$1);
var _ListBoxRole = _interopRequireDefault$4(ListBoxRole$1);
var _ListItemRole = _interopRequireDefault$4(ListItemRole$1);
var _ListMarkerRole = _interopRequireDefault$4(ListMarkerRole$1);
var _ListRole = _interopRequireDefault$4(ListRole$1);
var _LogRole = _interopRequireDefault$4(LogRole$1);
var _MainRole = _interopRequireDefault$4(MainRole$1);
var _MarkRole = _interopRequireDefault$4(MarkRole$1);
var _MarqueeRole = _interopRequireDefault$4(MarqueeRole$1);
var _MathRole = _interopRequireDefault$4(MathRole$1);
var _MenuBarRole = _interopRequireDefault$4(MenuBarRole$1);
var _MenuButtonRole = _interopRequireDefault$4(MenuButtonRole$1);
var _MenuItemRole = _interopRequireDefault$4(MenuItemRole$1);
var _MenuItemCheckBoxRole = _interopRequireDefault$4(MenuItemCheckBoxRole$1);
var _MenuItemRadioRole = _interopRequireDefault$4(MenuItemRadioRole$1);
var _MenuListOptionRole = _interopRequireDefault$4(MenuListOptionRole$1);
var _MenuListPopupRole = _interopRequireDefault$4(MenuListPopupRole$1);
var _MenuRole = _interopRequireDefault$4(MenuRole$1);
var _MeterRole = _interopRequireDefault$4(MeterRole$1);
var _NavigationRole = _interopRequireDefault$4(NavigationRole$1);
var _NoneRole = _interopRequireDefault$4(NoneRole$1);
var _NoteRole = _interopRequireDefault$4(NoteRole$1);
var _OutlineRole = _interopRequireDefault$4(OutlineRole$1);
var _ParagraphRole = _interopRequireDefault$4(ParagraphRole$1);
var _PopUpButtonRole = _interopRequireDefault$4(PopUpButtonRole$1);
var _PreRole = _interopRequireDefault$4(PreRole$1);
var _PresentationalRole = _interopRequireDefault$4(PresentationalRole$1);
var _ProgressIndicatorRole = _interopRequireDefault$4(ProgressIndicatorRole$1);
var _RadioButtonRole = _interopRequireDefault$4(RadioButtonRole$1);
var _RadioGroupRole = _interopRequireDefault$4(RadioGroupRole$1);
var _RegionRole = _interopRequireDefault$4(RegionRole$1);
var _RootWebAreaRole = _interopRequireDefault$4(RootWebAreaRole$1);
var _RowHeaderRole = _interopRequireDefault$4(RowHeaderRole$1);
var _RowRole = _interopRequireDefault$4(RowRole$1);
var _RubyRole = _interopRequireDefault$4(RubyRole$1);
var _RulerRole = _interopRequireDefault$4(RulerRole$1);
var _ScrollAreaRole = _interopRequireDefault$4(ScrollAreaRole$1);
var _ScrollBarRole = _interopRequireDefault$4(ScrollBarRole$1);
var _SeamlessWebAreaRole = _interopRequireDefault$4(SeamlessWebAreaRole$1);
var _SearchRole = _interopRequireDefault$4(SearchRole$1);
var _SearchBoxRole = _interopRequireDefault$4(SearchBoxRole$1);
var _SliderRole = _interopRequireDefault$4(SliderRole$1);
var _SliderThumbRole = _interopRequireDefault$4(SliderThumbRole$1);
var _SpinButtonRole = _interopRequireDefault$4(SpinButtonRole$1);
var _SpinButtonPartRole = _interopRequireDefault$4(SpinButtonPartRole$1);
var _SplitterRole = _interopRequireDefault$4(SplitterRole$1);
var _StaticTextRole = _interopRequireDefault$4(StaticTextRole$1);
var _StatusRole = _interopRequireDefault$4(StatusRole$1);
var _SVGRootRole = _interopRequireDefault$4(SVGRootRole$1);
var _SwitchRole = _interopRequireDefault$4(SwitchRole$1);
var _TabGroupRole = _interopRequireDefault$4(TabGroupRole$1);
var _TabRole = _interopRequireDefault$4(TabRole$1);
var _TableHeaderContainerRole = _interopRequireDefault$4(TableHeaderContainerRole$1);
var _TableRole = _interopRequireDefault$4(TableRole$1);
var _TabListRole = _interopRequireDefault$4(TabListRole$1);
var _TabPanelRole = _interopRequireDefault$4(TabPanelRole$1);
var _TermRole = _interopRequireDefault$4(TermRole$1);
var _TextAreaRole = _interopRequireDefault$4(TextAreaRole$1);
var _TextFieldRole = _interopRequireDefault$4(TextFieldRole$1);
var _TimeRole = _interopRequireDefault$4(TimeRole$1);
var _TimerRole = _interopRequireDefault$4(TimerRole$1);
var _ToggleButtonRole = _interopRequireDefault$4(ToggleButtonRole$1);
var _ToolbarRole = _interopRequireDefault$4(ToolbarRole$1);
var _TreeRole = _interopRequireDefault$4(TreeRole$1);
var _TreeGridRole = _interopRequireDefault$4(TreeGridRole$1);
var _TreeItemRole = _interopRequireDefault$4(TreeItemRole$1);
var _UserInterfaceTooltipRole = _interopRequireDefault$4(UserInterfaceTooltipRole$1);
var _VideoRole = _interopRequireDefault$4(VideoRole$1);
var _WebAreaRole = _interopRequireDefault$4(WebAreaRole$1);
var _WindowRole = _interopRequireDefault$4(WindowRole$1);
function _interopRequireDefault$4(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _slicedToArray$3(arr, i) { return _arrayWithHoles$3(arr) || _iterableToArrayLimit$3(arr, i) || _unsupportedIterableToArray$3(arr, i) || _nonIterableRest$3(); }
function _nonIterableRest$3() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit$3(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles$3(arr) { if (Array.isArray(arr)) return arr; }
function _createForOfIteratorHelper$3(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$3(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray$3(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$3(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$3(o, minLen); }
function _arrayLikeToArray$3(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
var AXObjects$1 = [['AbbrRole', _AbbrRole.default], ['AlertDialogRole', _AlertDialogRole.default], ['AlertRole', _AlertRole.default], ['AnnotationRole', _AnnotationRole.default], ['ApplicationRole', _ApplicationRole.default], ['ArticleRole', _ArticleRole.default], ['AudioRole', _AudioRole.default], ['BannerRole', _BannerRole.default], ['BlockquoteRole', _BlockquoteRole.default], ['BusyIndicatorRole', _BusyIndicatorRole.default], ['ButtonRole', _ButtonRole.default], ['CanvasRole', _CanvasRole.default], ['CaptionRole', _CaptionRole.default], ['CellRole', _CellRole.default], ['CheckBoxRole', _CheckBoxRole.default], ['ColorWellRole', _ColorWellRole.default], ['ColumnHeaderRole', _ColumnHeaderRole.default], ['ColumnRole', _ColumnRole.default], ['ComboBoxRole', _ComboBoxRole.default], ['ComplementaryRole', _ComplementaryRole.default], ['ContentInfoRole', _ContentInfoRole.default], ['DateRole', _DateRole.default], ['DateTimeRole', _DateTimeRole.default], ['DefinitionRole', _DefinitionRole.default], ['DescriptionListDetailRole', _DescriptionListDetailRole.default], ['DescriptionListRole', _DescriptionListRole.default], ['DescriptionListTermRole', _DescriptionListTermRole.default], ['DetailsRole', _DetailsRole.default], ['DialogRole', _DialogRole.default], ['DirectoryRole', _DirectoryRole.default], ['DisclosureTriangleRole', _DisclosureTriangleRole.default], ['DivRole', _DivRole.default], ['DocumentRole', _DocumentRole.default], ['EmbeddedObjectRole', _EmbeddedObjectRole.default], ['FeedRole', _FeedRole.default], ['FigcaptionRole', _FigcaptionRole.default], ['FigureRole', _FigureRole.default], ['FooterRole', _FooterRole.default], ['FormRole', _FormRole.default], ['GridRole', _GridRole.default], ['GroupRole', _GroupRole.default], ['HeadingRole', _HeadingRole.default], ['IframePresentationalRole', _IframePresentationalRole.default], ['IframeRole', _IframeRole.default], ['IgnoredRole', _IgnoredRole.default], ['ImageMapLinkRole', _ImageMapLinkRole.default], ['ImageMapRole', _ImageMapRole.default], ['ImageRole', _ImageRole.default], ['InlineTextBoxRole', _InlineTextBoxRole.default], ['InputTimeRole', _InputTimeRole.default], ['LabelRole', _LabelRole.default], ['LegendRole', _LegendRole.default], ['LineBreakRole', _LineBreakRole.default], ['LinkRole', _LinkRole.default], ['ListBoxOptionRole', _ListBoxOptionRole.default], ['ListBoxRole', _ListBoxRole.default], ['ListItemRole', _ListItemRole.default], ['ListMarkerRole', _ListMarkerRole.default], ['ListRole', _ListRole.default], ['LogRole', _LogRole.default], ['MainRole', _MainRole.default], ['MarkRole', _MarkRole.default], ['MarqueeRole', _MarqueeRole.default], ['MathRole', _MathRole.default], ['MenuBarRole', _MenuBarRole.default], ['MenuButtonRole', _MenuButtonRole.default], ['MenuItemRole', _MenuItemRole.default], ['MenuItemCheckBoxRole', _MenuItemCheckBoxRole.default], ['MenuItemRadioRole', _MenuItemRadioRole.default], ['MenuListOptionRole', _MenuListOptionRole.default], ['MenuListPopupRole', _MenuListPopupRole.default], ['MenuRole', _MenuRole.default], ['MeterRole', _MeterRole.default], ['NavigationRole', _NavigationRole.default], ['NoneRole', _NoneRole.default], ['NoteRole', _NoteRole.default], ['OutlineRole', _OutlineRole.default], ['ParagraphRole', _ParagraphRole.default], ['PopUpButtonRole', _PopUpButtonRole.default], ['PreRole', _PreRole.default], ['PresentationalRole', _PresentationalRole.default], ['ProgressIndicatorRole', _ProgressIndicatorRole.default], ['RadioButtonRole', _RadioButtonRole.default], ['RadioGroupRole', _RadioGroupRole.default], ['RegionRole', _RegionRole.default], ['RootWebAreaRole', _RootWebAreaRole.default], ['RowHeaderRole', _RowHeaderRole.default], ['RowRole', _RowRole.default], ['RubyRole', _RubyRole.default], ['RulerRole', _RulerRole.default], ['ScrollAreaRole', _ScrollAreaRole.default], ['ScrollBarRole', _ScrollBarRole.default], ['SeamlessWebAreaRole', _SeamlessWebAreaRole.default], ['SearchRole', _SearchRole.default], ['SearchBoxRole', _SearchBoxRole.default], ['SliderRole', _SliderRole.default], ['SliderThumbRole', _SliderThumbRole.default], ['SpinButtonRole', _SpinButtonRole.default], ['SpinButtonPartRole', _SpinButtonPartRole.default], ['SplitterRole', _SplitterRole.default], ['StaticTextRole', _StaticTextRole.default], ['StatusRole', _StatusRole.default], ['SVGRootRole', _SVGRootRole.default], ['SwitchRole', _SwitchRole.default], ['TabGroupRole', _TabGroupRole.default], ['TabRole', _TabRole.default], ['TableHeaderContainerRole', _TableHeaderContainerRole.default], ['TableRole', _TableRole.default], ['TabListRole', _TabListRole.default], ['TabPanelRole', _TabPanelRole.default], ['TermRole', _TermRole.default], ['TextAreaRole', _TextAreaRole.default], ['TextFieldRole', _TextFieldRole.default], ['TimeRole', _TimeRole.default], ['TimerRole', _TimerRole.default], ['ToggleButtonRole', _ToggleButtonRole.default], ['ToolbarRole', _ToolbarRole.default], ['TreeRole', _TreeRole.default], ['TreeGridRole', _TreeGridRole.default], ['TreeItemRole', _TreeItemRole.default], ['UserInterfaceTooltipRole', _UserInterfaceTooltipRole.default], ['VideoRole', _VideoRole.default], ['WebAreaRole', _WebAreaRole.default], ['WindowRole', _WindowRole.default]];
var AXObjectsMap = {
  entries: function entries() {
    return AXObjects$1;
  },
  forEach: function forEach(fn) {
    var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
    var _iterator = _createForOfIteratorHelper$3(AXObjects$1),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var _step$value = _slicedToArray$3(_step.value, 2),
          key = _step$value[0],
          values = _step$value[1];
        fn.call(thisArg, values, key, AXObjects$1);
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
  },
  get: function get(key) {
    var item = AXObjects$1.find(function (tuple) {
      return tuple[0] === key ? true : false;
    });
    return item && item[1];
  },
  has: function has(key) {
    return !!AXObjectsMap.get(key);
  },
  keys: function keys() {
    return AXObjects$1.map(function (_ref) {
      var _ref2 = _slicedToArray$3(_ref, 1),
        key = _ref2[0];
      return key;
    });
  },
  values: function values() {
    return AXObjects$1.map(function (_ref3) {
      var _ref4 = _slicedToArray$3(_ref3, 2),
        values = _ref4[1];
      return values;
    });
  }
};
var _default$3 = (0, _iterationDecorator$3.default)(AXObjectsMap, AXObjectsMap.entries());
AXObjectsMap$1.default = _default$3;

Object.defineProperty(AXObjectElementMap$1, "__esModule", {
  value: true
});
AXObjectElementMap$1.default = void 0;
var _iterationDecorator$2 = _interopRequireDefault$3(iterationDecorator$1);
var _AXObjectsMap$3 = _interopRequireDefault$3(AXObjectsMap$1);
function _interopRequireDefault$3(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _slicedToArray$2(arr, i) { return _arrayWithHoles$2(arr) || _iterableToArrayLimit$2(arr, i) || _unsupportedIterableToArray$2(arr, i) || _nonIterableRest$2(); }
function _nonIterableRest$2() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit$2(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles$2(arr) { if (Array.isArray(arr)) return arr; }
function _createForOfIteratorHelper$2(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$2(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray$2(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$2(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$2(o, minLen); }
function _arrayLikeToArray$2(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
var AXObjectElements$1 = [];
var _iterator$2 = _createForOfIteratorHelper$2(_AXObjectsMap$3.default.entries()),
  _step$2;
try {
  var _loop$2 = function _loop() {
    var _step$value = _slicedToArray$2(_step$2.value, 2),
      name = _step$value[0],
      def = _step$value[1];
    var relatedConcepts = def.relatedConcepts;
    if (Array.isArray(relatedConcepts)) {
      relatedConcepts.forEach(function (relation) {
        if (relation.module === 'HTML') {
          var concept = relation.concept;
          if (concept) {
            var index = AXObjectElements$1.findIndex(function (_ref5) {
              var _ref6 = _slicedToArray$2(_ref5, 1),
                key = _ref6[0];
              return key === name;
            });
            if (index === -1) {
              AXObjectElements$1.push([name, []]);
              index = AXObjectElements$1.length - 1;
            }
            AXObjectElements$1[index][1].push(concept);
          }
        }
      });
    }
  };
  for (_iterator$2.s(); !(_step$2 = _iterator$2.n()).done;) {
    _loop$2();
  }
} catch (err) {
  _iterator$2.e(err);
} finally {
  _iterator$2.f();
}
var AXObjectElementMap = {
  entries: function entries() {
    return AXObjectElements$1;
  },
  forEach: function forEach(fn) {
    var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
    var _iterator2 = _createForOfIteratorHelper$2(AXObjectElements$1),
      _step2;
    try {
      for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
        var _step2$value = _slicedToArray$2(_step2.value, 2),
          key = _step2$value[0],
          values = _step2$value[1];
        fn.call(thisArg, values, key, AXObjectElements$1);
      }
    } catch (err) {
      _iterator2.e(err);
    } finally {
      _iterator2.f();
    }
  },
  get: function get(key) {
    var item = AXObjectElements$1.find(function (tuple) {
      return tuple[0] === key ? true : false;
    });
    return item && item[1];
  },
  has: function has(key) {
    return !!AXObjectElementMap.get(key);
  },
  keys: function keys() {
    return AXObjectElements$1.map(function (_ref) {
      var _ref2 = _slicedToArray$2(_ref, 1),
        key = _ref2[0];
      return key;
    });
  },
  values: function values() {
    return AXObjectElements$1.map(function (_ref3) {
      var _ref4 = _slicedToArray$2(_ref3, 2),
        values = _ref4[1];
      return values;
    });
  }
};
var _default$2 = (0, _iterationDecorator$2.default)(AXObjectElementMap, AXObjectElementMap.entries());
AXObjectElementMap$1.default = _default$2;

var AXObjectRoleMap$1 = {};

Object.defineProperty(AXObjectRoleMap$1, "__esModule", {
  value: true
});
AXObjectRoleMap$1.default = void 0;
var _iterationDecorator$1 = _interopRequireDefault$2(iterationDecorator$1);
var _AXObjectsMap$2 = _interopRequireDefault$2(AXObjectsMap$1);
function _interopRequireDefault$2(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _slicedToArray$1(arr, i) { return _arrayWithHoles$1(arr) || _iterableToArrayLimit$1(arr, i) || _unsupportedIterableToArray$1(arr, i) || _nonIterableRest$1(); }
function _nonIterableRest$1() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit$1(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles$1(arr) { if (Array.isArray(arr)) return arr; }
function _createForOfIteratorHelper$1(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$1(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); }
function _arrayLikeToArray$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
var AXObjectRoleElements = [];
var _iterator$1 = _createForOfIteratorHelper$1(_AXObjectsMap$2.default.entries()),
  _step$1;
try {
  var _loop$1 = function _loop() {
    var _step$value = _slicedToArray$1(_step$1.value, 2),
      name = _step$value[0],
      def = _step$value[1];
    var relatedConcepts = def.relatedConcepts;
    if (Array.isArray(relatedConcepts)) {
      relatedConcepts.forEach(function (relation) {
        if (relation.module === 'ARIA') {
          var concept = relation.concept;
          if (concept) {
            var index = AXObjectRoleElements.findIndex(function (_ref5) {
              var _ref6 = _slicedToArray$1(_ref5, 1),
                key = _ref6[0];
              return key === name;
            });
            if (index === -1) {
              AXObjectRoleElements.push([name, []]);
              index = AXObjectRoleElements.length - 1;
            }
            AXObjectRoleElements[index][1].push(concept);
          }
        }
      });
    }
  };
  for (_iterator$1.s(); !(_step$1 = _iterator$1.n()).done;) {
    _loop$1();
  }
} catch (err) {
  _iterator$1.e(err);
} finally {
  _iterator$1.f();
}
var AXObjectRoleMap = {
  entries: function entries() {
    return AXObjectRoleElements;
  },
  forEach: function forEach(fn) {
    var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
    var _iterator2 = _createForOfIteratorHelper$1(AXObjectRoleElements),
      _step2;
    try {
      for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
        var _step2$value = _slicedToArray$1(_step2.value, 2),
          key = _step2$value[0],
          values = _step2$value[1];
        fn.call(thisArg, values, key, AXObjectRoleElements);
      }
    } catch (err) {
      _iterator2.e(err);
    } finally {
      _iterator2.f();
    }
  },
  get: function get(key) {
    var item = AXObjectRoleElements.find(function (tuple) {
      return tuple[0] === key ? true : false;
    });
    return item && item[1];
  },
  has: function has(key) {
    return !!AXObjectRoleMap.get(key);
  },
  keys: function keys() {
    return AXObjectRoleElements.map(function (_ref) {
      var _ref2 = _slicedToArray$1(_ref, 1),
        key = _ref2[0];
      return key;
    });
  },
  values: function values() {
    return AXObjectRoleElements.map(function (_ref3) {
      var _ref4 = _slicedToArray$1(_ref3, 2),
        values = _ref4[1];
      return values;
    });
  }
};
var _default$1 = (0, _iterationDecorator$1.default)(AXObjectRoleMap, AXObjectRoleMap.entries());
AXObjectRoleMap$1.default = _default$1;

var elementAXObjectMap$1 = {};

Object.defineProperty(elementAXObjectMap$1, "__esModule", {
  value: true
});
elementAXObjectMap$1.default = void 0;
var _lite = lite;
var _AXObjectsMap$1 = _interopRequireDefault$1(AXObjectsMap$1);
var _iterationDecorator = _interopRequireDefault$1(iterationDecorator$1);
function _interopRequireDefault$1(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
var elementAXObjects$1 = [];
var _iterator = _createForOfIteratorHelper(_AXObjectsMap$1.default.entries()),
  _step;
try {
  var _loop = function _loop() {
    var _step$value = _slicedToArray(_step.value, 2),
      name = _step$value[0],
      def = _step$value[1];
    var relatedConcepts = def.relatedConcepts;
    if (Array.isArray(relatedConcepts)) {
      relatedConcepts.forEach(function (relation) {
        if (relation.module === 'HTML') {
          var concept = relation.concept;
          if (concept != null) {
            var conceptStr = JSON.stringify(concept);
            var axObjects;
            var index = 0;
            for (; index < elementAXObjects$1.length; index++) {
              var key = elementAXObjects$1[index][0];
              if (JSON.stringify(key) === conceptStr) {
                axObjects = elementAXObjects$1[index][1];
                break;
              }
            }
            if (!Array.isArray(axObjects)) {
              axObjects = [];
            }
            var loc = axObjects.findIndex(function (item) {
              return item === name;
            });
            if (loc === -1) {
              axObjects.push(name);
            }
            if (index < elementAXObjects$1.length) {
              elementAXObjects$1.splice(index, 1, [concept, axObjects]);
            } else {
              elementAXObjects$1.push([concept, axObjects]);
            }
          }
        }
      });
    }
  };
  for (_iterator.s(); !(_step = _iterator.n()).done;) {
    _loop();
  }
} catch (err) {
  _iterator.e(err);
} finally {
  _iterator.f();
}
var elementAXObjectMap = {
  entries: function entries() {
    return elementAXObjects$1;
  },
  forEach: function forEach(fn) {
    var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
    var _iterator2 = _createForOfIteratorHelper(elementAXObjects$1),
      _step2;
    try {
      for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
        var _step2$value = _slicedToArray(_step2.value, 2),
          key = _step2$value[0],
          values = _step2$value[1];
        fn.call(thisArg, values, key, elementAXObjects$1);
      }
    } catch (err) {
      _iterator2.e(err);
    } finally {
      _iterator2.f();
    }
  },
  get: function get(key) {
    var item = elementAXObjects$1.find(function (tuple) {
      return key.name === tuple[0].name && (0, _lite.dequal)(key.attributes, tuple[0].attributes);
    });
    return item && item[1];
  },
  has: function has(key) {
    return !!elementAXObjectMap.get(key);
  },
  keys: function keys() {
    return elementAXObjects$1.map(function (_ref) {
      var _ref2 = _slicedToArray(_ref, 1),
        key = _ref2[0];
      return key;
    });
  },
  values: function values() {
    return elementAXObjects$1.map(function (_ref3) {
      var _ref4 = _slicedToArray(_ref3, 2),
        values = _ref4[1];
      return values;
    });
  }
};
var _default = (0, _iterationDecorator.default)(elementAXObjectMap, elementAXObjectMap.entries());
elementAXObjectMap$1.default = _default;

Object.defineProperty(lib, "__esModule", {
  value: true
});
var elementAXObjects_1 = lib.elementAXObjects = AXObjects_1 = lib.AXObjects = AXObjectRoles_1 = lib.AXObjectRoles = lib.AXObjectElements = void 0;
var _AXObjectElementMap = _interopRequireDefault(AXObjectElementMap$1);
var _AXObjectRoleMap = _interopRequireDefault(AXObjectRoleMap$1);
var _AXObjectsMap = _interopRequireDefault(AXObjectsMap$1);
var _elementAXObjectMap = _interopRequireDefault(elementAXObjectMap$1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var AXObjectElements = _AXObjectElementMap.default;
lib.AXObjectElements = AXObjectElements;
var AXObjectRoles = _AXObjectRoleMap.default;
var AXObjectRoles_1 = lib.AXObjectRoles = AXObjectRoles;
var AXObjects = _AXObjectsMap.default;
var AXObjects_1 = lib.AXObjects = AXObjects;
var elementAXObjects = _elementAXObjectMap.default;
elementAXObjects_1 = lib.elementAXObjects = elementAXObjects;

const aria_roles$1 = roles_1.keys();
const abstract_roles = new Set(aria_roles$1.filter((role) => roles_1.get(role).abstract));
const non_abstract_roles = aria_roles$1.filter((name) => !abstract_roles.has(name));
const non_interactive_roles = new Set(
	non_abstract_roles
		.filter((name) => {
			const role = roles_1.get(name);
			return (
				// 'toolbar' does not descend from widget, but it does support
				// aria-activedescendant, thus in practice we treat it as a widget.
				// focusable tabpanel elements are recommended if any panels in a set contain content where the first element in the panel is not focusable.
				// 'generic' is meant to have no semantic meaning.
				// 'cell' is treated as CellRole by the AXObject which is interactive, so we treat 'cell' it as interactive as well.
				!['toolbar', 'tabpanel', 'generic', 'cell'].includes(name) &&
				!role.superClass.some((classes) => classes.includes('widget'))
			);
		})
		.concat(
			// The `progressbar` is descended from `widget`, but in practice, its
			// value is always `readonly`, so we treat it as a non-interactive role.
			'progressbar'
		)
);
const interactive_roles = new Set(
	non_abstract_roles.filter(
		(name) =>
			!non_interactive_roles.has(name) &&
			// 'generic' is meant to have no semantic meaning.
			name !== 'generic'
	)
);

/**
 * @param {import('aria-query').ARIARoleDefinitionKey} role
 */
function is_non_interactive_roles(role) {
	return non_interactive_roles.has(role);
}

/**
 * @param {import('aria-query').ARIARoleDefinitionKey} role
 */
function is_interactive_roles(role) {
	return interactive_roles.has(role);
}

/**
 * @param {import('aria-query').ARIARoleDefinitionKey} role
 */
function is_abstract_role(role) {
	return abstract_roles.has(role);
}
const presentation_roles = new Set(['presentation', 'none']);

/**
 * @param {import('aria-query').ARIARoleDefinitionKey} role
 */
function is_presentation_role(role) {
	return presentation_roles.has(role);
}

/**
 * @param {string} tag_name
 * @param {Map<string, import('../nodes/Attribute.js').default>} attribute_map
 */
function is_hidden_from_screen_reader(tag_name, attribute_map) {
	if (tag_name === 'input') {
		const type = attribute_map.get('type')?.get_static_value();
		if (type && type === 'hidden') {
			return true;
		}
	}
	const aria_hidden = attribute_map.get('aria-hidden');
	if (!aria_hidden) return false;
	if (!aria_hidden.is_static) return true;
	const aria_hidden_value = aria_hidden.get_static_value();
	return aria_hidden_value === true || aria_hidden_value === 'true';
}

/**
 * @param {Map<string, import('../nodes/Attribute.js').default>} attribute_map
 */
function has_disabled_attribute(attribute_map) {
	const disabled_attr = attribute_map.get('disabled');
	const disabled_attr_value = disabled_attr && disabled_attr.get_static_value();
	if (disabled_attr_value) {
		return true;
	}
	const aria_disabled_attr = attribute_map.get('aria-disabled');
	if (aria_disabled_attr) {
		const aria_disabled_attr_value = aria_disabled_attr.get_static_value();
		if (aria_disabled_attr_value === true) {
			return true;
		}
	}
	return false;
}

/**
 * @type {import('aria-query').ARIARoleRelationConcept[]}
 */
const non_interactive_element_role_schemas = [];
elementRoles_1.entries().forEach(([schema, roles]) => {
	if ([...roles].every((role) => role !== 'generic' && non_interactive_roles.has(role))) {
		non_interactive_element_role_schemas.push(schema);
	}
});

/**
 * @type {import('aria-query').ARIARoleRelationConcept[]}
 */
const interactive_element_role_schemas = [];
elementRoles_1.entries().forEach(([schema, roles]) => {
	if ([...roles].every((role) => interactive_roles.has(role))) {
		interactive_element_role_schemas.push(schema);
	}
});
const interactive_ax_objects = new Set(
	[...AXObjects_1.keys()].filter((name) => AXObjects_1.get(name).type === 'widget')
);
const non_interactive_ax_objects = new Set(
	[...AXObjects_1.keys()].filter((name) =>
		['windows', 'structure'].includes(AXObjects_1.get(name).type)
	)
);

/**
 * @type {import('aria-query').ARIARoleRelationConcept[]}
 */
const interactive_element_ax_object_schemas = [];
elementAXObjects_1.entries().forEach(([schema, ax_object]) => {
	if ([...ax_object].every((role) => interactive_ax_objects.has(role))) {
		interactive_element_ax_object_schemas.push(schema);
	}
});

/**
 * @type {import('aria-query').ARIARoleRelationConcept[]}
 */
const non_interactive_element_ax_object_schemas = [];
elementAXObjects_1.entries().forEach(([schema, ax_object]) => {
	if ([...ax_object].every((role) => non_interactive_ax_objects.has(role))) {
		non_interactive_element_ax_object_schemas.push(schema);
	}
});

/**
 * @param {import('aria-query').ARIARoleRelationConcept} schema
 * @param {string} tag_name
 * @param {Map<string, import('../nodes/Attribute.js').default>} attribute_map
 */
function match_schema(schema, tag_name, attribute_map) {
	if (schema.name !== tag_name) return false;
	if (!schema.attributes) return true;
	return schema.attributes.every((schema_attribute) => {
		const attribute = attribute_map.get(schema_attribute.name);
		if (!attribute) return false;
		if (schema_attribute.value && schema_attribute.value !== attribute.get_static_value()) {
			return false;
		}
		return true;
	});
}

const ElementInteractivity = /** @type {const} */ ({
	Interactive: 'interactive',
	NonInteractive: 'non-interactive',
	Static: 'static'
});

/**
 * @param {string} tag_name
 * @param {Map<string, import('../nodes/Attribute.js').default>} attribute_map
 * @returns {ElementInteractivity[keyof ElementInteractivity]}
 */
function element_interactivity(tag_name, attribute_map) {
	if (
		interactive_element_role_schemas.some((schema) => match_schema(schema, tag_name, attribute_map))
	) {
		return ElementInteractivity.Interactive;
	}
	if (
		tag_name !== 'header' &&
		non_interactive_element_role_schemas.some((schema) =>
			match_schema(schema, tag_name, attribute_map)
		)
	) {
		return ElementInteractivity.NonInteractive;
	}
	if (
		interactive_element_ax_object_schemas.some((schema) =>
			match_schema(schema, tag_name, attribute_map)
		)
	) {
		return ElementInteractivity.Interactive;
	}
	if (
		non_interactive_element_ax_object_schemas.some((schema) =>
			match_schema(schema, tag_name, attribute_map)
		)
	) {
		return ElementInteractivity.NonInteractive;
	}
	return ElementInteractivity.Static;
}

/**
 * @param {string} tag_name
 * @param {Map<string, import('../nodes/Attribute.js').default>} attribute_map
 * @returns {boolean}
 */
function is_interactive_element(tag_name, attribute_map) {
	return element_interactivity(tag_name, attribute_map) === ElementInteractivity.Interactive;
}

/**
 * @param {string} tag_name
 * @param {Map<string, import('../nodes/Attribute.js').default>} attribute_map
 * @returns {boolean}
 */
function is_non_interactive_element(tag_name, attribute_map) {
	return element_interactivity(tag_name, attribute_map) === ElementInteractivity.NonInteractive;
}

/**
 * @param {string} tag_name
 * @param {Map<string, import('../nodes/Attribute.js').default>} attribute_map
 * @returns {boolean}
 */
function is_static_element(tag_name, attribute_map) {
	return element_interactivity(tag_name, attribute_map) === ElementInteractivity.Static;
}

/**
 * @param {import('aria-query').ARIARoleDefinitionKey} role
 * @param {string} tag_name
 * @param {Map<string, import('../nodes/Attribute.js').default>} attribute_map
 */
function is_semantic_role_element(role, tag_name, attribute_map) {
	for (const [schema, ax_object] of elementAXObjects_1.entries()) {
		if (
			schema.name === tag_name &&
			(!schema.attributes ||
				schema.attributes.every(
					(attr) =>
						attribute_map.has(attr.name) &&
						attribute_map.get(attr.name).get_static_value() === attr.value
				))
		) {
			for (const name of ax_object) {
				const roles = AXObjectRoles_1.get(name);
				if (roles) {
					for (const { name } of roles) {
						if (name === role) {
							return true;
						}
					}
				}
			}
		}
	}
	return false;
}
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute
const address_type_tokens = new Set(['shipping', 'billing']);
const autofill_field_name_tokens = new Set([
	'',
	'on',
	'off',
	'name',
	'honorific-prefix',
	'given-name',
	'additional-name',
	'family-name',
	'honorific-suffix',
	'nickname',
	'username',
	'new-password',
	'current-password',
	'one-time-code',
	'organization-title',
	'organization',
	'street-address',
	'address-line1',
	'address-line2',
	'address-line3',
	'address-level4',
	'address-level3',
	'address-level2',
	'address-level1',
	'country',
	'country-name',
	'postal-code',
	'cc-name',
	'cc-given-name',
	'cc-additional-name',
	'cc-family-name',
	'cc-number',
	'cc-exp',
	'cc-exp-month',
	'cc-exp-year',
	'cc-csc',
	'cc-type',
	'transaction-currency',
	'transaction-amount',
	'language',
	'bday',
	'bday-day',
	'bday-month',
	'bday-year',
	'sex',
	'url',
	'photo'
]);
const contact_type_tokens = new Set(['home', 'work', 'mobile', 'fax', 'pager']);
const autofill_contact_field_name_tokens = new Set([
	'tel',
	'tel-country-code',
	'tel-national',
	'tel-area-code',
	'tel-local',
	'tel-local-prefix',
	'tel-local-suffix',
	'tel-extension',
	'email',
	'impp'
]);

/**
 * @param {null | true | string} autocomplete
 */
function is_valid_autocomplete(autocomplete) {
	if (autocomplete === true) {
		return false;
	} else if (!autocomplete) {
		return true; // dynamic value
	}
	const tokens = autocomplete.trim().toLowerCase().split(regex_whitespaces);
	if (typeof tokens[0] === 'string' && tokens[0].startsWith('section-')) {
		tokens.shift();
	}
	if (address_type_tokens.has(tokens[0])) {
		tokens.shift();
	}
	if (autofill_field_name_tokens.has(tokens[0])) {
		tokens.shift();
	} else {
		if (contact_type_tokens.has(tokens[0])) {
			tokens.shift();
		}
		if (autofill_contact_field_name_tokens.has(tokens[0])) {
			tokens.shift();
		} else {
			return false;
		}
	}
	if (tokens[0] === 'webauthn') {
		tokens.shift();
	}
	return tokens.length === 0;
}

const aria_attributes =
	'activedescendant atomic autocomplete busy checked colcount colindex colspan controls current describedby description details disabled dropeffect errormessage expanded flowto grabbed haspopup hidden invalid keyshortcuts label labelledby level live modal multiline multiselectable orientation owns placeholder posinset pressed readonly relevant required roledescription rowcount rowindex rowspan selected setsize sort valuemax valuemin valuenow valuetext'.split(
		' '
	);
const aria_attribute_set = new Set(aria_attributes);
const aria_roles = roles_1.keys();
const aria_role_set = new Set(aria_roles);
const a11y_required_attributes = {
	a: ['href'],
	area: ['alt', 'aria-label', 'aria-labelledby'],
	// html-has-lang
	html: ['lang'],
	// iframe-has-title
	iframe: ['title'],
	img: ['alt'],
	object: ['title', 'aria-label', 'aria-labelledby']
};
const a11y_distracting_elements = new Set(['blink', 'marquee']);
const a11y_required_content = new Set([
	// anchor-has-content
	'a',
	// heading-has-content
	'h1',
	'h2',
	'h3',
	'h4',
	'h5',
	'h6'
]);
const a11y_labelable = new Set([
	'button',
	'input',
	'keygen',
	'meter',
	'output',
	'progress',
	'select',
	'textarea'
]);
const a11y_interactive_handlers = new Set([
	// Keyboard events
	'keypress',
	'keydown',
	'keyup',
	// Click events
	'click',
	'contextmenu',
	'dblclick',
	'drag',
	'dragend',
	'dragenter',
	'dragexit',
	'dragleave',
	'dragover',
	'dragstart',
	'drop',
	'mousedown',
	'mouseenter',
	'mouseleave',
	'mousemove',
	'mouseout',
	'mouseover',
	'mouseup'
]);
const a11y_recommended_interactive_handlers = new Set([
	'click',
	'mousedown',
	'mouseup',
	'keypress',
	'keydown',
	'keyup'
]);
const a11y_nested_implicit_semantics = new Map([
	['header', 'banner'],
	['footer', 'contentinfo']
]);
const a11y_implicit_semantics = new Map([
	['a', 'link'],
	['area', 'link'],
	['article', 'article'],
	['aside', 'complementary'],
	['body', 'document'],
	['button', 'button'],
	['datalist', 'listbox'],
	['dd', 'definition'],
	['dfn', 'term'],
	['dialog', 'dialog'],
	['details', 'group'],
	['dt', 'term'],
	['fieldset', 'group'],
	['figure', 'figure'],
	['form', 'form'],
	['h1', 'heading'],
	['h2', 'heading'],
	['h3', 'heading'],
	['h4', 'heading'],
	['h5', 'heading'],
	['h6', 'heading'],
	['hr', 'separator'],
	['img', 'img'],
	['li', 'listitem'],
	['link', 'link'],
	['main', 'main'],
	['menu', 'list'],
	['meter', 'progressbar'],
	['nav', 'navigation'],
	['ol', 'list'],
	['option', 'option'],
	['optgroup', 'group'],
	['output', 'status'],
	['progress', 'progressbar'],
	['section', 'region'],
	['summary', 'button'],
	['table', 'table'],
	['tbody', 'rowgroup'],
	['textarea', 'textbox'],
	['tfoot', 'rowgroup'],
	['thead', 'rowgroup'],
	['tr', 'row'],
	['ul', 'list']
]);
const menuitem_type_to_implicit_role = new Map([
	['command', 'menuitem'],
	['checkbox', 'menuitemcheckbox'],
	['radio', 'menuitemradio']
]);
const input_type_to_implicit_role = new Map([
	['button', 'button'],
	['image', 'button'],
	['reset', 'button'],
	['submit', 'button'],
	['checkbox', 'checkbox'],
	['radio', 'radio'],
	['range', 'slider'],
	['number', 'spinbutton'],
	['email', 'textbox'],
	['search', 'searchbox'],
	['tel', 'textbox'],
	['text', 'textbox'],
	['url', 'textbox']
]);
/**
 * Exceptions to the rule which follows common A11y conventions
 * TODO make this configurable by the user
 */
const a11y_non_interactive_element_to_interactive_role_exceptions = {
	ul: ['listbox', 'menu', 'menubar', 'radiogroup', 'tablist', 'tree', 'treegrid'],
	ol: ['listbox', 'menu', 'menubar', 'radiogroup', 'tablist', 'tree', 'treegrid'],
	li: ['menuitem', 'option', 'row', 'tab', 'treeitem'],
	table: ['grid'],
	td: ['gridcell'],
	fieldset: ['radiogroup', 'presentation']
};
const combobox_if_list = new Set(['email', 'search', 'tel', 'text', 'url']);

/** @param {Map<string, import('./Attribute.js').default>} attribute_map */
function input_implicit_role(attribute_map) {
	const type_attribute = attribute_map.get('type');
	if (!type_attribute || !type_attribute.is_static) return;
	const type = /** @type {string} */ (type_attribute.get_static_value());
	const list_attribute_exists = attribute_map.has('list');
	if (list_attribute_exists && combobox_if_list.has(type)) {
		return 'combobox';
	}
	return input_type_to_implicit_role.get(type);
}

/** @param {Map<string, import('./Attribute.js').default>} attribute_map */
function menuitem_implicit_role(attribute_map) {
	const type_attribute = attribute_map.get('type');
	if (!type_attribute || !type_attribute.is_static) return;
	const type = /** @type {string} */ (type_attribute.get_static_value());
	return menuitem_type_to_implicit_role.get(type);
}

/**
 * @param {string} name
 * @param {Map<string, import('./Attribute.js').default>} attribute_map
 * @returns {string}
 */
function get_implicit_role(name, attribute_map) {
	if (name === 'menuitem') {
		return menuitem_implicit_role(attribute_map);
	} else if (name === 'input') {
		return input_implicit_role(attribute_map);
	} else {
		return a11y_implicit_semantics.get(name);
	}
}
const invisible_elements = new Set(['meta', 'html', 'script', 'style']);
const valid_modifiers = new Set([
	'preventDefault',
	'stopPropagation',
	'stopImmediatePropagation',
	'capture',
	'once',
	'passive',
	'nonpassive',
	'self',
	'trusted'
]);
const passive_events = new Set(['wheel', 'touchstart', 'touchmove', 'touchend', 'touchcancel']);
const react_attributes = new Map([
	['className', 'class'],
	['htmlFor', 'for']
]);
const attributes_to_compact_whitespace = ['class', 'style'];

/**
 * @param {import('./interfaces.js').INode} parent
 * @param {string[]} elements
 */
function is_parent(parent, elements) {
	let check = false;
	while (parent) {
		const parent_name = /** @type {Element} */ (parent).name;
		if (elements.includes(parent_name)) {
			check = true;
			break;
		}
		if (parent.type === 'Element') {
			break;
		}
		parent = parent.parent;
	}
	return check;
}

/**
 * @param {Element} parent
 * @param {Element} element
 * @param {string} explicit_namespace
 */
function get_namespace$1(parent, element, explicit_namespace) {
	const parent_element = parent.find_nearest(/^Element/);
	if (!parent_element) {
		return explicit_namespace || (is_svg(element.name) ? namespaces.svg : null);
	}
	if (parent_element.namespace !== namespaces.foreign) {
		if (is_svg(element.name.toLowerCase())) return namespaces.svg;
		if (parent_element.name.toLowerCase() === 'foreignobject') return null;
	}
	return parent_element.namespace;
}

/**
 * @param {import('aria-query').ARIAPropertyDefinition} schema
 * @param {string | boolean} value
 * @returns {boolean}
 */
function is_valid_aria_attribute_value(schema, value) {
	switch (schema.type) {
		case 'boolean':
			return typeof value === 'boolean';
		case 'string':
		case 'id':
			return typeof value === 'string';
		case 'tristate':
			return typeof value === 'boolean' || value === 'mixed';
		case 'integer':
		case 'number':
			return typeof value !== 'boolean' && isNaN(Number(value)) === false;
		case 'token': // single token
			return (
				(schema.values || []).indexOf(typeof value === 'string' ? value.toLowerCase() : value) > -1
			);
		case 'idlist': // if list of ids, split each
			return (
				typeof value === 'string' &&
				value
					.split(regex_any_repeated_whitespaces)
					.every(/** @param {any} id */ (id) => typeof id === 'string')
			);
		case 'tokenlist': // if list of tokens, split each
			return (
				typeof value === 'string' &&
				value
					.split(regex_any_repeated_whitespaces)
					.every(
						/** @param {any} token */ (token) =>
							(schema.values || []).indexOf(token.toLowerCase()) > -1
					)
			);
		default:
			return false;
	}
}
const regex_any_repeated_whitespaces = /[\s]+/g;
const regex_heading_tags = /^h[1-6]$/;
const regex_illegal_attribute_character = /(^[0-9-.])|[\^$@%&#?!|()[\]{}^*+~;]/;

/** @extends Node<'Element'> */
let Element$1 = class Element extends Node {
	/** @type {string} */
	name;

	/** @type {import('./shared/TemplateScope.js').default} */
	scope;

	/** @type {import('./Action.js').default[]} */
	actions = [];

	/** @type {import('./Binding.js').default[]} */
	bindings = [];

	/** @type {import('./Class.js').default[]} */
	classes = [];

	/** @type {import('./StyleDirective.js').default[]} */
	styles = [];

	/** @type {import('./EventHandler.js').default[]} */
	handlers = [];

	/** @type {import('./Let.js').default[]} */
	lets = [];

	/** @type {import('./Transition.js').default} */
	intro = null;

	/** @type {import('./Transition.js').default} */
	outro = null;

	/** @type {import('./Animation.js').default} */
	animation = null;

	/** @type {import('./interfaces.js').INode[]} */
	children;

	/** @type {string} */
	namespace;

	/** @type {boolean} */
	needs_manual_style_scoping;

	/** @type {import('./shared/Expression.js').default} */
	tag_expr;

	/** @type {boolean} */
	contains_a11y_label;
	get is_dynamic_element() {
		return this.name === 'svelte:element';
	}

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./shared/Node.js').default} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {any} info  undefined
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		this.name = info.name;
		if (info.name === 'svelte:element') {
			if (typeof info.tag !== 'string') {
				this.tag_expr = new Expression(component, this, scope, info.tag);
			} else {
				this.tag_expr = new Expression(
					component,
					this,
					scope,
					/** @type {import('estree').Literal} */ (string_literal(info.tag))
				);
				this.name = info.tag;
			}
		} else {
			this.tag_expr = new Expression(
				component,
				this,
				scope,
				/** @type {import('estree').Literal} */ (string_literal(this.name))
			);
		}
		this.namespace = get_namespace$1(/** @type {Element} */ (parent), this, component.namespace);
		if (this.namespace !== namespaces.foreign) {
			if (this.name === 'pre' || this.name === 'textarea') {
				const first = info.children[0];
				if (first && first.type === 'Text') {
					// The leading newline character needs to be stripped because of a quirk,
					// it is ignored by browsers if the tag and its contents are set through
					// innerHTML (NOT if set through the innerHTML of the tag or dynamically).
					// Therefore strip it here but add it back in the appropriate
					// places if there's another newline afterwards.
					// see https://html.spec.whatwg.org/multipage/syntax.html#element-restrictions
					// see https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
					first.data = first.data.replace(regex_starts_with_newline, '');
				}
			}
			if (this.name === 'textarea') {
				if (info.children.length > 0) {
					const value_attribute = info.attributes.find(
						/** @param {any} node */ (node) => node.name === 'value'
					);
					if (value_attribute) {
						component.error(value_attribute, compiler_errors.textarea_duplicate_value);
						return;
					}
					// this is an egregious hack, but it's the easiest way to get <textarea>
					// children treated the same way as a value attribute
					info.attributes.push({
						type: 'Attribute',
						name: 'value',
						value: info.children
					});
					info.children = [];
				}
			}
			if (this.name === 'option') {
				// Special case — treat these the same way:
				//   <option>{foo}</option>
				//   <option value={foo}>{foo}</option>
				const value_attribute = info.attributes.find(
					/** @param {any} attribute */ (attribute) => attribute.name === 'value'
				);
				if (!value_attribute) {
					info.attributes.push({
						type: 'Attribute',
						name: 'value',
						value: info.children,
						synthetic: true
					});
				}
			}
		}
		const has_let = info.attributes.some(/** @param {any} node */ (node) => node.type === 'Let');
		if (has_let) {
			scope = scope.child();
		}
		// Binding relies on Attribute, defer its evaluation
		const order = ['Binding']; // everything else is -1
		info.attributes.sort(
			/**
			 * @param {any} a
			 * @param {any} b
			 */ (a, b) => order.indexOf(a.type) - order.indexOf(b.type)
		);
		info.attributes.forEach(
			/** @param {any} node */ (node) => {
				switch (node.type) {
					case 'Action':
						this.actions.push(new Action(component, this, scope, node));
						break;
					case 'Attribute':
					case 'Spread':
						// special case
						if (node.name === 'xmlns') this.namespace = node.value[0].data;
						this.attributes.push(new Attribute(component, this, scope, node));
						break;
					case 'Binding':
						this.bindings.push(new Binding(component, this, scope, node));
						break;
					case 'Class':
						this.classes.push(new Class(component, this, scope, node));
						break;
					case 'StyleDirective':
						this.styles.push(new StyleDirective(component, this, scope, node));
						break;
					case 'EventHandler':
						this.handlers.push(new EventHandler(component, this, scope, node));
						break;
					case 'Let': {
						const l = new Let(component, this, scope, node);
						this.lets.push(l);
						const dependencies = new Set([l.name.name]);
						l.names.forEach(
							/** @param {any} name */ (name) => {
								scope.add(name, dependencies, this);
							}
						);
						break;
					}
					case 'Transition': {
						const transition = new Transition(component, this, scope, node);
						if (node.intro) this.intro = transition;
						if (node.outro) this.outro = transition;
						break;
					}
					case 'Animation':
						this.animation = new Animation(component, this, scope, node);
						break;
					default:
						throw new Error(`Not implemented: ${node.type}`);
				}
			}
		);
		this.scope = scope;
		this.children = map_children(component, this, this.scope, info.children);
		this.validate();
		this.optimise();
		component.apply_stylesheet(this);
		if (this.parent) {
			if (
				this.actions.length > 0 ||
				this.animation ||
				this.bindings.length > 0 ||
				this.classes.length > 0 ||
				this.intro ||
				this.outro ||
				this.handlers.length > 0 ||
				this.styles.length > 0 ||
				this.name === 'option' ||
				this.is_dynamic_element ||
				this.tag_expr.dynamic_dependencies().length ||
				this.is_dynamic_element ||
				component.compile_options.dev
			) {
				this.parent.cannot_use_innerhtml(); // need to use add_location
				this.parent.not_static_content();
			}
		}
	}
	validate() {
		if (
			this.component.var_lookup.has(this.name) &&
			this.component.var_lookup.get(this.name).imported &&
			!is_svg(this.name) &&
			!is_html(this.name)
		) {
			this.component.warn(this, compiler_warnings.component_name_lowercase(this.name));
		}
		this.validate_attributes();
		this.validate_event_handlers();
		if (this.namespace === namespaces.foreign) {
			this.validate_bindings_foreign();
		} else {
			this.validate_attributes_a11y();
			this.validate_special_cases();
			this.validate_bindings();
			this.validate_content();
		}
	}
	validate_attributes() {
		const { component, parent } = this;
		this.attributes.forEach(
			/** @param {any} attribute */ (attribute) => {
				if (attribute.is_spread) return;
				const name = attribute.name.toLowerCase();
				// Errors
				if (regex_illegal_attribute_character.test(name)) {
					return component.error(attribute, compiler_errors.illegal_attribute(name));
				}
				if (name === 'slot') {
					if (!attribute.is_static) {
						return component.error(attribute, compiler_errors.invalid_slot_attribute);
					}
					if (component.slot_outlets.has(name)) {
						return component.error(attribute, compiler_errors.duplicate_slot_attribute(name));
						// this code was unreachable. Still needed?
						// component.slot_outlets.add(name);
					}
					if (!(parent.type === 'SlotTemplate' || within_custom_element(parent))) {
						return component.error(attribute, compiler_errors.invalid_slotted_content);
					}
				}
				// Warnings
				if (this.namespace !== namespaces.foreign) {
					if (name === 'is') {
						component.warn(attribute, compiler_warnings.avoid_is);
					}
					if (react_attributes.has(attribute.name)) {
						component.warn(
							attribute,
							compiler_warnings.invalid_html_attribute(
								attribute.name,
								react_attributes.get(attribute.name)
							)
						);
					}
				}
			}
		);
	}
	validate_attributes_a11y() {
		const { component, attributes, handlers } = this;
		const attribute_map = new Map();
		const handlers_map = new Map();
		attributes.forEach(
			/** @param {any} attribute */ (attribute) => attribute_map.set(attribute.name, attribute)
		);
		handlers.forEach(
			/** @param {any} handler */ (handler) => handlers_map.set(handler.name, handler)
		);
		attributes.forEach(
			/** @param {any} attribute */ (attribute) => {
				if (attribute.is_spread) return;
				const name = attribute.name.toLowerCase();
				// aria-props
				if (name.startsWith('aria-')) {
					if (invisible_elements.has(this.name)) {
						// aria-unsupported-elements
						component.warn(attribute, compiler_warnings.a11y_aria_attributes(this.name));
					}
					const type = name.slice(5);
					if (!aria_attribute_set.has(type)) {
						const match = fuzzymatch(type, aria_attributes);
						component.warn(attribute, compiler_warnings.a11y_unknown_aria_attribute(type, match));
					}
					if (name === 'aria-hidden' && regex_heading_tags.test(this.name)) {
						component.warn(attribute, compiler_warnings.a11y_hidden(this.name));
					}
					// aria-proptypes
					let value = attribute.get_static_value();
					if (value === 'true') value = true;
					if (value === 'false') value = false;
					if (
						value !== null &&
						value !== undefined &&
						aria_1.has(/** @type {import('aria-query').ARIAProperty} */ (name))
					) {
						const schema = aria_1.get(/** @type {import('aria-query').ARIAProperty} */ (name));
						if (!is_valid_aria_attribute_value(schema, value)) {
							component.warn(
								attribute,
								compiler_warnings.a11y_incorrect_attribute_type(schema, name)
							);
						}
					}
					// aria-activedescendant-has-tabindex
					if (
						name === 'aria-activedescendant' &&
						!this.is_dynamic_element &&
						!is_interactive_element(this.name, attribute_map) &&
						!attribute_map.has('tabindex')
					) {
						component.warn(attribute, compiler_warnings.a11y_aria_activedescendant_has_tabindex);
					}
				}
				// aria-role
				if (name === 'role') {
					if (invisible_elements.has(this.name)) {
						// aria-unsupported-elements
						component.warn(attribute, compiler_warnings.a11y_misplaced_role(this.name));
					}
					const value = attribute.get_static_value();
					if (typeof value === 'string') {
						value.split(regex_any_repeated_whitespaces).forEach(
							/** @param {import('aria-query').ARIARoleDefinitionKey} current_role */ (
								current_role
							) => {
								if (current_role && is_abstract_role(current_role)) {
									component.warn(attribute, compiler_warnings.a11y_no_abstract_role(current_role));
								} else if (current_role && !aria_role_set.has(current_role)) {
									const match = fuzzymatch(current_role, aria_roles);
									component.warn(
										attribute,
										compiler_warnings.a11y_unknown_role(current_role, match)
									);
								}
								// no-redundant-roles
								if (
									current_role === get_implicit_role(this.name, attribute_map) &&
									// <ul role="list"> is ok because CSS list-style:none removes the semantics and this is a way to bring them back
									!['ul', 'ol', 'li'].includes(this.name)
								) {
									component.warn(
										attribute,
										compiler_warnings.a11y_no_redundant_roles(current_role)
									);
								}
								// Footers and headers are special cases, and should not have redundant roles unless they are the children of sections or articles.
								const is_parent_section_or_article = is_parent(this.parent, ['section', 'article']);
								if (!is_parent_section_or_article) {
									const has_nested_redundant_role =
										current_role === a11y_nested_implicit_semantics.get(this.name);
									if (has_nested_redundant_role) {
										component.warn(
											attribute,
											compiler_warnings.a11y_no_redundant_roles(current_role)
										);
									}
								}
								// role-has-required-aria-props
								if (
									!this.is_dynamic_element &&
									!is_semantic_role_element(current_role, this.name, attribute_map)
								) {
									const role = roles_1.get(current_role);
									if (role) {
										const required_role_props = Object.keys(role.requiredProps);
										const has_missing_props = required_role_props.some(
											/** @param {any} prop */
											(prop) => !attributes.find(/** @param {any} a */ (a) => a.name === prop)
										);
										if (has_missing_props) {
											component.warn(
												attribute,
												compiler_warnings.a11y_role_has_required_aria_props(
													current_role,
													required_role_props
												)
											);
										}
									}
								}
								// interactive-supports-focus
								if (
									!has_disabled_attribute(attribute_map) &&
									!is_hidden_from_screen_reader(this.name, attribute_map) &&
									!is_presentation_role(current_role) &&
									is_interactive_roles(current_role) &&
									is_static_element(this.name, attribute_map) &&
									!attribute_map.get('tabindex')
								) {
									const has_interactive_handlers = handlers.some(
										/** @param {any} handler */ (handler) =>
											a11y_interactive_handlers.has(handler.name)
									);
									if (has_interactive_handlers) {
										component.warn(
											this,
											compiler_warnings.a11y_interactive_supports_focus(current_role)
										);
									}
								}
								// no-interactive-element-to-noninteractive-role
								if (
									is_interactive_element(this.name, attribute_map) &&
									(is_non_interactive_roles(current_role) || is_presentation_role(current_role))
								) {
									component.warn(
										this,
										compiler_warnings.a11y_no_interactive_element_to_noninteractive_role(
											current_role,
											this.name
										)
									);
								}
								// no-noninteractive-element-to-interactive-role
								if (
									is_non_interactive_element(this.name, attribute_map) &&
									is_interactive_roles(current_role) &&
									!a11y_non_interactive_element_to_interactive_role_exceptions[this.name]?.includes(
										current_role
									)
								) {
									component.warn(
										this,
										compiler_warnings.a11y_no_noninteractive_element_to_interactive_role(
											current_role,
											this.name
										)
									);
								}
							}
						);
					}
				}
				// no-access-key
				if (name === 'accesskey') {
					component.warn(attribute, compiler_warnings.a11y_accesskey);
				}
				// no-autofocus
				if (name === 'autofocus') {
					component.warn(attribute, compiler_warnings.a11y_autofocus);
				}
				// scope
				if (name === 'scope' && !this.is_dynamic_element && this.name !== 'th') {
					component.warn(attribute, compiler_warnings.a11y_misplaced_scope);
				}
				// tabindex-no-positive
				if (name === 'tabindex') {
					const value = attribute.get_static_value();
					// @ts-ignore todo is tabindex=true correct case?
					if (!isNaN(value) && +value > 0) {
						component.warn(attribute, compiler_warnings.a11y_positive_tabindex);
					}
				}
			}
		);
		// click-events-have-key-events
		if (handlers_map.has('click')) {
			const role = attribute_map.get('role');
			const is_non_presentation_role =
				role?.is_static &&
				!is_presentation_role(
					/** @type {import('aria-query').ARIARoleDefinitionKey} */ (role.get_static_value())
				);
			if (
				!this.is_dynamic_element &&
				!is_hidden_from_screen_reader(this.name, attribute_map) &&
				(!role || is_non_presentation_role) &&
				!is_interactive_element(this.name, attribute_map) &&
				!this.attributes.find(/** @param {any} attr */ (attr) => attr.is_spread)
			) {
				const has_key_event =
					handlers_map.has('keydown') || handlers_map.has('keyup') || handlers_map.has('keypress');
				if (!has_key_event) {
					component.warn(this, compiler_warnings.a11y_click_events_have_key_events);
				}
			}
		}
		const role = attribute_map.get('role');
		const role_static_value = /** @type {import('aria-query').ARIARoleDefinitionKey} */ (
			role?.get_static_value()
		);
		const role_value = /** @type {import('aria-query').ARIARoleDefinitionKey} */ (
			role ? role_static_value : get_implicit_role(this.name, attribute_map)
		);
		// no-noninteractive-tabindex
		if (
			!this.is_dynamic_element &&
			!is_interactive_element(this.name, attribute_map) &&
			!is_interactive_roles(role_static_value)
		) {
			const tab_index = attribute_map.get('tabindex');
			if (tab_index && (!tab_index.is_static || Number(tab_index.get_static_value()) >= 0)) {
				component.warn(this, compiler_warnings.a11y_no_noninteractive_tabindex);
			}
		}
		// role-supports-aria-props
		if (typeof role_value === 'string' && roles_1.has(role_value)) {
			const { props } = roles_1.get(role_value);
			const invalid_aria_props = new Set(
				aria_1.keys().filter(/** @param {any} attribute */ (attribute) => !(attribute in props))
			);
			const is_implicit = role_value && role === undefined;
			attributes
				.filter(/** @param {any} prop */ (prop) => prop.type !== 'Spread')
				.forEach(
					/** @param {any} prop */ (prop) => {
						if (
							invalid_aria_props.has(/** @type {import('aria-query').ARIAProperty} */ (prop.name))
						) {
							component.warn(
								prop,
								compiler_warnings.a11y_role_supports_aria_props(
									prop.name,
									role_value,
									is_implicit,
									this.name
								)
							);
						}
					}
				);
		}
		// no-noninteractive-element-interactions
		if (
			!has_contenteditable_attr(this) &&
			!is_hidden_from_screen_reader(this.name, attribute_map) &&
			!is_presentation_role(role_static_value) &&
			((!is_interactive_element(this.name, attribute_map) &&
				is_non_interactive_roles(role_static_value)) ||
				(is_non_interactive_element(this.name, attribute_map) && !role))
		) {
			const has_interactive_handlers = handlers.some(
				/** @param {any} handler */ (handler) =>
					a11y_recommended_interactive_handlers.has(handler.name)
			);
			if (has_interactive_handlers) {
				component.warn(
					this,
					compiler_warnings.a11y_no_noninteractive_element_interactions(this.name)
				);
			}
		}
		const has_dynamic_role = attribute_map.get('role') && !attribute_map.get('role').is_static;
		// no-static-element-interactions
		if (
			!has_dynamic_role &&
			!is_hidden_from_screen_reader(this.name, attribute_map) &&
			!is_presentation_role(role_static_value) &&
			!is_interactive_element(this.name, attribute_map) &&
			!is_interactive_roles(role_static_value) &&
			!is_non_interactive_element(this.name, attribute_map) &&
			!is_non_interactive_roles(role_static_value) &&
			!is_abstract_role(role_static_value)
		) {
			const interactive_handlers = handlers
				.map(/** @param {any} handler */ (handler) => handler.name)
				.filter(
					/** @param {any} handlerName */ (handlerName) =>
						a11y_interactive_handlers.has(handlerName)
				);
			if (interactive_handlers.length > 0) {
				component.warn(
					this,
					compiler_warnings.a11y_no_static_element_interactions(this.name, interactive_handlers)
				);
			}
		}
	}
	validate_special_cases() {
		const { component, attributes, handlers } = this;
		const attribute_map = new Map();
		const handlers_map = new Map();
		attributes.forEach(
			/** @param {any} attribute */ (attribute) => attribute_map.set(attribute.name, attribute)
		);
		handlers.forEach(
			/** @param {any} handler */ (handler) => handlers_map.set(handler.name, handler)
		);
		if (this.name === 'a') {
			const href_attribute = attribute_map.get('href') || attribute_map.get('xlink:href');
			const id_attribute = attribute_map.get('id');
			const name_attribute = attribute_map.get('name');
			const target_attribute = attribute_map.get('target');
			const aria_label_attribute = attribute_map.get('aria-label');
			// links with target="_blank" should have noopener or noreferrer: https://developer.chrome.com/docs/lighthouse/best-practices/external-anchors-use-rel-noopener/
			// modern browsers add noopener by default, so we only need to check legacy browsers
			// legacy browsers don't support noopener so we only check for noreferrer there
			if (
				component.compile_options.legacy &&
				target_attribute &&
				target_attribute.get_static_value() === '_blank' &&
				href_attribute
			) {
				const href_static_value = href_attribute.get_static_value()
					? href_attribute.get_static_value().toLowerCase()
					: null;
				if (href_static_value === null || href_static_value.match(/^(https?:)?\/\//i)) {
					const rel = attribute_map.get('rel');
					if (rel == null || rel.is_static) {
						const rel_values = rel
							? rel.get_static_value().split(regex_any_repeated_whitespaces)
							: [];
						if (!rel || !rel_values.includes('noreferrer')) {
							component.warn(this, {
								code: 'security-anchor-rel-noreferrer',
								message:
									'Security: Anchor with "target=_blank" should have rel attribute containing the value "noreferrer"'
							});
						}
					}
				}
			}
			if (aria_label_attribute) {
				const aria_value = aria_label_attribute.get_static_value();
				if (aria_value != '') {
					this.contains_a11y_label = true;
				}
			}
			if (href_attribute) {
				const href_value = href_attribute.get_static_value();
				if (href_value === '' || href_value === '#' || /^\W*javascript:/i.test(href_value)) {
					component.warn(
						href_attribute,
						compiler_warnings.a11y_invalid_attribute(href_attribute.name, href_value)
					);
				}
			} else {
				const id_attribute_valid = id_attribute && id_attribute.get_static_value() !== '';
				const name_attribute_valid = name_attribute && name_attribute.get_static_value() !== '';
				if (!id_attribute_valid && !name_attribute_valid) {
					component.warn(this, compiler_warnings.a11y_missing_attribute('a', 'an', 'href'));
				}
			}
		} else {
			const required_attributes = a11y_required_attributes[this.name];
			if (required_attributes) {
				const has_attribute = required_attributes.some(
					/** @param {any} name */ (name) => attribute_map.has(name)
				);
				if (!has_attribute) {
					should_have_attribute(this, required_attributes);
				}
			}
		}
		if (this.name === 'input') {
			const type = attribute_map.get('type');
			if (type && type.get_static_value() === 'image') {
				const required_attributes = ['alt', 'aria-label', 'aria-labelledby'];
				const has_attribute = required_attributes.some(
					/** @param {any} name */ (name) => attribute_map.has(name)
				);
				if (!has_attribute) {
					should_have_attribute(this, required_attributes, 'input type="image"');
				}
			}
			// autocomplete-valid
			const autocomplete = attribute_map.get('autocomplete');
			if (type && autocomplete) {
				const type_value = type.get_static_value();
				const autocomplete_value = autocomplete.get_static_value();
				if (!is_valid_autocomplete(autocomplete_value)) {
					component.warn(
						autocomplete,
						compiler_warnings.a11y_autocomplete_valid(type_value, autocomplete_value)
					);
				}
			}
		}
		if (this.name === 'img') {
			const alt_attribute = attribute_map.get('alt');
			const aria_hidden_attribute = attribute_map.get('aria-hidden');
			const aria_hidden_exist = aria_hidden_attribute && aria_hidden_attribute.get_static_value();
			if (alt_attribute && !aria_hidden_exist) {
				const alt_value = alt_attribute.get_static_value();
				if (/\b(image|picture|photo)\b/i.test(alt_value)) {
					component.warn(this, compiler_warnings.a11y_img_redundant_alt);
				}
			}
		}
		if (this.name === 'label') {
			/** @param {import('./interfaces.js').INode[]} children */
			const has_input_child = (children) => {
				if (
					children.some(
						/** @param {any} child */
						(child) =>
							child instanceof Element && (a11y_labelable.has(child.name) || child.name === 'slot')
					)
				) {
					return true;
				}
				for (const child of children) {
					if (!('children' in child) || child.children.length === 0) {
						continue;
					}
					if (has_input_child(child.children)) {
						return true;
					}
				}
				return false;
			};
			if (!attribute_map.has('for') && !has_input_child(this.children)) {
				component.warn(this, compiler_warnings.a11y_label_has_associated_control);
			}
		}
		if (this.name === 'video') {
			const aria_hidden_attribute = attribute_map.get('aria-hidden');
			const aria_hidden_exist = aria_hidden_attribute && aria_hidden_attribute.get_static_value();
			if (attribute_map.has('muted') || aria_hidden_exist === 'true') {
				return;
			}
			let has_caption;
			const track = this.children.find(/** @param {Element} i */ (i) => i.name === 'track');
			if (track) {
				has_caption = track.attributes.find(
					/** @param {any} a */
					(a) => a.name === 'kind' && a.get_static_value() === 'captions'
				);
			}
			if (!has_caption) {
				component.warn(this, compiler_warnings.a11y_media_has_caption);
			}
		}
		if (a11y_distracting_elements.has(this.name)) {
			// no-distracting-elements
			component.warn(this, compiler_warnings.a11y_distracting_elements(this.name));
		}
		if (this.name === 'figcaption') {
			let { parent } = this;
			let is_figure_parent = false;
			while (parent) {
				if (/** @type {Element} */ (parent).name === 'figure') {
					is_figure_parent = true;
					break;
				}
				if (parent.type === 'Element') {
					break;
				}
				parent = parent.parent;
			}
			if (!is_figure_parent) {
				component.warn(this, compiler_warnings.a11y_structure_immediate);
			}
		}
		if (this.name === 'figure') {
			const children = this.children.filter(
				/** @param {any} node */ (node) => {
					if (node.type === 'Comment') return false;
					if (node.type === 'Text') return regex_non_whitespace_character.test(node.data);
					return true;
				}
			);
			const index = children.findIndex(
				/** @param {any} child */ (child) => /** @type {Element} */ (child).name === 'figcaption'
			);
			if (index !== -1 && index !== 0 && index !== children.length - 1) {
				component.warn(children[index], compiler_warnings.a11y_structure_first_or_last);
			}
		}
		if (handlers_map.has('mouseover') && !handlers_map.has('focus')) {
			component.warn(
				this,
				compiler_warnings.a11y_mouse_events_have_key_events('mouseover', 'focus')
			);
		}
		if (handlers_map.has('mouseout') && !handlers_map.has('blur')) {
			component.warn(this, compiler_warnings.a11y_mouse_events_have_key_events('mouseout', 'blur'));
		}
	}
	validate_bindings_foreign() {
		this.bindings.forEach(
			/** @param {any} binding */ (binding) => {
				if (binding.name !== 'this') {
					return this.component.error(
						binding,
						compiler_errors.invalid_binding_foreign(binding.name)
					);
				}
			}
		);
	}
	validate_bindings() {
		const { component } = this;
		const check_type_attribute = () => {
			const attribute = this.attributes.find(
				/** @param {import('./Attribute.js').default} attribute */ (attribute) =>
					attribute.name === 'type'
			);
			if (!attribute) return null;
			if (!attribute.is_static) {
				return component.error(attribute, compiler_errors.invalid_type);
			}
			const value = attribute.get_static_value();
			if (value === true) {
				return component.error(attribute, compiler_errors.missing_type);
			}
			return value;
		};
		this.bindings.forEach(
			/** @param {any} binding */ (binding) => {
				const { name } = binding;
				if (name === 'value') {
					if (this.name !== 'input' && this.name !== 'textarea' && this.name !== 'select') {
						return component.error(
							binding,
							compiler_errors.invalid_binding_elements(this.name, 'value')
						);
					}
					if (this.name === 'select') {
						const attribute = this.attributes.find(
							/** @param {import('./Attribute.js').default} attribute */
							(attribute) => attribute.name === 'multiple'
						);
						if (attribute && !attribute.is_static) {
							return component.error(attribute, compiler_errors.dynamic_multiple_attribute);
						}
					} else {
						check_type_attribute();
					}
				} else if (name === 'checked' || name === 'indeterminate') {
					if (this.name !== 'input') {
						return component.error(
							binding,
							compiler_errors.invalid_binding_elements(this.name, name)
						);
					}
					const type = check_type_attribute();
					if (type !== 'checkbox') {
						return component.error(
							binding,
							compiler_errors.invalid_binding_no_checkbox(name, type === 'radio')
						);
					}
				} else if (name === 'group') {
					if (this.name !== 'input') {
						return component.error(
							binding,
							compiler_errors.invalid_binding_elements(this.name, 'group')
						);
					}
					const type = check_type_attribute();
					if (type !== 'checkbox' && type !== 'radio') {
						return component.error(
							binding,
							compiler_errors.invalid_binding_element_with(
								'<input type="checkbox"> or <input type="radio">',
								'group'
							)
						);
					}
				} else if (name === 'files') {
					if (this.name !== 'input') {
						return component.error(
							binding,
							compiler_errors.invalid_binding_elements(this.name, 'files')
						);
					}
					const type = check_type_attribute();
					if (type !== 'file') {
						return component.error(
							binding,
							compiler_errors.invalid_binding_element_with('<input type="file">', 'files')
						);
					}
				} else if (name === 'open') {
					if (this.name !== 'details') {
						return component.error(
							binding,
							compiler_errors.invalid_binding_element_with('<details>', name)
						);
					}
				} else if (
					name === 'currentTime' ||
					name === 'duration' ||
					name === 'paused' ||
					name === 'buffered' ||
					name === 'seekable' ||
					name === 'played' ||
					name === 'volume' ||
					name === 'muted' ||
					name === 'playbackRate' ||
					name === 'seeking' ||
					name === 'ended' ||
					name === 'readyState'
				) {
					if (this.name !== 'audio' && this.name !== 'video') {
						return component.error(
							binding,
							compiler_errors.invalid_binding_element_with('audio> or <video>', name)
						);
					}
				} else if (name === 'videoHeight' || name === 'videoWidth') {
					if (this.name !== 'video') {
						return component.error(
							binding,
							compiler_errors.invalid_binding_element_with('<video>', name)
						);
					}
				} else if (regex_dimensions.test(name)) {
					if (this.name === 'svg' && (name === 'offsetWidth' || name === 'offsetHeight')) {
						return component.error(
							binding,
							compiler_errors.invalid_binding_on(
								binding.name,
								`<svg>. Use '${name.replace('offset', 'client')}' instead`
							)
						);
					} else if (is_svg(this.name)) {
						return component.error(
							binding,
							compiler_errors.invalid_binding_on(binding.name, 'SVG elements')
						);
					} else if (is_void(this.name)) {
						return component.error(
							binding,
							compiler_errors.invalid_binding_on(
								binding.name,
								`void elements like <${this.name}>. Use a wrapper element instead`
							)
						);
					}
				} else if (name === 'naturalWidth' || name === 'naturalHeight') {
					if (this.name !== 'img') {
						return component.error(
							binding,
							compiler_errors.invalid_binding_element_with('<img>', name)
						);
					}
				} else if (is_name_contenteditable(name)) {
					const contenteditable = get_contenteditable_attr(this);
					if (!contenteditable) {
						return component.error(binding, compiler_errors.missing_contenteditable_attribute);
					} else if (contenteditable && !contenteditable.is_static) {
						return component.error(
							contenteditable,
							compiler_errors.dynamic_contenteditable_attribute
						);
					}
				} else if (name !== 'this' && !regex_box_size.test(name)) {
					return component.error(binding, compiler_errors.invalid_binding(binding.name));
				}
			}
		);
	}
	validate_content() {
		if (!a11y_required_content.has(this.name)) return;
		if (this.contains_a11y_label) return;
		if (
			this.bindings.some(
				/** @param {any} binding */ (binding) => ['textContent', 'innerHTML'].includes(binding.name)
			)
		)
			return;
		if (this.children.length === 0) {
			this.component.warn(this, compiler_warnings.a11y_missing_content(this.name));
		}
	}
	validate_event_handlers() {
		const { component } = this;
		this.handlers.forEach(
			/** @param {any} handler */ (handler) => {
				if (handler.modifiers.has('passive') && handler.modifiers.has('preventDefault')) {
					return component.error(
						handler,
						compiler_errors.invalid_event_modifier_combination('passive', 'preventDefault')
					);
				}
				if (handler.modifiers.has('passive') && handler.modifiers.has('nonpassive')) {
					return component.error(
						handler,
						compiler_errors.invalid_event_modifier_combination('passive', 'nonpassive')
					);
				}
				handler.modifiers.forEach(
					/** @param {any} modifier */ (modifier) => {
						if (!valid_modifiers.has(modifier)) {
							return component.error(
								handler,
								compiler_errors.invalid_event_modifier(list(Array.from(valid_modifiers)))
							);
						}
						if (modifier === 'passive') {
							if (passive_events.has(handler.name)) {
								if (handler.can_make_passive) {
									component.warn(handler, compiler_warnings.redundant_event_modifier_for_touch);
								}
							} else {
								component.warn(handler, compiler_warnings.redundant_event_modifier_passive);
							}
						}
						if (
							component.compile_options.legacy &&
							(modifier === 'once' || modifier === 'passive')
						) {
							// TODO this could be supported, but it would need a few changes to
							// how event listeners work
							return component.error(
								handler,
								compiler_errors.invalid_event_modifier_legacy(modifier)
							);
						}
					}
				);
				if (
					passive_events.has(handler.name) &&
					handler.can_make_passive &&
					!handler.modifiers.has('preventDefault') &&
					!handler.modifiers.has('nonpassive')
				) {
					// touch/wheel events should be passive by default
					handler.modifiers.add('passive');
				}
			}
		);
	}
	is_media_node() {
		return this.name === 'audio' || this.name === 'video';
	}
	add_css_class() {
		if (this.attributes.some(/** @param {any} attr */ (attr) => attr.is_spread)) {
			this.needs_manual_style_scoping = true;
			return;
		}
		const { id } = this.component.stylesheet;
		const class_attribute = this.attributes.find(/** @param {any} a */ (a) => a.name === 'class');
		if (class_attribute && !class_attribute.is_true) {
			if (class_attribute.chunks.length === 1 && class_attribute.chunks[0].type === 'Text') {
				/** @type {import('./Text.js').default} */ (class_attribute.chunks[0]).data += ` ${id}`;
			} else {
				/** @type {import('./shared/Node.js').default[]} */ (class_attribute.chunks).push(
					new Text$1(
						this.component,
						this,
						this.scope,
						/** @type {any} */ ({
							type: 'Text',
							data: ` ${id}`,
							synthetic: true
						})
					)
				);
			}
		} else {
			this.attributes.push(
				new Attribute(
					this.component,
					this,
					this.scope,
					/** @type {any} */ ({
						type: 'Attribute',
						name: 'class',
						value: [{ type: 'Text', data: id, synthetic: true }]
					})
				)
			);
		}
	}
	get slot_template_name() {
		return /** @type {string} */ (
			this.attributes
				.find(/** @param {any} attribute */ (attribute) => attribute.name === 'slot')
				.get_static_value()
		);
	}
	optimise() {
		attributes_to_compact_whitespace.forEach(
			/** @param {any} attribute_name */ (attribute_name) => {
				const attribute = this.attributes.find(
					/** @param {any} a */ (a) => a.name === attribute_name
				);
				if (attribute && !attribute.is_true) {
					attribute.chunks.forEach(
						/**
						 * @param {any} chunk
						 * @param {any} index
						 */ (chunk, index) => {
							if (chunk.type === 'Text') {
								let data = chunk.data.replace(regex_any_repeated_whitespaces, ' ');
								if (index === 0) {
									data = data.trimLeft();
								} else if (index === attribute.chunks.length - 1) {
									data = data.trimRight();
								}
								chunk.data = data;
							}
						}
					);
				}
			}
		);
	}
	get can_use_textcontent() {
		return (
			this.is_static_content &&
			this.children.every(
				/** @param {any} node */ (node) => node.type === 'Text' || node.type === 'MustacheTag'
			)
		);
	}
	get can_optimise_to_html_string() {
		const can_use_textcontent = this.can_use_textcontent;
		const is_template_with_text_content = this.name === 'template' && can_use_textcontent;
		return (
			!is_template_with_text_content &&
			!this.namespace &&
			(this.can_use_innerhtml || can_use_textcontent) &&
			this.children.length > 0
		);
	}
	get can_optimise_hydration() {
		// In contrast to normal html string optimization, we also bail in case of mustache tags even
		// if they seem to contain static content. This is because we cannot know whether that static
		// value is different between client and server builds, e.g. {browser ? 'hi' : 'bye'} which
		// becomes {'hi'} and {'bye'} respectively.
		const is_static_text_content =
			this.is_static_content && this.children.every((node) => node.type === 'Text');
		return this.can_optimise_to_html_string && (this.can_use_innerhtml || is_static_text_content);
	}
	hash() {
		return `svelte-${hash(this.component.source.slice(this.start, this.end))}`;
	}
};
const regex_starts_with_vowel = /^[aeiou]/;

/**
 * @param {any} node
 * @param {string[]} attributes
 * @param {any} name
 */
function should_have_attribute(node, attributes, name = node.name) {
	const article = regex_starts_with_vowel.test(attributes[0]) ? 'an' : 'a';
	const sequence =
		attributes.length > 1
			? attributes.slice(0, -1).join(', ') + ` or ${attributes[attributes.length - 1]}`
			: attributes[0];
	node.component.warn(node, compiler_warnings.a11y_missing_attribute(name, article, sequence));
}
const regex_minus_sign$1 = /-/;

/** @param {import('./interfaces.js').INode} parent */
function within_custom_element(parent) {
	while (parent) {
		if (parent.type === 'InlineComponent') return false;
		if (parent.type === 'Element' && regex_minus_sign$1.test(parent.name)) return true;
		parent = parent.parent;
	}
	return false;
}

/** @extends Node<'Head'> */
let Head$1 = class Head extends Node {
	/** @type {any[]} */
	children; // TODO

	/** @type {string} */
	id;

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./shared/Node.js').default} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		this.cannot_use_innerhtml();
		if (info.attributes.length) {
			component.error(info.attributes[0], compiler_errors.invalid_attribute_head);
			return;
		}
		this.children = map_children(
			component,
			parent,
			scope,
			info.children.filter(
				/** @param {any} child */ (child) => {
					return child.type !== 'Text' || regex_non_whitespace_character.test(child.data);
				}
			)
		);
		if (this.children.length > 0) {
			this.id = `svelte-${hash(this.component.source.slice(this.start, this.end))}`;
		}
	}
};

/** @extends AbstractBlock<'IfBlock'> */
let IfBlock$1 = class IfBlock extends AbstractBlock {
	/** @type {import('./shared/Expression.js').default} */
	expression;

	/** @type {import('./ElseBlock.js').default} */
	else;

	/** @type {import('./shared/TemplateScope.js').default} */
	scope;

	/** @type {import('./ConstTag.js').default[]} */
	const_tags;

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./shared/Node.js').default} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		this.scope = scope.child();
		this.cannot_use_innerhtml();
		this.not_static_content();
		this.expression = new Expression(component, this, this.scope, info.expression);
		[this.const_tags, this.children] = get_const_tags$1(info.children, component, this, this);
		this.else = info.else ? new ElseBlock(component, this, scope, info.else) : null;
		this.warn_if_empty_block();
	}
};

/** @extends Node<'InlineComponent'> */
let InlineComponent$1 = class InlineComponent extends Node {
	/** @type {string} */
	name;

	/** @type {import('./shared/Expression.js').default} */
	expression;

	/** @type {import('./Binding.js').default[]} */
	bindings = [];

	/** @type {import('./EventHandler.js').default[]} */
	handlers = [];

	/** @type {import('./Attribute.js').default[]} */
	css_custom_properties = [];

	/** @type {import('./interfaces.js').INode[]} */
	children;

	/** @type {import('./shared/TemplateScope.js').default} */
	scope;

	/** @type {string} */
	namespace;

	/** @type {Attribute[]} */
	let_attributes;
	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./shared/Node.js').default} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		this.cannot_use_innerhtml();
		this.not_static_content();
		if (info.name !== 'svelte:component' && info.name !== 'svelte:self') {
			const name = info.name.split('.')[0]; // accommodate namespaces
			component.warn_if_undefined(name, info, scope);
			component.add_reference(/** @type {any} */ (this), name);
		}
		this.name = info.name;
		this.namespace = get_namespace(parent, component.namespace);
		this.expression =
			this.name === 'svelte:component'
				? new Expression(component, this, scope, info.expression)
				: null;

		const let_attributes = (this.let_attributes = []);
		info.attributes.forEach(
			/** @param {import('../../interfaces.js').BaseDirective | import('../../interfaces.js').Attribute | import('../../interfaces.js').SpreadAttribute} node */ (
				node
			) => {
				/* eslint-disable no-fallthrough */
				switch (node.type) {
					case 'Action':
						return component.error(node, compiler_errors.invalid_action);
					case 'Attribute':
						if (node.name.startsWith('--')) {
							this.css_custom_properties.push(new Attribute(component, this, scope, node));
							break;
						}
					// fallthrough
					case 'Spread':
						this.attributes.push(new Attribute(component, this, scope, node));
						break;
					case 'Binding':
						this.bindings.push(new Binding(component, this, scope, node));
						break;
					case 'Class':
						return component.error(node, compiler_errors.invalid_class);
					case 'EventHandler':
						this.handlers.push(new EventHandler(component, this, scope, node));
						break;
					case 'Let':
						let_attributes.push(node);
						break;
					case 'Transition':
						return component.error(node, compiler_errors.invalid_transition);
					case 'StyleDirective':
						return component.error(node, compiler_errors.invalid_component_style_directive);
					case 'Animation':
						return component.error(node, compiler_errors.invalid_animation);
					default:
						throw new Error(`Not implemented: ${node.type}`);
				}
				/* eslint-enable no-fallthrough */
			}
		);

		this.scope = scope;

		this.handlers.forEach(
			/** @param {any} handler */ (handler) => {
				handler.modifiers.forEach(
					/** @param {any} modifier */ (modifier) => {
						if (modifier !== 'once') {
							return component.error(handler, compiler_errors.invalid_event_modifier_component);
						}
					}
				);
			}
		);
		const children = [];
		for (let i = info.children.length - 1; i >= 0; i--) {
			const child = info.children[i];
			if (child.type === 'SlotTemplate') {
				children.push(child);
				info.children.splice(i, 1);
			} else if (
				(child.type === 'Element' || child.type === 'InlineComponent' || child.type === 'Slot') &&
				child.attributes.find(
					/** @param {any} attribute */ (attribute) => attribute.name === 'slot'
				)
			) {
				const slot_template = {
					start: child.start,
					end: child.end,
					type: 'SlotTemplate',
					name: 'svelte:fragment',
					attributes: [],
					children: [child]
				};
				// transfer attributes
				for (let i = child.attributes.length - 1; i >= 0; i--) {
					const attribute = child.attributes[i];
					if (attribute.type === 'Let') {
						slot_template.attributes.push(attribute);
						child.attributes.splice(i, 1);
					} else if (attribute.type === 'Attribute' && attribute.name === 'slot') {
						slot_template.attributes.push(attribute);
					}
				}
				// transfer const
				for (let i = child.children.length - 1; i >= 0; i--) {
					const child_child = child.children[i];
					if (child_child.type === 'ConstTag') {
						slot_template.children.push(child_child);
						child.children.splice(i, 1);
					}
				}
				children.push(slot_template);
				info.children.splice(i, 1);
			} else if (child.type === 'Comment' && children.length > 0) {
				children[children.length - 1].children.unshift(child);
			}
		}
		if (info.children.some(/** @param {any} node */ (node) => not_whitespace_text(node))) {
			children.push({
				start: info.start,
				end: info.end,
				type: 'SlotTemplate',
				name: 'svelte:fragment',
				attributes: [],
				children: info.children
			});
		}

		if (let_attributes.length) {
			// copy let: attribute from <Component /> to <svelte:fragment slot="default" />
			// as they are for `slot="default"` only
			children.forEach((child) => {
				const slot = child.attributes.find((attribute) => attribute.name === 'slot');
				if (!slot || slot.value[0].data === 'default') {
					child.attributes.push(...let_attributes);
				}
			});
		}

		this.children = map_children(component, this, this.scope, children);
	}
	get slot_template_name() {
		return /** @type {string} */ (
			this.attributes
				.find(/** @param {any} attribute */ (attribute) => attribute.name === 'slot')
				.get_static_value()
		);
	}
};

/** @param {any} node */
function not_whitespace_text(node) {
	return !(node.type === 'Text' && regex_only_whitespaces.test(node.data));
}

/**
 * @param {import('./shared/Node.js').default} parent
 * @param {string} explicit_namespace
 */
function get_namespace(parent, explicit_namespace) {
	const parent_element = parent.find_nearest(/^Element/);
	if (!parent_element) {
		return explicit_namespace;
	}
	return parent_element.namespace;
}

/** @extends AbstractBlock<'KeyBlock'> */
let KeyBlock$1 = class KeyBlock extends AbstractBlock {
	/** @type {import('./shared/Expression.js').default} */
	expression;

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./shared/Node.js').default} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		this.cannot_use_innerhtml();
		this.not_static_content();
		this.expression = new Expression(component, this, scope, info.expression);
		this.children = map_children(component, this, scope, info.children);
		this.warn_if_empty_block();
	}
};

/**
 * @template {'MustacheTag' | 'RawMustacheTag'} [Type='MustacheTag' | 'RawMustacheTag']
 * @extends Node<Type>
 */
let Tag$2 = class Tag extends Node {
	/** @type {import('./Expression.js').default} */
	expression;

	/** @type {boolean} */
	should_cache;

	/**
	 * @param {any} component
	 * @param {any} parent
	 * @param {any} scope
	 * @param {any} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		component.tags.push(this);
		this.cannot_use_innerhtml();
		this.expression = new Expression(component, this, scope, info.expression);
		this.should_cache =
			info.expression.type !== 'Identifier' ||
			(this.expression.dependencies.size && scope.names.has(info.expression.name));
	}
	is_dependencies_static() {
		return (
			this.expression.dynamic_contextual_dependencies().length === 0 &&
			this.expression.dynamic_dependencies().length === 0
		);
	}
	check_if_content_dynamic() {
		if (!this.is_dependencies_static()) {
			this.not_static_content();
		}
	}
};

/** @extends Tag<'MustacheTag'> */
class MustacheTag extends Tag$2 {}

/** @extends Node<'Options'> */
class Options extends Node {}

/** @extends Tag<'RawMustacheTag'> */
class RawMustacheTag extends Tag$2 {
	/**
	 * @param {any} component
	 * @param {any} parent
	 * @param {any} scope
	 * @param {any} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		this.cannot_use_innerhtml();
		this.not_static_content();
	}
}

/** @extends Node<'DebugTag'> */
let DebugTag$1 = class DebugTag extends Node {
	/** @type {import('./shared/Expression.js').default[]} */
	expressions;

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./interfaces.js').INode} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		this.expressions = info.identifiers.map(
			/** @param {import('estree').Node} node */ (node) => {
				return new Expression(component, parent, scope, node);
			}
		);
	}
};

/** @extends Element */
let Slot$1 = class Slot extends Element$1 {
	/** @type {'Slot'} */
	// @ts-ignore Slot elements have the 'Slot' type, but TypeScript doesn't allow us to have 'Slot' when it extends Element
	type = 'Slot';

	/** @type {string} */
	slot_name;

	/** @type {Map<string, import('./Attribute.js').default>} */
	values = new Map();

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./interfaces.js').INode} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		info.attributes.forEach(
			/** @param {any} attr */ (attr) => {
				if (attr.type !== 'Attribute' && attr.type !== 'Spread') {
					return component.error(attr, compiler_errors.invalid_slot_directive);
				}
				if (attr.name === 'name') {
					if (attr.value.length !== 1 || attr.value[0].type !== 'Text') {
						return component.error(attr, compiler_errors.dynamic_slot_name);
					}
					this.slot_name = attr.value[0].data;
					if (this.slot_name === 'default') {
						return component.error(attr, compiler_errors.invalid_slot_name);
					}
				}
				this.values.set(attr.name, new Attribute(component, this, scope, attr));
			}
		);
		if (!this.slot_name) this.slot_name = 'default';

		component.slots.set(this.slot_name, this);
		this.cannot_use_innerhtml();
		this.not_static_content();
	}
};

/** @extends Node<'SlotTemplate'> */
let SlotTemplate$1 = class SlotTemplate extends Node {
	/** @type {import('./shared/TemplateScope.js').default} */
	scope;

	/** @type {import('./interfaces.js').INode[]} */
	children;

	/** @type {import('./Let.js').default[]} */
	lets = [];

	/** @type {import('./ConstTag.js').default[]} */
	const_tags;

	/** @type {import('./Attribute.js').default} */
	slot_attribute;

	/** @type {string} */
	slot_template_name = 'default';

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./interfaces.js').INode} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {any} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		this.validate_slot_template_placement();
		scope = scope.child();
		info.attributes.forEach(
			/** @param {any} node */ (node) => {
				switch (node.type) {
					case 'Let': {
						const l = new Let(component, this, scope, node);
						this.lets.push(l);
						const dependencies = new Set([l.name.name]);
						l.names.forEach(
							/** @param {any} name */ (name) => {
								scope.add(name, dependencies, this);
							}
						);
						break;
					}
					case 'Attribute': {
						if (node.name === 'slot') {
							this.slot_attribute = new Attribute(component, this, scope, node);
							if (!this.slot_attribute.is_static) {
								return component.error(node, compiler_errors.invalid_slot_attribute);
							}
							const value = this.slot_attribute.get_static_value();
							if (typeof value === 'boolean') {
								return component.error(node, compiler_errors.invalid_slot_attribute_value_missing);
							}
							this.slot_template_name = /** @type {string} */ (value);
							break;
						}
						throw new Error(`Invalid attribute '${node.name}' in <svelte:fragment>`);
					}
					default:
						throw new Error(`Not implemented: ${node.type}`);
				}
			}
		);
		this.scope = scope;
		[this.const_tags, this.children] = get_const_tags$1(info.children, component, this, this);
	}
	validate_slot_template_placement() {
		if (this.parent.type !== 'InlineComponent') {
			return this.component.error(this, compiler_errors.invalid_slotted_content_fragment);
		}
	}
};

/** @extends Node<'Title'> */
let Title$1 = class Title extends Node {
	/** @type {import('./shared/map_children.js').Children} */
	children;

	/** @type {boolean} */
	should_cache;

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./shared/Node.js').default} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		this.children = map_children(component, parent, scope, info.children);
		if (info.attributes.length > 0) {
			component.error(info.attributes[0], compiler_errors.illegal_attribute_title);
			return;
		}
		info.children.forEach(
			/** @param {any} child */ (child) => {
				if (child.type !== 'Text' && child.type !== 'MustacheTag') {
					return component.error(child, compiler_errors.illegal_structure_title);
				}
			}
		);
		this.should_cache =
			info.children.length === 1
				? info.children[0].type !== 'Identifier' || scope.names.has(info.children[0].name)
				: true;
	}
};

const valid_bindings = [
	'innerWidth',
	'innerHeight',
	'outerWidth',
	'outerHeight',
	'scrollX',
	'scrollY',
	'devicePixelRatio',
	'online'
];

/** @extends Node<'Window'> */
class Window extends Node {
	/** @type {import('./EventHandler.js').default[]} */
	handlers = [];

	/** @type {import('./Binding.js').default[]} */
	bindings = [];

	/** @type {import('./Action.js').default[]} */
	actions = [];

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./shared/Node.js').default} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		info.attributes.forEach(
			/** @param {any} node */ (node) => {
				if (node.type === 'EventHandler') {
					this.handlers.push(new EventHandler(component, this, scope, node));
				} else if (node.type === 'Binding') {
					if (node.expression.type !== 'Identifier') {
						const { parts } = flatten_reference(node.expression);
						// TODO is this constraint necessary?
						return component.error(node.expression, compiler_errors.invalid_binding_window(parts));
					}
					if (!~valid_bindings.indexOf(node.name)) {
						const match =
							node.name === 'width'
								? 'innerWidth'
								: node.name === 'height'
								? 'innerHeight'
								: fuzzymatch(node.name, valid_bindings);
						if (match) {
							return component.error(
								node,
								compiler_errors.invalid_binding_on(
									node.name,
									'<svelte:window>',
									` (did you mean '${match}'?)`
								)
							);
						} else {
							return component.error(
								node,
								compiler_errors.invalid_binding_on(
									node.name,
									'<svelte:window>',
									` — valid bindings are ${list(valid_bindings)}`
								)
							);
						}
					}
					this.bindings.push(new Binding(component, this, scope, node));
				} else if (node.type === 'Action') {
					this.actions.push(new Action(component, this, scope, node));
				} else ;
			}
		);
	}
}

/**
 * Pushes all `items` into `array` using `push`, therefore mutating the array.
 * We do this for memory and perf reasons, and because `array.push(...items)` would
 * run into a "max call stack size exceeded" error with too many items (~65k).
 * @template T
 * @param {T[]} array
 * @param {T[]} items
 */
function push_array(array, items) {
	for (let i = 0; i < items.length; i++) {
		array.push(items[i]);
	}
}

/** @typedef {ReturnType<typeof map_children>} Children */

/** @param {any} type */
function get_constructor(type) {
	switch (type) {
		case 'AwaitBlock':
			return AwaitBlock$1;
		case 'Body':
			return Body;
		case 'Comment':
			return Comment$1;
		case 'ConstTag':
			return ConstTag;
		case 'Document':
			return Document;
		case 'EachBlock':
			return EachBlock$1;
		case 'Element':
			return Element$1;
		case 'Head':
			return Head$1;
		case 'IfBlock':
			return IfBlock$1;
		case 'InlineComponent':
			return InlineComponent$1;
		case 'KeyBlock':
			return KeyBlock$1;
		case 'MustacheTag':
			return MustacheTag;
		case 'Options':
			return Options;
		case 'RawMustacheTag':
			return RawMustacheTag;
		case 'DebugTag':
			return DebugTag$1;
		case 'Slot':
			return Slot$1;
		case 'SlotTemplate':
			return SlotTemplate$1;
		case 'Text':
			return Text$1;
		case 'Title':
			return Title$1;
		case 'Window':
			return Window;
		default:
			throw new Error(`Not implemented: ${type}`);
	}
}

/**
 * @param {any} component
 * @param {any} parent
 * @param {any} scope
 * @param {import('../../../interfaces.js').TemplateNode[]} children
 */
function map_children(component, parent, scope, children) {
	let last = null;
	let ignores = [];
	return children.map(
		/** @param {any} child */ (child) => {
			const constructor = get_constructor(child.type);
			const use_ignores = child.type !== 'Text' && child.type !== 'Comment' && ignores.length;
			if (use_ignores) component.push_ignores(ignores);
			const node = new constructor(component, parent, scope, child);
			if (use_ignores) component.pop_ignores(), (ignores = []);
			if (node.type === 'Comment' && node.ignores.length) {
				push_array(ignores, node.ignores);
			}
			if (last) last.next = node;
			node.prev = last;
			last = node;
			return node;
		}
	);
}

/**
 * @param {Array<[any, any]>} edges
 * @returns {any[]}
 */
function check_graph_for_cycles(edges) {
	/** @type {Map<any, any[]>} */
	const graph = edges.reduce((g, edge) => {
		const [u, v] = edge;
		if (!g.has(u)) g.set(u, []);
		if (!g.has(v)) g.set(v, []);
		g.get(u).push(v);
		return g;
	}, new Map());

	const visited = new Set();
	const on_stack = new Set();
	const cycles = [];

	function visit(v) {
		visited.add(v);
		on_stack.add(v);

		graph.get(v).forEach((w) => {
			if (!visited.has(w)) {
				visit(w);
			} else if (on_stack.has(w)) {
				cycles.push([...on_stack, w]);
			}
		});

		on_stack.delete(v);
	}

	graph.forEach((_, v) => {
		if (!visited.has(v)) {
			visit(v);
		}
	});

	return cycles[0];
}

/**
 * @param {import('../../../interfaces.js').TemplateNode[]} children
 * @param {import('../../Component.js').default} component
 * @param {import('../interfaces.js').INodeAllowConstTag} node
 * @param {import('../interfaces.js').INode} parent
 * @returns {[ConstTag[], Array<Exclude<import('../interfaces.js').INode, ConstTag>>]}
 */
function get_const_tags$1(children, component, node, parent) {
	/** @type {import('../../../interfaces.js').ConstTag[]} */
	const const_tags = [];

	/** @type {Array<Exclude<import('../../../interfaces.js').TemplateNode, import('../../../interfaces.js').ConstTag>>} */
	const others = [];
	for (const child of children) {
		if (child.type === 'ConstTag') {
			const_tags.push(/** @type {import('../../../interfaces.js').ConstTag} */ (child));
		} else {
			others.push(child);
		}
	}
	const consts_nodes = const_tags.map(
		/** @param {any} tag */ (tag) => new ConstTag(component, node, node.scope, tag)
	);
	const sorted_consts_nodes = sort_consts_nodes(consts_nodes, component);
	sorted_consts_nodes.forEach(/** @param {any} node */ (node) => node.parse_expression());
	const children_nodes = map_children(component, parent, node.scope, others);
	return [
		sorted_consts_nodes,
		/** @type {Array<Exclude<import('../interfaces.js').INode, ConstTag>>} */ (children_nodes)
	];
}

/**
 * @param {ConstTag[]} consts_nodes
 * @param {import('../../Component.js').default} component
 */
function sort_consts_nodes(consts_nodes, component) {
	/** @typedef {{ assignees: Set<string>; dependencies: Set<string>; node: ConstTag; }} ConstNode */

	/** @type {ConstNode[]} */
	const sorted_consts_nodes = [];

	/** @type {ConstNode[]} */
	const unsorted_consts_nodes = consts_nodes.map(
		/** @param {any} node */ (node) => {
			return {
				assignees: node.assignees,
				dependencies: node.dependencies,
				node
			};
		}
	);
	const lookup = new Map();
	unsorted_consts_nodes.forEach(
		/** @param {any} node */ (node) => {
			node.assignees.forEach(
				/** @param {any} name */ (name) => {
					if (!lookup.has(name)) {
						lookup.set(name, []);
					}
					lookup.get(name).push(node);
				}
			);
		}
	);
	const cycle = check_graph_for_cycles(
		unsorted_consts_nodes.reduce(
			/**
			 * @param {any} acc
			 * @param {any} node
			 */ (acc, node) => {
				node.assignees.forEach(
					/** @param {any} v */ (v) => {
						node.dependencies.forEach(
							/** @param {any} w */ (w) => {
								if (!node.assignees.has(w)) {
									acc.push([v, w]);
								}
							}
						);
					}
				);
				return acc;
			},
			[]
		)
	);
	if (cycle && cycle.length) {
		const nodeList = lookup.get(cycle[0]);
		const node = nodeList[0];
		component.error(node.node, compiler_errors.cyclical_const_tags(cycle));
	}

	/** @param {ConstNode} node */
	const add_node = (node) => {
		if (sorted_consts_nodes.includes(node)) return;
		node.dependencies.forEach(
			/** @param {any} name */ (name) => {
				if (node.assignees.has(name)) return;
				const earlier_nodes = lookup.get(name);
				if (earlier_nodes) {
					earlier_nodes.forEach(add_node);
				}
			}
		);
		sorted_consts_nodes.push(node);
	};
	unsorted_consts_nodes.forEach(add_node);
	return sorted_consts_nodes.map(/** @param {any} node */ (node) => node.node);
}

/** @extends AbstractBlock<'ThenBlock'> */
class ThenBlock extends AbstractBlock {
	/** @type {import('./shared/TemplateScope.js').default} */
	scope;

	/** @type {import('./ConstTag.js').default[]} */
	const_tags;

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('./AwaitBlock.js').default} parent
	 * @param {import('./shared/TemplateScope.js').default} scope
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, parent, scope, info) {
		super(component, parent, scope, info);
		this.scope = scope.child();
		if (parent.then_node) {
			parent.then_contexts.forEach(
				/** @param {any} context */ (context) => {
					if (context.type !== 'DestructuredVariable') return;
					this.scope.add(context.key.name, parent.expression.dependencies, this);
				}
			);
		}
		[this.const_tags, this.children] = get_const_tags$1(info.children, component, this, parent);
		if (!info.skip) {
			this.warn_if_empty_block();
		}
	}
}

/**
 * @param {import('../../Block.js').default} block
 * @param {import('../../../nodes/ConstTag.js').default[]} const_tags
 * @param {string} ctx
 */
function add_const_tags(block, const_tags, ctx) {
	const const_tags_props = [];
	const_tags.forEach((const_tag, i) => {
		const name = `#constants_${i}`;
		const_tags_props.push(b$1`const ${name} = ${const_tag.expression.manipulate(block, ctx)}`);

		/** @param {string} name */
		const to_ctx = (name) =>
			block.renderer.context_lookup.has(name)
				? x$1`${ctx}[${block.renderer.context_lookup.get(name).index}]`
				: /** @type {import('code-red').Node} */ ({ type: 'Identifier', name });
		const_tag.contexts.forEach((context) => {
			if (context.type === 'DestructuredVariable') {
				const_tags_props.push(
					b$1`${ctx}[${
						block.renderer.context_lookup.get(context.key.name).index
					}] = ${context.default_modifier(context.modifier({ type: 'Identifier', name }), to_ctx)}`
				);
			} else {
				const expression = new Expression(
					block.renderer.component,
					const_tag,
					const_tag.scope,
					context.key
				);
				const_tags_props.push(
					b$1`const ${context.property_name} = ${expression.manipulate(block, ctx)}`
				);
			}
		});
	});
	return const_tags_props;
}

/**
 * @param {import('../../Renderer.js').default} renderer
 * @param {import('../../../nodes/ConstTag.js').default[]} const_tags
 */
function add_const_tags_context(renderer, const_tags) {
	const_tags.forEach((const_tag) => {
		const_tag.contexts.forEach((context) => {
			if (context.type !== 'DestructuredVariable') return;
			renderer.add_to_context(context.key.name, true);
		});
	});
}

/** @extends Wrapper<import('../../nodes/PendingBlock.js').default | import('../../nodes/ThenBlock.js').default | import('../../nodes/CatchBlock.js').default> */
class AwaitBlockBranch extends Wrapper {
	/** @typedef {'pending' | 'then' | 'catch'} Status */

	/** @type {import('../Block.js').default} */
	block;

	/** @type {import('./Fragment.js').default} */
	fragment;

	/** @type {boolean} */
	is_dynamic;

	var = null;

	/** @type {Status} */
	status;

	/** @type {string} */
	value;

	/** @type {import('estree').Literal} */
	value_index;

	/** @type {import('../../nodes/shared/Context.js').Context[]} */
	value_contexts;

	/** @type {boolean} */
	is_destructured;

	/**
	 * @param {Status} status
	 * @param {import('../Renderer.js').default} renderer
	 * @param {import('../Block.js').default} block
	 * @param {AwaitBlockWrapper} parent
	 * @param {import('../../nodes/PendingBlock.js').default | import('../../nodes/ThenBlock.js').default | import('../../nodes/CatchBlock.js').default} node
	 * @param {boolean} strip_whitespace
	 * @param {import('./shared/Wrapper.js').default} next_sibling
	 */
	constructor(status, renderer, block, parent, node, strip_whitespace, next_sibling) {
		super(renderer, block, parent, node);
		this.status = status;
		this.block = block.child({
			comment: create_debugging_comment(node, this.renderer.component),
			name: this.renderer.component.get_unique_name(`create_${status}_block`),
			type: status
		});
		this.add_context(parent.node[status + '_node'], parent.node[status + '_contexts']);
		this.fragment = new FragmentWrapper(
			renderer,
			this.block,
			this.node.children,
			parent,
			strip_whitespace,
			next_sibling
		);
		this.is_dynamic = this.block.dependencies.size > 0;
	}

	/**
	 * @param {import('estree').Node | null} node
	 * @param {import('../../nodes/shared/Context.js').Context[]} contexts
	 */
	add_context(node, contexts) {
		if (!node) return;
		if (node.type === 'Identifier') {
			this.value = node.name;
			this.renderer.add_to_context(this.value, true);
		} else {
			contexts.forEach((context) => {
				if (context.type !== 'DestructuredVariable') return;
				this.renderer.add_to_context(context.key.name, true);
			});
			this.value = this.block.parent.get_unique_name('value').name;
			this.value_contexts = contexts;
			this.renderer.add_to_context(this.value, true);
			this.is_destructured = true;
		}
		this.value_index = this.renderer.context_lookup.get(this.value).index;
		if (this.has_consts(this.node)) {
			add_const_tags_context(this.renderer, this.node.const_tags);
		}
	}

	/**
	 * @param {import('../../nodes/PendingBlock.js').default | import('../../nodes/ThenBlock.js').default | import('../../nodes/CatchBlock.js').default} node
	 * @returns {node is import('../../nodes/ThenBlock.js').default | import('../../nodes/CatchBlock.js').default}
	 */
	has_consts(node) {
		return node instanceof ThenBlock || node instanceof CatchBlock;
	}

	/**
	 * @param {import('../Block.js').default} block
	 * @param {import('estree').Identifier} parent_node
	 * @param {import('estree').Identifier} parent_nodes
	 */
	render(block, parent_node, parent_nodes) {
		this.fragment.render(block, parent_node, parent_nodes);
		if (this.is_destructured || (this.has_consts(this.node) && this.node.const_tags.length > 0)) {
			this.render_get_context();
		}
	}
	render_get_context() {
		const props = this.is_destructured
			? this.value_contexts.map((prop) => {
					if (prop.type === 'ComputedProperty') {
						const expression = new Expression(
							this.renderer.component,
							this.node,
							this.has_consts(this.node) ? this.node.scope : null,
							prop.key
						);
						return b$1`const ${prop.property_name} = ${expression.manipulate(this.block, '#ctx')};`;
					} else {
						/** @param {any} name */
						const to_ctx = (name) => this.renderer.reference(name);
						return b$1`#ctx[${
							this.block.renderer.context_lookup.get(prop.key.name).index
						}] = ${prop.default_modifier(prop.modifier(x$1`#ctx[${this.value_index}]`), to_ctx)};`;
					}
			  })
			: null;
		const const_tags_props = this.has_consts(this.node)
			? add_const_tags(this.block, this.node.const_tags, '#ctx')
			: null;
		const get_context = this.block.renderer.component.get_unique_name(`get_${this.status}_context`);
		this.block.renderer.blocks.push(b$1`
			function ${get_context}(#ctx) {
				${props}
				${const_tags_props}
			}
		`);
		this.block.chunks.declarations.push(b$1`${get_context}(#ctx)`);
		if (this.block.has_update_method) {
			this.block.chunks.update.unshift(b$1`${get_context}(#ctx)`);
		}
	}
}

/** @extends Wrapper<import('../../nodes/AwaitBlock.js').default> */
class AwaitBlockWrapper extends Wrapper {
	/** @type {AwaitBlockBranch} */
	pending;

	/** @type {AwaitBlockBranch} */
	then;

	/** @type {AwaitBlockBranch} */
	catch;

	/** @type {import('estree').Identifier} */
	var = { type: 'Identifier', name: 'await_block' };

	/**
	 * @param {import('../Renderer.js').default} renderer
	 * @param {import('../Block.js').default} block
	 * @param {import('./shared/Wrapper.js').default} parent
	 * @param {import('../../nodes/AwaitBlock.js').default} node
	 * @param {boolean} strip_whitespace
	 * @param {import('./shared/Wrapper.js').default} next_sibling
	 */
	constructor(renderer, block, parent, node, strip_whitespace, next_sibling) {
		super(renderer, block, parent, node);
		block.add_dependencies(this.node.expression.dependencies);
		let is_dynamic = false;
		let has_intros = false;
		let has_outros = false;
		/** @type {const} */ (['pending', 'then', 'catch']).forEach((status) => {
			const child = this.node[status];
			const branch = new AwaitBlockBranch(
				status,
				renderer,
				block,
				this,
				child,
				strip_whitespace,
				next_sibling
			);
			renderer.blocks.push(branch.block);
			if (branch.is_dynamic) {
				is_dynamic = true;
				// TODO should blocks update their own parents?
				block.add_dependencies(branch.block.dependencies);
			}
			if (branch.block.has_intros) has_intros = true;
			if (branch.block.has_outros) has_outros = true;
			this[status] = branch;
		});
		['pending', 'then', 'catch'].forEach((status) => {
			this[status].block.has_update_method = is_dynamic;
			this[status].block.has_intro_method = has_intros;
			this[status].block.has_outro_method = has_outros;
		});
		if (has_outros) {
			block.add_outro();
		}
	}

	/**
	 * @param {import('../Block.js').default} block
	 * @param {import('estree').Identifier} parent_node
	 * @param {import('estree').Identifier} parent_nodes
	 */
	render(block, parent_node, parent_nodes) {
		const anchor = this.get_or_create_anchor(block, parent_node, parent_nodes);
		const update_mount_node = this.get_update_mount_node(anchor);
		const snippet = this.node.expression.manipulate(block);
		const info = block.get_unique_name('info');
		const promise = block.get_unique_name('promise');
		block.add_variable(promise);
		block.maintain_context = true;

		/** @type {any} */
		const info_props = x$1`{
			ctx: #ctx,
			current: null,
			token: null,
			hasCatch: ${this.catch.node.start !== null ? 'true' : 'false'},
			pending: ${this.pending.block.name},
			then: ${this.then.block.name},
			catch: ${this.catch.block.name},
			value: ${this.then.value_index},
			error: ${this.catch.value_index},
			blocks: ${this.pending.block.has_outro_method && x$1`[,,,]`}
		}`;
		block.chunks.init.push(b$1`
			let ${info} = ${info_props};
		`);
		block.chunks.init.push(b$1`
			@handle_promise(${promise} = ${snippet}, ${info});
		`);
		block.chunks.create.push(b$1`
			${info}.block.c();
		`);
		if (parent_nodes && this.renderer.options.hydratable) {
			block.chunks.claim.push(b$1`
				${info}.block.l(${parent_nodes});
			`);
		}
		const initial_mount_node = parent_node || '#target';
		const anchor_node = parent_node ? 'null' : '#anchor';
		const has_transitions =
			this.pending.block.has_intro_method || this.pending.block.has_outro_method;
		block.chunks.mount.push(b$1`
			${info}.block.m(${initial_mount_node}, ${info}.anchor = ${anchor_node});
			${info}.mount = () => ${update_mount_node};
			${info}.anchor = ${anchor};
		`);
		if (has_transitions) {
			block.chunks.intro.push(b$1`@transition_in(${info}.block);`);
		}
		const dependencies = this.node.expression.dynamic_dependencies();
		const update_await_block_branch = b$1`@update_await_block_branch(${info}, #ctx, #dirty)`;
		if (dependencies.length > 0) {
			const condition = x$1`
				${block.renderer.dirty(dependencies)} &&
				${promise} !== (${promise} = ${snippet}) &&
				@handle_promise(${promise}, ${info})`;
			block.chunks.update.push(b$1`${info}.ctx = #ctx;`);
			if (this.pending.block.has_update_method) {
				block.chunks.update.push(b$1`
					if (${condition}) {

					} else {
						${update_await_block_branch}
					}
				`);
			} else {
				block.chunks.update.push(b$1`
					${condition}
				`);
			}
		} else {
			if (this.pending.block.has_update_method) {
				block.chunks.update.push(b$1`
					${update_await_block_branch}
				`);
			}
		}
		if (this.pending.block.has_outro_method) {
			block.chunks.outro.push(b$1`
				for (let #i = 0; #i < 3; #i += 1) {
					const block = ${info}.blocks[#i];
					@transition_out(block);
				}
			`);
		}
		block.chunks.destroy.push(b$1`
			${info}.block.d(${parent_node ? null : 'detaching'});
			${info}.token = null;
			${info} = null;
		`);
		[this.pending, this.then, this.catch].forEach((branch) => {
			branch.render(branch.block, null, /** @type {import('estree').Identifier} */ (x$1`#nodes`));
		});
	}
}

const TRUE = x$1`true`;
const FALSE = x$1`false`;

class EventHandlerWrapper {
	/** @type {import('../../../nodes/EventHandler.js').default} */
	node;

	/** @type {import('../shared/Wrapper.js').default} */
	parent;

	/**
	 * @param {import('../../../nodes/EventHandler.js').default} node
	 * @param {import('../shared/Wrapper.js').default} parent
	 */
	constructor(node, parent) {
		this.node = node;
		this.parent = parent;
		if (!node.expression) {
			this.parent.renderer.add_to_context(node.handler_name.name);
			this.parent.renderer.component.partly_hoisted.push(b$1`
				function ${node.handler_name.name}(event) {
					@bubble.call(this, $$self, event);
				}
			`);
		}
	}

	/** @param {import('../../Block.js').default} block */
	get_snippet(block) {
		const snippet = this.node.expression
			? this.node.expression.manipulate(block)
			: block.renderer.reference(this.node.handler_name);
		if (this.node.reassigned) {
			block.maintain_context = true;
			return x$1`function () { if (@is_function(${snippet})) ${snippet}.apply(this, arguments); }`;
		}
		return snippet;
	}

	/**
	 * @param {import('../../Block.js').default} block
	 * @param {string | import('estree').Expression} target
	 */
	render(block, target) {
		let snippet = this.get_snippet(block);
		if (this.node.modifiers.has('preventDefault')) snippet = x$1`@prevent_default(${snippet})`;
		if (this.node.modifiers.has('stopPropagation')) snippet = x$1`@stop_propagation(${snippet})`;
		if (this.node.modifiers.has('stopImmediatePropagation'))
			snippet = x$1`@stop_immediate_propagation(${snippet})`;
		if (this.node.modifiers.has('self')) snippet = x$1`@self(${snippet})`;
		if (this.node.modifiers.has('trusted')) snippet = x$1`@trusted(${snippet})`;
		const args = [];
		const opts = ['nonpassive', 'passive', 'once', 'capture'].filter((mod) =>
			this.node.modifiers.has(mod)
		);
		if (opts.length) {
			if (opts.length === 1 && opts[0] === 'capture') {
				args.push(TRUE);
			} else {
				args.push(
					x$1`{ ${opts.map((opt) => (opt === 'nonpassive' ? p`passive: false` : p`${opt}: true`))} }`
				);
			}
		} else if (block.renderer.options.dev) {
			args.push(FALSE);
		}
		if (block.renderer.options.dev) {
			args.push(this.node.modifiers.has('preventDefault') ? TRUE : FALSE);
			args.push(this.node.modifiers.has('stopPropagation') ? TRUE : FALSE);
			args.push(this.node.modifiers.has('stopImmediatePropagation') ? TRUE : FALSE);
		}
		block.event_listeners.push(x$1`@listen(${target}, "${this.node.name}", ${snippet}, ${args})`);
	}
}

/**
 * @param {import('../../Block.js').default} block
 * @param {string | import('estree').Expression} target
 * @param {import('../Element/EventHandler.js').default[]} handlers
 */
function add_event_handlers(block, target, handlers) {
	handlers.forEach((handler) => add_event_handler(block, target, handler));
}

/**
 * @param {import('../../Block.js').default} block
 * @param {string | import('estree').Expression} target
 * @param {import('../Element/EventHandler.js').default} handler
 */
function add_event_handler(block, target, handler) {
	handler.render(block, target);
}

/**
 * @param {import('../../Block.js').default} block
 * @param {string | import('estree').Expression} target
 * @param {import('../../../nodes/Action.js').default[]} actions
 */
function add_actions(block, target, actions) {
	actions.forEach((action) => add_action(block, target, action));
}

const regex_invalid_variable_identifier_characters$3 = /[^a-zA-Z0-9_$]/g;

/**
 * @param {import('../../Block.js').default} block
 * @param {string | import('estree').Expression} target
 * @param {import('../../../nodes/Action.js').default} action
 */
function add_action(block, target, action) {
	const { expression, template_scope } = action;

	/** @type {import('estree').Node | undefined} */
	let snippet;

	/** @type {string[] | undefined} */
	let dependencies;
	if (expression) {
		snippet = expression.manipulate(block);
		dependencies = expression.dynamic_dependencies();
	}
	const id = block.get_unique_name(
		`${action.name.replace(regex_invalid_variable_identifier_characters$3, '_')}_action`
	);
	block.add_variable(id);
	const [obj, ...properties] = action.name.split('.');
	const fn = is_contextual(action.component, template_scope, obj)
		? block.renderer.reference(obj)
		: obj;
	if (properties.length) {
		const member_expression = properties.reduce((lhs, rhs) => x$1`${lhs}.${rhs}`, fn);
		block.event_listeners.push(
			x$1`@action_destroyer(${id} = ${member_expression}(${target}, ${snippet}))`
		);
	} else {
		block.event_listeners.push(
			x$1`@action_destroyer(${id} = ${fn}.call(null, ${target}, ${snippet}))`
		);
	}
	if (dependencies && dependencies.length > 0) {
		let condition = x$1`${id} && @is_function(${id}.update)`;
		if (dependencies.length > 0) {
			condition = x$1`${condition} && ${block.renderer.dirty(dependencies)}`;
		}
		block.chunks.update.push(b$1`if (${condition}) ${id}.update.call(null, ${snippet});`);
	}
}

/** @extends Wrapper<import('../../nodes/Body.js').default> */
class BodyWrapper extends Wrapper {
	/** @type {import('./Element/EventHandler.js').default[]} */
	handlers;

	/**
	 * @param {import('../Renderer.js').default} renderer
	 * @param {import('../Block.js').default} block
	 * @param {import('./shared/Wrapper.js').default} parent
	 * @param {import('../../nodes/Body.js').default} node
	 */
	constructor(renderer, block, parent, node) {
		super(renderer, block, parent, node);
		this.handlers = this.node.handlers.map((handler) => new EventHandlerWrapper(handler, this));
	}

	/**
	 * @param {import('../Block.js').default} block
	 * @param {import('estree').Identifier} _parent_node
	 * @param {import('estree').Identifier} _parent_nodes
	 */
	render(block, _parent_node, _parent_nodes) {
		add_event_handlers(block, x$1`@_document.body`, this.handlers);
		add_actions(block, x$1`@_document.body`, this.node.actions);
	}
}

/** @extends Wrapper<import('../../nodes/DebugTag.js').default> */
class DebugTagWrapper extends Wrapper {
	/**
	 * @param {import('../Renderer.js').default} renderer
	 * @param {import('../Block.js').default} block
	 * @param {import('./shared/Wrapper.js').default} parent
	 * @param {import('../../nodes/DebugTag.js').default} node
	 * @param {boolean} _strip_whitespace
	 * @param {import('./shared/Wrapper.js').default} _next_sibling
	 */
	constructor(renderer, block, parent, node, _strip_whitespace, _next_sibling) {
		super(renderer, block, parent, node);
	}

	/**
	 * @param {import('../Block.js').default} block
	 * @param {import('estree').Identifier} _parent_node
	 * @param {import('estree').Identifier} _parent_nodes
	 */
	render(block, _parent_node, _parent_nodes) {
		const { renderer } = this;
		const { component } = renderer;
		if (!renderer.options.dev) return;
		const { var_lookup } = component;
		const start = component.locate(this.node.start + 1);
		const end = { line: start.line, column: start.column + 6 };
		const loc = { start, end };

		/** @type {import('estree').DebuggerStatement} */
		const debug = {
			type: 'DebuggerStatement',
			loc
		};
		if (this.node.expressions.length === 0) {
			// Debug all
			block.chunks.create.push(debug);
			block.chunks.update.push(debug);
		} else {
			/** @type {import('estree').Identifier} */
			const log = {
				type: 'Identifier',
				name: 'log',
				loc
			};

			/** @type {Set<string>} */
			const dependencies = new Set();
			this.node.expressions.forEach((expression) => {
				add_to_set(dependencies, expression.dependencies);
			});
			const contextual_identifiers = this.node.expressions
				.filter((e) => {
					const variable = var_lookup.get(/** @type {import('estree').Identifier} */ (e.node).name);
					return !(variable && variable.hoistable);
				})
				.map((e) => /** @type {import('estree').Identifier} */ (e.node).name);
			const logged_identifiers = this.node.expressions.map(
				(e) => p`${/** @type {import('estree').Identifier} */ (e.node).name}`
			);
			const debug_statements = b$1`
				${contextual_identifiers.map((name) => b$1`const ${name} = ${renderer.reference(name)};`)}
				@_console.${log}({ ${logged_identifiers} });
				debugger;`;
			if (dependencies.size) {
				const condition = renderer.dirty(Array.from(dependencies));
				block.chunks.update.push(b$1`
					if (${condition}) {
						${debug_statements}
					}
				`);
			}
			block.chunks.create.push(b$1`{
				${debug_statements}
			}`);
		}
	}
}

const associated_events$1 = {
	fullscreenElement: ['fullscreenchange'],
	visibilityState: ['visibilitychange']
};
const readonly$1 = new Set(['fullscreenElement', 'visibilityState']);

/** @extends Wrapper<import('../../nodes/Document.js').default> */
class DocumentWrapper extends Wrapper {
	/** @type {import('./Element/EventHandler.js').default[]} */
	handlers;

	/**
	 * @param {import('../Renderer.js').default} renderer
	 * @param {import('../Block.js').default} block
	 * @param {import('./shared/Wrapper.js').default} parent
	 * @param {import('../../nodes/Document.js').default} node
	 */
	constructor(renderer, block, parent, node) {
		super(renderer, block, parent, node);
		this.handlers = this.node.handlers.map((handler) => new EventHandlerWrapper(handler, this));
	}

	/**
	 * @param {import('../Block.js').default} block
	 * @param {import('estree').Identifier} _parent_node
	 * @param {import('estree').Identifier} _parent_nodes
	 */
	render(block, _parent_node, _parent_nodes) {
		const { renderer } = this;
		const { component } = renderer;

		/** @type {Record<string, Array<{ name: string; value: string }>>} */
		const events = {};

		/** @type {Record<string, string>} */
		const bindings = {};
		add_event_handlers(block, x$1`@_document`, this.handlers);
		add_actions(block, x$1`@_document`, this.node.actions);
		this.node.bindings.forEach((binding) => {
			// TODO: what if it's a MemberExpression?
			const binding_name = /** @type {import('estree').Identifier} */ (binding.expression.node)
				.name;
			// in dev mode, throw if read-only values are written to
			if (readonly$1.has(binding.name)) {
				renderer.readonly.add(binding_name);
			}
			bindings[binding.name] = binding_name;
			const binding_events = associated_events$1[binding.name];
			const property = binding.name;
			binding_events.forEach((associated_event) => {
				if (!events[associated_event]) events[associated_event] = [];
				events[associated_event].push({
					name: binding_name,
					value: property
				});
			});
		});
		Object.keys(events).forEach((event) => {
			const id = block.get_unique_name(`ondocument${event}`);
			const props = events[event];
			renderer.add_to_context(id.name);
			const fn = renderer.reference(id.name);
			props.forEach((prop) => {
				renderer.meta_bindings.push(b$1`this._state.${prop.name} = @_document.${prop.value};`);
			});
			block.event_listeners.push(x$1`
				@listen(@_document, "${event}", ${fn})
			`);
			component.partly_hoisted.push(b$1`
				function ${id}() {
					${props.map((prop) => renderer.invalidate(prop.name, x$1`${prop.name} = @_document.${prop.value}`))}
				}
			`);
			block.chunks.init.push(b$1`
				@add_render_callback(${fn});
			`);
			component.has_reactive_assignments = true;
		});
	}
}

/** @extends Wrapper<import('../../nodes/ElseBlock.js').default> */
class ElseBlockWrapper extends Wrapper {
	/** @type {import('../Block.js').default} */
	block;

	/** @type {import('./Fragment.js').default} */
	fragment;

	/** @type {boolean} */
	is_dynamic;

	var = null;

	/**
	 * @param {import('../Renderer.js').default} renderer
	 * @param {import('../Block.js').default} block
	 * @param {import('./shared/Wrapper.js').default} parent
	 * @param {import('../../nodes/ElseBlock.js').default} node
	 * @param {boolean} strip_whitespace
	 * @param {import('./shared/Wrapper.js').default} next_sibling
	 */
	constructor(renderer, block, parent, node, strip_whitespace, next_sibling) {
		super(renderer, block, parent, node);
		add_const_tags_context(renderer, this.node.const_tags);
		this.block = block.child({
			comment: create_debugging_comment(node, this.renderer.component),
			name: this.renderer.component.get_unique_name('create_else_block'),
			type: 'else'
		});
		this.fragment = new FragmentWrapper(
			renderer,
			this.block,
			this.node.children,
			parent,
			strip_whitespace,
			next_sibling
		);
		this.is_dynamic = this.block.dependencies.size > 0;
	}
}

/** @extends Wrapper<import('../../nodes/EachBlock.js').default> */
class EachBlockWrapper extends Wrapper {
	/** @type {import('../Block.js').default} */
	block;

	/** @type {import('./Fragment.js').default} */
	fragment;

	/** @type {ElseBlockWrapper} */
	else;
	/**
	 * @type {{
	 * 		create_each_block: import('estree').Identifier;
	 * 		each_block_value: import('estree').Identifier;
	 * 		get_each_context: import('estree').Identifier;
	 * 		iterations: import('estree').Identifier;
	 * 		fixed_length: number;
	 * 		data_length: import('estree').Node | number;
	 * 		view_length: import('estree').Node | number;
	 * 	}}
	 */
	vars;

	/** @type {Array<import('estree').Node | import('estree').Node[]>} */
	context_props;

	/** @type {import('estree').Identifier} */
	index_name;

	/** @type {Array<import('estree').Node | import('estree').Node[]>} */
	updates = [];

	/** @type {Set<string>} */
	dependencies;

	/** @type {import('estree').Identifier} */
	var = { type: 'Identifier', name: 'each' };

	/**
	 * @param {import('../Renderer.js').default} renderer
	 * @param {import('../Block.js').default} block
	 * @param {import('./shared/Wrapper.js').default} parent
	 * @param {import('../../nodes/EachBlock.js').default} node
	 * @param {boolean} strip_whitespace
	 * @param {import('./shared/Wrapper.js').default} next_sibling
	 */
	constructor(renderer, block, parent, node, strip_whitespace, next_sibling) {
		super(renderer, block, parent, node);
		const { dependencies } = node.expression;
		block.add_dependencies(dependencies);
		this.node.contexts.forEach((context) => {
			if (context.type !== 'DestructuredVariable') return;
			renderer.add_to_context(context.key.name, true);
		});
		add_const_tags_context(renderer, this.node.const_tags);
		this.block = block.child({
			comment: create_debugging_comment(this.node, this.renderer.component),
			name: renderer.component.get_unique_name('create_each_block'),
			type: 'each',
			// @ts-ignore todo: probably error
			key: /** @type {string} */ (node.key),
			bindings: new Map(block.bindings)
		});
		// TODO this seems messy
		this.block.has_animation = this.node.has_animation;
		this.index_name = this.node.index
			? { type: 'Identifier', name: this.node.index }
			: renderer.component.get_unique_name(`${this.node.context}_index`);
		const fixed_length =
			node.expression.node.type === 'ArrayExpression' &&
			node.expression.node.elements.every((element) => element.type !== 'SpreadElement')
				? node.expression.node.elements.length
				: null;
		// hack the sourcemap, so that if data is missing the bug
		// is easy to find
		let c = this.node.start + 2;
		while (renderer.component.source[c] !== 'e') c += 1;
		const start = renderer.component.locate(c);
		const end = { line: start.line, column: start.column + 4 };
		const length = {
			type: 'Identifier',
			name: 'length',
			loc: { start, end }
		};
		const each_block_value = renderer.component.get_unique_name(`${this.var.name}_value`);
		const iterations = block.get_unique_name(`${this.var.name}_blocks`);
		renderer.add_to_context(each_block_value.name, true);
		renderer.add_to_context(this.index_name.name, true);
		this.vars = {
			create_each_block: this.block.name,
			each_block_value,
			get_each_context: renderer.component.get_unique_name(`get_${this.var.name}_context`),
			iterations,
			// optimisation for array literal
			fixed_length,
			data_length: fixed_length === null ? x$1`${each_block_value}.${length}` : fixed_length,
			view_length: fixed_length === null ? x$1`${iterations}.length` : fixed_length
		};
		const object = get_object(node.expression.node);
		const store =
			object.type === 'Identifier' && object.name[0] === '$' ? object.name.slice(1) : null;
		node.contexts.forEach((prop) => {
			if (prop.type !== 'DestructuredVariable') return;
			this.block.bindings.set(prop.key.name, {
				object: this.vars.each_block_value,
				property: this.index_name,
				modifier: prop.modifier,
				snippet: prop.modifier(
					/** @type {import('estree').Node} */ (
						x$1`${this.vars.each_block_value}[${this.index_name}]`
					)
				),
				store
			});
		});
		if (this.node.index) {
			this.block.get_unique_name(this.node.index); // this prevents name collisions (#1254)
		}
		renderer.blocks.push(this.block);
		this.fragment = new FragmentWrapper(
			renderer,
			this.block,
			node.children,
			this,
			strip_whitespace,
			next_sibling
		);
		if (this.node.else) {
			this.else = new ElseBlockWrapper(
				renderer,
				block,
				this,
				this.node.else,
				strip_whitespace,
				next_sibling
			);
			renderer.blocks.push(this.else.block);
			if (this.else.is_dynamic) {
				this.block.add_dependencies(this.else.block.dependencies);
			}
		}
		block.add_dependencies(this.block.dependencies);
		if (this.block.has_outros || (this.else && this.else.block.has_outros)) {
			block.add_outro();
		}
	}

	/**
	 * @param {import('../Block.js').default} block
	 * @param {import('estree').Identifier} parent_node
	 * @param {import('estree').Identifier} parent_nodes
	 */
	render(block, parent_node, parent_nodes) {
		if (this.fragment.nodes.length === 0) return;
		const { renderer } = this;
		const { component } = renderer;
		const needs_anchor = this.next
			? !this.next.is_dom_node()
			: !parent_node || !this.parent.is_dom_node();
		const snippet = x$1`@ensure_array_like(${this.node.expression.manipulate(block)})`;
		block.chunks.init.push(b$1`let ${this.vars.each_block_value} = ${snippet};`);

		/** @type {import('estree').Identifier} */
		const initial_anchor_node = {
			type: 'Identifier',
			name: parent_node ? 'null' : '#anchor'
		};

		/** @type {import('estree').Identifier} */
		const initial_mount_node = parent_node || { type: 'Identifier', name: '#target' };
		const update_anchor_node = needs_anchor
			? block.get_unique_name(`${this.var.name}_anchor`)
			: (this.next && this.next.var) || { type: 'Identifier', name: 'null' };

		/** @type {import('estree').Identifier} */
		const update_mount_node = this.get_update_mount_node(
			/** @type {import('estree').Identifier} */ (update_anchor_node)
		);
		const args = {
			block,
			parent_node,
			parent_nodes,
			snippet,
			initial_anchor_node,
			initial_mount_node,
			update_anchor_node,
			update_mount_node
		};
		const all_dependencies = new Set(this.block.dependencies); // TODO should be dynamic deps only
		this.node.expression.dynamic_dependencies().forEach((dependency) => {
			all_dependencies.add(dependency);
		});
		if (this.node.key) {
			this.node.key.dynamic_dependencies().forEach((dependency) => {
				all_dependencies.add(dependency);
			});
		}
		this.dependencies = all_dependencies;
		if (this.node.key) {
			this.render_keyed(args);
		} else {
			this.render_unkeyed(args);
		}
		if (this.block.has_intro_method || this.block.has_outro_method) {
			block.chunks.intro.push(b$1`
				for (let #i = 0; #i < ${this.vars.data_length}; #i += 1) {
					@transition_in(${this.vars.iterations}[#i]);
				}
			`);
		}
		if (needs_anchor) {
			block.add_element(
				/** @type {import('estree').Identifier} */ (update_anchor_node),
				x$1`@empty()`,
				parent_nodes && x$1`@empty()`,
				parent_node
			);
		}
		if (this.else) {
			let else_ctx = x$1`#ctx`;
			if (this.else.node.const_tags.length > 0) {
				const get_ctx_name = this.renderer.component.get_unique_name('get_else_ctx');
				this.renderer.blocks.push(b$1`
					function ${get_ctx_name}(#ctx) {
						const child_ctx = #ctx.slice();
						${add_const_tags(block, this.else.node.const_tags, 'child_ctx')}
						return child_ctx;
					}
				`);
				else_ctx = x$1`${get_ctx_name}(#ctx)`;
			}
			const each_block_else = component.get_unique_name(`${this.var.name}_else`);
			block.chunks.init.push(b$1`let ${each_block_else} = null;`);
			// TODO neaten this up... will end up with an empty line in the block
			block.chunks.init.push(b$1`
				if (!${this.vars.data_length}) {
					${each_block_else} = ${this.else.block.name}(${else_ctx});
				}
			`);
			block.chunks.create.push(b$1`
				if (${each_block_else}) {
					${each_block_else}.c();
				}
			`);
			if (this.renderer.options.hydratable) {
				block.chunks.claim.push(b$1`
					if (${each_block_else}) {
						${each_block_else}.l(${parent_nodes});
					}
				`);
			}
			block.chunks.mount.push(b$1`
				if (${each_block_else}) {
					${each_block_else}.m(${initial_mount_node}, ${initial_anchor_node});
				}
			`);
			const has_transitions = !!(
				this.else.block.has_intro_method || this.else.block.has_outro_method
			);
			const destroy_block_else = this.else.block.has_outro_method
				? b$1`
					@group_outros();
					@transition_out(${each_block_else}, 1, 1, () => {
						${each_block_else} = null;
					});
					@check_outros();`
				: b$1`
					${each_block_else}.d(1);
					${each_block_else} = null;`;
			if (this.else.block.has_update_method) {
				this.updates.push(b$1`
					if (!${this.vars.data_length} && ${each_block_else}) {
						${each_block_else}.p(${else_ctx}, #dirty);
					} else if (!${this.vars.data_length}) {
						${each_block_else} = ${this.else.block.name}(${else_ctx});
						${each_block_else}.c();
						${has_transitions && b$1`@transition_in(${each_block_else}, 1);`}
						${each_block_else}.m(${update_mount_node}, ${update_anchor_node});
					} else if (${each_block_else}) {
						${destroy_block_else};
					}
				`);
			} else {
				this.updates.push(b$1`
					if (${this.vars.data_length}) {
						if (${each_block_else}) {
							${destroy_block_else};
						}
					} else if (!${each_block_else}) {
						${each_block_else} = ${this.else.block.name}(${else_ctx});
						${each_block_else}.c();
						${has_transitions && b$1`@transition_in(${each_block_else}, 1);`}
						${each_block_else}.m(${update_mount_node}, ${update_anchor_node});
					}
				`);
			}
			block.chunks.destroy.push(b$1`
				if (${each_block_else}) ${each_block_else}.d(${parent_node ? '' : 'detaching'});
			`);
		}
		if (this.updates.length) {
			block.chunks.update.push(b$1`
				if (${block.renderer.dirty(Array.from(all_dependencies))}) {
					${this.updates}
				}
			`);
		}
		this.fragment.render(this.block, null, /** @type {import('estree').Identifier} */ (x$1`#nodes`));
		if (this.else) {
			this.else.fragment.render(
				this.else.block,
				null,
				/** @type {import('estree').Identifier} */ (x$1`#nodes`)
			);
		}
		this.context_props = this.node.contexts.map((prop) => {
			if (prop.type === 'DestructuredVariable') {
				/** @param {string} name */
				const to_ctx = (name) =>
					renderer.context_lookup.has(name)
						? x$1`child_ctx[${renderer.context_lookup.get(name).index}]`
						: /** @type {import('estree').Node} */ ({ type: 'Identifier', name });
				return b$1`child_ctx[${
					renderer.context_lookup.get(prop.key.name).index
				}] = ${prop.default_modifier(prop.modifier(x$1`list[i]`), to_ctx)};`;
			} else {
				const expression = new Expression(
					this.renderer.component,
					this.node,
					this.node.scope,
					prop.key
				);
				return b$1`const ${prop.property_name} = ${expression.manipulate(block, 'child_ctx')};`;
			}
		});
		if (this.node.has_binding)
			this.context_props.push(
				b$1`child_ctx[${renderer.context_lookup.get(this.vars.each_block_value.name).index}] = list;`
			);
		if (this.node.has_binding || this.node.has_index_binding || this.node.index)
			this.context_props.push(
				b$1`child_ctx[${renderer.context_lookup.get(this.index_name.name).index}] = i;`
			);
		// TODO which is better — Object.create(array) or array.slice()?
		renderer.blocks.push(b$1`
			function ${this.vars.get_each_context}(#ctx, list, i) {
				const child_ctx = #ctx.slice();
				${this.context_props}
				${add_const_tags(this.block, this.node.const_tags, 'child_ctx')}
				return child_ctx;
			}
		`);
	}
	/**
	 * @param {{
	 * 		block: import('../Block.js').default;
	 * 		parent_node: import('estree').Identifier;
	 * 		parent_nodes: import('estree').Identifier;
	 * 		snippet: import('estree').Node;
	 * 		initial_anchor_node: import('estree').Identifier;
	 * 		initial_mount_node: import('estree').Identifier;
	 * 		update_anchor_node: import('estree').Identifier;
	 * 		update_mount_node: import('estree').Identifier;
	 * 	}} params
	 */
	render_keyed({
		block,
		parent_node,
		parent_nodes,
		snippet,
		initial_anchor_node,
		initial_mount_node,
		update_anchor_node,
		update_mount_node
	}) {
		const { create_each_block, iterations, data_length, view_length } = this.vars;
		const get_key = block.get_unique_name('get_key');
		const lookup = block.get_unique_name(`${this.var.name}_lookup`);
		block.add_variable(iterations, x$1`[]`);
		block.add_variable(lookup, x$1`new @_Map()`);
		if (this.fragment.nodes[0].is_dom_node()) {
			this.block.first = this.fragment.nodes[0].var;
		} else {
			this.block.first = this.block.get_unique_name('first');
			this.block.add_element(this.block.first, x$1`@empty()`, parent_nodes && x$1`@empty()`, null);
		}
		block.chunks.init.push(b$1`
			const ${get_key} = #ctx => ${this.node.key.manipulate(block)};

			${
				this.renderer.options.dev &&
				b$1`@validate_each_keys(#ctx, ${this.vars.each_block_value}, ${this.vars.get_each_context}, ${get_key});`
			}
			for (let #i = 0; #i < ${data_length}; #i += 1) {
				let child_ctx = ${this.vars.get_each_context}(#ctx, ${this.vars.each_block_value}, #i);
				let key = ${get_key}(child_ctx);
				${lookup}.set(key, ${iterations}[#i] = ${create_each_block}(key, child_ctx));
			}
		`);
		block.chunks.create.push(b$1`
			for (let #i = 0; #i < ${view_length}; #i += 1) {
				${iterations}[#i].c();
			}
		`);
		if (parent_nodes && this.renderer.options.hydratable) {
			block.chunks.claim.push(b$1`
				for (let #i = 0; #i < ${view_length}; #i += 1) {
					${iterations}[#i].l(${parent_nodes});
				}
			`);
		}
		block.chunks.mount.push(b$1`
			for (let #i = 0; #i < ${view_length}; #i += 1) {
				if (${iterations}[#i]) {
					${iterations}[#i].m(${initial_mount_node}, ${initial_anchor_node});
				}
			}
		`);
		const dynamic = this.block.has_update_method;
		const destroy = this.node.has_animation
			? this.block.has_outros
				? '@fix_and_outro_and_destroy_block'
				: '@fix_and_destroy_block'
			: this.block.has_outros
			? '@outro_and_destroy_block'
			: '@destroy_block';
		if (this.dependencies.size) {
			this.block.maintain_context = true;
			this.updates.push(b$1`
				${this.vars.each_block_value} = ${snippet};

				${this.block.has_outros && b$1`@group_outros();`}
				${
					this.node.has_animation &&
					b$1`for (let #i = 0; #i < ${view_length}; #i += 1) ${iterations}[#i].r();`
				}
				${
					this.renderer.options.dev &&
					b$1`@validate_each_keys(#ctx, ${this.vars.each_block_value}, ${this.vars.get_each_context}, ${get_key});`
				}
				${iterations} = @update_keyed_each(${iterations}, #dirty, ${get_key}, ${dynamic ? 1 : 0}, #ctx, ${
				this.vars.each_block_value
			}, ${lookup}, ${update_mount_node}, ${destroy}, ${create_each_block}, ${update_anchor_node}, ${
				this.vars.get_each_context
			});
				${
					this.node.has_animation &&
					b$1`for (let #i = 0; #i < ${view_length}; #i += 1) ${iterations}[#i].a();`
				}
				${this.block.has_outros && b$1`@check_outros();`}
			`);
		}
		if (this.block.has_outros) {
			block.chunks.outro.push(b$1`
				for (let #i = 0; #i < ${view_length}; #i += 1) {
					@transition_out(${iterations}[#i]);
				}
			`);
		}
		block.chunks.destroy.push(b$1`
			for (let #i = 0; #i < ${view_length}; #i += 1) {
				${iterations}[#i].d(${parent_node ? null : 'detaching'});
			}
		`);
	}
	/**
	 * @param {{
	 * 		block: import('../Block.js').default;
	 * 		parent_nodes: import('estree').Identifier;
	 * 		snippet: import('estree').Node;
	 * 		initial_anchor_node: import('estree').Identifier;
	 * 		initial_mount_node: import('estree').Identifier;
	 * 		update_anchor_node: import('estree').Identifier;
	 * 		update_mount_node: import('estree').Identifier;
	 * 	}} params
	 */
	render_unkeyed({
		block,
		parent_nodes,
		snippet,
		initial_anchor_node,
		initial_mount_node,
		update_anchor_node,
		update_mount_node
	}) {
		const { create_each_block, iterations, fixed_length, data_length, view_length } = this.vars;
		block.chunks.init.push(b$1`
			let ${iterations} = [];

			for (let #i = 0; #i < ${data_length}; #i += 1) {
				${iterations}[#i] = ${create_each_block}(${this.vars.get_each_context}(#ctx, ${this.vars.each_block_value}, #i));
			}
		`);
		block.chunks.create.push(b$1`
			for (let #i = 0; #i < ${view_length}; #i += 1) {
				${iterations}[#i].c();
			}
		`);
		if (parent_nodes && this.renderer.options.hydratable) {
			block.chunks.claim.push(b$1`
				for (let #i = 0; #i < ${view_length}; #i += 1) {
					${iterations}[#i].l(${parent_nodes});
				}
			`);
		}
		block.chunks.mount.push(b$1`
			for (let #i = 0; #i < ${view_length}; #i += 1) {
				if (${iterations}[#i]) {
					${iterations}[#i].m(${initial_mount_node}, ${initial_anchor_node});
				}
			}
		`);
		if (this.dependencies.size) {
			const has_transitions = !!(this.block.has_intro_method || this.block.has_outro_method);
			const for_loop_body = this.block.has_update_method
				? b$1`
					if (${iterations}[#i]) {
						${iterations}[#i].p(child_ctx, #dirty);
						${has_transitions && b$1`@transition_in(${this.vars.iterations}[#i], 1);`}
					} else {
						${iterations}[#i] = ${create_each_block}(child_ctx);
						${iterations}[#i].c();
						${has_transitions && b$1`@transition_in(${this.vars.iterations}[#i], 1);`}
						${iterations}[#i].m(${update_mount_node}, ${update_anchor_node});
					}
				`
				: has_transitions
				? b$1`
						if (${iterations}[#i]) {
							@transition_in(${this.vars.iterations}[#i], 1);
						} else {
							${iterations}[#i] = ${create_each_block}(child_ctx);
							${iterations}[#i].c();
							@transition_in(${this.vars.iterations}[#i], 1);
							${iterations}[#i].m(${update_mount_node}, ${update_anchor_node});
						}
					`
				: b$1`
						if (!${iterations}[#i]) {
							${iterations}[#i] = ${create_each_block}(child_ctx);
							${iterations}[#i].c();
							${iterations}[#i].m(${update_mount_node}, ${update_anchor_node});
						}
					`;
			const start = this.block.has_update_method ? 0 : '#old_length';

			/** @type {import('estree').Node[]} */
			let remove_old_blocks;
			if (this.block.has_outros) {
				const out = block.get_unique_name('out');
				block.chunks.init.push(b$1`
					const ${out} = i => @transition_out(${iterations}[i], 1, 1, () => {
						${iterations}[i] = null;
					});
				`);
				remove_old_blocks = b$1`
					@group_outros();
					for (#i = ${data_length}; #i < ${view_length}; #i += 1) {
						${out}(#i);
					}
					@check_outros();
				`;
			} else {
				remove_old_blocks = b$1`
					for (${this.block.has_update_method ? null : x$1`#i = ${data_length}`}; #i < ${
					this.block.has_update_method ? view_length : '#old_length'
				}; #i += 1) {
						${iterations}[#i].d(1);
					}
					${!fixed_length && b$1`${view_length} = ${data_length};`}
				`;
			}
			// We declare `i` as block scoped here, as the `remove_old_blocks` code
			// may rely on continuing where this iteration stopped.
			const update = b$1`
				${!this.block.has_update_method && b$1`const #old_length = ${this.vars.each_block_value}.length;`}
				${this.vars.each_block_value} = ${snippet};

				let #i;
				for (#i = ${start}; #i < ${data_length}; #i += 1) {
					const child_ctx = ${this.vars.get_each_context}(#ctx, ${this.vars.each_block_value}, #i);

					${for_loop_body}
				}

				${remove_old_blocks}
			`;
			this.updates.push(update);
		}
		if (this.block.has_outros) {
			block.chunks.outro.push(b$1`
				${iterations} = ${iterations}.filter(@_Boolean);
				for (let #i = 0; #i < ${view_length}; #i += 1) {
					@transition_out(${iterations}[#i]);
				}
			`);
		}
		block.chunks.destroy.push(b$1`@destroy_each(${iterations}, detaching);`);
	}
}

/** @extends Wrapper<import('../../nodes/Text.js').default> */
class TextWrapper extends Wrapper {
	/** @type {string} */
	_data;

	/** @type {boolean} */
	skip;

	/** @type {import('estree').Identifier} */
	var;

	/**
	 * @param {import('../Renderer.js').default} renderer
	 * @param {import('../Block.js').default} block
	 * @param {import('./shared/Wrapper.js').default} parent
	 * @param {import('../../nodes/Text.js').default} node
	 * @param {string} data
	 */
	constructor(renderer, block, parent, node, data) {
		super(renderer, block, parent, node);
		this.skip = this.node.should_skip();
		this._data = data;
		this.var = /** @type {unknown} */ /** @type {import('estree').Identifier} */ (
			this.skip ? null : x$1`t`
		);
	}
	use_space() {
		return this.node.use_space();
	}
	set data(value) {
		// when updating `this.data` during optimisation
		// propagate the changes over to the underlying node
		// so that the node.use_space reflects on the latest `data` value
		this.node.data = this._data = value;
	}
	get data() {
		return this._data;
	}

	/**
	 * @param {import('../Block.js').default} block
	 * @param {import('estree').Identifier} parent_node
	 * @param {import('estree').Identifier} parent_nodes
	 */
	render(block, parent_node, parent_nodes) {
		if (this.skip) return;
		const use_space = this.use_space();
		const string_literal = {
			type: 'Literal',
			value: this.data,
			loc: {
				start: this.renderer.locate(this.node.start),
				end: this.renderer.locate(this.node.end)
			}
		};
		block.add_element(
			this.var,
			use_space ? x$1`@space()` : x$1`@text(${string_literal})`,
			parent_nodes &&
				(use_space
					? x$1`@claim_space(${parent_nodes})`
					: x$1`@claim_text(${parent_nodes}, ${string_literal})`),
			/** @type {import('estree').Identifier} */ (parent_node)
		);
	}
}

const svg_attributes =
	'accent-height accumulate additive alignment-baseline allowReorder alphabetic amplitude arabic-form ascent attributeName attributeType autoReverse azimuth baseFrequency baseline-shift baseProfile bbox begin bias by calcMode cap-height class clip clipPathUnits clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering contentScriptType contentStyleType cursor cx cy d decelerate descent diffuseConstant direction display divisor dominant-baseline dur dx dy edgeMode elevation enable-background end exponent externalResourcesRequired fill fill-opacity fill-rule filter filterRes filterUnits flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight format from fr fx fy g1 g2 glyph-name glyph-orientation-horizontal glyph-orientation-vertical glyphRef gradientTransform gradientUnits hanging height href horiz-adv-x horiz-origin-x id ideographic image-rendering in in2 intercept k k1 k2 k3 k4 kernelMatrix kernelUnitLength kerning keyPoints keySplines keyTimes lang lengthAdjust letter-spacing lighting-color limitingConeAngle local marker-end marker-mid marker-start markerHeight markerUnits markerWidth mask maskContentUnits maskUnits mathematical max media method min mode name numOctaves offset onabort onactivate onbegin onclick onend onerror onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup onrepeat onresize onscroll onunload opacity operator order orient orientation origin overflow overline-position overline-thickness panose-1 paint-order pathLength patternContentUnits patternTransform patternUnits pointer-events points pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits r radius refX refY rendering-intent repeatCount repeatDur requiredExtensions requiredFeatures restart result rotate rx ry scale seed shape-rendering slope spacing specularConstant specularExponent speed spreadMethod startOffset stdDeviation stemh stemv stitchTiles stop-color stop-opacity strikethrough-position strikethrough-thickness string stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style surfaceScale systemLanguage tabindex tableValues target targetX targetY text-anchor text-decoration text-rendering textLength to transform type u1 u2 underline-position underline-thickness unicode unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical values version vert-adv-y vert-origin-x vert-origin-y viewBox viewTarget visibility width widths word-spacing writing-mode x x-height x1 x2 xChannelSelector xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space y y1 y2 yChannelSelector z zoomAndPan'.split(
		' '
	);

const svg_attribute_lookup = new Map();

svg_attributes.forEach((name) => {
	svg_attribute_lookup.set(name.toLowerCase(), name);
});

/**
 * @param {string} name
 */
function fix_attribute_casing(name) {
	name = name.toLowerCase();
	return svg_attribute_lookup.get(name) || name;
}

/**
 * @param {import('./Attribute.js').default | import('./Binding.js').default} attr
 * @param {Set<string>} dependencies
 */
function handle_select_value_binding(attr, dependencies) {
	const { parent } = attr;
	if (parent.node.name === 'select') {
		/** @type {import('./index.js').default} */ (parent).select_binding_dependencies = dependencies;
		dependencies.forEach((prop) => {
			parent.renderer.component.indirect_dependencies.set(prop, new Set());
		});
	}
}

const _boolean_attributes = /** @type {const} */ ([
	'allowfullscreen',
	'allowpaymentrequest',
	'async',
	'autofocus',
	'autoplay',
	'checked',
	'controls',
	'default',
	'defer',
	'disabled',
	'formnovalidate',
	'hidden',
	'inert',
	'ismap',
	'loop',
	'multiple',
	'muted',
	'nomodule',
	'novalidate',
	'open',
	'playsinline',
	'readonly',
	'required',
	'reversed',
	'selected'
]);

/**
 * List of HTML boolean attributes (e.g. `<input disabled>`).
 * Source: https://html.spec.whatwg.org/multipage/indices.html
 *
 * @type {Set<string>}
 */
const boolean_attributes = new Set([..._boolean_attributes]);

/** @typedef {typeof _boolean_attributes[number]} BooleanAttributes */

const non_textlike_input_types = new Set([
	'button',
	'checkbox',
	'color',
	'date',
	'datetime-local',
	'file',
	'hidden',
	'image',
	'radio',
	'range',
	'reset',
	'submit'
]);

class BaseAttributeWrapper {
	/** @type {import('../../../nodes/Attribute.js').default} */
	node;

	/** @type {import('./index.js').default} */
	parent;

	/**
	 * @param {import('./index.js').default} parent
	 * @param {import('../../Block.js').default} block
	 * @param {import('../../../nodes/Attribute.js').default} node
	 */
	constructor(parent, block, node) {
		this.node = node;
		this.parent = parent;
		if (node.dependencies.size > 0) {
			block.add_dependencies(node.dependencies);
		}
	}

	/** @param {import('../../Block.js').default} _block */
	render(_block) {}
}
const regex_minus_sign = /-/;
const regex_invalid_variable_identifier_characters$2 = /[^a-zA-Z_$]/g;

/** @extends BaseAttributeWrapper */
class AttributeWrapper extends BaseAttributeWrapper {
	/** @type {any} */
	metadata;

	/** @type {string} */
	name;

	/** @type {string} */
	property_name;

	/** @type {boolean} */
	is_indirectly_bound_value;

	/** @type {boolean} */
	is_src;

	/** @type {boolean} */
	is_srcset;

	/** @type {boolean} */
	is_select_value_attribute;

	/** @type {boolean} */
	is_input_value;

	/** @type {boolean} */
	should_cache;

	/** @type {import('estree').Identifier} */
	last;
	constructor(parent, block, node) {
		super(parent, block, node);
		if (node.dependencies.size > 0) {
			// special case — <option value={foo}> — see below
			if (this.parent.node.name === 'option' && node.name === 'value') {
				let select = this.parent;
				while (select && (select.node.type !== 'Element' || select.node.name !== 'select')) {
					// @ts-ignore todo: doublecheck this, but looks to be correct
					select = select.parent;
				}
				if (select && select.select_binding_dependencies) {
					select.select_binding_dependencies.forEach((prop) => {
						this.node.dependencies.forEach((dependency) => {
							this.parent.renderer.component.indirect_dependencies.get(prop).add(dependency);
						});
					});
				}
			}
			if (node.name === 'value') {
				handle_select_value_binding(this, node.dependencies);
				this.parent.has_dynamic_value = true;
			}
		}
		if (this.parent.node.namespace == namespaces.foreign) {
			// leave attribute case alone for elements in the "foreign" namespace
			this.name = this.node.name;
			this.metadata = this.get_metadata();
			this.is_indirectly_bound_value = false;
			this.property_name = null;
			this.is_select_value_attribute = false;
			this.is_input_value = false;
		} else {
			this.name = fix_attribute_casing(this.node.name);
			this.metadata = this.get_metadata();
			this.is_indirectly_bound_value = is_indirectly_bound_value(this);
			this.property_name = this.is_indirectly_bound_value
				? '__value'
				: this.metadata && this.metadata.property_name;
			this.is_select_value_attribute = this.name === 'value' && this.parent.node.name === 'select';
			this.is_input_value = this.name === 'value' && this.parent.node.name === 'input';
		}
		// TODO retire this exception in favour of https://github.com/sveltejs/svelte/issues/3750
		this.is_src =
			this.name === 'src' &&
			(!this.parent.node.namespace || this.parent.node.namespace === namespaces.html);
		this.is_srcset =
			this.name === 'srcset' &&
			(!this.parent.node.namespace || this.parent.node.namespace === namespaces.html);
		this.should_cache = should_cache(this);
	}

	/** @param {import('../../Block.js').default} block */
	render(block) {
		const element = this.parent;
		const { name, property_name, should_cache, is_indirectly_bound_value } = this;
		// xlink is a special case... we could maybe extend this to generic
		// namespaced attributes but I'm not sure that's applicable in
		// HTML5?
		const method = regex_minus_sign.test(element.node.name)
			? '@set_custom_element_data'
			: name.slice(0, 6) === 'xlink:'
			? '@xlink_attr'
			: '@attr';
		const is_legacy_input_type =
			element.renderer.component.compile_options.legacy &&
			name === 'type' &&
			this.parent.node.name === 'input';
		const dependencies = this.get_dependencies();
		const value = this.get_value(block);

		/** @type {import('estree').Node[]} */
		let updater;
		const init = this.get_init(block, value);
		if (is_legacy_input_type) {
			block.chunks.hydrate.push(b$1`@set_input_type(${element.var}, ${init});`);
			updater = b$1`@set_input_type(${element.var}, ${should_cache ? this.last : value});`;
		} else if (this.is_select_value_attribute) {
			// annoying special case
			const is_multiple_select = element.node.get_static_attribute_value('multiple');
			if (is_multiple_select) {
				updater = b$1`@select_options(${element.var}, ${value});`;
			} else {
				updater = b$1`@select_option(${element.var}, ${value});`;
			}
			block.chunks.mount.push(b$1`
				${updater}
			`);
		} else if (this.is_src) {
			block.chunks.hydrate.push(
				b$1`if (!@src_url_equal(${element.var}.src, ${init})) ${method}(${element.var}, "${name}", ${this.last});`
			);
			updater = b$1`${method}(${element.var}, "${name}", ${should_cache ? this.last : value});`;
		} else if (this.is_srcset) {
			block.chunks.hydrate.push(
				b$1`if (!@srcset_url_equal(${element.var}, ${init})) ${method}(${element.var}, "${name}", ${this.last});`
			);
			updater = b$1`${method}(${element.var}, "${name}", ${should_cache ? this.last : value});`;
		} else if (property_name) {
			block.chunks.hydrate.push(b$1`${element.var}.${property_name} = ${init};`);
			updater = block.renderer.options.dev
				? b$1`@prop_dev(${element.var}, "${property_name}", ${should_cache ? this.last : value});`
				: b$1`${element.var}.${property_name} = ${should_cache ? this.last : value};`;
		} else {
			block.chunks.hydrate.push(b$1`${method}(${element.var}, "${name}", ${init});`);
			updater = b$1`${method}(${element.var}, "${name}", ${should_cache ? this.last : value});`;
		}
		if (is_indirectly_bound_value) {
			const update_value = b$1`@set_input_value(${element.var}, ${element.var}.__value);`;
			block.chunks.hydrate.push(update_value);
			updater = b$1`
				${updater}
				${update_value};
			`;
		}
		if (this.node.name === 'value' && dependencies.length > 0) {
			if (this.parent.bindings.some((binding) => binding.node.name === 'group')) {
				this.parent.dynamic_value_condition = block.get_unique_name('value_has_changed');
				block.add_variable(this.parent.dynamic_value_condition, x$1`false`);
				updater = b$1`
					${updater}
					${this.parent.dynamic_value_condition} = true;
				`;
			}
		}
		if (dependencies.length > 0) {
			const condition = this.get_dom_update_conditions(block, block.renderer.dirty(dependencies));
			block.chunks.update.push(b$1`
				if (${condition}) {
					${updater}
				}`);
		}
		// special case – autofocus. has to be handled in a bit of a weird way
		if (name === 'autofocus') {
			block.autofocus = {
				element_var: element.var,
				condition_expression: this.node.is_true ? undefined : value
			};
		}
	}

	/**
	 * @param {import('../../Block.js').default} block
	 * @param {any} value
	 */
	get_init(block, value) {
		this.last =
			this.should_cache &&
			block.get_unique_name(
				`${this.parent.var.name}_${this.name.replace(
					regex_invalid_variable_identifier_characters$2,
					'_'
				)}_value`
			);
		if (this.should_cache) block.add_variable(this.last);
		return this.should_cache ? x$1`${this.last} = ${value}` : value;
	}

	/**
	 * @param {import('../../Block.js').default} block
	 * @param {import('estree').Node} dependency_condition
	 */
	get_dom_update_conditions(block, dependency_condition) {
		const { property_name, should_cache, last } = this;
		const element = this.parent;
		const value = this.get_value(block);
		let condition = dependency_condition;
		if (should_cache) {
			condition = this.is_src
				? x$1`${condition} && (!@src_url_equal(${element.var}.src, (${last} = ${value})))`
				: x$1`${condition} && (${last} !== (${last} = ${value}))`;
		}
		if (this.is_input_value) {
			const type = element.node.get_static_attribute_value('type');
			if (type !== true && !non_textlike_input_types.has(type)) {
				condition = x$1`${condition} && ${element.var}.${property_name} !== ${
					should_cache ? last : value
				}`;
			}
		}
		if (block.has_outros) {
			condition = x$1`!#current || ${condition}`;
		}
		return condition;
	}
	get_dependencies() {
		const node_dependencies = this.node.get_dependencies();
		const dependencies = new Set(node_dependencies);
		node_dependencies.forEach((prop) => {
			const indirect_dependencies = this.parent.renderer.component.indirect_dependencies.get(prop);
			if (indirect_dependencies) {
				indirect_dependencies.forEach((indirect_dependency) => {
					dependencies.add(indirect_dependency);
				});
			}
		});
		return Array.from(dependencies);
	}
	get_metadata() {
		if (this.parent.node.namespace) return null;
		const metadata = attribute_lookup[this.name];
		if (metadata && metadata.applies_to && !metadata.applies_to.includes(this.parent.node.name))
			return null;
		return metadata;
	}

	/** @param {import('../../Block.js').default} block */
	get_value(block) {
		if (this.node.is_true) {
			if (this.metadata && boolean_attributes.has(this.metadata.property_name.toLowerCase())) {
				return x$1`true`;
			}
			return x$1`""`;
		}
		if (this.node.chunks.length === 0) return x$1`""`;
		// TODO some of this code is repeated in Tag.ts — would be good to
		// DRY it out if that's possible without introducing crazy indirection
		if (this.node.chunks.length === 1) {
			return this.node.chunks[0].type === 'Text'
				? string_literal(
						/** @type {import('../../../nodes/Text.js').default} */ (this.node.chunks[0]).data
				  )
				: /** @type {import('../../../nodes/shared/Expression.js').default} */ (
						this.node.chunks[0]
				  ).manipulate(block);
		}
		let value =
			this.node.name === 'class'
				? this.get_class_name_text(block)
				: this.render_chunks(block).reduce((lhs, rhs) => x$1`${lhs} + ${rhs}`);
		// '{foo} {bar}' — treat as string concatenation
		if (this.node.chunks[0].type !== 'Text') {
			value = x$1`"" + ${value}`;
		}
		return value;
	}

	/** @param {import('../../Block.js').default} block */
	get_class_name_text(block) {
		const scoped_css = this.node.chunks.some(
			(/** @type {import('../../../nodes/Text.js').default} */ chunk) => chunk.synthetic
		);
		const rendered = this.render_chunks(block);
		if (scoped_css && rendered.length === 2) {
			// we have a situation like class={possiblyUndefined}
			rendered[0] = x$1`@null_to_empty(${rendered[0]})`;
		}
		return rendered.reduce((lhs, rhs) => x$1`${lhs} + ${rhs}`);
	}

	/** @param {import('../../Block.js').default} block */
	render_chunks(block) {
		return this.node.chunks.map((chunk) => {
			if (chunk.type === 'Text') {
				return string_literal(chunk.data);
			}
			return chunk.manipulate(block);
		});
	}
	stringify() {
		if (this.node.is_true) return '';
		const value = this.node.chunks;
		if (value.length === 0) return '=""';
		return `="${value
			.map((chunk) => {
				return chunk.type === 'Text'
					? chunk.data.replace(regex_double_quotes, '\\"')
					: `\${${chunk.manipulate()}}`;
			})
			.join('')}"`;
	}
}
/**
 * @type {{
 *  [key in import('../../../../../shared/boolean_attributes.js').BooleanAttributes]: { property_name?: string; applies_to?: string[] } } &
 *  { [key in string]: { property_name?: string; applies_to?: string[] }; }
 * }
 */
const attribute_lookup = {
	allowfullscreen: { property_name: 'allowFullscreen', applies_to: ['iframe'] },
	allowpaymentrequest: { property_name: 'allowPaymentRequest', applies_to: ['iframe'] },
	async: { applies_to: ['script'] },
	autofocus: { applies_to: ['button', 'input', 'keygen', 'select', 'textarea'] },
	autoplay: { applies_to: ['audio', 'video'] },
	checked: { applies_to: ['input'] },
	controls: { applies_to: ['audio', 'video'] },
	default: { applies_to: ['track'] },
	defer: { applies_to: ['script'] },
	disabled: {
		applies_to: [
			'button',
			'fieldset',
			'input',
			'keygen',
			'optgroup',
			'option',
			'select',
			'textarea'
		]
	},
	formnovalidate: { property_name: 'formNoValidate', applies_to: ['button', 'input'] },
	hidden: {},
	indeterminate: { applies_to: ['input'] },
	inert: {},
	ismap: { property_name: 'isMap', applies_to: ['img'] },
	loop: { applies_to: ['audio', 'bgsound', 'video'] },
	multiple: { applies_to: ['input', 'select'] },
	muted: { applies_to: ['audio', 'video'] },
	nomodule: { property_name: 'noModule', applies_to: ['script'] },
	novalidate: { property_name: 'noValidate', applies_to: ['form'] },
	open: { applies_to: ['details', 'dialog'] },
	playsinline: { property_name: 'playsInline', applies_to: ['video'] },
	readonly: { property_name: 'readOnly', applies_to: ['input', 'textarea'] },
	required: { applies_to: ['input', 'select', 'textarea'] },
	reversed: { applies_to: ['ol'] },
	selected: { applies_to: ['option'] },
	value: {
		applies_to: [
			'button',
			'option',
			'input',
			'li',
			'meter',
			'progress',
			'param',
			'select',
			'textarea'
		]
	}
};
Object.keys(attribute_lookup).forEach((name) => {
	const metadata = attribute_lookup[name];
	if (!metadata.property_name) metadata.property_name = name;
});

/** @param {AttributeWrapper} attribute */
function should_cache(attribute) {
	return attribute.is_src || attribute.is_srcset || attribute.node.should_cache();
}
const regex_contains_checked_or_group = /checked|group/;

/** @param {AttributeWrapper} attribute */
function is_indirectly_bound_value(attribute) {
	const element = attribute.parent;
	return (
		attribute.name === 'value' &&
		(element.node.name === 'option' || // TODO check it's actually bound
			(element.node.name === 'input' &&
				element.node.bindings.some((binding) =>
					regex_contains_checked_or_group.test(binding.name)
				)))
	);
}

/** @extends AttributeWrapper */
class StyleAttributeWrapper extends AttributeWrapper {
	/** @param {import('../../Block.js').default} block */
	render(block) {
		const style_props = optimize_style(this.node.chunks);
		if (!style_props) return super.render(block);
		style_props.forEach((prop) => {
			let value;
			if (is_dynamic(prop.value)) {
				const prop_dependencies = new Set();
				value = prop.value
					.map((chunk) => {
						if (chunk.type === 'Text') {
							return string_literal(chunk.data);
						} else {
							add_to_set(prop_dependencies, chunk.dynamic_dependencies());
							return chunk.manipulate(block);
						}
					})
					.reduce((lhs, rhs) => x$1`${lhs} + ${rhs}`);
				// TODO is this necessary? style.setProperty always treats value as string, no?
				// if (prop.value.length === 1 || prop.value[0].type !== 'Text') {
				// 	value = x`"" + ${value}`;
				// }
				if (prop_dependencies.size) {
					let condition = block.renderer.dirty(Array.from(prop_dependencies));
					if (block.has_outros) {
						condition = x$1`!#current || ${condition}`;
					}
					const update = b$1`
						if (${condition}) {
							@set_style(${this.parent.var}, "${prop.key}", ${value}, ${prop.important ? 1 : null});
						}`;
					block.chunks.update.push(update);
				}
			} else {
				value = string_literal(
					/** @type {import('../../../nodes/Text.js').default} */ (prop.value[0]).data
				);
			}
			block.chunks.hydrate.push(
				b$1`@set_style(${this.parent.var}, "${prop.key}", ${value}, ${prop.important ? 1 : null});`
			);
		});
	}
}
const regex_style_prop_key = /^\s*([\w-]+):\s*/;

/** @param {Array<import('../../../nodes/Text.js').default | import('../../../nodes/shared/Expression.js').default>} value */
function optimize_style(value) {
	/** @type {Array<{ key: string; value: Array<import('../../../nodes/Text.js').default | import('../../../nodes/shared/Expression.js').default>; important: boolean; }>} */
	const props = [];
	let chunks = value.slice();
	while (chunks.length) {
		const chunk = chunks[0];
		if (chunk.type !== 'Text') return null;
		const key_match = regex_style_prop_key.exec(chunk.data);
		if (!key_match) return null;
		const key = key_match[1];
		const offset = key_match.index + key_match[0].length;
		const remaining_data = chunk.data.slice(offset);
		if (remaining_data) {
			chunks[0] = /** @type {import('../../../nodes/Text.js').default} */ ({
				start: chunk.start + offset,
				end: chunk.end,
				type: 'Text',
				data: remaining_data
			});
		} else {
			chunks.shift();
		}
		const result = get_style_value(chunks);
		props.push({ key, value: result.value, important: result.important });
		chunks = result.chunks;
	}
	return props;
}
const regex_important_flag = /\s*!important\s*$/;
const regex_semicolon_or_whitespace = /[;\s]/;

/** @param {Array<import('../../../nodes/Text.js').default | import('../../../nodes/shared/Expression.js').default>} chunks */
function get_style_value(chunks) {
	/** @type {Array<import('../../../nodes/Text.js').default | import('../../../nodes/shared/Expression.js').default>} */
	const value = [];
	let in_url = false;
	let quote_mark = null;
	let escaped = false;
	let closed = false;
	while (chunks.length && !closed) {
		const chunk = chunks.shift();
		if (chunk.type === 'Text') {
			let c = 0;
			while (c < chunk.data.length) {
				const char = chunk.data[c];
				if (escaped) {
					escaped = false;
				} else if (char === '\\') {
					escaped = true;
				} else if (char === quote_mark) {
					quote_mark = null;
				} else if (char === '"' || char === "'") {
					quote_mark = char;
				} else if (char === ')' && in_url) {
					in_url = false;
				} else if (char === 'u' && chunk.data.slice(c, c + 4) === 'url(') {
					in_url = true;
				} else if (char === ';' && !in_url && !quote_mark) {
					closed = true;
					break;
				}
				c += 1;
			}
			if (c > 0) {
				value.push(
					/** @type {import('../../../nodes/Text.js').default} */ ({
						type: 'Text',
						start: chunk.start,
						end: chunk.start + c,
						data: chunk.data.slice(0, c)
					})
				);
			}
			while (regex_semicolon_or_whitespace.test(chunk.data[c])) c += 1;
			const remaining_data = chunk.data.slice(c);
			if (remaining_data) {
				chunks.unshift(
					/** @type {import('../../../nodes/Text.js').default} */ ({
						start: chunk.start + c,
						end: chunk.end,
						type: 'Text',
						data: remaining_data
					})
				);
				break;
			}
		} else {
			value.push(chunk);
		}
	}
	let important = false;
	const last_chunk = value[value.length - 1];
	if (last_chunk && last_chunk.type === 'Text' && regex_important_flag.test(last_chunk.data)) {
		important = true;
		last_chunk.data = last_chunk.data.replace(regex_important_flag, '');
		if (!last_chunk.data) value.pop();
	}
	return {
		chunks,
		value,
		important
	};
}

/** @param {Array<import('../../../nodes/Text.js').default | import('../../../nodes/shared/Expression.js').default>} value */
function is_dynamic(value) {
	return value.length > 1 || value[0].type !== 'Text';
}

class SpreadAttributeWrapper extends BaseAttributeWrapper {}

/**
 * @param {import('../Element/index.js').default | import('../InlineComponent/index.js').default} parent
 * @param {import('../../../nodes/Binding.js').default} binding
 */
function mark_each_block_bindings(parent, binding) {
	// we need to ensure that the each block creates a context including
	// the list and the index, if they're not otherwise referenced
	binding.expression.references.forEach((name) => {
		const each_block = parent.node.scope.get_owner(name);
		if (each_block) {
			/** @type {import('../../../nodes/EachBlock.js').default} */ (each_block).has_binding = true;
		}
	});
	if (binding.name === 'group') {
		/** @param {string} name */
		const add_index_binding = (name) => {
			const each_block = parent.node.scope.get_owner(name);
			if (each_block.type === 'EachBlock') {
				each_block.has_index_binding = true;
				for (const dep of each_block.expression.contextual_dependencies) {
					add_index_binding(dep);
				}
			}
		};
		// for `<input bind:group={} >`, we make sure that all the each blocks creates context with `index`
		for (const name of binding.expression.contextual_dependencies) {
			add_index_binding(name);
		}
	}
}

/** */
class BindingWrapper {
	/** @type {import('../../../nodes/Binding.js').default} */
	node = undefined;

	/** @type {import('./index.js').default | import('../InlineComponent/index.js').default} */
	parent = undefined;

	/** @type {string} */
	object = undefined;
	/**
	 * @type {{
	 * 		uses_context: boolean;
	 * 		mutation: import('estree').Node | import('estree').Node[];
	 * 		contextual_dependencies: Set<string>;
	 * 		lhs?: import('estree').Node;
	 * 	}}
	 */
	handler = undefined;

	/** @type {import('estree').Node} */
	snippet = undefined;

	/** @type {boolean} */
	is_readonly = undefined;

	/** @type {boolean} */
	needs_lock = undefined;

	/** @type {import('../../Renderer.js').BindingGroup} */
	binding_group = undefined;

	/**
	 * @param {import('../../Block.js').default} block
	 * @param {import('../../../nodes/Binding.js').default} node
	 * @param {import('./index.js').default | import('../InlineComponent/index.js').default} parent
	 */
	constructor(block, node, parent) {
		this.node = node;
		this.parent = parent;
		const { dependencies } = this.node.expression;
		block.add_dependencies(dependencies);
		// TODO does this also apply to e.g. `<input type='checkbox' bind:group='foo'>`?
		handle_select_value_binding(this, dependencies);
		if (node.is_contextual) {
			mark_each_block_bindings(this.parent, this.node);
		}
		this.object = get_object(this.node.expression.node).name;
		if (this.node.name === 'group') {
			this.binding_group = get_binding_group(parent.renderer, this, block);
		}
		// view to model
		this.handler = get_event_handler(
			this,
			parent.renderer,
			block,
			this.object,
			this.node.raw_expression
		);
		this.snippet = this.node.expression.manipulate(block);
		this.is_readonly = this.node.is_readonly;
		this.needs_lock = this.node.name === 'currentTime'; // TODO others?
	}
	get_dependencies() {
		const dependencies = new Set(this.node.expression.dependencies);
		this.node.expression.dependencies.forEach((prop) => {
			const indirect_dependencies = this.parent.renderer.component.indirect_dependencies.get(prop);
			if (indirect_dependencies) {
				indirect_dependencies.forEach((indirect_dependency) => {
					dependencies.add(indirect_dependency);
				});
			}
		});
		if (this.binding_group) {
			this.binding_group.list_dependencies.forEach((dep) => dependencies.add(dep));
		}
		return dependencies;
	}
	get_update_dependencies() {
		const object = this.object;
		const dependencies = new Set();
		if (this.node.expression.template_scope.names.has(object)) {
			this.node.expression.template_scope.dependencies_for_name
				.get(object)
				.forEach((name) => dependencies.add(name));
		} else {
			dependencies.add(object);
		}
		const result = new Set(dependencies);
		dependencies.forEach((dependency) => {
			const indirect_dependencies =
				this.parent.renderer.component.indirect_dependencies.get(dependency);
			if (indirect_dependencies) {
				indirect_dependencies.forEach((indirect_dependency) => {
					result.add(indirect_dependency);
				});
			}
		});
		return result;
	}
	is_readonly_media_attribute() {
		return this.node.is_readonly_media_attribute();
	}

	/**
	 * @param {import('../../Block.js').default} block
	 * @param {import('estree').Identifier} lock
	 */
	render(block, lock) {
		if (this.is_readonly) return;
		const { parent } = this;

		/** @type {any[]} */
		const update_conditions = this.needs_lock ? [x$1`!${lock}`] : [];

		/** @type {any[]} */
		const mount_conditions = [];

		/** @type {any} */
		let update_or_condition = null;
		const dependency_array = Array.from(this.get_dependencies());
		if (dependency_array.length > 0) {
			update_conditions.push(block.renderer.dirty(dependency_array));
		}
		if (parent.node.name === 'input') {
			const type = parent.node.get_static_attribute_value('type');
			if (
				type === null ||
				type === '' ||
				type === 'text' ||
				type === 'email' ||
				type === 'password' ||
				type === 'search' ||
				type === 'url'
			) {
				update_conditions.push(x$1`${parent.var}.${this.node.name} !== ${this.snippet}`);
			} else if (type === 'number') {
				update_conditions.push(x$1`@to_number(${parent.var}.${this.node.name}) !== ${this.snippet}`);
			}
		}
		// model to view
		let update_dom = get_dom_updater(parent, this, false);
		let mount_dom = get_dom_updater(parent, this, true);
		// special cases
		switch (this.node.name) {
			case 'group': {
				block.renderer.add_to_context('$$binding_groups');
				this.binding_group.add_element(block, this.parent.var);
				if (/** @type {import('./index.js').default} */ (this.parent).has_dynamic_value) {
					update_or_condition = /** @type {import('./index.js').default} */ (this.parent)
						.dynamic_value_condition;
				}
				break;
			}
			case 'textContent':
				update_conditions.push(x$1`${this.snippet} !== ${parent.var}.textContent`);
				mount_conditions.push(x$1`${this.snippet} !== void 0`);
				break;
			case 'innerText':
				update_conditions.push(x$1`${this.snippet} !== ${parent.var}.innerText`);
				mount_conditions.push(x$1`${this.snippet} !== void 0`);
				break;
			case 'innerHTML':
				update_conditions.push(x$1`${this.snippet} !== ${parent.var}.innerHTML`);
				mount_conditions.push(x$1`${this.snippet} !== void 0`);
				break;
			case 'currentTime':
				update_conditions.push(x$1`!@_isNaN(${this.snippet})`);
				mount_dom = null;
				break;
			case 'playbackRate':
			case 'volume':
				update_conditions.push(x$1`!@_isNaN(${this.snippet})`);
				mount_conditions.push(x$1`!@_isNaN(${this.snippet})`);
				break;
			case 'paused': {
				// this is necessary to prevent audio restarting by itself
				const last = block.get_unique_name(`${parent.var.name}_is_paused`);
				block.add_variable(last, x$1`true`);
				update_conditions.push(x$1`${last} !== (${last} = ${this.snippet})`);
				update_dom = b$1`${parent.var}[${last} ? "pause" : "play"]();`;
				mount_dom = null;
				break;
			}
			case 'value':
				if (parent.node.get_static_attribute_value('type') === 'file') {
					update_dom = null;
					mount_dom = null;
				}
		}
		if (update_dom) {
			if (update_conditions.length > 0) {
				let condition = update_conditions.reduce((lhs, rhs) => x$1`${lhs} && ${rhs}`);
				if (update_or_condition) condition = x$1`${update_or_condition} || (${condition})`;
				block.chunks.update.push(b$1`
					if (${condition}) {
						${update_dom}
					}
				`);
			} else {
				block.chunks.update.push(update_dom);
			}
		}
		if (mount_dom) {
			if (mount_conditions.length > 0) {
				const condition = mount_conditions.reduce((lhs, rhs) => x$1`${lhs} && ${rhs}`);
				block.chunks.mount.push(b$1`
					if (${condition}) {
						${mount_dom}
					}
				`);
			} else {
				block.chunks.mount.push(mount_dom);
			}
		}
	}
}

/**
 * @param {import('./index.js').default | import('../InlineComponent/index.js').default} element
 * @param {BindingWrapper} binding
 * @param {boolean} mounting
 */
function get_dom_updater(element, binding, mounting) {
	const { node } = element;
	if (binding.is_readonly_media_attribute()) {
		return null;
	}
	if (binding.node.name === 'this') {
		return null;
	}
	if (node.name === 'select') {
		return node.get_static_attribute_value('multiple') === true
			? b$1`@select_options(${element.var}, ${binding.snippet})`
			: mounting
			? b$1`@select_option(${element.var}, ${binding.snippet}, true)`
			: b$1`@select_option(${element.var}, ${binding.snippet})`;
	}
	if (binding.node.name === 'group') {
		const type = node.get_static_attribute_value('type');
		const condition =
			type === 'checkbox'
				? x$1`~(${binding.snippet} || []).indexOf(${element.var}.__value)`
				: x$1`${element.var}.__value === ${binding.snippet}`;
		return b$1`${element.var}.checked = ${condition};`;
	}
	if (binding.node.name === 'value') {
		return b$1`@set_input_value(${element.var}, ${binding.snippet});`;
	}
	return b$1`${element.var}.${binding.node.name} = ${binding.snippet};`;
}

/**
 * @param {import('../../Renderer.js').default} renderer
 * @param {BindingWrapper} binding
 * @param {import('../../Block.js').default} block
 */
function get_binding_group(renderer, binding, block) {
	const value = binding.node;
	const { parts } = flatten_reference(value.raw_expression);
	let keypath = parts.join('.');
	const contexts = [];
	const contextual_dependencies = new Set();
	const { template_scope } = value.expression;

	/** @param {string} dep */
	const add_contextual_dependency = (dep) => {
		contextual_dependencies.add(dep);
		const owner = template_scope.get_owner(dep);
		if (owner.type === 'EachBlock') {
			for (const dep of owner.expression.contextual_dependencies) {
				add_contextual_dependency(dep);
			}
		}
	};
	for (const dep of value.expression.contextual_dependencies) {
		add_contextual_dependency(dep);
	}
	for (const dep of contextual_dependencies) {
		const context = block.bindings.get(dep);
		let key;
		let name;
		if (context) {
			key = context.object.name;
			name = context.property.name;
		} else {
			key = dep;
			name = dep;
		}
		keypath = `${key}@${keypath}`;
		contexts.push(name);
	}
	// create a global binding_group across blocks
	if (!renderer.binding_groups.has(keypath)) {
		const index = renderer.binding_groups.size;
		// the bind:group depends on the list in the {#each} block as well
		// as reordering (removing and adding back to the DOM) may affect the value
		const list_dependencies = new Set();
		let parent = value.parent;
		while (parent) {
			if (parent.type === 'EachBlock') {
				for (const dep of parent.expression.dynamic_dependencies()) {
					list_dependencies.add(dep);
				}
			}
			parent = parent.parent;
		}
		/**
		 * When using bind:group with logic blocks, the inputs with bind:group may be scattered across different blocks.
		 * This therefore keeps track of all the <input> elements that have the same bind:group within the same block.
		 */
		const elements = new Map();
		contexts.forEach((context) => {
			renderer.add_to_context(context, true);
		});
		renderer.binding_groups.set(keypath, {
			binding_group: () => {
				let obj = x$1`$$binding_groups[${index}]`;
				if (contexts.length > 0) {
					contexts.forEach((secondary_index) => {
						obj = x$1`${obj}[${secondary_index}]`;
					});
				}
				return obj;
			},
			contexts,
			list_dependencies,
			keypath,
			add_element(block, element) {
				if (!elements.has(block)) {
					elements.set(block, []);
				}
				elements.get(block).push(element);
			},
			render(block) {
				const local_name = block.get_unique_name('binding_group');
				const binding_group = block.renderer.reference('$$binding_groups');
				block.add_variable(local_name);
				if (contexts.length > 0) {
					const indexes = {
						type: 'ArrayExpression',
						elements: contexts.map((name) => block.renderer.reference(name))
					};
					block.chunks.init.push(
						b$1`${local_name} = @init_binding_group_dynamic(${binding_group}[${index}], ${indexes})`
					);
					block.chunks.update.push(
						b$1`if (${block.renderer.dirty(
							Array.from(list_dependencies)
						)}) ${local_name}.u(${indexes})`
					);
				} else {
					block.chunks.init.push(
						b$1`${local_name} = @init_binding_group(${binding_group}[${index}])`
					);
				}
				block.chunks.hydrate.push(b$1`${local_name}.p(${elements.get(block)})`);
				block.chunks.destroy.push(b$1`${local_name}.r()`);
			}
		});
	}
	// register the binding_group for the block
	const binding_group = renderer.binding_groups.get(keypath);
	block.binding_groups.add(binding_group);
	return binding_group;
}

/**
 * @param {BindingWrapper} binding
 * @param {import('../../Renderer.js').default} renderer
 * @param {import('../../Block.js').default} block
 * @param {string} name
 * @param {import('estree').Node} lhs
 * @returns {{ uses_context: boolean; mutation: import('estree').Node | import('estree').Node[]; contextual_dependencies: Set<string>; lhs?: import('estree').Node; }}
 */
function get_event_handler(binding, renderer, block, name, lhs) {
	const contextual_dependencies = new Set(binding.node.expression.contextual_dependencies);
	const context = block.bindings.get(name);

	/** @type {import('estree').Node[] | undefined} */
	let set_store;
	if (context) {
		const { object, property, store, snippet } = context;
		lhs = replace_object(lhs, snippet);
		contextual_dependencies.add(object.name);
		contextual_dependencies.add(property.name);
		contextual_dependencies.delete(name);
		if (store) {
			set_store = b$1`${store}.set(${`$${store}`});`;
		}
	} else {
		const object = get_object(lhs);
		if (object.name[0] === '$') {
			const store = object.name.slice(1);
			set_store = b$1`${store}.set(${object.name});`;
		}
	}
	const value = get_value_from_dom(renderer, binding.parent, binding, contextual_dependencies);
	const mutation = b$1`
		${lhs} = ${value};
		${set_store}
	`;
	return {
		uses_context: binding.node.is_contextual || binding.node.expression.uses_context,
		mutation,
		contextual_dependencies,
		lhs
	};
}

/**
 * @param {import('../../Renderer.js').default} _renderer
 * @param {import('./index.js').default | import('../InlineComponent/index.js').default} element
 * @param {BindingWrapper} binding
 * @param {Set<string>} contextual_dependencies
 */
function get_value_from_dom(_renderer, element, binding, contextual_dependencies) {
	const { node } = element;
	const { name } = binding.node;
	if (name === 'this') {
		return x$1`$$value`;
	}
	// <div bind:contentRect|contentBoxSize|borderBoxSize|devicePixelContentBoxSize>
	if (regex_box_size.test(name)) {
		return x$1`@ResizeObserverSingleton.entries.get(this)?.${name}`;
	}
	// <select bind:value='selected>
	if (node.name === 'select') {
		return node.get_static_attribute_value('multiple') === true
			? x$1`@select_multiple_value(this)`
			: x$1`@select_value(this)`;
	}
	const type = node.get_static_attribute_value('type');
	// <input type='checkbox' bind:group='foo'>
	if (name === 'group') {
		if (type === 'checkbox') {
			const { binding_group, contexts } = binding.binding_group;
			add_to_set(contextual_dependencies, contexts);
			return x$1`@get_binding_group_value(${binding_group()}, this.__value, this.checked)`;
		}
		return x$1`this.__value`;
	}
	// <input type='range|number' bind:value>
	if (type === 'range' || type === 'number') {
		return x$1`@to_number(this.${name})`;
	}
	if (name === 'buffered' || name === 'seekable' || name === 'played') {
		return x$1`@time_ranges_to_array(this.${name})`;
	}
	// everything else
	return x$1`this.${name}`;
}

/**
 * @param {import('estree').Node | void} a
 * @param {import('estree').Node | void} b
 */
function compare_node(a, b) {
	if (a === b) return true;
	if (!a || !b) return false;
	if (a.type !== b.type) return false;
	switch (a.type) {
		case 'Identifier':
			return a.name === /** @type {import('estree').Identifier} */ (b).name;
		case 'MemberExpression':
			return (
				compare_node(a.object, /** @type {import('estree').MemberExpression} */ (b).object) &&
				compare_node(a.property, /** @type {import('estree').MemberExpression} */ (b).property) &&
				a.computed === /** @type {import('estree').MemberExpression} */ (b).computed
			);
		case 'Literal':
			return a.value === /** @type {import('estree').Literal} */ (b).value;
	}
}

/**
 * @param {import('../../../Component.js').default} component
 * @param {import('../../Block.js').default} block
 * @param {import('../Element/Binding.js').default} binding
 * @param {import('estree').Identifier} variable
 */
function bind_this(component, block, binding, variable) {
	const fn = component.get_unique_name(`${variable.name}_binding`);
	block.renderer.add_to_context(fn.name);
	const callee = block.renderer.reference(fn.name);
	const { contextual_dependencies, mutation } = binding.handler;
	const dependencies = binding.get_update_dependencies();
	const body = b$1`
		${mutation}
		${Array.from(dependencies)
			.filter((dep) => dep[0] !== '$')
			.filter((dep) => !contextual_dependencies.has(dep))
			.map((dep) => b$1`${block.renderer.invalidate(dep)};`)}
	`;
	if (contextual_dependencies.size) {
		/** @type {import('estree').Identifier[]} */
		const params = Array.from(contextual_dependencies).map((name) => ({
			type: 'Identifier',
			name
		}));
		component.partly_hoisted.push(b$1`
			function ${fn}($$value, ${params}) {
				@binding_callbacks[$$value ? 'unshift' : 'push'](() => {
					${body}
				});
			}
		`);
		const alias_map = new Map();
		const args = [];
		for (let id of params) {
			const value = block.renderer.reference(id.name);
			let found = false;
			if (block.variables.has(id.name)) {
				let alias = id.name;
				for (
					let i = 1;
					block.variables.has(alias) && !compare_node(block.variables.get(alias).init, value);
					alias = `${id.name}_${i++}`
				);
				alias_map.set(alias, id.name);
				id = { type: 'Identifier', name: alias };
				found = block.variables.has(alias);
			}
			args.push(id);
			if (!found) {
				block.add_variable(id, value);
			}
		}
		const assign = block.get_unique_name(`assign_${variable.name}`);
		const unassign = block.get_unique_name(`unassign_${variable.name}`);
		block.chunks.init.push(b$1`
			const ${assign} = () => ${callee}(${variable}, ${args});
			const ${unassign} = () => ${callee}(null, ${args});
		`);
		const condition = Array.from(args)
			.map(
				(name) => x$1`${name} !== ${block.renderer.reference(alias_map.get(name.name) || name.name)}`
			)
			.reduce((lhs, rhs) => x$1`${lhs} || ${rhs}`);
		// we push unassign and unshift assign so that references are
		// nulled out before they're created, to avoid glitches
		// with shifting indices
		block.chunks.update.push(b$1`
			if (${condition}) {
				${unassign}();
				${args.map((a) => b$1`${a} = ${block.renderer.reference(alias_map.get(a.name) || a.name)}`)};
				${assign}();
			}`);
		block.chunks.destroy.push(b$1`${unassign}();`);
		return b$1`${assign}();`;
	}
	component.partly_hoisted.push(b$1`
		function ${fn}($$value) {
			@binding_callbacks[$$value ? 'unshift' : 'push'](() => {
				${body}
			});
		}
	`);
	block.chunks.destroy.push(b$1`${callee}(null);`);
	return b$1`${callee}(${variable});`;
}

/**
 * @template {import('../../../nodes/MustacheTag.js').default | import('../../../nodes/RawMustacheTag.js').default} NodeType
 * @extends Wrapper<NodeType>
 */
let Tag$1 = class Tag extends Wrapper {
	/**
	 * @param {import('../../Renderer.js').default} renderer
	 * @param {import('../../Block.js').default} block
	 * @param {import('./Wrapper.js').default} parent
	 * @param {NodeType} node
	 */
	constructor(renderer, block, parent, node) {
		super(renderer, block, parent, node);
		block.add_dependencies(node.expression.dependencies);
	}

	/**
	 * @param {import('../../Block.js').default} block
	 * @param {(value: import('estree').Node) => import('estree').Node | import('estree').Node[]} update
	 */
	rename_this_method(block, update) {
		const dependencies = this.node.expression.dynamic_dependencies();
		let snippet = this.node.expression.manipulate(block);
		const value = this.node.should_cache && block.get_unique_name(`${this.var.name}_value`);
		const content = this.node.should_cache ? value : snippet;
		snippet = x$1`${snippet} + ""`;
		if (this.node.should_cache) block.add_variable(value, snippet); // TODO may need to coerce snippet to string
		if (dependencies.length > 0) {
			let condition = block.renderer.dirty(dependencies);
			if (block.has_outros) {
				condition = x$1`!#current || ${condition}`;
			}
			const update_cached_value = x$1`${value} !== (${value} = ${snippet})`;
			if (this.node.should_cache) {
				condition = x$1`${condition} && ${update_cached_value}`;
			}
			block.chunks.update.push(
				b$1`if (${condition}) ${update(/** @type {import('estree').Node} */ (content))}`
			);
		}
		return { init: content };
	}
};

/** @extends Tag */
class MustacheTagWrapper extends Tag$1 {
	/** @type {import('estree').Identifier} */
	var = { type: 'Identifier', name: 't' };

	/**
	 * @param {import('../Renderer.js').default} renderer
	 * @param {import('../Block.js').default} block
	 * @param {import('./shared/Wrapper.js').default} parent
	 * @param {import('../../nodes/MustacheTag.js').default | import('../../nodes/RawMustacheTag.js').default} node
	 */
	constructor(renderer, block, parent, node) {
		super(renderer, block, parent, node);
	}

	/**
	 * @param {import('../Block.js').default} block
	 * @param {import('estree').Identifier} parent_node
	 * @param {import('estree').Identifier} parent_nodes
	 * @param {Record<string, unknown> | undefined} data
	 */
	render(block, parent_node, parent_nodes, data) {
		const contenteditable_attributes =
			this.parent instanceof ElementWrapper &&
			this.parent.attributes.filter((a) => a.node.name === 'contenteditable');
		const spread_attributes =
			this.parent instanceof ElementWrapper &&
			this.parent.attributes.filter((a) => a.node.is_spread);

		/** @type {import('estree').Expression | true | undefined} */
		let contenteditable_attr_value = undefined;
		if (contenteditable_attributes.length > 0) {
			const attribute = /** @type {import('./Element/Attribute.js').default} */ (
				contenteditable_attributes[0]
			);
			if ([true, 'true', ''].includes(attribute.node.get_static_value())) {
				contenteditable_attr_value = true;
			} else {
				contenteditable_attr_value = x$1`${attribute.get_value(block)}`;
			}
		} else if (spread_attributes.length > 0 && data.element_data_name) {
			contenteditable_attr_value = x$1`${data.element_data_name}['contenteditable']`;
		}
		const { init } = this.rename_this_method(block, (value) => {
			if (contenteditable_attr_value) {
				if (contenteditable_attr_value === true) {
					return x$1`@set_data_contenteditable(${this.var}, ${value})`;
				} else {
					return x$1`@set_data_maybe_contenteditable(${this.var}, ${value}, ${contenteditable_attr_value})`;
				}
			} else {
				return x$1`@set_data(${this.var}, ${value})`;
			}
		});
		block.add_element(
			this.var,
			x$1`@text(${init})`,
			parent_nodes && x$1`@claim_text(${parent_nodes}, ${init})`,
			parent_node
		);
	}
}

/** @extends Tag */
class RawMustacheTagWrapper extends Tag$1 {
	/** @type {import('estree').Identifier} */
	var = { type: 'Identifier', name: 'raw' };

	/**
	 * @param {import('../Renderer.js').default} renderer
	 * @param {import('../Block.js').default} block
	 * @param {import('./shared/Wrapper.js').default} parent
	 * @param {import('../../nodes/MustacheTag.js').default | import('../../nodes/RawMustacheTag.js').default} node
	 */
	constructor(renderer, block, parent, node) {
		super(renderer, block, parent, node);
	}

	/**
	 * @param {import('../Block.js').default} block
	 * @param {import('estree').Identifier} parent_node
	 * @param {import('estree').Identifier} _parent_nodes
	 */
	render(block, parent_node, _parent_nodes) {
		const in_head = is_head(parent_node);
		const can_use_innerhtml = !in_head && parent_node && !this.prev && !this.next;
		if (can_use_innerhtml && !this.renderer.options.hydratable) {
			/** @param {import('estree').Node} content */
			const insert = (content) => b$1`${parent_node}.innerHTML = ${content};`[0];
			const { init } = this.rename_this_method(block, (content) => insert(content));
			block.chunks.mount.push(insert(init));
		} else {
			const needs_anchor =
				in_head ||
				(this.next ? !this.next.is_dom_node() : !this.parent || !this.parent.is_dom_node());
			const html_tag = block.get_unique_name('html_tag');
			const html_anchor = needs_anchor && block.get_unique_name('html_anchor');
			block.add_variable(html_tag);
			const { init } = this.rename_this_method(block, (content) => x$1`${html_tag}.p(${content})`);
			const update_anchor = needs_anchor ? html_anchor : this.next ? this.next.var : 'null';
			const parent_element = /** @type {import('../../nodes/Element.js').default} */ (
				this.node.find_nearest(/^Element/)
			);
			const is_svg = parent_element && parent_element.namespace === namespaces.svg;
			block.chunks.create.push(b$1`${html_tag} = new @HtmlTag(${is_svg ? 'true' : 'false'});`);
			if (this.renderer.options.hydratable) {
				block.chunks.claim.push(
					b$1`${html_tag} = @claim_html_tag(${_parent_nodes}, ${is_svg ? 'true' : 'false'});`
				);
			}
			block.chunks.hydrate.push(b$1`${html_tag}.a = ${update_anchor};`);
			block.chunks.mount.push(
				b$1`${html_tag}.m(${init}, ${parent_node || '#target'}, ${parent_node ? null : '#anchor'});`
			);
			if (needs_anchor) {
				block.add_element(html_anchor, x$1`@empty()`, x$1`@empty()`, parent_node);
			}
			if (!parent_node || in_head) {
				block.chunks.destroy.push(b$1`if (detaching) ${html_tag}.d();`);
			}
		}
	}
}

/** @extends Wrapper<import('../../nodes/Comment.js').default> */
class CommentWrapper extends Wrapper {
	/**
	 * @param {import('../Renderer.js').default} renderer
	 * @param {import('../Block.js').default} block
	 * @param {import('./shared/Wrapper.js').default} parent
	 * @param {import('../../nodes/Comment.js').default} node
	 */
	constructor(renderer, block, parent, node) {
		super(renderer, block, parent, node);
		this.var = /** @type {import('estree').Identifier} */ (x$1`c`);
	}

	/**
	 * @param {import('../Block.js').default} block
	 * @param {import('estree').Identifier} parent_node
	 * @param {import('estree').Identifier} parent_nodes
	 */
	render(block, parent_node, parent_nodes) {
		if (!this.renderer.options.preserveComments) return;
		const string_literal = {
			type: 'Literal',
			value: this.node.data,
			loc: {
				start: this.renderer.locate(this.node.start),
				end: this.renderer.locate(this.node.end)
			}
		};
		block.add_element(
			this.var,
			x$1`@comment(${string_literal})`,
			parent_nodes && x$1`@claim_comment(${parent_nodes}, ${string_literal})`,
			parent_node
		);
	}
	text() {
		if (!this.renderer.options.preserveComments) return '';
		return `<!--${this.node.data}-->`;
	}
}

const regex_contains_radio_or_checkbox_or_file = /radio|checkbox|file/;
const regex_contains_radio_or_checkbox_or_range_or_file = /radio|checkbox|range|file/;
const events = [
	{
		event_names: ['input'],
		filter: (node, _name) =>
			node.name === 'textarea' ||
			(node.name === 'input' &&
				!regex_contains_radio_or_checkbox_or_range_or_file.test(
					/** @type {string} */ (node.get_static_attribute_value('type'))
				))
	},
	{
		event_names: ['input'],
		filter: (node, name) => is_name_contenteditable(name) && has_contenteditable_attr(node)
	},
	{
		event_names: ['change'],
		filter: (node, _name) =>
			node.name === 'select' ||
			(node.name === 'input' &&
				regex_contains_radio_or_checkbox_or_file.test(
					/** @type {string} */ (node.get_static_attribute_value('type'))
				))
	},
	{
		event_names: ['change', 'input'],
		filter: (node, _name) =>
			node.name === 'input' && node.get_static_attribute_value('type') === 'range'
	},
	// resize events
	{
		event_names: ['elementresize'],
		filter: (_node, name) => regex_dimensions.test(name)
	},
	{
		event_names: ['elementresizecontentbox'],
		filter: (_node, name) => regex_content_rect.test(name) ?? regex_content_box_size.test(name)
	},
	{
		event_names: ['elementresizeborderbox'],
		filter: (_node, name) => regex_border_box_size.test(name)
	},
	{
		event_names: ['elementresizedevicepixelcontentbox'],
		filter: (_node, name) => regex_device_pixel_content_box_size.test(name)
	},
	// media events
	{
		event_names: ['timeupdate'],
		filter: (node, name) =>
			node.is_media_node() && (name === 'currentTime' || name === 'played' || name === 'ended')
	},
	{
		event_names: ['durationchange'],
		filter: (node, name) => node.is_media_node() && name === 'duration'
	},
	{
		event_names: ['play', 'pause'],
		filter: (node, name) => node.is_media_node() && name === 'paused'
	},
	{
		event_names: ['progress'],
		filter: (node, name) => node.is_media_node() && name === 'buffered'
	},
	{
		event_names: ['loadedmetadata'],
		filter: (node, name) => node.is_media_node() && (name === 'buffered' || name === 'seekable')
	},
	{
		event_names: ['volumechange'],
		filter: (node, name) => node.is_media_node() && (name === 'volume' || name === 'muted')
	},
	{
		event_names: ['ratechange'],
		filter: (node, name) => node.is_media_node() && name === 'playbackRate'
	},
	{
		event_names: ['seeking', 'seeked'],
		filter: (node, name) => node.is_media_node() && name === 'seeking'
	},
	{
		event_names: ['ended'],
		filter: (node, name) => node.is_media_node() && name === 'ended'
	},
	{
		event_names: ['resize'],
		filter: (node, name) =>
			node.is_media_node() && (name === 'videoHeight' || name === 'videoWidth')
	},
	{
		// from https://html.spec.whatwg.org/multipage/media.html#ready-states
		// and https://html.spec.whatwg.org/multipage/media.html#loading-the-media-resource
		event_names: [
			'loadedmetadata',
			'loadeddata',
			'canplay',
			'canplaythrough',
			'playing',
			'waiting',
			'emptied'
		],
		filter: (node, name) => node.is_media_node() && name === 'readyState'
	},
	// details event
	{
		event_names: ['toggle'],
		filter: (node, _name) => node.name === 'details'
	},
	{
		event_names: ['load'],
		filter: (_, name) => name === 'naturalHeight' || name === 'naturalWidth'
	}
];
const CHILD_DYNAMIC_ELEMENT_BLOCK = 'child_dynamic_element';
const regex_invalid_variable_identifier_characters$1 = /[^a-zA-Z0-9_$]/g;
const regex_minus_signs = /-/g;

/** @extends Wrapper<import('../../../nodes/Element.js').default> */
class ElementWrapper extends Wrapper {
	/** @type {import('../Fragment.js').default} */
	fragment;

	/** @type {Array<AttributeWrapper | import('./StyleAttribute.js').default | import('./SpreadAttribute.js').default>} */
	attributes;

	/** @type {import('./Binding.js').default[]} */
	bindings;

	/** @type {import('./EventHandler.js').default[]} */
	event_handlers;

	/** @type {string[]} */
	class_dependencies;

	/** @type {Set<string>} */
	dynamic_style_dependencies;

	/** @type {boolean} */
	has_dynamic_attribute;

	/** @type {Set<string>} */
	select_binding_dependencies;

	/** @type {boolean} */
	has_dynamic_value;

	/** @type {any} */
	dynamic_value_condition;

	/** @type {any} */
	var;

	/** @type {boolean} */
	void;

	/** @type {import('../../Block.js').default} */
	child_dynamic_element_block = null;

	/** @type {ElementWrapper} */
	child_dynamic_element = null;
	/** */
	element_data_name = null;

	/**
	 * @param {import('../../Renderer.js').default} renderer
	 * @param {import('../../Block.js').default} block
	 * @param {import('../shared/Wrapper.js').default} parent
	 * @param {import('../../../nodes/Element.js').default} node
	 * @param {boolean} strip_whitespace
	 * @param {import('../shared/Wrapper.js').default} next_sibling
	 */
	constructor(renderer, block, parent, node, strip_whitespace, next_sibling) {
		super(renderer, block, parent, node);
		this.var = {
			type: 'Identifier',
			name: node.name.replace(regex_invalid_variable_identifier_characters$1, '_')
		};
		this.void = is_void(node.name);
		this.class_dependencies = [];
		if (node.is_dynamic_element && block.type !== CHILD_DYNAMIC_ELEMENT_BLOCK) {
			this.child_dynamic_element_block = block.child({
				comment: create_debugging_comment(node, renderer.component),
				name: renderer.component.get_unique_name('create_dynamic_element'),
				type: CHILD_DYNAMIC_ELEMENT_BLOCK
			});
			renderer.blocks.push(this.child_dynamic_element_block);
			this.child_dynamic_element = new ElementWrapper(
				renderer,
				this.child_dynamic_element_block,
				parent,
				node,
				strip_whitespace,
				next_sibling
			);

			// in the case of `parent_block -> child_dynamic_element_block -> child_dynamic_element`
			// `child_dynamic_element_block.add_intro/outro` is called inside `new ElementWrapper()`
			// but when `is_local === true` it does not bubble to parent_block
			// we manually add transitions back to the parent_block (#8233)
			if (node.intro) block.add_intro(node.intro.is_local);
			if (node.outro) block.add_outro(node.outro.is_local);

			// the original svelte:element is never used for rendering, because
			// it gets assigned a child_dynamic_element which is used in all rendering logic.
			// so doing all of this on the original svelte:element will just cause double
			// code, because it will be done again on the child_dynamic_element.
			return;
		}
		this.dynamic_style_dependencies = new Set();
		if (this.node.children.length) {
			this.node.lets.forEach((l) => {
				extract_names(l.value || l.name).forEach((name) => {
					renderer.add_to_context(name, true);
				});
			});
		}
		this.attributes = this.node.attributes.map((attribute) => {
			if (attribute.name === 'style') {
				return new StyleAttributeWrapper(this, block, attribute);
			}
			if (attribute.type === 'Spread') {
				return new SpreadAttributeWrapper(this, block, attribute);
			}
			return new AttributeWrapper(this, block, attribute);
		});
		this.has_dynamic_attribute = !!this.attributes.find(
			(attr) => attr.node.get_dependencies().length > 0
		);
		// ordinarily, there'll only be one... but we need to handle
		// the rare case where an element can have multiple bindings,
		// e.g. <audio bind:paused bind:currentTime>
		this.bindings = this.node.bindings.map((binding) => new BindingWrapper(block, binding, this));
		this.event_handlers = this.node.handlers.map(
			(event_handler) => new EventHandlerWrapper(event_handler, this)
		);

		if (node.intro) block.add_intro(node.intro.is_local);
		if (node.outro) block.add_outro(node.outro.is_local);

		if (node.animation) {
			block.add_animation();
		}
		block.add_dependencies(node.tag_expr.dependencies);
		// add directive and handler dependencies
		[node.animation, node.outro, ...node.actions, ...node.classes, ...node.styles].forEach(
			(directive) => {
				if (directive && directive.expression) {
					block.add_dependencies(directive.expression.dependencies);
				}
			}
		);
		node.handlers.forEach((handler) => {
			if (handler.expression) {
				block.add_dependencies(handler.expression.dependencies);
			}
		});
		this.fragment = new FragmentWrapper(
			renderer,
			block,
			node.children,
			this,
			strip_whitespace,
			next_sibling
		);
		this.element_data_name = block.get_unique_name(`${this.var.name}_data`);
	}

	/**
	 * @param {import('../../Block.js').default} block
	 * @param {import('estree').Identifier} parent_node
	 * @param {import('estree').Identifier} parent_nodes
	 */
	render(block, parent_node, parent_nodes) {
		if (this.child_dynamic_element) {
			this.render_dynamic_element(block, parent_node, parent_nodes);
		} else {
			this.render_element(block, parent_node, parent_nodes);
		}
	}

	/**
	 * @param {import('../../Block.js').default} block
	 * @param {import('estree').Identifier} parent_node
	 * @param {import('estree').Identifier} parent_nodes
	 */
	render_dynamic_element(block, parent_node, parent_nodes) {
		this.child_dynamic_element.render(
			this.child_dynamic_element_block,
			null,
			/** @type {unknown} */ /** @type {import('estree').Identifier} */ (x$1`#nodes`)
		);
		const is_tag_dynamic = this.node.tag_expr.dynamic_dependencies().length > 0;
		const tag = this.node.tag_expr.manipulate(block);
		block.chunks.init.push(b$1`
			${this.renderer.options.dev && b$1`@validate_dynamic_element(${tag});`}
			${
				this.renderer.options.dev &&
				this.node.children.length > 0 &&
				b$1`@validate_void_dynamic_element(${tag});`
			}
			let ${this.var} = ${tag} && ${this.child_dynamic_element_block.name}(#ctx);
		`);
		block.chunks.create.push(b$1`
			if (${this.var}) ${this.var}.c();
		`);
		if (this.renderer.options.hydratable) {
			block.chunks.claim.push(b$1`
				if (${this.var}) ${this.var}.l(${parent_nodes});
			`);
		}
		block.chunks.mount.push(b$1`
			if (${this.var}) ${this.var}.m(${parent_node || '#target'}, ${parent_node ? 'null' : '#anchor'});
		`);
		if (is_tag_dynamic) {
			const previous_tag = block.get_unique_name('previous_tag');
			block.add_variable(previous_tag, tag);
			const anchor = this.get_or_create_anchor(block, parent_node, parent_nodes);
			const has_transitions = !!(this.node.intro || this.node.outro);
			const not_equal = this.renderer.component.component_options.immutable
				? x$1`@not_equal`
				: x$1`@safe_not_equal`;
			const tag_will_be_removed = block.get_unique_name('tag_will_be_removed');
			if (has_transitions) {
				block.add_variable(tag_will_be_removed, x$1`false`);
			}
			block.chunks.update.push(b$1`
				if (${tag}) {
					if (!${previous_tag}) {
						${this.var} = ${this.child_dynamic_element_block.name}(#ctx);
						${previous_tag} = ${tag};
						${this.var}.c();
						${has_transitions && b$1`@transition_in(${this.var})`}
						${this.var}.m(${this.get_update_mount_node(anchor)}, ${anchor});
					} else if (${not_equal}(${previous_tag}, ${tag})) {
						${this.var}.d(1);
						${this.renderer.options.dev && b$1`@validate_dynamic_element(${tag});`}
						${
							this.renderer.options.dev &&
							this.node.children.length > 0 &&
							b$1`@validate_void_dynamic_element(${tag});`
						}
						${this.var} = ${this.child_dynamic_element_block.name}(#ctx);
						${previous_tag} = ${tag};
						${this.var}.c();
						${
							has_transitions &&
							b$1`if (${tag_will_be_removed}) {
							${tag_will_be_removed} = false;
							@transition_in(${this.var})
						}`
						}
						${this.var}.m(${this.get_update_mount_node(anchor)}, ${anchor});
					} else {
						${
							has_transitions &&
							b$1`if (${tag_will_be_removed}) {
							${tag_will_be_removed} = false;
							@transition_in(${this.var})
						}`
						}
						${this.var}.p(#ctx, #dirty);
					}
				} else if (${previous_tag}) {
					${
						has_transitions
							? b$1`
								${tag_will_be_removed} = true;
								@group_outros();
								@transition_out(${this.var}, 1, 1, () => {
									${this.var} = null;
									${previous_tag} = ${tag};
									${tag_will_be_removed} = false;
								});
								@check_outros();
							`
							: b$1`
								${this.var}.d(1);
								${this.var} = null;
								${previous_tag} = ${tag};
							`
					}
				}
			`);
		} else {
			block.chunks.update.push(b$1`
				if (${tag}) {
					${this.var}.p(#ctx, #dirty);
				}
			`);
		}
		if (this.child_dynamic_element_block.has_intros) {
			block.chunks.intro.push(b$1`@transition_in(${this.var}, #local);`);
		}
		if (this.child_dynamic_element_block.has_outros) {
			block.chunks.outro.push(b$1`@transition_out(${this.var}, #local);`);
		}
		block.chunks.destroy.push(b$1`if (${this.var}) ${this.var}.d(detaching)`);
		if (this.node.animation) {
			const measurements = block.get_unique_name('measurements');
			block.add_variable(measurements);
			block.chunks.measure.push(b$1`${measurements} = ${this.var}.r()`);
			block.chunks.fix.push(b$1`${this.var}.f();`);
			block.chunks.animate.push(b$1`
				${this.var}.s(${measurements});
				${this.var}.a()
			`);
		}
	}
	is_dom_node() {
		return super.is_dom_node() && !this.child_dynamic_element;
	}

	/**
	 * @param {import('../../Block.js').default} block
	 * @param {import('estree').Identifier} parent_node
	 * @param {import('estree').Identifier} parent_nodes
	 */
	render_element(block, parent_node, parent_nodes) {
		const { renderer } = this;
		const hydratable = renderer.options.hydratable;
		if (this.node.name === 'noscript') return;
		const node = this.var;
		const nodes = parent_nodes && block.get_unique_name(`${this.var.name}_nodes`); // if we're in unclaimable territory, i.e. <head>, parent_nodes is null
		const children = x$1`@children(${this.node.name === 'template' ? x$1`${node}.content` : node})`;
		block.add_variable(node);
		const render_statement = this.get_render_statement(block);
		block.chunks.create.push(b$1`${node} = ${render_statement};`);
		const { can_use_textcontent, can_optimise_to_html_string, can_optimise_hydration } = this.node;
		if (hydratable) {
			if (parent_nodes) {
				block.chunks.claim.push(b$1`
					${node} = ${this.get_claim_statement(block, parent_nodes, can_optimise_hydration)};
				`);
				if (!can_optimise_hydration && !this.void && this.node.children.length > 0) {
					block.chunks.claim.push(b$1`
						var ${nodes} = ${children};
					`);
				}
			} else {
				block.chunks.claim.push(b$1`${node} = ${render_statement};`);
			}
		}
		if (parent_node) {
			const append = b$1`@append(${parent_node}, ${node});`;
			/** @type {import('estree').CallExpression} */ (
				/** @type {import('estree').ExpressionStatement} */ (append[0]).expression
			).callee.loc = {
				start: this.renderer.locate(this.node.start),
				end: this.renderer.locate(this.node.end)
			};
			block.chunks.mount.push(append);
			if (is_head(parent_node)) {
				block.chunks.destroy.push(b$1`@detach(${node});`);
			}
		} else {
			const insert = b$1`@insert(#target, ${node}, #anchor);`;
			/** @type {import('estree').CallExpression} */ (
				/** @type {import('estree').ExpressionStatement} */ (insert[0]).expression
			).callee.loc = {
				start: this.renderer.locate(this.node.start),
				end: this.renderer.locate(this.node.end)
			};
			block.chunks.mount.push(insert);
			// TODO we eventually need to consider what happens to elements
			// that belong to the same outgroup as an outroing element...
			block.chunks.destroy.push(b$1`if (detaching) @detach(${node});`);
		}
		// insert static children with textContent or innerHTML
		// skip textcontent for <template>.  append nodes to TemplateElement.content instead
		if (can_optimise_to_html_string && (!hydratable || can_optimise_hydration)) {
			if (this.fragment.nodes.length === 1 && this.fragment.nodes[0].node.type === 'Text') {
				/** @type {import('estree').Node} */
				let text = string_literal(
					/** @type {import('../Text.js').default} */ (this.fragment.nodes[0]).data
				);
				if (hydratable) {
					const variable = block.get_unique_name('textContent');
					block.add_variable(variable, text);
					text = variable;
				}
				block.chunks.create.push(b$1`${node}.textContent = ${text};`);
				if (hydratable) {
					block.chunks.claim.push(
						b$1`if (@get_svelte_dataset(${node}) !== "${this.node.hash()}") ${node}.textContent = ${text};`
					);
				}
			} else {
				const state = {
					quasi: {
						type: 'TemplateElement',
						value: { raw: '' }
					}
				};
				/** @type {import('estree').Node} */
				let literal = {
					type: 'TemplateLiteral',
					expressions: [],
					quasis: []
				};
				const can_use_raw_text = !this.node.can_use_innerhtml && can_use_textcontent;
				to_html(
					/** @type {unknown} */ /** @type {Array<ElementWrapper | import('../Comment.js').default | import('../Text.js').default>} */ (
						this.fragment.nodes
					),
					block,
					literal,
					state,
					can_use_raw_text
				);
				literal.quasis.push(/** @type {any} */ (state.quasi));
				if (hydratable) {
					const variable = block.get_unique_name('textContent');
					block.add_variable(variable, literal);
					literal = variable;
				}
				const property = this.node.can_use_innerhtml ? 'innerHTML' : 'textContent';
				block.chunks.create.push(b$1`${node}.${property} = ${literal};`);
				if (hydratable) {
					block.chunks.claim.push(
						b$1`if (@get_svelte_dataset(${node}) !== "${this.node.hash()}") ${node}.${property} = ${literal};`
					);
				}
			}
		} else {
			this.fragment.nodes.forEach((child) => {
				child.render(block, this.node.name === 'template' ? x$1`${node}.content` : node, nodes, {
					element_data_name: this.element_data_name
				});
			});
		}
		const event_handler_or_binding_uses_context =
			this.bindings.some((binding) => binding.handler.uses_context) ||
			this.node.handlers.some((handler) => handler.uses_context) ||
			this.node.actions.some((action) => action.uses_context);
		if (event_handler_or_binding_uses_context) {
			block.maintain_context = true;
		}
		if (this.node.is_dynamic_element) {
			this.add_dynamic_element_attributes(block);
		} else {
			this.add_attributes(block);
		}
		this.add_directives_in_order(block);
		this.add_transitions(block);
		this.add_animation(block);
		this.add_classes(block);
		this.add_styles(block);
		this.add_manual_style_scoping(block);
		if (nodes && hydratable && !this.void && !can_optimise_hydration) {
			block.chunks.claim.push(
				b$1`${this.node.children.length > 0 ? nodes : children}.forEach(@detach);`
			);
		}
		if (renderer.options.dev) {
			const loc = renderer.meta_locate(this.node.start);
			block.chunks.hydrate.push(
				b$1`@add_location(${this.var}, ${renderer.file_var}, ${loc.line - 1}, ${loc.column}, ${
					// TODO this.node.start isn't correct if there's a source map. But since we don't know how the
					// original source file looked, there's not much we can do.
					this.node.start
				});`
			);
		}
		block.renderer.dirty(this.node.tag_expr.dynamic_dependencies());
	}

	/** @param {import('../../Block.js').default} block */
	get_render_statement(block) {
		const { name, namespace, tag_expr } = this.node;
		const reference = tag_expr.manipulate(block);
		if (namespace === namespaces.svg) {
			return x$1`@svg_element(${reference})`;
		}
		if (namespace) {
			return x$1`@_document.createElementNS("${namespace}", "${name}")`;
		}

		/** @type {import('./Attribute.js').default} */
		const is = /** @type {any} */ (this.attributes.find((attr) => attr.node.name === 'is'));
		if (is) {
			return x$1`@element_is("${name}", ${is
				.render_chunks(block)
				.reduce((lhs, rhs) => x$1`${lhs} + ${rhs}`)})`;
		}
		return x$1`@element(${reference})`;
	}

	/**
	 * @param {import('../../Block.js').default} block
	 * @param {import('estree').Identifier} nodes
	 * @param {boolean} to_optimise_hydration
	 */
	get_claim_statement(block, nodes, to_optimise_hydration) {
		const attributes = this.attributes
			.filter((attr) => !(attr instanceof SpreadAttributeWrapper) && !attr.property_name)
			.map(
				(attr) =>
					p`${
						/** @type {import('./StyleAttribute.js').default | import('./Attribute.js').default} */ (
							attr
						).name
					}: true`
			);

		/** @type {string | ReturnType<typeof x>} */
		let reference;
		if (this.node.tag_expr.node.type === 'Literal') {
			if (this.node.namespace) {
				reference = `"${this.node.tag_expr.node.value}"`;
			} else {
				reference = `"${
					/** @type {String} */ (this.node.tag_expr.node.value || '').toUpperCase()
				}"`;
			}
		} else if (this.node.namespace) {
			reference = x$1`${this.node.tag_expr.manipulate(block)}`;
		} else {
			reference = x$1`(${this.node.tag_expr.manipulate(block)} || 'null').toUpperCase()`;
		}
		if (to_optimise_hydration) {
			attributes.push(p`["data-svelte-h"]: true`);
		}
		if (this.node.namespace === namespaces.svg) {
			return x$1`@claim_svg_element(${nodes}, ${reference}, { ${attributes} })`;
		} else {
			return x$1`@claim_element(${nodes}, ${reference}, { ${attributes} })`;
		}
	}

	/** @param {import('../../Block.js').default} block */
	add_directives_in_order(block) {
		/** @typedef {EventHandler | BindingGroup | Binding | Action} OrderedAttribute */

		const binding_groups = events
			.map((event) => ({
				events: event.event_names,
				bindings: this.bindings
					.filter((binding) => binding.node.name !== 'this')
					.filter((binding) => event.filter(this.node, binding.node.name))
			}))
			.filter((group) => group.bindings.length);
		const this_binding = this.bindings.find((b) => b.node.name === 'this');

		/** @param {OrderedAttribute} item */
		function getOrder(item) {
			if (item instanceof EventHandlerWrapper) {
				return item.node.start;
			} else if (item instanceof BindingWrapper) {
				return item.node.start;
			} else if (item instanceof Action) {
				return item.start;
			} else {
				return item.bindings[0].node.start;
			}
		}
		/** @type {OrderedAttribute[]} */ ([
			...binding_groups,
			...this.event_handlers,
			this_binding,
			...this.node.actions
		])
			.filter(Boolean)
			.sort((a, b) => getOrder(a) - getOrder(b))
			.forEach((item) => {
				if (item instanceof EventHandlerWrapper) {
					add_event_handler(block, this.var, item);
				} else if (item instanceof BindingWrapper) {
					this.add_this_binding(block, item);
				} else if (item instanceof Action) {
					add_action(block, this.var, item);
				} else {
					this.add_bindings(block, item);
				}
			});
	}

	/**
	 * @param {import('../../Block.js').default} block
	 * @param {BindingGroup} binding_group
	 */
	add_bindings(block, binding_group) {
		const { renderer } = this;
		if (binding_group.bindings.length === 0) return;
		renderer.component.has_reactive_assignments = true;
		const lock = binding_group.bindings.some((binding) => binding.needs_lock)
			? block.get_unique_name(`${this.var.name}_updating`)
			: null;
		if (lock) block.add_variable(lock, x$1`false`);
		const handler = renderer.component.get_unique_name(
			`${this.var.name}_${binding_group.events.join('_')}_handler`
		);
		renderer.add_to_context(handler.name);
		// TODO figure out how to handle locks
		const needs_lock = binding_group.bindings.some((binding) => binding.needs_lock);

		/** @type {Set<string>} */
		const dependencies = new Set();

		/** @type {Set<string>} */
		const contextual_dependencies = new Set();
		binding_group.bindings.forEach((binding) => {
			// TODO this is a mess
			add_to_set(dependencies, binding.get_update_dependencies());
			add_to_set(contextual_dependencies, binding.handler.contextual_dependencies);
			binding.render(block, lock);
		});
		// media bindings — awkward special case. The native timeupdate events
		// fire too infrequently, so we need to take matters into our
		// own hands

		/** @type {import('estree').Identifier | undefined} */
		let animation_frame;
		if (binding_group.events[0] === 'timeupdate') {
			animation_frame = block.get_unique_name(`${this.var.name}_animationframe`);
			block.add_variable(animation_frame);
		}
		const has_local_function = contextual_dependencies.size > 0 || needs_lock || animation_frame;
		let callee = renderer.reference(handler);
		// TODO dry this out — similar code for event handlers and component bindings
		if (has_local_function) {
			const args = Array.from(contextual_dependencies).map((name) => renderer.reference(name));
			// need to create a block-local function that calls an instance-level function
			if (animation_frame) {
				block.chunks.init.push(b$1`
					function ${handler}() {
						@_cancelAnimationFrame(${animation_frame});
						if (!${this.var}.paused) {
							${animation_frame} = @raf(${handler});
							${needs_lock && b$1`${lock} = true;`}
						}
						${callee}.call(${this.var}, ${args});
					}
				`);
			} else {
				block.chunks.init.push(b$1`
					function ${handler}() {
						${needs_lock && b$1`${lock} = true;`}
						${callee}.call(${this.var}, ${args});
					}
				`);
			}
			callee = handler;
		}
		const params = Array.from(contextual_dependencies).map((name) => ({
			type: 'Identifier',
			name
		}));
		this.renderer.component.partly_hoisted.push(b$1`
			function ${handler}(${params}) {
				${binding_group.bindings.map((b) => b.handler.mutation)}
				${Array.from(dependencies)
					.filter((dep) => dep[0] !== '$')
					.filter((dep) => !contextual_dependencies.has(dep))
					.map((dep) => b$1`${this.renderer.invalidate(dep)};`)}
			}
		`);
		binding_group.events.forEach((name) => {
			if (
				[
					'elementresize',
					'elementresizecontentbox',
					'elementresizeborderbox',
					'elementresizedevicepixelcontentbox'
				].indexOf(name) !== -1
			) {
				const resize_listener = block.get_unique_name(`${this.var.name}_resize_listener`);
				block.add_variable(resize_listener);
				// Can't dynamically do `@fn[name]`, code-red doesn't know how to resolve it
				switch (name) {
					case 'elementresize':
						block.chunks.mount.push(
							b$1`${resize_listener} = @add_iframe_resize_listener(${this.var}, ${callee}.bind(${this.var}));`
						);
						break;
					case 'elementresizecontentbox':
						block.chunks.mount.push(
							b$1`${resize_listener} = @resize_observer_content_box.observe(${this.var}, ${callee}.bind(${this.var}));`
						);
						break;
					case 'elementresizeborderbox':
						block.chunks.mount.push(
							b$1`${resize_listener} = @resize_observer_border_box.observe(${this.var}, ${callee}.bind(${this.var}));`
						);
						break;
					case 'elementresizedevicepixelcontentbox':
						block.chunks.mount.push(
							b$1`${resize_listener} = @resize_observer_device_pixel_content_box.observe(${this.var}, ${callee}.bind(${this.var}));`
						);
						break;
				}
				block.chunks.destroy.push(b$1`${resize_listener}();`);
			} else {
				block.event_listeners.push(x$1`@listen(${this.var}, "${name}", ${callee})`);
			}
		});
		const some_initial_state_is_undefined = binding_group.bindings
			.map((binding) => x$1`${binding.snippet} === void 0`)
			.reduce((lhs, rhs) => x$1`${lhs} || ${rhs}`);
		const should_initialise =
			this.node.name === 'select' ||
			binding_group.bindings.find(
				(binding) =>
					binding.node.name === 'indeterminate' ||
					is_name_contenteditable(binding.node.name) ||
					binding.is_readonly_media_attribute()
			);
		if (should_initialise) {
			const callback = has_local_function ? handler : x$1`() => ${callee}.call(${this.var})`;
			block.chunks.hydrate.push(
				b$1`if (${some_initial_state_is_undefined}) @add_render_callback(${callback});`
			);
		}
		if (binding_group.events[0] === 'elementresize') {
			block.chunks.hydrate.push(b$1`@add_render_callback(() => ${callee}.call(${this.var}));`);
		}
		if (lock) {
			block.chunks.update.push(b$1`${lock} = false;`);
		}
	}

	/**
	 * @param {import('../../Block.js').default} block
	 * @param {import('./Binding.js').default} this_binding
	 */
	add_this_binding(block, this_binding) {
		const { renderer } = this;
		renderer.component.has_reactive_assignments = true;
		const binding_callback = bind_this(renderer.component, block, this_binding, this.var);
		block.chunks.mount.push(binding_callback);
	}

	/** @param {import('../../Block.js').default} block */
	add_attributes(block) {
		// Get all the class and style dependencies first
		this.attributes.forEach((attribute) => {
			if (attribute.node.name === 'class') {
				const dependencies = attribute.node.get_dependencies();
				push_array(this.class_dependencies, dependencies);
			} else if (attribute.node.name === 'style') {
				add_to_set(this.dynamic_style_dependencies, attribute.node.get_dependencies());
			}
		});
		if (this.node.attributes.some((attr) => attr.is_spread)) {
			this.add_spread_attributes(block);
			return;
		}
		this.attributes.forEach((attribute) => {
			attribute.render(block);
		});
	}

	/** @param {import('../../Block.js').default} block */
	add_spread_attributes(block) {
		const levels = block.get_unique_name(`${this.var.name}_levels`);
		const initial_props = [];
		const updates = [];
		this.attributes.forEach((attr) => {
			const dependencies = attr.node.get_dependencies();
			const condition = dependencies.length > 0 ? block.renderer.dirty(dependencies) : null;
			if (attr instanceof SpreadAttributeWrapper) {
				const snippet = attr.node.expression.manipulate(block);
				initial_props.push(snippet);
				updates.push(condition ? x$1`${condition} && ${snippet}` : snippet);
			} else {
				const name = attr.property_name || attr.name;
				initial_props.push(x$1`{ ${name}: ${attr.get_init(block, attr.get_value(block))} }`);
				const snippet = x$1`{ ${name}: ${attr.should_cache ? attr.last : attr.get_value(block)} }`;
				updates.push(
					condition ? x$1`${attr.get_dom_update_conditions(block, condition)} && ${snippet}` : snippet
				);
			}
		});
		block.chunks.init.push(b$1`
			let ${levels} = [${initial_props}];

			let ${this.element_data_name} = {};
			for (let #i = 0; #i < ${levels}.length; #i += 1) {
				${this.element_data_name} = @assign(${this.element_data_name}, ${levels}[#i]);
			}
		`);
		const fn =
			this.node.namespace === namespaces.svg
				? x$1`@set_svg_attributes`
				: this.node.is_dynamic_element
				? x$1`@set_dynamic_element_data(${this.node.tag_expr.manipulate(block)})`
				: x$1`@set_attributes`;
		block.chunks.hydrate.push(b$1`${fn}(${this.var}, ${this.element_data_name});`);
		if (this.has_dynamic_attribute) {
			block.chunks.update.push(b$1`
				${fn}(${this.var}, ${this.element_data_name} = @get_spread_update(${levels}, [
					${updates}
				]));
			`);
		}
		// handle edge cases for elements
		if (this.node.name === 'select') {
			const dependencies = new Set();
			for (const attr of this.attributes) {
				for (const dep of attr.node.dependencies) {
					dependencies.add(dep);
				}
			}
			block.chunks.mount.push(b$1`
				'value' in ${this.element_data_name} && (${this.element_data_name}.multiple ? @select_options : @select_option)(${this.var}, ${this.element_data_name}.value);
			`);
			block.chunks.update.push(b$1`
				if (${block.renderer.dirty(Array.from(dependencies))} && 'value' in ${this.element_data_name}) (${
				this.element_data_name
			}.multiple ? @select_options : @select_option)(${this.var}, ${this.element_data_name}.value);
			`);
		} else if (
			this.node.name === 'input' &&
			this.attributes.find((attr) => attr.node.name === 'value')
		) {
			const type = this.node.get_static_attribute_value('type');
			if (
				type === null ||
				type === '' ||
				type === 'text' ||
				type === 'email' ||
				type === 'password'
			) {
				block.chunks.mount.push(b$1`
					if ('value' in ${this.element_data_name}) {
						${this.var}.value = ${this.element_data_name}.value;
					}
				`);
				block.chunks.update.push(b$1`
					if ('value' in ${this.element_data_name}) {
						${this.var}.value = ${this.element_data_name}.value;
					}
				`);
			}
		}
		if (['button', 'input', 'keygen', 'select', 'textarea'].includes(this.node.name)) {
			block.chunks.mount.push(b$1`
				if (${this.var}.autofocus) ${this.var}.focus();
			`);
		}
	}

	/** @param {import('../../Block.js').default} block */
	add_dynamic_element_attributes(block) {
		if (this.attributes.length === 0) return;
		if (this.has_dynamic_attribute) {
			this.add_spread_attributes(block);
			return;
		}
		const static_attributes = [];
		this.attributes.forEach((attr) => {
			if (attr instanceof SpreadAttributeWrapper) {
				static_attributes.push({ type: 'SpreadElement', argument: attr.node.expression.node });
			} else {
				const name = attr.property_name || attr.name;
				static_attributes.push(p`${name}: ${attr.get_value(block)}`);
			}
		});
		const fn =
			this.node.namespace === namespaces.svg
				? x$1`@set_svg_attributes`
				: this.node.is_dynamic_element
				? x$1`@set_dynamic_element_data(${this.node.tag_expr.manipulate(block)})`
				: x$1`@set_attributes`;
		block.chunks.hydrate.push(b$1`${fn}(${this.var}, {${static_attributes}});`);
	}

	/** @param {import('../../Block.js').default} block */
	add_transitions(block) {
		const { intro, outro } = this.node;
		if (!intro && !outro) return;
		if (intro === outro) {
			// bidirectional transition
			const name = block.get_unique_name(`${this.var.name}_transition`);
			const snippet = intro.expression ? intro.expression.manipulate(block) : x$1`{}`;
			block.add_variable(name);
			const fn = this.renderer.reference(intro.name);
			const intro_block = b$1`
				@add_render_callback(() => {
					if (!#current) return;
					if (!${name}) ${name} = @create_bidirectional_transition(${this.var}, ${fn}, ${snippet}, true);
					${name}.run(1);
				});
			`;
			const outro_block = b$1`
				if (!${name}) ${name} = @create_bidirectional_transition(${this.var}, ${fn}, ${snippet}, false);
				${name}.run(0);
			`;
			if (intro.is_local) {
				block.chunks.intro.push(b$1`
					if (#local) {
						${intro_block}
					}
				`);
				block.chunks.outro.push(b$1`
					if (#local) {
						${outro_block}
					}
				`);
			} else {
				block.chunks.intro.push(intro_block);
				block.chunks.outro.push(outro_block);
			}
			block.chunks.destroy.push(b$1`if (detaching && ${name}) ${name}.end();`);
		} else {
			const intro_name = intro && block.get_unique_name(`${this.var.name}_intro`);
			const outro_name = outro && block.get_unique_name(`${this.var.name}_outro`);
			if (intro) {
				block.add_variable(intro_name);
				const snippet = intro.expression ? intro.expression.manipulate(block) : x$1`{}`;
				const fn = this.renderer.reference(intro.name);
				let intro_block;
				if (outro) {
					intro_block = b$1`
						@add_render_callback(() => {
							if (!#current) return;
							if (${outro_name}) ${outro_name}.end(1);
							${intro_name} = @create_in_transition(${this.var}, ${fn}, ${snippet});
							${intro_name}.start();
						});
					`;
					block.chunks.outro.push(b$1`if (${intro_name}) ${intro_name}.invalidate();`);
				} else {
					intro_block = b$1`
						if (!${intro_name}) {
							@add_render_callback(() => {
								${intro_name} = @create_in_transition(${this.var}, ${fn}, ${snippet});
								${intro_name}.start();
							});
						}
					`;
				}
				if (intro.is_local) {
					intro_block = b$1`
						if (#local) {
							${intro_block}
						}
					`;
				}
				block.chunks.intro.push(intro_block);
			}
			if (outro) {
				block.add_variable(outro_name);
				const snippet = outro.expression ? outro.expression.manipulate(block) : x$1`{}`;
				const fn = this.renderer.reference(outro.name);
				if (!intro) {
					block.chunks.intro.push(b$1`
						if (${outro_name}) ${outro_name}.end(1);
					`);
				}
				// TODO hide elements that have outro'd (unless they belong to a still-outroing
				// group) prior to their removal from the DOM
				let outro_block = b$1`
					${outro_name} = @create_out_transition(${this.var}, ${fn}, ${snippet});
				`;
				if (outro.is_local) {
					outro_block = b$1`
						if (#local) {
							${outro_block}
						}
					`;
				}
				block.chunks.outro.push(outro_block);
				block.chunks.destroy.push(b$1`if (detaching && ${outro_name}) ${outro_name}.end();`);
			}
		}
		if (
			(intro && intro.expression && intro.expression.dependencies.size) ||
			(outro && outro.expression && outro.expression.dependencies.size)
		) {
			block.maintain_context = true;
		}
	}

	/** @param {import('../../Block.js').default} block */
	add_animation(block) {
		if (!this.node.animation) return;
		const { outro } = this.node;
		const rect = block.get_unique_name('rect');
		const stop_animation = block.get_unique_name('stop_animation');
		block.add_variable(rect);
		block.add_variable(stop_animation, x$1`@noop`);
		block.chunks.measure.push(b$1`
			${rect} = ${this.var}.getBoundingClientRect();
		`);
		if (block.type === CHILD_DYNAMIC_ELEMENT_BLOCK) {
			block.chunks.measure.push(b$1`return ${rect}`);
			block.chunks.restore_measurements.push(b$1`${rect} = #measurement;`);
		}
		block.chunks.fix.push(b$1`
			@fix_position(${this.var});
			${stop_animation}();
			${outro && b$1`@add_transform(${this.var}, ${rect});`}
		`);

		/** @type {import('estree').Node | ReturnType<typeof x>} */
		let params;
		if (this.node.animation.expression) {
			params = this.node.animation.expression.manipulate(block);
			if (this.node.animation.expression.dynamic_dependencies().length) {
				// if `params` is dynamic, calculate params ahead of time in the `.r()` method
				const params_var = block.get_unique_name('params');
				block.add_variable(params_var);
				block.chunks.measure.push(b$1`${params_var} = ${params};`);
				params = params_var;
			}
		} else {
			params = x$1`{}`;
		}
		const name = this.renderer.reference(this.node.animation.name);
		block.chunks.animate.push(b$1`
			${stop_animation}();
			${stop_animation} = @create_animation(${this.var}, ${rect}, ${name}, ${params});
		`);
	}

	/** @param {import('../../Block.js').default} block */
	add_classes(block) {
		const has_spread = this.node.attributes.some((attr) => attr.is_spread);
		this.node.classes.forEach((class_directive) => {
			const { expression, name } = class_directive;
			let snippet;
			let dependencies;
			if (expression) {
				snippet = expression.manipulate(block);
				dependencies = expression.dependencies;
			} else {
				snippet = name;
				dependencies = new Set([name]);
			}
			const updater = b$1`@toggle_class(${this.var}, "${name}", ${snippet});`;
			block.chunks.hydrate.push(updater);
			if ((this.node.is_dynamic_element || has_spread) && this.has_dynamic_attribute) {
				block.chunks.update.push(updater);
			} else if ((dependencies && dependencies.size > 0) || this.class_dependencies.length) {
				const all_dependencies = this.class_dependencies.concat(...dependencies);
				let condition = block.renderer.dirty(all_dependencies);
				if (block.has_outros) {
					condition = x$1`!#current || ${condition}`;
				}
				// If all of the dependencies are non-dynamic (don't get updated) then there is no reason
				// to add an updater for this.
				const any_dynamic_dependencies = all_dependencies.some((dep) => {
					const variable = this.renderer.component.var_lookup.get(dep);
					return !variable || is_dynamic$1(variable);
				});
				if (any_dynamic_dependencies) {
					block.chunks.update.push(b$1`
						if (${condition}) {
							${updater}
						}
					`);
				}
			}
		});
	}

	/** @param {import('../../Block.js').default} block */
	add_styles(block) {
		const has_spread = this.node.attributes.some((attr) => attr.is_spread);

		/** @type {import('estree').Identifier | undefined} */
		let style_changed_var;
		const maybe_create_style_changed_var = () => {
			if (!style_changed_var && this.dynamic_style_dependencies.size) {
				style_changed_var = block.get_unique_name('style_changed');
				const style_attr_dirty = block.renderer.dirty([...this.dynamic_style_dependencies]);
				block.chunks.update.push(b$1`const ${style_changed_var} = ${style_attr_dirty};`);
			}
		};
		this.node.styles.forEach((style_directive) => {
			const { name, expression, important, should_cache } = style_directive;
			const snippet = expression.manipulate(block);
			let cached_snippet;
			if (should_cache) {
				cached_snippet = block.get_unique_name(`style_${name.replace(regex_minus_signs, '_')}`);
				block.add_variable(cached_snippet, snippet);
			}
			const updater = b$1`@set_style(${this.var}, "${name}", ${
				should_cache ? cached_snippet : snippet
			}, ${important ? 1 : null})`;
			block.chunks.hydrate.push(updater);
			const self_deps = expression.dynamic_dependencies();
			const all_deps = new Set([...self_deps, ...this.dynamic_style_dependencies]);
			let condition = block.renderer.dirty([...all_deps]);
			// Assume that style has changed through the spread attribute
			if (has_spread) {
				if (should_cache && all_deps.size) {
					// Update the cached value
					block.chunks.update.push(b$1`
						if (${condition}) {
							${cached_snippet} = ${snippet};
						}`);
				}
				block.chunks.update.push(updater);
			} else {
				if (all_deps.size === 0) return;
				if (should_cache) {
					condition = x$1`${condition} && ${cached_snippet} !== (${cached_snippet} = ${snippet})`;
				}
				if (this.dynamic_style_dependencies.size > 0) {
					maybe_create_style_changed_var();
					// If all dependencies are same as the style attribute dependencies, then we can skip the dirty check
					condition =
						all_deps.size === this.dynamic_style_dependencies.size
							? style_changed_var
							: x$1`${style_changed_var} || ${condition}`;
				}
				block.chunks.update.push(b$1`
					if (${condition}) {
						${updater}
					}
				`);
			}
		});
	}

	/** @param {import('../../Block.js').default} block */
	add_manual_style_scoping(block) {
		if (this.node.needs_manual_style_scoping) {
			const updater = b$1`@toggle_class(${this.var}, "${this.node.component.stylesheet.id}", true);`;
			block.chunks.hydrate.push(updater);
			block.chunks.update.push(updater);
		}
	}
}
const regex_backticks = /`/g;
const regex_dollar_signs = /\$/g;
/**
 * @param {Array<
 * 		import('../Comment.js').default | ElementWrapper | import('../Text.js').default | import('../MustacheTag.js').default | import('../RawMustacheTag.js').default
 * 	>} wrappers
 * @param {import('../../Block.js').default} block
 * @param {any} literal
 * @param {any} state
 * @param {boolean} [can_use_raw_text]
 */
function to_html(wrappers, block, literal, state, can_use_raw_text) {
	wrappers.forEach((wrapper) => {
		if (wrapper instanceof CommentWrapper) {
			state.quasi.value.raw += wrapper.text();
		} else if (wrapper instanceof TextWrapper) {
			// Don't add the <pre>/<textarea> newline logic here because pre/textarea.innerHTML
			// would keep the leading newline, too, only someParent.innerHTML = '..<pre/textarea>..' won't
			if (wrapper.use_space()) {
				// use space instead of the text content
				state.quasi.value.raw += ' ';
				return;
			}
			const parent = /** @type {import('../../../nodes/Element.js').default} */ (
				wrapper.node.parent
			);
			const raw =
				parent && (parent.name === 'script' || parent.name === 'style' || can_use_raw_text);
			state.quasi.value.raw += (raw ? wrapper.data : escape_html(wrapper.data))
				.replace(regex_backslashes, '\\\\')
				.replace(regex_backticks, '\\`')
				.replace(regex_dollar_signs, '\\$');
		} else if (wrapper instanceof MustacheTagWrapper || wrapper instanceof RawMustacheTagWrapper) {
			literal.quasis.push(state.quasi);
			literal.expressions.push(wrapper.node.expression.manipulate(block));
			state.quasi = {
				type: 'TemplateElement',
				value: { raw: '' }
			};
		} else if (wrapper.node.name === 'noscript') ; else {
			const nodeName = wrapper.node.name;
			// element
			state.quasi.value.raw += `<${nodeName}`;
			const is_empty_textarea = nodeName === 'textarea' && wrapper.fragment.nodes.length === 0;
			/** @type {ElementWrapper} */ (wrapper).attributes.forEach((attr) => {
				if (is_empty_textarea && attr.node.name === 'value') {
					// The value attribute of <textarea> renders as content.
					return;
				}
				state.quasi.value.raw += ` ${fix_attribute_casing(attr.node.name)}="`;
				to_html_for_attr_value(attr, block, literal, state);
				state.quasi.value.raw += '"';
			});
			if (!wrapper.void) {
				state.quasi.value.raw += '>';
				if (nodeName === 'pre') {
					// Two or more leading newlines are required to restore the leading newline immediately after `<pre>`.
					// see https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
					const first = wrapper.fragment.nodes[0];
					if (
						first &&
						first.node.type === 'Text' &&
						regex_starts_with_newline.test(first.node.data)
					) {
						state.quasi.value.raw += '\n';
					}
				}
				if (is_empty_textarea) {
					// The <textarea> renders the value attribute as content because the content is stored in the value attribute.
					const value_attribute = wrapper.attributes.find((attr) => attr.node.name === 'value');
					if (value_attribute) {
						// Two or more leading newlines are required to restore the leading newline immediately after `<textarea>`.
						// see https://html.spec.whatwg.org/multipage/syntax.html#element-restrictions
						const first = value_attribute.node.chunks[0];
						if (first && first.type === 'Text' && regex_starts_with_newline.test(first.data)) {
							state.quasi.value.raw += '\n';
						}
						to_html_for_attr_value(value_attribute, block, literal, state);
					}
				}
				to_html(
					/** @type {Array<ElementWrapper | import('../Text.js').default>} */ (
						wrapper.fragment.nodes
					),
					block,
					literal,
					state
				);
				state.quasi.value.raw += `</${nodeName}>`;
			} else {
				state.quasi.value.raw += '/>';
			}
		}
	});
}

/**
 * @param {import('./Attribute.js').default | import('./StyleAttribute.js').default | import('./SpreadAttribute.js').default} attr
 * @param {import('../../Block.js').default} block
 * @param {any} literal
 * @param {any} state
 */
function to_html_for_attr_value(attr, block, literal, state) {
	attr.node.chunks.forEach((chunk) => {
		if (chunk.type === 'Text') {
			state.quasi.value.raw += escape_html(chunk.data);
		} else {
			literal.quasis.push(state.quasi);
			literal.expressions.push(chunk.manipulate(block));
			state.quasi = {
				type: 'TemplateElement',
				value: { raw: '' }
			};
		}
	});
}

/** @typedef {Object} BindingGroup
 * @property {string[]} events
 * @property {Binding[]} bindings
 */

/** @extends Wrapper<import('../../nodes/Head.js').default> */
class HeadWrapper extends Wrapper {
	/** @type {import('./Fragment.js').default} */
	fragment;

	/**
	 * @param {import('../Renderer.js').default} renderer
	 * @param {import('../Block.js').default} block
	 * @param {import('./shared/Wrapper.js').default} parent
	 * @param {import('../../nodes/Head.js').default} node
	 * @param {boolean} strip_whitespace
	 * @param {import('./shared/Wrapper.js').default} next_sibling
	 */
	constructor(renderer, block, parent, node, strip_whitespace, next_sibling) {
		super(renderer, block, parent, node);
		this.fragment = new FragmentWrapper(
			renderer,
			block,
			node.children,
			this,
			strip_whitespace,
			next_sibling
		);
	}

	/**
	 * @param {import('../Block.js').default} block
	 * @param {import('estree').Identifier} _parent_node
	 * @param {import('estree').Identifier} _parent_nodes
	 */
	render(block, _parent_node, _parent_nodes) {
		/** @type {import('estree').Identifier} */
		let nodes;
		if (this.renderer.options.hydratable && this.fragment.nodes.length) {
			nodes = block.get_unique_name('head_nodes');
			block.chunks.claim.push(
				b$1`const ${nodes} = @head_selector('${this.node.id}', @_document.head);`
			);
		}
		this.fragment.render(
			block,
			/** @type {unknown} */ /** @type {import('estree').Identifier} */ (x$1`@_document.head`),
			nodes
		);
		if (nodes && this.renderer.options.hydratable) {
			block.chunks.claim.push(b$1`${nodes}.forEach(@detach);`);
		}
	}
}

/** @param {import('../../nodes/ElseBlock.js').default} node */
function is_else_if(node) {
	return node && node.children.length === 1 && node.children[0].type === 'IfBlock';
}

/** @extends Wrapper<import('../../nodes/IfBlock.js').default | import('../../nodes/ElseBlock.js').default> */
class IfBlockBranch extends Wrapper {
	/** @type {import('../Block.js').default} */
	block;

	/** @type {import('./Fragment.js').default} */
	fragment;

	/** @type {string[]} */
	dependencies;

	/** @type {any} */
	condition;

	/** @type {import('estree').Node} */
	snippet;

	/** @type {boolean} */
	is_dynamic;

	/** */
	var = null;

	/** @type {import('estree').Node | undefined} */
	get_ctx_name;

	/**
	 * @param {import('../Renderer.js').default} renderer
	 * @param {import('../Block.js').default} block
	 * @param {IfBlockWrapper} parent
	 * @param {import('../../nodes/IfBlock.js').default | import('../../nodes/ElseBlock.js').default} node
	 * @param {boolean} strip_whitespace
	 * @param {import('./shared/Wrapper.js').default} next_sibling
	 */
	constructor(renderer, block, parent, node, strip_whitespace, next_sibling) {
		super(renderer, block, parent, node);
		const { expression } = /** @type {import('../../nodes/IfBlock.js').default} */ (node);
		const is_else = !expression;
		if (expression) {
			this.dependencies = expression.dynamic_dependencies();
			// TODO is this the right rule? or should any non-reference count?
			// const should_cache = !is_reference(expression.node, null) && dependencies.length > 0;
			let should_cache = false;
			walk(expression.node, {
				enter(node) {
					if (node.type === 'CallExpression' || node.type === 'NewExpression') {
						should_cache = true;
					}
				}
			});
			if (should_cache) {
				this.condition = block.get_unique_name('show_if');
				this.snippet = /** @type {import('estree').Node} */ (expression.manipulate(block));
			} else {
				this.condition = expression.manipulate(block);
			}
		}
		add_const_tags_context(renderer, this.node.const_tags);
		this.block = block.child({
			comment: create_debugging_comment(node, parent.renderer.component),
			name: parent.renderer.component.get_unique_name(
				is_else ? 'create_else_block' : 'create_if_block'
			),
			type: /** @type {import('../../nodes/IfBlock.js').default} */ (node).expression
				? 'if'
				: 'else'
		});
		this.fragment = new FragmentWrapper(
			renderer,
			this.block,
			node.children,
			parent,
			strip_whitespace,
			next_sibling
		);
		this.is_dynamic = this.block.dependencies.size > 0;
		if (node.const_tags.length > 0) {
			this.get_ctx_name = parent.renderer.component.get_unique_name(
				is_else ? 'get_else_ctx' : 'get_if_ctx'
			);
		}
	}
}

/** @extends Wrapper<import('../../nodes/IfBlock.js').default> */
class IfBlockWrapper extends Wrapper {
	/** @typedef {'detaching' | null} DetachingOrNull */

	/** @type {IfBlockBranch[]} */
	branches;
	/** */
	needs_update = false;

	/** @type {import('estree').Identifier} */
	var = { type: 'Identifier', name: 'if_block' };

	/**
	 * @param {import('../Renderer.js').default} renderer
	 * @param {import('../Block.js').default} block
	 * @param {import('./shared/Wrapper.js').default} parent
	 * @param {import('../../nodes/IfBlock.js').default} node
	 * @param {boolean} strip_whitespace
	 * @param {import('./shared/Wrapper.js').default} next_sibling
	 */
	constructor(renderer, block, parent, node, strip_whitespace, next_sibling) {
		super(renderer, block, parent, node);
		this.branches = [];

		/** @type {import('../Block.js').default[]} */
		const blocks = [];
		let is_dynamic = false;
		let has_intros = false;
		let has_outros = false;

		/** @param {import('../../nodes/IfBlock.js').default} node */
		const create_branches = (node) => {
			const branch = new IfBlockBranch(renderer, block, this, node, strip_whitespace, next_sibling);
			this.branches.push(branch);
			blocks.push(branch.block);
			block.add_dependencies(node.expression.dependencies);
			if (branch.block.dependencies.size > 0) {
				// the condition, or its contents, is dynamic
				is_dynamic = true;
				block.add_dependencies(branch.block.dependencies);
			}
			if (branch.dependencies && branch.dependencies.length > 0) {
				// the condition itself is dynamic
				this.needs_update = true;
			}
			if (branch.block.has_intros) has_intros = true;
			if (branch.block.has_outros) has_outros = true;
			if (is_else_if(node.else)) {
				create_branches(
					/** @type {import('../../nodes/IfBlock.js').default} */ (node.else.children[0])
				);
			} else if (node.else) {
				const branch = new IfBlockBranch(
					renderer,
					block,
					this,
					node.else,
					strip_whitespace,
					next_sibling
				);
				this.branches.push(branch);
				blocks.push(branch.block);
				if (branch.block.dependencies.size > 0) {
					is_dynamic = true;
					block.add_dependencies(branch.block.dependencies);
				}
				if (branch.block.has_intros) has_intros = true;
				if (branch.block.has_outros) has_outros = true;
			}
		};
		create_branches(this.node);
		blocks.forEach((block) => {
			block.has_update_method = is_dynamic;
			block.has_intro_method = has_intros;
			block.has_outro_method = has_outros;
		});
		push_array(renderer.blocks, blocks);
	}

	/**
	 * @param {import('../Block.js').default} block
	 * @param {import('estree').Identifier} parent_node
	 * @param {import('estree').Identifier} parent_nodes
	 */
	render(block, parent_node, parent_nodes) {
		const name = this.var;
		const needs_anchor = this.next
			? !this.next.is_dom_node()
			: !parent_node || !this.parent.is_dom_node();
		const anchor = needs_anchor
			? block.get_unique_name(`${this.var.name}_anchor`)
			: (this.next && this.next.var) || 'null';
		const has_else = !this.branches[this.branches.length - 1].condition;
		const if_exists_condition = has_else ? null : name;
		const dynamic = this.branches[0].block.has_update_method; // can use [0] as proxy for all, since they necessarily have the same value
		const has_intros = this.branches[0].block.has_intro_method;
		const has_outros = this.branches[0].block.has_outro_method;
		const has_transitions = has_intros || has_outros;
		this.branches.forEach((branch) => {
			if (branch.get_ctx_name) {
				this.renderer.blocks.push(b$1`
				function ${branch.get_ctx_name}(#ctx) {
					const child_ctx = #ctx.slice();
					${add_const_tags(block, branch.node.const_tags, 'child_ctx')}
					return child_ctx;
				}
				`);
			}
		});
		const vars = { name, anchor, if_exists_condition, has_else, has_transitions };

		/** @type {DetachingOrNull} */
		const detaching = parent_node && !is_head(parent_node) ? null : 'detaching';
		if (this.node.else) {
			this.branches.forEach((branch) => {
				if (branch.snippet) block.add_variable(branch.condition);
			});
			if (has_outros) {
				this.render_compound_with_outros(
					block,
					parent_node,
					parent_nodes,
					dynamic,
					vars,
					detaching
				);
				block.chunks.outro.push(b$1`@transition_out(${name});`);
			} else {
				this.render_compound(block, parent_node, parent_nodes, dynamic, vars, detaching);
			}
		} else {
			this.render_simple(block, parent_node, parent_nodes, dynamic, vars, detaching);
			if (has_outros) {
				block.chunks.outro.push(b$1`@transition_out(${name});`);
			}
		}
		if (if_exists_condition) {
			block.chunks.create.push(b$1`if (${if_exists_condition}) ${name}.c();`);
		} else {
			block.chunks.create.push(b$1`${name}.c();`);
		}
		if (parent_nodes && this.renderer.options.hydratable) {
			if (if_exists_condition) {
				block.chunks.claim.push(b$1`if (${if_exists_condition}) ${name}.l(${parent_nodes});`);
			} else {
				block.chunks.claim.push(b$1`${name}.l(${parent_nodes});`);
			}
		}
		if (has_intros || has_outros) {
			block.chunks.intro.push(b$1`@transition_in(${name});`);
		}
		if (needs_anchor) {
			block.add_element(
				/** @type {import('estree').Identifier} */ (anchor),
				x$1`@empty()`,
				parent_nodes && x$1`@empty()`,
				parent_node
			);
		}
		this.branches.forEach((branch) => {
			branch.fragment.render(
				branch.block,
				null,
				/** @type {unknown} */ /** @type {import('estree').Identifier} */ (x$1`#nodes`)
			);
		});
	}

	/**
	 * @param {import('../Block.js').default} block
	 * @param {import('estree').Identifier} parent_node
	 * @param {import('estree').Identifier} _parent_nodes
	 * @param {boolean} dynamic
	 * @param {any} opts
	 * @param {DetachingOrNull} detaching
	 */
	render_compound(
		block,
		parent_node,
		_parent_nodes,
		dynamic,
		{ name, anchor, has_else, if_exists_condition, has_transitions },
		detaching
	) {
		const select_block_type = this.renderer.component.get_unique_name('select_block_type');
		const current_block_type = block.get_unique_name('current_block_type');
		const need_select_block_ctx = this.branches.some((branch) => branch.get_ctx_name);
		const select_block_ctx = need_select_block_ctx
			? block.get_unique_name('select_block_ctx')
			: null;
		const if_ctx = select_block_ctx ? x$1`${select_block_ctx}(#ctx, ${current_block_type})` : x$1`#ctx`;
		const get_block = has_else
			? x$1`${current_block_type}(${if_ctx})`
			: x$1`${current_block_type} && ${current_block_type}(${if_ctx})`;
		if (this.needs_update) {
			block.chunks.init.push(b$1`
				function ${select_block_type}(#ctx, #dirty) {
					${this.branches.map(({ dependencies, condition, snippet }) => {
						return b$1`${
							snippet && dependencies.length > 0
								? b$1`if (${block.renderer.dirty(dependencies)}) ${condition} = null;`
								: null
						}`;
					})}
					${this.branches.map(({ condition, snippet, block }) =>
						condition
							? b$1`
								${snippet && b$1`if (${condition} == null) ${condition} = !!${snippet}`}
								if (${condition}) return ${block.name};`
							: b$1`return ${block.name};`
					)}
				}
			`);
		} else {
			block.chunks.init.push(b$1`
				function ${select_block_type}(#ctx, #dirty) {
					${this.branches.map(({ condition, snippet, block }) =>
						condition
							? b$1`if (${snippet || condition}) return ${block.name};`
							: b$1`return ${block.name};`
					)}
				}
			`);
		}
		if (need_select_block_ctx) {
			// if all branches needs create a context
			if (this.branches.every((branch) => branch.get_ctx_name)) {
				block.chunks.init.push(b$1`
					function ${select_block_ctx}(#ctx, #type) {
						${this.branches
							.map(({ condition, get_ctx_name, block }) => {
								return condition
									? b$1`if (#type === ${block.name}) return ${get_ctx_name}(#ctx);`
									: b$1`return ${get_ctx_name}(#ctx);`;
							})
							.filter(Boolean)}
					}
				`);
			} else {
				// when not all branches need to create a new context,
				// this code is simpler
				block.chunks.init.push(b$1`
					function ${select_block_ctx}(#ctx, #type) {
						${this.branches
							.map(({ get_ctx_name, block }) => {
								return get_ctx_name
									? b$1`if (#type === ${block.name}) return ${get_ctx_name}(#ctx);`
									: null;
							})
							.filter(Boolean)}
						return #ctx;
					}
				`);
			}
		}
		block.chunks.init.push(b$1`
			let ${current_block_type} = ${select_block_type}(#ctx, ${this.renderer.get_initial_dirty()});
			let ${name} = ${get_block};
		`);
		const initial_mount_node = parent_node || '#target';
		const anchor_node = parent_node ? 'null' : '#anchor';
		if (if_exists_condition) {
			block.chunks.mount.push(
				b$1`if (${if_exists_condition}) ${name}.m(${initial_mount_node}, ${anchor_node});`
			);
		} else {
			block.chunks.mount.push(b$1`${name}.m(${initial_mount_node}, ${anchor_node});`);
		}
		if (this.needs_update) {
			const update_mount_node = this.get_update_mount_node(anchor);
			const change_block = b$1`
				${if_exists_condition ? b$1`if (${if_exists_condition}) ${name}.d(1)` : b$1`${name}.d(1)`};
				${name} = ${get_block};
				if (${name}) {
					${name}.c();
					${has_transitions && b$1`@transition_in(${name}, 1);`}
					${name}.m(${update_mount_node}, ${anchor});
				}
			`;
			if (dynamic) {
				block.chunks.update.push(b$1`
					if (${current_block_type} === (${current_block_type} = ${select_block_type}(#ctx, #dirty)) && ${name}) {
						${name}.p(${if_ctx}, #dirty);
					} else {
						${change_block}
					}
				`);
			} else {
				block.chunks.update.push(b$1`
					if (${current_block_type} !== (${current_block_type} = ${select_block_type}(#ctx, #dirty))) {
						${change_block}
					}
				`);
			}
		} else if (dynamic) {
			if (if_exists_condition) {
				block.chunks.update.push(b$1`if (${if_exists_condition}) ${name}.p(${if_ctx}, #dirty);`);
			} else {
				block.chunks.update.push(b$1`${name}.p(${if_ctx}, #dirty);`);
			}
		}
		if (if_exists_condition) {
			block.chunks.destroy.push(b$1`
				if (${if_exists_condition}) {
					${name}.d(${detaching});
				}
			`);
		} else {
			block.chunks.destroy.push(b$1`
				${name}.d(${detaching});
			`);
		}
	}
	// if any of the siblings have outros, we need to keep references to the blocks
	// (TODO does this only apply to bidi transitions?)

	/**
	 * @param {import('../Block.js').default} block
	 * @param {import('estree').Identifier} parent_node
	 * @param {import('estree').Identifier} _parent_nodes
	 * @param {boolean} dynamic
	 * @param {any} opts
	 * @param {DetachingOrNull} detaching
	 */
	render_compound_with_outros(
		block,
		parent_node,
		_parent_nodes,
		dynamic,
		{ name, anchor, has_else, has_transitions, if_exists_condition },
		detaching
	) {
		const select_block_type = this.renderer.component.get_unique_name('select_block_type');
		const current_block_type_index = block.get_unique_name('current_block_type_index');
		const previous_block_index = block.get_unique_name('previous_block_index');
		const if_block_creators = block.get_unique_name('if_block_creators');
		const if_blocks = block.get_unique_name('if_blocks');
		const need_select_block_ctx = this.branches.some((branch) => branch.get_ctx_name);
		const select_block_ctx = need_select_block_ctx
			? block.get_unique_name('select_block_ctx')
			: null;
		const if_ctx = select_block_ctx
			? x$1`${select_block_ctx}(#ctx, ${current_block_type_index})`
			: x$1`#ctx`;
		const if_current_block_type_index = has_else
			? (nodes) => nodes
			: (nodes) => b$1`if (~${current_block_type_index}) { ${nodes} }`;
		block.add_variable(current_block_type_index);
		block.add_variable(name);
		block.chunks.init.push(b$1`
			const ${if_block_creators} = [
				${this.branches.map((branch) => branch.block.name)}
			];

			const ${if_blocks} = [];

			${
				this.needs_update
					? b$1`
					function ${select_block_type}(#ctx, #dirty) {
						${this.branches.map(({ dependencies, condition, snippet }) => {
							return b$1`${
								snippet && dependencies.length > 0
									? b$1`if (${block.renderer.dirty(dependencies)}) ${condition} = null;`
									: null
							}`;
						})}
						${this.branches.map(({ condition, snippet }, i) =>
							condition
								? b$1`
								${snippet && b$1`if (${condition} == null) ${condition} = !!${snippet}`}
								if (${condition}) return ${i};`
								: b$1`return ${i};`
						)}
								${!has_else && b$1`return -1;`}
							}
						`
					: b$1`
					function ${select_block_type}(#ctx, #dirty) {
						${this.branches.map(({ condition, snippet }, i) =>
							condition ? b$1`if (${snippet || condition}) return ${i};` : b$1`return ${i};`
						)}
						${!has_else && b$1`return -1;`}
					}
				`
			}
		`);
		if (need_select_block_ctx) {
			// if all branches needs create a context
			if (this.branches.every((branch) => branch.get_ctx_name)) {
				block.chunks.init.push(b$1`
					function ${select_block_ctx}(#ctx, #index) {
						${this.branches
							.map(({ condition, get_ctx_name }, i) => {
								return condition
									? b$1`if (#index === ${i}) return ${get_ctx_name}(#ctx);`
									: b$1`return ${get_ctx_name}(#ctx);`;
							})
							.filter(Boolean)}
					}
				`);
			} else {
				// when not all branches need to create a new context,
				// this code is simpler
				block.chunks.init.push(b$1`
					function ${select_block_ctx}(#ctx, #index) {
						${this.branches
							.map(({ get_ctx_name }, i) => {
								return get_ctx_name ? b$1`if (#index === ${i}) return ${get_ctx_name}(#ctx);` : null;
							})
							.filter(Boolean)}
						return #ctx;
					}
				`);
			}
		}
		if (has_else) {
			block.chunks.init.push(b$1`
				${current_block_type_index} = ${select_block_type}(#ctx, ${this.renderer.get_initial_dirty()});
				${name} = ${if_blocks}[${current_block_type_index}] = ${if_block_creators}[${current_block_type_index}](${if_ctx});
			`);
		} else {
			block.chunks.init.push(b$1`
				if (~(${current_block_type_index} = ${select_block_type}(#ctx, ${this.renderer.get_initial_dirty()}))) {
					${name} = ${if_blocks}[${current_block_type_index}] = ${if_block_creators}[${current_block_type_index}](${if_ctx});
				}
			`);
		}
		const initial_mount_node = parent_node || '#target';
		const anchor_node = parent_node ? 'null' : '#anchor';
		block.chunks.mount.push(
			if_current_block_type_index(
				b$1`${if_blocks}[${current_block_type_index}].m(${initial_mount_node}, ${anchor_node});`
			)
		);
		if (this.needs_update) {
			const update_mount_node = this.get_update_mount_node(anchor);
			const destroy_old_block = b$1`
				@group_outros();
				@transition_out(${if_blocks}[${previous_block_index}], 1, 1, () => {
					${if_blocks}[${previous_block_index}] = null;
				});
				@check_outros();
			`;
			const create_new_block = b$1`
				${name} = ${if_blocks}[${current_block_type_index}];
				if (!${name}) {
					${name} = ${if_blocks}[${current_block_type_index}] = ${if_block_creators}[${current_block_type_index}](${if_ctx});
					${name}.c();
				} else {
					${dynamic && b$1`${name}.p(${if_ctx}, #dirty);`}
				}
				${has_transitions && b$1`@transition_in(${name}, 1);`}
				${name}.m(${update_mount_node}, ${anchor});
			`;
			const change_block = has_else
				? b$1`
					${destroy_old_block}

					${create_new_block}
				`
				: b$1`
					if (${name}) {
						${destroy_old_block}
					}

					if (~${current_block_type_index}) {
						${create_new_block}
					} else {
						${name} = null;
					}
				`;
			block.chunks.update.push(b$1`
				let ${previous_block_index} = ${current_block_type_index};
				${current_block_type_index} = ${select_block_type}(#ctx, #dirty);
			`);
			if (dynamic) {
				block.chunks.update.push(b$1`
					if (${current_block_type_index} === ${previous_block_index}) {
						${if_current_block_type_index(b$1`${if_blocks}[${current_block_type_index}].p(${if_ctx}, #dirty);`)}
					} else {
						${change_block}
					}
				`);
			} else {
				block.chunks.update.push(b$1`
					if (${current_block_type_index} !== ${previous_block_index}) {
						${change_block}
					}
				`);
			}
		} else if (dynamic) {
			if (if_exists_condition) {
				block.chunks.update.push(b$1`if (${if_exists_condition}) ${name}.p(${if_ctx}, #dirty);`);
			} else {
				block.chunks.update.push(b$1`${name}.p(${if_ctx}, #dirty);`);
			}
		}
		block.chunks.destroy.push(
			if_current_block_type_index(b$1`${if_blocks}[${current_block_type_index}].d(${detaching});`)
		);
	}

	/**
	 * @param {import('../Block.js').default} block
	 * @param {import('estree').Identifier} parent_node
	 * @param {import('estree').Identifier} _parent_nodes
	 * @param {boolean} dynamic
	 * @param {any} opts
	 * @param {DetachingOrNull} detaching
	 */
	render_simple(
		block,
		parent_node,
		_parent_nodes,
		dynamic,
		{ name, anchor, if_exists_condition, has_transitions },
		detaching
	) {
		const branch = this.branches[0];
		const if_ctx = branch.get_ctx_name ? x$1`${branch.get_ctx_name}(#ctx)` : x$1`#ctx`;
		if (branch.snippet) block.add_variable(branch.condition, branch.snippet);
		block.chunks.init.push(b$1`
			let ${name} = ${branch.condition} && ${branch.block.name}(${if_ctx});
		`);
		const initial_mount_node = parent_node || '#target';
		const anchor_node = parent_node ? 'null' : '#anchor';
		block.chunks.mount.push(b$1`if (${name}) ${name}.m(${initial_mount_node}, ${anchor_node});`);
		if (branch.dependencies.length > 0) {
			const update_mount_node = this.get_update_mount_node(anchor);
			const enter = b$1`
				if (${name}) {
					${dynamic && b$1`${name}.p(${if_ctx}, #dirty);`}
					${
						has_transitions &&
						b$1`if (${block.renderer.dirty(branch.dependencies)}) {
									@transition_in(${name}, 1);
								}`
					}
				} else {
					${name} = ${branch.block.name}(${if_ctx});
					${name}.c();
					${has_transitions && b$1`@transition_in(${name}, 1);`}
					${name}.m(${update_mount_node}, ${anchor});
				}
			`;
			if (branch.snippet) {
				block.chunks.update.push(
					b$1`if (${block.renderer.dirty(branch.dependencies)}) ${branch.condition} = ${
						branch.snippet
					}`
				);
			}
			// no `p()` here — we don't want to update outroing nodes,
			// as that will typically result in glitching
			if (branch.block.has_outro_method) {
				block.chunks.update.push(b$1`
					if (${branch.condition}) {
						${enter}
					} else if (${name}) {
						@group_outros();
						@transition_out(${name}, 1, 1, () => {
							${name} = null;
						});
						@check_outros();
					}
				`);
			} else {
				block.chunks.update.push(b$1`
					if (${branch.condition}) {
						${enter}
					} else if (${name}) {
						${name}.d(1);
						${name} = null;
					}
				`);
			}
		} else if (dynamic) {
			block.chunks.update.push(b$1`
				if (${branch.condition}) ${name}.p(${if_ctx}, #dirty);
			`);
		}
		if (if_exists_condition) {
			block.chunks.destroy.push(b$1`
				if (${if_exists_condition}) ${name}.d(${detaching});
			`);
		} else {
			block.chunks.destroy.push(b$1`
				${name}.d(${detaching});
			`);
		}
	}
}

/** @extends Wrapper<import('../../nodes/KeyBlock.js').default> */
class KeyBlockWrapper extends Wrapper {
	/** @type {import('./Fragment.js').default} */
	fragment;

	/** @type {import('../Block.js').default} */
	block;

	/** @type {string[]} */
	dependencies;

	/** @type {import('estree').Identifier} */
	var = { type: 'Identifier', name: 'key_block' };

	/**
	 * @param {import('../Renderer.js').default} renderer
	 * @param {import('../Block.js').default} block
	 * @param {import('./shared/Wrapper.js').default} parent
	 * @param {import('../../nodes/KeyBlock.js').default} node
	 * @param {boolean} strip_whitespace
	 * @param {import('./shared/Wrapper.js').default} next_sibling
	 */
	constructor(renderer, block, parent, node, strip_whitespace, next_sibling) {
		super(renderer, block, parent, node);
		this.dependencies = node.expression.dynamic_dependencies();
		if (this.dependencies.length) {
			block = block.child({
				comment: create_debugging_comment(node, renderer.component),
				name: renderer.component.get_unique_name('create_key_block'),
				type: 'key'
			});
			block.add_dependencies(node.expression.dependencies);
			renderer.blocks.push(block);
		}
		this.block = block;
		this.fragment = new FragmentWrapper(
			renderer,
			this.block,
			node.children,
			this,
			strip_whitespace,
			next_sibling
		);
	}

	/**
	 * @param {import('../Block.js').default} block
	 * @param {import('estree').Identifier} parent_node
	 * @param {import('estree').Identifier} parent_nodes
	 */
	render(block, parent_node, parent_nodes) {
		if (this.dependencies.length === 0) {
			this.render_static_key(block, parent_node, parent_nodes);
		} else {
			this.render_dynamic_key(block, parent_node, parent_nodes);
		}
	}

	/**
	 * @param {import('../Block.js').default} _block
	 * @param {import('estree').Identifier} parent_node
	 * @param {import('estree').Identifier} parent_nodes
	 */
	render_static_key(_block, parent_node, parent_nodes) {
		this.fragment.render(this.block, parent_node, parent_nodes);
	}

	/**
	 * @param {import('../Block.js').default} block
	 * @param {import('estree').Identifier} parent_node
	 * @param {import('estree').Identifier} parent_nodes
	 */
	render_dynamic_key(block, parent_node, parent_nodes) {
		this.fragment.render(
			this.block,
			null,
			/** @type {unknown} */ /** @type {import('estree').Identifier} */ (x$1`#nodes`)
		);
		const has_transitions = !!(this.block.has_intro_method || this.block.has_outro_method);
		const dynamic = this.block.has_update_method;
		const previous_key = block.get_unique_name('previous_key');
		const snippet = this.node.expression.manipulate(block);
		block.add_variable(previous_key, snippet);
		const not_equal = this.renderer.component.component_options.immutable
			? x$1`@not_equal`
			: x$1`@safe_not_equal`;
		const condition = x$1`${this.renderer.dirty(
			this.dependencies
		)} && ${not_equal}(${previous_key}, ${previous_key} = ${snippet})`;
		block.chunks.init.push(b$1`
			let ${this.var} = ${this.block.name}(#ctx);
		`);
		block.chunks.create.push(b$1`${this.var}.c();`);
		if (this.renderer.options.hydratable) {
			block.chunks.claim.push(b$1`${this.var}.l(${parent_nodes});`);
		}
		block.chunks.mount.push(
			b$1`${this.var}.m(${parent_node || '#target'}, ${parent_node ? 'null' : '#anchor'});`
		);
		const anchor = this.get_or_create_anchor(block, parent_node, parent_nodes);
		const body = b$1`
			${
				has_transitions
					? b$1`
						@group_outros();
						@transition_out(${this.var}, 1, 1, @noop);
						@check_outros();
					`
					: b$1`${this.var}.d(1);`
			}
			${this.var} = ${this.block.name}(#ctx);
			${this.var}.c();
			${has_transitions && b$1`@transition_in(${this.var}, 1)`}
			${this.var}.m(${this.get_update_mount_node(anchor)}, ${anchor});
		`;
		if (dynamic) {
			block.chunks.update.push(b$1`
				if (${condition}) {
					${body}
				} else {
					${this.var}.p(#ctx, #dirty);
				}
			`);
		} else {
			block.chunks.update.push(b$1`
				if (${condition}) {
					${body}
				}
			`);
		}
		if (has_transitions) {
			block.chunks.intro.push(b$1`@transition_in(${this.var})`);
			block.chunks.outro.push(b$1`@transition_out(${this.var})`);
		}
		block.chunks.destroy.push(b$1`${this.var}.d(detaching)`);
	}
}

/**
 * @param {string} name
 */
function string_to_member_expression(name) {
	const parts = name.split('.');
	/** @type {import('estree').MemberExpression | import('estree').Identifier} */
	let node = {
		type: 'Identifier',
		name: parts[0]
	};
	for (let i = 1; i < parts.length; i++) {
		node = /** @type {import('estree').MemberExpression} */ ({
			type: 'MemberExpression',
			object: node,
			property: { type: 'Identifier', name: parts[i] }
		});
	}
	return node;
}

/**
 * @param {import('../../Block.js').default} block
 * @param {import('../../../nodes/shared/TemplateScope.js').default} scope
 * @param {import('../../../nodes/Let.js').default[]} lets
 */
function get_slot_definition(block, scope, lets) {
	if (lets.length === 0) return { block, scope };
	const context_input = {
		type: 'ObjectPattern',
		properties: lets.map((l) => ({
			type: 'Property',
			kind: 'init',
			key: l.name,
			value: l.value || l.name
		}))
	};
	const properties = [];
	const value_map = new Map();
	lets.forEach((l) => {
		/** @type {import('estree').Identifier} */
		let value;
		if (l.names.length > 1) {
			// more than one, probably destructuring
			const unique_name = block.get_unique_name(l.names.join('_')).name;
			value_map.set(l.value, unique_name);
			value = { type: 'Identifier', name: unique_name };
		} else {
			value = l.value || l.name;
		}
		properties.push({
			type: 'Property',
			kind: 'init',
			key: l.name,
			value
		});
	});
	const changes_input = {
		type: 'ObjectPattern',
		properties
	};

	/** @type {Set<string>} */
	const names = new Set();

	/** @type {Map<string, string>} */
	const names_lookup = new Map();
	lets.forEach((l) => {
		l.names.forEach((name) => {
			names.add(name);
			if (value_map.has(l.value)) {
				names_lookup.set(name, value_map.get(l.value));
			}
		});
	});
	const context = {
		type: 'ObjectExpression',
		properties: Array.from(names).map(
			(name) => p`${block.renderer.context_lookup.get(name).index}: ${name}`
		)
	};
	const { context_lookup } = block.renderer;
	// i am well aware that this code is gross
	// TODO: context-overflow make it less gross
	const changes = {
		type: 'ParenthesizedExpression',
		get expression() {
			if (block.renderer.context_overflow) {
				const grouped = [];
				Array.from(names).forEach((name) => {
					const i = /** @type {number} */ (context_lookup.get(name).index.value);
					const g = Math.floor(i / 31);
					const lookup_name = names_lookup.has(name) ? names_lookup.get(name) : name;
					if (!grouped[g]) grouped[g] = [];
					grouped[g].push({ name: lookup_name, n: i % 31 });
				});
				const elements = [];
				for (let g = 0; g < grouped.length; g += 1) {
					elements[g] = grouped[g]
						? grouped[g]
								.map(({ name, n }) => x$1`${name} ? ${1 << n} : 0`)
								.reduce((lhs, rhs) => x$1`${lhs} | ${rhs}`)
						: x$1`0`;
				}
				return {
					type: 'ArrayExpression',
					elements
				};
			}
			return /** @type {import('estree').BinaryExpression} */ (
				Array.from(names)
					.map((name) => {
						const lookup_name = names_lookup.has(name) ? names_lookup.get(name) : name;
						const i = /** @type {number} */ (context_lookup.get(name).index.value);
						return x$1`${lookup_name} ? ${1 << i} : 0`;
					})
					.reduce((lhs, rhs) => x$1`${lhs} | ${rhs}`)
			);
		}
	};
	return {
		block,
		scope,
		get_context: x$1`${context_input} => ${context}`,
		get_changes: x$1`${changes_input} => ${changes}`
	};
}

/** @extends Wrapper<import('../../nodes/SlotTemplate.js').default> */
class SlotTemplateWrapper extends Wrapper {
	/** @type {import('./Fragment.js').default} */
	fragment;

	/** @type {import('../Block.js').default} */
	block;

	/**
	 * @param {import('../Renderer.js').default} renderer
	 * @param {import('../Block.js').default} block
	 * @param {import('./shared/Wrapper.js').default} parent
	 * @param {import('../../nodes/SlotTemplate.js').default} node
	 * @param {boolean} strip_whitespace
	 * @param {import('./shared/Wrapper.js').default} next_sibling
	 */
	constructor(renderer, block, parent, node, strip_whitespace, next_sibling) {
		super(renderer, block, parent, node);
		const { scope, lets, const_tags, slot_template_name } = this.node;
		lets.forEach((l) => {
			extract_names(l.value || l.name).forEach((name) => {
				renderer.add_to_context(name, true);
			});
		});
		add_const_tags_context(renderer, const_tags);
		this.block = block.child({
			comment: create_debugging_comment(this.node, this.renderer.component),
			name: this.renderer.component.get_unique_name(`create_${sanitize(slot_template_name)}_slot`),
			type: 'slot'
		});
		this.renderer.blocks.push(this.block);

		/** @type {import('./InlineComponent/index.js').default} */ (this.parent).set_slot(
			slot_template_name,
			get_slot_definition(this.block, scope, lets)
		);
		this.fragment = new FragmentWrapper(
			renderer,
			this.block,
			node.type === 'SlotTemplate' ? node.children : [node],
			this,
			strip_whitespace,
			next_sibling
		);
		this.block.parent.add_dependencies(this.block.dependencies);
	}
	render() {
		this.fragment.render(this.block, null, /** @type {import('estree').Identifier} */ (x$1`#nodes`));
		if (this.node.const_tags.length > 0) {
			this.render_get_context();
		}
	}
	render_get_context() {
		const get_context = this.block.renderer.component.get_unique_name('get_context');
		this.block.renderer.blocks.push(b$1`
			function ${get_context}(#ctx) {
				${add_const_tags(this.block, this.node.const_tags, '#ctx')}
			}
		`);
		this.block.chunks.declarations.push(b$1`${get_context}(#ctx)`);
		if (this.block.has_update_method) {
			this.block.chunks.update.unshift(b$1`${get_context}(#ctx)`);
		}
	}
}

const regex_invalid_variable_identifier_characters = /[^a-zA-Z_$]/g;

/** @extends Wrapper<import('../../../nodes/InlineComponent.js').default> */
class InlineComponentWrapper extends Wrapper {
	/**
	 * @typedef {{
	 * 	block: import('../../Block.js').default;
	 * 	scope: import('../../../nodes/shared/TemplateScope.js').default;
	 * 	get_context?: import('estree').Node;
	 * 	get_changes?: import('estree').Node;
	 * }} SlotDefinition
	 */

	/** @type {Map<string, SlotDefinition>} */
	slots = new Map();

	/** @type {import('../Fragment.js').default} */
	fragment;

	/** @type {Array<Wrapper | import('../Fragment.js').default>} */
	children = [];

	/**
	 * @param {import('../../Renderer.js').default} renderer
	 * @param {import('../../Block.js').default} block
	 * @param {import('../shared/Wrapper.js').default} parent
	 * @param {import('../../../nodes/InlineComponent.js').default} node
	 * @param {boolean} strip_whitespace
	 * @param {import('../shared/Wrapper.js').default} next_sibling
	 */
	constructor(renderer, block, parent, node, strip_whitespace, next_sibling) {
		super(renderer, block, parent, node);
		if (this.node.expression) {
			block.add_dependencies(this.node.expression.dependencies);
		}
		this.node.attributes.forEach((attr) => {
			block.add_dependencies(attr.dependencies);
		});
		this.node.bindings.forEach((binding) => {
			if (binding.is_contextual) {
				mark_each_block_bindings(this, binding);
			}
			block.add_dependencies(binding.expression.dependencies);
		});
		this.node.handlers.forEach((handler) => {
			if (handler.expression) {
				block.add_dependencies(handler.expression.dependencies);
			}
		});
		this.node.css_custom_properties.forEach((attr) => {
			block.add_dependencies(attr.dependencies);
		});
		this.var = {
			type: /** @type {const} */ ('Identifier'),
			name: (this.node.name === 'svelte:self'
				? renderer.component.name.name
				: this.node.name === 'svelte:component'
				? 'switch_instance'
				: sanitize(this.node.name)
			).toLowerCase()
		};
		if (this.node.children.length) {
			this.children = this.node.children.map(
				(child) =>
					new SlotTemplateWrapper(
						renderer,
						block,
						this,
						/** @type {import('../../../nodes/SlotTemplate.js').default} */ (child),
						strip_whitespace,
						next_sibling
					)
			);
		}
		block.add_outro();
	}

	/**
	 * @param {string} name
	 * @param {SlotDefinition} slot_definition
	 */
	set_slot(name, slot_definition) {
		if (this.slots.has(name)) {
			if (name === 'default') {
				throw new Error('Found elements without slot attribute when using slot="default"');
			}
			throw new Error(`Duplicate slot name "${name}" in <${this.node.name}>`);
		}
		this.slots.set(name, slot_definition);
	}
	warn_if_reactive() {
		const { name } = this.node;
		const variable = this.renderer.component.var_lookup.get(name);
		if (!variable) {
			return;
		}
		const ignores = extract_ignores_above_node(this.node);
		this.renderer.component.push_ignores(ignores);
		if (variable.reassigned || variable.export_name || variable.is_reactive_dependency) {
			this.renderer.component.warn(this.node, compiler_warnings.reactive_component(name));
		}
		this.renderer.component.pop_ignores();
	}

	/**
	 * @param {import('../../Block.js').default} block
	 * @param {import('estree').Identifier} parent_node
	 * @param {import('estree').Identifier} parent_nodes
	 */
	render(block, parent_node, parent_nodes) {
		this.warn_if_reactive();
		const { renderer } = this;
		const { component } = renderer;
		const name = this.var;
		block.add_variable(name);
		const component_opts = /** @type {import('estree').ObjectExpression} */ (x$1`{}`);

		/** @type {Array<import('estree').Node | import('estree').Node[]>} */
		const statements = [];

		/** @type {Array<import('estree').Node | import('estree').Node[]>} */
		const updates = [];
		this.children.forEach((child) => {
			this.renderer.add_to_context('$$scope', true);
			child.render(block, null, /** @type {import('estree').Identifier} */ (x$1`#nodes`));
		});

		/** @type {import('estree').Identifier | undefined} */
		let props;
		const name_changes = block.get_unique_name(`${name.name}_changes`);
		const uses_spread = !!this.node.attributes.find((a) => a.is_spread);
		// removing empty slot
		for (const slot of this.slots.keys()) {
			if (!this.slots.get(slot).block.has_content()) {
				this.renderer.remove_block(this.slots.get(slot).block);
				this.slots.delete(slot);
			}
		}
		const has_css_custom_properties = this.node.css_custom_properties.length > 0;
		const is_svg_namespace = this.node.namespace === namespaces.svg;
		const css_custom_properties_wrapper_element = is_svg_namespace ? 'g' : 'div';
		const css_custom_properties_wrapper = has_css_custom_properties
			? block.get_unique_name(css_custom_properties_wrapper_element)
			: null;
		if (has_css_custom_properties) {
			block.add_variable(css_custom_properties_wrapper);
		}
		const initial_props =
			this.slots.size > 0
				? [
						p`$$slots: {
					${Array.from(this.slots).map(([name, slot]) => {
						return p`${name}: [${slot.block.name}, ${slot.get_context || null}, ${
							slot.get_changes || null
						}]`;
					})}
				}`,
						p`$$scope: {
					ctx: #ctx
				}`
				  ]
				: [];
		const attribute_object = uses_spread
			? x$1`{ ${initial_props} }`
			: x$1`{
				${this.node.attributes.map((attr) => p`${attr.name}: ${attr.get_value(block)}`)},
				${initial_props}
			}`;
		if (this.node.attributes.length || this.node.bindings.length || initial_props.length) {
			if (!uses_spread && this.node.bindings.length === 0) {
				component_opts.properties.push(p`props: ${attribute_object}`);
			} else {
				props = block.get_unique_name(`${name.name}_props`);
				component_opts.properties.push(p`props: ${props}`);
			}
		}
		if (component.compile_options.dev) {
			// TODO this is a terrible hack, but without it the component
			// will complain that options.target is missing. This would
			// work better if components had separate public and private
			// APIs
			component_opts.properties.push(p`$$inline: true`);
		}
		const fragment_dependencies = new Set(this.slots.size ? ['$$scope'] : []);
		this.slots.forEach((slot) => {
			slot.block.dependencies.forEach((name) => {
				const is_let = slot.scope.is_let(name);
				const variable = renderer.component.var_lookup.get(name);
				if (is_let || is_dynamic$1(variable)) fragment_dependencies.add(name);
			});
		});
		const dynamic_attributes = this.node.attributes.filter((a) => a.get_dependencies().length > 0);
		if (
			!uses_spread &&
			(dynamic_attributes.length > 0 ||
				this.node.bindings.length > 0 ||
				fragment_dependencies.size > 0)
		) {
			updates.push(b$1`const ${name_changes} = {};`);
		}
		if (this.node.attributes.length) {
			if (uses_spread) {
				const levels = block.get_unique_name(`${this.var.name}_spread_levels`);
				const initial_props = [];
				const changes = [];

				/** @type {Set<string>} */
				const all_dependencies = new Set();
				this.node.attributes.forEach((attr) => {
					add_to_set(all_dependencies, attr.dependencies);
				});
				this.node.attributes.forEach((attr, i) => {
					const { name, dependencies } = attr;
					const condition =
						dependencies.size > 0 && dependencies.size !== all_dependencies.size
							? renderer.dirty(Array.from(dependencies))
							: null;
					const unchanged = dependencies.size === 0;

					/** @type {import('estree').Node | ReturnType<typeof x>} */
					let change_object;
					if (attr.is_spread) {
						const value = attr.expression.manipulate(block);
						initial_props.push(value);
						let value_object = value;
						if (attr.expression.node.type !== 'ObjectExpression') {
							value_object = x$1`@get_spread_object(${value})`;
						}
						change_object = value_object;
					} else {
						const obj = x$1`{ ${name}: ${attr.get_value(block)} }`;
						initial_props.push(obj);
						change_object = obj;
					}
					changes.push(
						unchanged
							? x$1`${levels}[${i}]`
							: condition
							? x$1`${condition} && ${change_object}`
							: change_object
					);
				});
				block.chunks.init.push(b$1`
					const ${levels} = [
						${initial_props}
					];
				`);
				statements.push(b$1`
					for (let #i = 0; #i < ${levels}.length; #i += 1) {
						${props} = @assign(${props}, ${levels}[#i]);
					}
				`);
				if (all_dependencies.size) {
					const condition = renderer.dirty(Array.from(all_dependencies));
					updates.push(b$1`
						const ${name_changes} = ${condition} ? @get_spread_update(${levels}, [
							${changes}
						]) : {}
					`);
				} else {
					updates.push(b$1`
						const ${name_changes} = {};
					`);
				}
			} else {
				dynamic_attributes.forEach((attribute) => {
					const dependencies = attribute.get_dependencies();
					if (dependencies.length > 0) {
						const condition = renderer.dirty(dependencies);
						updates.push(b$1`
							if (${condition}) ${name_changes}.${attribute.name} = ${attribute.get_value(block)};
						`);
					}
				});
			}
		}
		if (fragment_dependencies.size > 0) {
			updates.push(b$1`
				if (${renderer.dirty(Array.from(fragment_dependencies))}) {
					${name_changes}.$$scope = { dirty: #dirty, ctx: #ctx };
				}`);
		}
		const munged_bindings = this.node.bindings.map((binding) => {
			component.has_reactive_assignments = true;
			if (binding.name === 'this') {
				return bind_this(component, block, new BindingWrapper(block, binding, this), this.var);
			}
			const id = component.get_unique_name(`${this.var.name}_${binding.name}_binding`);
			renderer.add_to_context(id.name);
			const callee = renderer.reference(id);
			const updating = block.get_unique_name(`updating_${binding.name}`);
			block.add_variable(updating);
			const snippet = binding.expression.manipulate(block);
			statements.push(b$1`
				if (${snippet} !== void 0) {
					${props}.${binding.name} = ${snippet};
				}`);
			updates.push(b$1`
				if (!${updating} && ${renderer.dirty(Array.from(binding.expression.dependencies))}) {
					${updating} = true;
					${name_changes}.${binding.name} = ${snippet};
					@add_flush_callback(() => ${updating} = false);
				}
			`);
			const contextual_dependencies = Array.from(binding.expression.contextual_dependencies);
			const dependencies = Array.from(binding.expression.dependencies);
			let lhs = binding.raw_expression;
			if (binding.is_contextual && binding.expression.node.type === 'Identifier') {
				// bind:x={y} — we can't just do `y = x`, we need to
				// to `array[index] = x;
				const { name } = binding.expression.node;
				const { object, property, snippet } = block.bindings.get(name);
				lhs = snippet;
				contextual_dependencies.push(object.name, property.name);
			}

			/** @type {import('estree').Identifier[]} */
			const params = [/** @type {import('estree').Identifier} */ (x$1`#value`)];
			const args = [x$1`#value`];
			if (contextual_dependencies.length > 0) {
				contextual_dependencies.forEach((name) => {
					params.push({
						type: 'Identifier',
						name
					});
					renderer.add_to_context(name, true);
					args.push(renderer.reference(name));
				});
				block.maintain_context = true; // TODO put this somewhere more logical
			}
			block.chunks.init.push(b$1`
				function ${id}(#value) {
					${callee}(${args});
				}
			`);
			let invalidate_binding = b$1`
				${lhs} = #value;
				${renderer.invalidate(dependencies[0])};
			`;
			if (binding.expression.node.type === 'MemberExpression') {
				invalidate_binding = b$1`
					if ($$self.$$.not_equal(${lhs}, #value)) {
						${invalidate_binding}
					}
				`;
			}
			const body = b$1`
				function ${id}(${params}) {
					${invalidate_binding}
				}
			`;
			component.partly_hoisted.push(body);
			return b$1`@binding_callbacks.push(() => @bind(${this.var}, '${binding.name}', ${id}));`;
		});
		const munged_handlers = this.node.handlers.map((handler) => {
			const event_handler = new EventHandlerWrapper(handler, this);
			let snippet = event_handler.get_snippet(block);
			if (handler.modifiers.has('once')) snippet = x$1`@once(${snippet})`;
			return b$1`${name}.$on("${handler.name}", ${snippet});`;
		});
		const mount_target = has_css_custom_properties
			? css_custom_properties_wrapper
			: parent_node || '#target';
		const mount_anchor = has_css_custom_properties ? 'null' : parent_node ? 'null' : '#anchor';
		const to_claim = parent_nodes && this.renderer.options.hydratable;
		let claim_nodes = parent_nodes;
		if (this.node.name === 'svelte:component') {
			const switch_value = block.get_unique_name('switch_value');
			const switch_props = block.get_unique_name('switch_props');
			const snippet = this.node.expression.manipulate(block);
			const dependencies = this.node.expression.dynamic_dependencies();
			if (has_css_custom_properties) {
				this.set_css_custom_properties(
					block,
					css_custom_properties_wrapper,
					css_custom_properties_wrapper_element,
					is_svg_namespace
				);
			}
			block.chunks.init.push(b$1`
				var ${switch_value} = ${snippet};

				function ${switch_props}(#ctx) {
					${
						(this.node.attributes.length > 0 || this.node.bindings.length > 0) &&
						b$1`
					${props && b$1`let ${props} = ${attribute_object};`}`
					}
					${statements}
					return ${component_opts};
				}

				if (${switch_value}) {
					${name} = @construct_svelte_component(${switch_value}, ${switch_props}(#ctx));

					${munged_bindings}
					${munged_handlers}
				}
			`);
			block.chunks.create.push(b$1`if (${name}) @create_component(${name}.$$.fragment);`);
			if (css_custom_properties_wrapper)
				this.create_css_custom_properties_wrapper_mount_chunk(
					block,
					parent_node,
					css_custom_properties_wrapper
				);
			block.chunks.mount.push(
				b$1`if (${name}) @mount_component(${name}, ${mount_target}, ${mount_anchor});`
			);
			if (to_claim) {
				if (css_custom_properties_wrapper)
					claim_nodes = this.create_css_custom_properties_wrapper_claim_chunk(
						block,
						claim_nodes,
						css_custom_properties_wrapper,
						css_custom_properties_wrapper_element,
						is_svg_namespace
					);
				block.chunks.claim.push(
					b$1`if (${name}) @claim_component(${name}.$$.fragment, ${claim_nodes});`
				);
			}
			if (updates.length) {
				block.chunks.update.push(b$1`
					${updates}
				`);
			}
			const tmp_anchor = this.get_or_create_anchor(block, parent_node, parent_nodes);
			const anchor = has_css_custom_properties ? 'null' : tmp_anchor;
			const update_mount_node = has_css_custom_properties
				? css_custom_properties_wrapper
				: this.get_update_mount_node(tmp_anchor);
			const update_insert =
				css_custom_properties_wrapper &&
				(tmp_anchor.name !== 'null'
					? b$1`@insert(${tmp_anchor}.parentNode, ${css_custom_properties_wrapper}, ${tmp_anchor});`
					: b$1`@insert(${parent_node}, ${css_custom_properties_wrapper}, ${tmp_anchor});`);
			let update_condition = x$1`${switch_value} !== (${switch_value} = ${snippet})`;
			if (dependencies.length > 0) {
				update_condition = x$1`${block.renderer.dirty(dependencies)} && ${update_condition}`;
			}
			block.chunks.update.push(b$1`
				if (${update_condition}) {
					if (${name}) {
						@group_outros();
						const old_component = ${name};
						@transition_out(old_component.$$.fragment, 1, 0, () => {
							@destroy_component(old_component, 1);
							${has_css_custom_properties ? b$1`@detach(${update_mount_node})` : null}
						});
						@check_outros();
					}

					if (${switch_value}) {
						${update_insert}
						${name} = @construct_svelte_component(${switch_value}, ${switch_props}(#ctx));

						${munged_bindings}
						${munged_handlers}

						@create_component(${name}.$$.fragment);
						@transition_in(${name}.$$.fragment, 1);
						@mount_component(${name}, ${update_mount_node}, ${anchor});
					} else {
						${name} = null;
					}
				} else if (${switch_value}) {
					${updates.length > 0 && b$1`${name}.$set(${name_changes});`}
				}
			`);
			block.chunks.intro.push(b$1`
				if (${name}) @transition_in(${name}.$$.fragment, #local);
			`);
			block.chunks.outro.push(b$1`if (${name}) @transition_out(${name}.$$.fragment, #local);`);
			block.chunks.destroy.push(
				b$1`if (${name}) @destroy_component(${name}, ${parent_node ? null : 'detaching'});`
			);
		} else {
			const expression =
				this.node.name === 'svelte:self'
					? component.name
					: this.renderer.reference(string_to_member_expression(this.node.name));
			block.chunks.init.push(b$1`
				${
					(this.node.attributes.length > 0 || this.node.bindings.length > 0) &&
					b$1`
				${props && b$1`let ${props} = ${attribute_object};`}`
				}
				${statements}
				${name} = new ${expression}(${component_opts});

				${munged_bindings}
				${munged_handlers}
			`);
			if (has_css_custom_properties) {
				this.set_css_custom_properties(
					block,
					css_custom_properties_wrapper,
					css_custom_properties_wrapper_element,
					is_svg_namespace
				);
			}
			block.chunks.create.push(b$1`@create_component(${name}.$$.fragment);`);
			if (css_custom_properties_wrapper)
				this.create_css_custom_properties_wrapper_mount_chunk(
					block,
					parent_node,
					css_custom_properties_wrapper
				);
			block.chunks.mount.push(b$1`@mount_component(${name}, ${mount_target}, ${mount_anchor});`);
			if (to_claim) {
				if (css_custom_properties_wrapper)
					claim_nodes = this.create_css_custom_properties_wrapper_claim_chunk(
						block,
						claim_nodes,
						css_custom_properties_wrapper,
						css_custom_properties_wrapper_element,
						is_svg_namespace
					);
				block.chunks.claim.push(b$1`@claim_component(${name}.$$.fragment, ${claim_nodes});`);
			}
			block.chunks.intro.push(b$1`
				@transition_in(${name}.$$.fragment, #local);
			`);
			if (updates.length) {
				block.chunks.update.push(b$1`
					${updates}
					${name}.$set(${name_changes});
				`);
			}
			block.chunks.destroy.push(b$1`
				@destroy_component(${name}, ${parent_node ? null : 'detaching'});
			`);
			block.chunks.outro.push(b$1`@transition_out(${name}.$$.fragment, #local);`);
		}
	}

	/**
	 * @private
	 * @param {import('../../Block.js').default} block
	 * @param {import('estree').Identifier} parent_node
	 * @param {import('estree').Identifier | null} css_custom_properties_wrapper
	 */
	create_css_custom_properties_wrapper_mount_chunk(
		block,
		parent_node,
		css_custom_properties_wrapper
	) {
		if (parent_node) {
			block.chunks.mount.push(b$1`@append(${parent_node}, ${css_custom_properties_wrapper})`);
			if (is_head(parent_node)) {
				block.chunks.destroy.push(b$1`@detach(${css_custom_properties_wrapper});`);
			}
		} else {
			block.chunks.mount.push(b$1`@insert(#target, ${css_custom_properties_wrapper}, #anchor);`);
			// TODO we eventually need to consider what happens to elements
			// that belong to the same outgroup as an outroing element...
			block.chunks.destroy.push(
				b$1`if (detaching && ${this.var}) @detach(${css_custom_properties_wrapper});`
			);
		}
	}

	/**
	 * @private
	 * @param {import('../../Block.js').default} block
	 * @param {import('estree').Identifier} parent_nodes
	 * @param {import('estree').Identifier | null} css_custom_properties_wrapper
	 * @param {string} css_custom_properties_wrapper_element
	 * @param {boolean} is_svg_namespace
	 */
	create_css_custom_properties_wrapper_claim_chunk(
		block,
		parent_nodes,
		css_custom_properties_wrapper,
		css_custom_properties_wrapper_element,
		is_svg_namespace
	) {
		const nodes = block.get_unique_name(`${css_custom_properties_wrapper.name}_nodes`);
		const claim_element = is_svg_namespace ? x$1`@claim_svg_element` : x$1`@claim_element`;
		block.chunks.claim.push(b$1`
			${css_custom_properties_wrapper} = ${claim_element}(${parent_nodes}, "${css_custom_properties_wrapper_element.toUpperCase()}", { style: true })
			var ${nodes} = @children(${css_custom_properties_wrapper});
		`);
		return nodes;
	}

	/**
	 * @private
	 * @param {import('../../Block.js').default} block
	 * @param {import('estree').Identifier} css_custom_properties_wrapper
	 * @param {string} css_custom_properties_wrapper_element
	 * @param {boolean} is_svg_namespace
	 */
	set_css_custom_properties(
		block,
		css_custom_properties_wrapper,
		css_custom_properties_wrapper_element,
		is_svg_namespace
	) {
		const element = is_svg_namespace ? x$1`@svg_element` : x$1`@element`;
		block.chunks.create.push(
			b$1`${css_custom_properties_wrapper} = ${element}("${css_custom_properties_wrapper_element}");`
		);
		if (!is_svg_namespace)
			block.chunks.hydrate.push(
				b$1`@set_style(${css_custom_properties_wrapper}, "display", "contents");`
			);
		this.node.css_custom_properties.forEach((attr) => {
			const dependencies = attr.get_dependencies();
			const should_cache = attr.should_cache();
			const last =
				should_cache &&
				block.get_unique_name(
					`${attr.name.replace(regex_invalid_variable_identifier_characters, '_')}_last`
				);
			if (should_cache) block.add_variable(last);
			const value = attr.get_value(block);
			const init = should_cache ? x$1`${last} = ${value}` : value;
			block.chunks.hydrate.push(
				b$1`@set_style(${css_custom_properties_wrapper}, "${attr.name}", ${init});`
			);
			if (dependencies.length > 0) {
				let condition = block.renderer.dirty(dependencies);
				if (should_cache) condition = x$1`${condition} && (${last} !== (${last} = ${value}))`;
				block.chunks.update.push(b$1`
					if (${condition}) {
						@set_style(${css_custom_properties_wrapper}, "${attr.name}", ${should_cache ? last : value});
					}
				`);
			}
		});
	}
}

/**
 * @param {Map<string, import('../nodes/Attribute.js').default>} values
 * @param {import('../render_dom/Block.js').default} block
 */
function get_slot_data(values, block = null) {
	return {
		type: 'ObjectExpression',
		properties: Array.from(values.values())
			.filter((attribute) => attribute.name !== 'name')
			.map((attribute) => {
				if (attribute.is_spread) {
					const argument = get_spread_value(block, attribute);
					return {
						type: 'SpreadElement',
						argument
					};
				}
				const value = get_value(block, attribute);
				return p`${attribute.name}: ${value}`;
			})
	};
}

/**
 * @param {import('../render_dom/Block.js').default} block
 * @param {import('../nodes/Attribute.js').default} attribute
 */
function get_value(block, attribute) {
	if (attribute.is_true) return x$1`true`;
	if (attribute.chunks.length === 0) return x$1`""`;
	let value = attribute.chunks
		.map((chunk) =>
			chunk.type === 'Text'
				? string_literal(chunk.data)
				: block
				? chunk.manipulate(block)
				: chunk.node
		)
		.reduce((lhs, rhs) => x$1`${lhs} + ${rhs}`);
	if (attribute.chunks.length > 1 && attribute.chunks[0].type !== 'Text') {
		value = x$1`"" + ${value}`;
	}
	return value;
}

/**
 * @param {import('../render_dom/Block.js').default} block
 * @param {import('../nodes/Attribute.js').default} attribute
 */
function get_spread_value(block, attribute) {
	return block ? attribute.expression.manipulate(block) : attribute.expression.node;
}

/** @extends Wrapper<import('../../nodes/Slot.js').default> */
class SlotWrapper extends Wrapper {
	/** @type {import('./Fragment.js').default} */
	fragment;

	/** @type {import('../Block.js').default | null} */
	fallback = null;

	/** @type {import('../Block.js').default} */
	slot_block;

	/** @type {import('estree').Identifier} */
	var = { type: 'Identifier', name: 'slot' };

	/** @type {Set<string>} */
	dependencies = new Set(['$$scope']);

	/**
	 * @param {import('../Renderer.js').default} renderer
	 * @param {import('../Block.js').default} block
	 * @param {import('./shared/Wrapper.js').default} parent
	 * @param {import('../../nodes/Slot.js').default} node
	 * @param {boolean} strip_whitespace
	 * @param {import('./shared/Wrapper.js').default} next_sibling
	 */
	constructor(renderer, block, parent, node, strip_whitespace, next_sibling) {
		super(renderer, block, parent, node);
		if (this.node.children.length) {
			this.fallback = block.child({
				comment: create_debugging_comment(this.node.children[0], this.renderer.component),
				name: this.renderer.component.get_unique_name('fallback_block'),
				type: 'fallback'
			});
			renderer.blocks.push(this.fallback);
		}
		this.fragment = new FragmentWrapper(
			renderer,
			this.fallback,
			node.children,
			this,
			strip_whitespace,
			next_sibling
		);
		this.node.values.forEach((attribute) => {
			add_to_set(this.dependencies, attribute.dependencies);
		});
		block.add_dependencies(this.dependencies);
		// we have to do this, just in case
		block.add_intro();
		block.add_outro();
	}

	/**
	 * @param {import('../Block.js').default} block
	 * @param {import('estree').Identifier} parent_node
	 * @param {import('estree').Identifier} parent_nodes
	 */
	render(block, parent_node, parent_nodes) {
		const { renderer } = this;
		const { slot_name } = this.node;
		if (this.slot_block) {
			block = this.slot_block;
		}

		/** @type {import('estree').Identifier | 'null'} */
		let get_slot_changes_fn;

		/** @type {import('estree').Identifier | undefined} */
		let get_slot_spread_changes_fn;

		/** @type {import('estree').Identifier | 'null'} */
		let get_slot_context_fn;
		if (this.node.values.size > 0) {
			get_slot_changes_fn = renderer.component.get_unique_name(
				`get_${sanitize(slot_name)}_slot_changes`
			);
			get_slot_context_fn = renderer.component.get_unique_name(
				`get_${sanitize(slot_name)}_slot_context`
			);
			const changes = /** @type {import('estree').ObjectExpression} */ (x$1`{}`);
			const spread_dynamic_dependencies = new Set();
			this.node.values.forEach((attribute) => {
				if (attribute.type === 'Spread') {
					add_to_set(
						spread_dynamic_dependencies,
						Array.from(attribute.dependencies).filter((name) => this.is_dependency_dynamic(name))
					);
				} else {
					const dynamic_dependencies = Array.from(attribute.dependencies).filter((name) =>
						this.is_dependency_dynamic(name)
					);
					if (dynamic_dependencies.length > 0) {
						changes.properties.push(p`${attribute.name}: ${renderer.dirty(dynamic_dependencies)}`);
					}
				}
			});
			renderer.blocks.push(b$1`
				const ${get_slot_changes_fn} = #dirty => ${changes};
				const ${get_slot_context_fn} = #ctx => ${get_slot_data(this.node.values, block)};
			`);
			if (spread_dynamic_dependencies.size) {
				get_slot_spread_changes_fn = renderer.component.get_unique_name(
					`get_${sanitize(slot_name)}_slot_spread_changes`
				);
				renderer.blocks.push(b$1`
					const ${get_slot_spread_changes_fn} = #dirty => ${renderer.dirty(
					Array.from(spread_dynamic_dependencies)
				)};
				`);
			}
		} else {
			get_slot_changes_fn = 'null';
			get_slot_context_fn = 'null';
		}
		let has_fallback = !!this.fallback;
		if (this.fallback) {
			this.fragment.render(
				this.fallback,
				null,
				/** @type {import('estree').Identifier} */ (x$1`#nodes`)
			);
			has_fallback = this.fallback.has_content();
			if (!has_fallback) {
				renderer.remove_block(this.fallback);
			}
		}
		const slot = block.get_unique_name(`${sanitize(slot_name)}_slot`);
		const slot_definition = block.get_unique_name(`${sanitize(slot_name)}_slot_template`);
		const slot_or_fallback = has_fallback
			? block.get_unique_name(`${sanitize(slot_name)}_slot_or_fallback`)
			: slot;
		block.chunks.init.push(b$1`
			const ${slot_definition} = ${renderer.reference('#slots')}.${slot_name};
			const ${slot} = @create_slot(${slot_definition}, #ctx, ${renderer.reference(
			'$$scope'
		)}, ${get_slot_context_fn});
			${has_fallback ? b$1`const ${slot_or_fallback} = ${slot} || ${this.fallback.name}(#ctx);` : null}
		`);
		block.chunks.create.push(b$1`if (${slot_or_fallback}) ${slot_or_fallback}.c();`);
		if (renderer.options.hydratable) {
			block.chunks.claim.push(b$1`if (${slot_or_fallback}) ${slot_or_fallback}.l(${parent_nodes});`);
		}
		block.chunks.mount.push(b$1`
			if (${slot_or_fallback}) {
				${slot_or_fallback}.m(${parent_node || '#target'}, ${parent_node ? 'null' : '#anchor'});
			}
		`);
		block.chunks.intro.push(b$1`@transition_in(${slot_or_fallback}, #local);`);
		block.chunks.outro.push(b$1`@transition_out(${slot_or_fallback}, #local);`);
		const dynamic_dependencies = Array.from(this.dependencies).filter((name) =>
			this.is_dependency_dynamic(name)
		);
		const fallback_dynamic_dependencies = has_fallback
			? Array.from(this.fallback.dependencies).filter((name) => this.is_dependency_dynamic(name))
			: [];
		let condition = renderer.dirty(dynamic_dependencies);
		if (block.has_outros) {
			condition = x$1`!#current || ${condition}`;
		}
		// conditions to treat everything as dirty
		const all_dirty_conditions = [
			get_slot_spread_changes_fn ? x$1`${get_slot_spread_changes_fn}(#dirty)` : null,
			block.has_outros ? x$1`!#current` : null
		].filter(Boolean);
		const all_dirty_condition = all_dirty_conditions.length
			? all_dirty_conditions.reduce((condition1, condition2) => x$1`${condition1} || ${condition2}`)
			: null;

		/** @type {import('estree').Node[]} */
		let slot_update;
		if (all_dirty_condition) {
			const dirty = x$1`${all_dirty_condition} ? @get_all_dirty_from_scope(${renderer.reference(
				'$$scope'
			)}) : @get_slot_changes(${slot_definition}, ${renderer.reference(
				'$$scope'
			)}, #dirty, ${get_slot_changes_fn})`;
			slot_update = b$1`
				if (${slot}.p && ${condition}) {
					@update_slot_base(${slot}, ${slot_definition}, #ctx, ${renderer.reference(
				'$$scope'
			)}, ${dirty}, ${get_slot_context_fn});
				}
			`;
		} else {
			slot_update = b$1`
				if (${slot}.p && ${condition}) {
					@update_slot(${slot}, ${slot_definition}, #ctx, ${renderer.reference(
				'$$scope'
			)}, #dirty, ${get_slot_changes_fn}, ${get_slot_context_fn});
				}
			`;
		}
		let fallback_condition = renderer.dirty(fallback_dynamic_dependencies);
		let fallback_dirty = x$1`#dirty`;
		if (block.has_outros) {
			fallback_condition = x$1`!#current || ${fallback_condition}`;
			fallback_dirty = x$1`!#current ? ${renderer.get_initial_dirty()} : ${fallback_dirty}`;
		}
		const fallback_update =
			has_fallback &&
			fallback_dynamic_dependencies.length > 0 &&
			b$1`
			if (${slot_or_fallback} && ${slot_or_fallback}.p && ${fallback_condition}) {
				${slot_or_fallback}.p(#ctx, ${fallback_dirty});
			}
		`;
		if (fallback_update) {
			block.chunks.update.push(b$1`
				if (${slot}) {
					${slot_update}
				} else {
					${fallback_update}
				}
			`);
		} else {
			block.chunks.update.push(b$1`
				if (${slot}) {
					${slot_update}
				}
			`);
		}
		block.chunks.destroy.push(b$1`if (${slot_or_fallback}) ${slot_or_fallback}.d(detaching);`);
	}

	/** @param {string} name */
	is_dependency_dynamic(name) {
		if (name === '$$scope') return true;
		if (this.node.scope.is_let(name)) return true;
		if (is_reserved_keyword(name)) return true;
		const variable = this.renderer.component.var_lookup.get(name);
		return is_dynamic$1(variable);
	}
}

/** @extends Wrapper<import('../../nodes/Title.js').default> */
class TitleWrapper extends Wrapper {
	/**
	 * @param {import('../Renderer.js').default} renderer
	 * @param {import('../Block.js').default} block
	 * @param {import('./shared/Wrapper.js').default} parent
	 * @param {import('../../nodes/Title.js').default} node
	 * @param {boolean} _strip_whitespace
	 * @param {import('./shared/Wrapper.js').default} _next_sibling
	 */
	constructor(renderer, block, parent, node, _strip_whitespace, _next_sibling) {
		super(renderer, block, parent, node);
	}

	/**
	 * @param {import('../Block.js').default} block
	 * @param {import('estree').Identifier} _parent_node
	 * @param {import('estree').Identifier} _parent_nodes
	 */
	render(block, _parent_node, _parent_nodes) {
		const is_dynamic = !!this.node.children.find((node) => node.type !== 'Text');
		if (is_dynamic) {
			let value;

			/** @type {Set<string>} */
			const all_dependencies = new Set();
			// TODO some of this code is repeated in Tag.ts — would be good to
			// DRY it out if that's possible without introducing crazy indirection
			if (this.node.children.length === 1) {
				// single {tag} — may be a non-string
				// @ts-ignore todo: check this
				const { expression } = this.node.children[0];
				value = expression.manipulate(block);
				add_to_set(all_dependencies, expression.dependencies);
			} else {
				// '{foo} {bar}' — treat as string concatenation
				value = this.node.children
					.map((chunk) => {
						if (chunk.type === 'Text') return string_literal(chunk.data);
						/** @type {import('../../nodes/MustacheTag.js').default} */ (
							chunk
						).expression.dependencies.forEach((d) => {
							all_dependencies.add(d);
						});
						return /** @type {import('../../nodes/MustacheTag.js').default} */ (
							chunk
						).expression.manipulate(block);
					})
					.reduce((lhs, rhs) => x$1`${lhs} + ${rhs}`);
				if (this.node.children[0].type !== 'Text') {
					value = x$1`"" + ${value}`;
				}
			}
			const last = this.node.should_cache && block.get_unique_name('title_value');
			if (this.node.should_cache) block.add_variable(last);
			const init = this.node.should_cache ? x$1`${last} = ${value}` : value;
			block.chunks.init.push(b$1`@_document.title = ${init};`);
			const updater = b$1`@_document.title = ${this.node.should_cache ? last : value};`;
			if (all_dependencies.size) {
				const dependencies = Array.from(all_dependencies);
				let condition = block.renderer.dirty(dependencies);
				if (block.has_outros) {
					condition = x$1`!#current || ${condition}`;
				}
				if (this.node.should_cache) {
					condition = x$1`${condition} && (${last} !== (${last} = ${value}))`;
				}
				block.chunks.update.push(b$1`
					if (${condition}) {
						${updater}
					}`);
			}
		} else {
			const value =
				this.node.children.length > 0
					? string_literal(
							/** @type {import('../../nodes/Text.js').default} */ (this.node.children[0]).data
					  )
					: x$1`""`;
			block.chunks.hydrate.push(b$1`@_document.title = ${value};`);
		}
	}
}

const associated_events = {
	innerWidth: 'resize',
	innerHeight: 'resize',
	outerWidth: 'resize',
	outerHeight: 'resize',
	devicePixelRatio: 'resize',
	scrollX: 'scroll',
	scrollY: 'scroll'
};
const properties = {
	scrollX: 'pageXOffset',
	scrollY: 'pageYOffset'
};
const readonly = new Set([
	'innerWidth',
	'innerHeight',
	'outerWidth',
	'outerHeight',
	'devicePixelRatio',
	'online'
]);

/** @extends Wrapper<import('../../nodes/Window.js').default> */
class WindowWrapper extends Wrapper {
	/** @type {import('./Element/EventHandler.js').default[]} */
	handlers;

	/**
	 * @param {import('../Renderer.js').default} renderer
	 * @param {import('../Block.js').default} block
	 * @param {import('./shared/Wrapper.js').default} parent
	 * @param {import('../../nodes/Window.js').default} node
	 */
	constructor(renderer, block, parent, node) {
		super(renderer, block, parent, node);
		this.handlers = this.node.handlers.map((handler) => new EventHandlerWrapper(handler, this));
	}

	/**
	 * @param {import('../Block.js').default} block
	 * @param {import('estree').Identifier} _parent_node
	 * @param {import('estree').Identifier} _parent_nodes
	 */
	render(block, _parent_node, _parent_nodes) {
		const { renderer } = this;
		const { component } = renderer;

		/** @type {Record<string, Array<{ name: string; value: string }>>} */
		const events = {};

		/** @type {Record<string, string>} */
		const bindings = {};
		add_actions(block, '@_window', this.node.actions);
		add_event_handlers(block, '@_window', this.handlers);
		this.node.bindings.forEach((binding) => {
			// TODO: what if it's a MemberExpression?
			const binding_name = /** @type {import('estree').Identifier} */ (binding.expression.node)
				.name;
			// in dev mode, throw if read-only values are written to
			if (readonly.has(binding.name)) {
				renderer.readonly.add(binding_name);
			}
			bindings[binding.name] = binding_name;
			// bind:online is a special case, we need to listen for two separate events
			if (binding.name === 'online') return;
			const associated_event = associated_events[binding.name];
			const property = properties[binding.name] || binding.name;
			if (!events[associated_event]) events[associated_event] = [];
			events[associated_event].push({
				name: binding_name,
				value: property
			});
		});
		const scrolling = block.get_unique_name('scrolling');
		const clear_scrolling = block.get_unique_name('clear_scrolling');
		const scrolling_timeout = block.get_unique_name('scrolling_timeout');
		Object.keys(events).forEach((event) => {
			const id = block.get_unique_name(`onwindow${event}`);
			const props = events[event];
			renderer.add_to_context(id.name);
			const fn = renderer.reference(id.name);
			if (event === 'scroll') {
				// TODO other bidirectional bindings...
				block.add_variable(scrolling, x$1`false`);
				block.add_variable(clear_scrolling, x$1`() => { ${scrolling} = false }`);
				block.add_variable(scrolling_timeout);
				const condition =
					bindings.scrollX && bindings.scrollY
						? x$1`"${bindings.scrollX}" in this._state || "${bindings.scrollY}" in this._state`
						: x$1`"${bindings.scrollX || bindings.scrollY}" in this._state`;
				const scrollX = bindings.scrollX && x$1`this._state.${bindings.scrollX}`;
				const scrollY = bindings.scrollY && x$1`this._state.${bindings.scrollY}`;
				renderer.meta_bindings.push(b$1`
					if (${condition}) {
						@_scrollTo(${scrollX || '@_window.pageXOffset'}, ${scrollY || '@_window.pageYOffset'});
					}
					${scrollX && `${scrollX} = @_window.pageXOffset;`}
					${scrollY && `${scrollY} = @_window.pageYOffset;`}
				`);
				block.event_listeners.push(x$1`
					@listen(@_window, "${event}", () => {
						${scrolling} = true;
						@_clearTimeout(${scrolling_timeout});
						${scrolling_timeout} = @_setTimeout(${clear_scrolling}, 100);
						${fn}();
					})
				`);
			} else {
				props.forEach((prop) => {
					renderer.meta_bindings.push(b$1`this._state.${prop.name} = @_window.${prop.value};`);
				});
				block.event_listeners.push(x$1`
					@listen(@_window, "${event}", ${fn})
				`);
			}
			component.partly_hoisted.push(b$1`
				function ${id}() {
					${props.map((prop) => renderer.invalidate(prop.name, x$1`${prop.name} = @_window.${prop.value}`))}
				}
			`);
			block.chunks.init.push(b$1`
				@add_render_callback(${fn});
			`);
			component.has_reactive_assignments = true;
		});
		// special case... might need to abstract this out if we add more special cases
		if (bindings.scrollX || bindings.scrollY) {
			const condition = renderer.dirty([bindings.scrollX, bindings.scrollY].filter(Boolean));
			const scrollX = bindings.scrollX
				? renderer.reference(bindings.scrollX)
				: x$1`@_window.pageXOffset`;
			const scrollY = bindings.scrollY
				? renderer.reference(bindings.scrollY)
				: x$1`@_window.pageYOffset`;
			block.chunks.update.push(b$1`
				if (${condition} && !${scrolling}) {
					${scrolling} = true;
					@_clearTimeout(${scrolling_timeout});
					@_scrollTo(${scrollX}, ${scrollY});
					${scrolling_timeout} = @_setTimeout(${clear_scrolling}, 100);
				}
			`);
		}
		// another special case. (I'm starting to think these are all special cases.)
		if (bindings.online) {
			const id = block.get_unique_name('onlinestatuschanged');
			const name = bindings.online;
			renderer.add_to_context(id.name);
			const reference = renderer.reference(id.name);
			component.partly_hoisted.push(b$1`
				function ${id}() {
					${renderer.invalidate(name, x$1`${name} = @_navigator.onLine`)}
				}
			`);
			block.chunks.init.push(b$1`
				@add_render_callback(${reference});
			`);
			block.event_listeners.push(
				x$1`@listen(@_window, "online", ${reference})`,
				x$1`@listen(@_window, "offline", ${reference})`
			);
			component.has_reactive_assignments = true;
		}
	}
}

/**
 * @template {{ next?: T; prev?: T }} T
 * @param {T} next
 * @param {T} prev
 */
function link(next, prev) {
	prev.next = next;
	if (next) next.prev = prev;
}

const wrappers = {
	AwaitBlock: AwaitBlockWrapper,
	Body: BodyWrapper,
	Comment: CommentWrapper,
	DebugTag: DebugTagWrapper,
	Document: DocumentWrapper,
	EachBlock: EachBlockWrapper,
	Element: ElementWrapper,
	Head: HeadWrapper,
	IfBlock: IfBlockWrapper,
	InlineComponent: InlineComponentWrapper,
	KeyBlock: KeyBlockWrapper,
	MustacheTag: MustacheTagWrapper,
	Options: null,
	RawMustacheTag: RawMustacheTagWrapper,
	Slot: SlotWrapper,
	SlotTemplate: SlotTemplateWrapper,
	Text: TextWrapper,
	Title: TitleWrapper,
	Window: WindowWrapper
};

/**
 * @param {import('../../nodes/interfaces.js').INode} child
 * @param {import('./shared/Wrapper.js').default} next_sibling
 * @returns {boolean}
 */
function trimmable_at$1(child, next_sibling) {
	// Whitespace is trimmable if one of the following is true:
	// The child and its sibling share a common nearest each block (not at an each block boundary)
	// The next sibling's previous node is an each block
	return (
		next_sibling.node.find_nearest(/EachBlock/) === child.find_nearest(/EachBlock/) ||
		next_sibling.node.prev.type === 'EachBlock'
	);
}

class FragmentWrapper {
	/** @type {import('./shared/Wrapper.js').default[]} */
	nodes;

	/**
	 * @param {import('../Renderer.js').default} renderer
	 * @param {import('../Block.js').default} block
	 * @param {import('../../nodes/interfaces.js').INode[]} nodes
	 * @param {import('./shared/Wrapper.js').default} parent
	 * @param {boolean} strip_whitespace
	 * @param {import('./shared/Wrapper.js').default} next_sibling
	 */
	constructor(renderer, block, nodes, parent, strip_whitespace, next_sibling) {
		this.nodes = [];

		/** @type {import('./shared/Wrapper.js').default} */
		let last_child;

		/** @type {import('./Window.js').default | undefined} */
		let window_wrapper;
		let i = nodes.length;
		while (i--) {
			const child = nodes[i];
			if (!child.type) {
				throw new Error('missing type');
			}
			if (!(child.type in wrappers)) {
				throw new Error(`TODO implement ${child.type}`);
			}
			// special case — this is an easy way to remove whitespace surrounding
			// <svelte:window/>. lil hacky but it works
			if (child.type === 'Window') {
				window_wrapper = new WindowWrapper(renderer, block, parent, child);
				continue;
			}
			if (child.type === 'Text') {
				let { data } = child;
				// We want to remove trailing whitespace inside an element/component/block,
				// *unless* there is no whitespace between this node and its next sibling
				if (this.nodes.length === 0) {
					const should_trim = next_sibling
						? next_sibling.node.type === 'Text' &&
						  regex_starts_with_whitespace.test(next_sibling.node.data) &&
						  trimmable_at$1(child, next_sibling)
						: !child.has_ancestor('EachBlock');
					if (should_trim && !child.keep_space()) {
						data = trim_end(data);
						if (!data) continue;
					}
				}
				// glue text nodes (which could e.g. be separated by comments) together
				if (last_child && last_child.node.type === 'Text') {
					/** @type {import('./Text.js').default} */ (last_child).data =
						data + /** @type {import('./Text.js').default} */ (last_child).data;
					continue;
				}
				const wrapper = new TextWrapper(renderer, block, parent, child, data);
				if (wrapper.skip) continue;
				this.nodes.unshift(wrapper);
				link(last_child, (last_child = wrapper));
			} else {
				const Wrapper = wrappers[child.type];
				if (!Wrapper || (child.type === 'Comment' && !renderer.options.preserveComments)) continue;
				const wrapper = new Wrapper(
					renderer,
					block,
					parent,
					child,
					strip_whitespace,
					last_child || next_sibling
				);
				this.nodes.unshift(wrapper);
				link(last_child, (last_child = wrapper));
			}
		}
		if (strip_whitespace) {
			const first = /** @type {import('./Text.js').default} */ (this.nodes[0]);
			if (first && first.node.type === 'Text' && !first.node.keep_space()) {
				first.data = trim_start(first.data);
				if (!first.data) {
					first.var = null;
					this.nodes.shift();
					if (this.nodes[0]) {
						this.nodes[0].prev = null;
					}
				}
			}
		}
		if (window_wrapper) {
			this.nodes.unshift(window_wrapper);
			link(last_child, window_wrapper);
		}
	}

	/**
	 * @param {import('../Block.js').default} block
	 * @param {import('estree').Identifier} parent_node
	 * @param {import('estree').Identifier} parent_nodes
	 */
	render(block, parent_node, parent_nodes) {
		for (let i = 0; i < this.nodes.length; i += 1) {
			this.nodes[i].render(block, parent_node, parent_nodes);
		}
	}
}

let Renderer$1 = class Renderer {
	/**
	 * @typedef {Object} ContextMember
	 * @property {string} name
	 * @property {import('estree').Literal} index
	 * @property {boolean} is_contextual
	 * @property {boolean} is_non_contextual
	 * @property {import('../../interfaces.js').Var} variable
	 * @property {number} priority
	 */

	/**
	 * @typedef {Array<{
	 * 	n: number;
	 * 	names: string[];
	 * }>} BitMasks
	 */

	/** @type {import('../Component.js').default} */
	component; // TODO Maybe Renderer shouldn't know about Component?

	/** @type {import('../../interfaces.js').CompileOptions} */
	options;

	/** @type {ContextMember[]} */
	context = [];

	/** @type {ContextMember[]} */
	initial_context = [];

	/** @type {Map<string, ContextMember>} */
	context_lookup = new Map();

	/** @type {boolean} */
	context_overflow;

	/** @type {Array<import('./Block.js').default | import('estree').Node | import('estree').Node[]>} */
	blocks = [];

	/** @type {Set<string>} */
	readonly = new Set();

	/** @type {Array<import('estree').Node | import('estree').Node[]>} */
	meta_bindings = []; // initial values for e.g. window.innerWidth, if there's a <svelte:window> meta tag

	/** @type {Map<string, BindingGroup>} */
	binding_groups = new Map();

	/** @type {import('./Block.js').default} */
	block;

	/** @type {import('./wrappers/Fragment.js').default} */
	fragment;

	/** @type {import('estree').Identifier} */
	file_var;

	/**
	 * Use this for stack traces. It is 1-based and acts on pre-processed sources.
	 * Use `meta_locate` for metadata on DOM elements.
	 * @type {(c: number) => { line: number; column: number }}
	 */
	locate;

	/**
	 * Use this for metadata on DOM elements. It is 1-based and acts on sources that have not been pre-processed.
	 * Use `locate` for source mappings.
	 * @type {(c: number) => { line: number; column: number }}
	 */
	meta_locate;

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('../../interfaces.js').CompileOptions} options
	 */
	constructor(component, options) {
		this.component = component;
		this.options = options;
		this.locate = component.locate; // TODO messy
		this.meta_locate = component.meta_locate; // TODO messy
		this.file_var = options.dev && this.component.get_unique_name('file');
		component.vars
			.filter((v) => !v.hoistable || (v.export_name && !v.module))
			.forEach((v) => this.add_to_context(v.name));
		// ensure store values are included in context
		component.vars.filter((v) => v.subscribable).forEach((v) => this.add_to_context(`$${v.name}`));
		reserved_keywords.forEach((keyword) => {
			if (component.var_lookup.has(keyword)) {
				this.add_to_context(keyword);
			}
		});
		if (component.slots.size > 0) {
			this.add_to_context('$$scope');
			this.add_to_context('#slots');
		}
		// main block
		this.block = new Block$1({
			renderer: this,
			name: null,
			type: 'component',
			key: null,
			bindings: new Map(),
			dependencies: new Set()
		});
		this.block.has_update_method = true;
		this.fragment = new FragmentWrapper(
			this,
			this.block,
			component.fragment.children,
			null,
			true,
			null
		);
		// TODO messy
		this.blocks.forEach((block) => {
			if (block instanceof Block$1) {
				block.assign_variable_names();
			}
		});
		this.block.assign_variable_names();
		this.fragment.render(this.block, null, /** @type {import('estree').Identifier} */ (x$1`#nodes`));
		this.context_overflow = this.context.length > 31;
		this.context.forEach((member) => {
			const { variable } = member;
			if (variable) {
				member.priority += 2;
				if (variable.mutated || variable.reassigned) member.priority += 4;
				// these determine whether variable is included in initial context
				// array, so must have the highest priority
				if (variable.is_reactive_dependency && (variable.mutated || variable.reassigned))
					member.priority += 16;
				if (variable.export_name) member.priority += 32;
				if (variable.referenced) member.priority += 64;
			} else if (member.is_non_contextual) {
				// determine whether variable is included in initial context
				// array, so must have the highest priority
				member.priority += 8;
			}
			if (!member.is_contextual) {
				member.priority += 1;
			}
		});
		this.context.sort(
			(a, b) =>
				b.priority - a.priority ||
				/** @type {number} */ (a.index.value) - /** @type {number} */ (b.index.value)
		);
		this.context.forEach((member, i) => (member.index.value = i));
		let i = this.context.length;
		while (i--) {
			const member = this.context[i];
			if (member.variable) {
				if (
					member.variable.referenced ||
					member.variable.export_name ||
					(member.variable.is_reactive_dependency &&
						(member.variable.mutated || member.variable.reassigned))
				)
					break;
			} else if (member.is_non_contextual) {
				break;
			}
		}
		this.initial_context = this.context.slice(0, i + 1);
	}

	/**
	 * @param {string} name
	 * @param {any} contextual
	 */
	add_to_context(name, contextual = false) {
		if (!this.context_lookup.has(name)) {
			/** @type {ContextMember} */
			const member = {
				name,
				index: { type: 'Literal', value: this.context.length },
				is_contextual: false,
				is_non_contextual: false,
				variable: null,
				priority: 0
			};
			this.context_lookup.set(name, member);
			this.context.push(member);
		}
		const member = this.context_lookup.get(name);
		if (contextual) {
			member.is_contextual = true;
		} else {
			member.is_non_contextual = true;
			member.variable = this.component.var_lookup.get(name);
		}
		return member;
	}

	/**
	 * @param {string} name
	 * @param {unknown} [value]
	 * @param {boolean} main_execution_context
	 */
	invalidate(name, value, main_execution_context = false) {
		return renderer_invalidate(this, name, value, main_execution_context);
	}

	/**
	 * @param {string[]} names
	 * @param {any} is_reactive_declaration
	 * @returns {import('estree').Expression}
	 */
	dirty(names, is_reactive_declaration = false) {
		const renderer = this;
		const dirty = /** @type {| import('estree').Identifier
                    | import('estree').MemberExpression} */ (
			is_reactive_declaration ? x$1`$$self.$$.dirty` : x$1`#dirty`
		);
		const get_bitmask = () => {
			/** @type {BitMasks} */
			const bitmask = [];
			names.forEach((name) => {
				const member = renderer.context_lookup.get(name);
				if (!member) return;
				if (member.index.value === -1) {
					throw new Error('unset index');
				}
				const value = /** @type {number} */ (member.index.value);
				const i = (value / 31) | 0;
				const n = 1 << value % 31;
				if (!bitmask[i]) bitmask[i] = { n: 0, names: [] };
				bitmask[i].n |= n;
				bitmask[i].names.push(name);
			});
			return bitmask;
		};
		// TODO: context-overflow make it less gross
		return /** @type {any} */ ({
			// Using a ParenthesizedExpression allows us to create
			// the expression lazily. TODO would be better if
			// context was determined before rendering, so that
			// this indirection was unnecessary
			type: 'ParenthesizedExpression',
			get expression() {
				const bitmask = get_bitmask();
				if (!bitmask.length) {
					return /** @type {import('estree').BinaryExpression} */ (
						x$1`${dirty} & /*${names.join(', ')}*/ 0`
					);
				}
				if (renderer.context_overflow) {
					return bitmask
						.map((b, i) => ({ b, i }))
						.filter(({ b }) => b)
						.map(({ b, i }) => x$1`${dirty}[${i}] & /*${b.names.join(', ')}*/ ${b.n}`)
						.reduce((lhs, rhs) => x$1`${lhs} | ${rhs}`);
				}
				return /** @type {import('estree').BinaryExpression} */ (
					x$1`${dirty} & /*${names.join(', ')}*/ ${bitmask[0].n}`
				);
			}
		});
	}
	// NOTE: this method may be called before this.context_overflow / this.context is fully defined
	// therefore, they can only be evaluated later in a getter function

	/** @returns {import('estree').UnaryExpression | import('estree').ArrayExpression} */
	get_initial_dirty() {
		const _this = this;
		// TODO: context-overflow make it less gross

		/** @type {import('estree').UnaryExpression} */
		const val = /** @type {import('estree').UnaryExpression} */ (x$1`-1`);
		return {
			get type() {
				return _this.context_overflow ? 'ArrayExpression' : 'UnaryExpression';
			},
			// as [-1]
			get elements() {
				const elements = [];
				for (let i = 0; i < _this.context.length; i += 31) {
					elements.push(val);
				}
				return elements;
			},
			// as -1
			operator: val.operator,
			prefix: val.prefix,
			argument: val.argument
		};
	}

	/**
	 * @param {string | import('estree').Identifier | import('estree').MemberExpression} node
	 * @param {string | void} ctx
	 */
	reference(node, ctx = '#ctx') {
		if (typeof node === 'string') {
			node = { type: 'Identifier', name: node };
		}
		const { name, nodes } = flatten_reference(node);
		const member = this.context_lookup.get(name);
		// TODO is this correct?
		if (this.component.var_lookup.get(name)) {
			this.component.add_reference(node, name);
		}
		if (member !== undefined) {
			const replacement = /** @type {import('estree').MemberExpression} */ (
				x$1`/*${member.name}*/ ${ctx}[${member.index}]`
			);
			if (nodes[0].loc) replacement.object.loc = nodes[0].loc;
			nodes[0] = replacement;
			return nodes.reduce((lhs, rhs) => x$1`${lhs}.${rhs}`);
		}
		return node;
	}

	/** @param {import('./Block.js').default | import('estree').Node | import('estree').Node[]} block */
	remove_block(block) {
		this.blocks.splice(this.blocks.indexOf(block), 1);
	}
};

/**
 * @typedef {Object} BindingGroup
 * @property {(to_reference?:boolean)=>import('estree').Node} binding_group
 * @property {string[]} contexts
 * @property {Set<string>} list_dependencies
 * @property {string} keypath
 * @property {(block:Block,element:import('estree').PrivateIdentifier) => void} add_element
 * @property {(block:Block)=>void} render
 */

const comma = ','.charCodeAt(0);
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
const intToChar = new Uint8Array(64); // 64 possible chars.
const charToInt = new Uint8Array(128); // z is 122 in ASCII
for (let i = 0; i < chars.length; i++) {
    const c = chars.charCodeAt(i);
    intToChar[i] = c;
    charToInt[c] = i;
}
function decode(mappings) {
    const state = new Int32Array(5);
    const decoded = [];
    let index = 0;
    do {
        const semi = indexOf(mappings, index);
        const line = [];
        let sorted = true;
        let lastCol = 0;
        state[0] = 0;
        for (let i = index; i < semi; i++) {
            let seg;
            i = decodeInteger(mappings, i, state, 0); // genColumn
            const col = state[0];
            if (col < lastCol)
                sorted = false;
            lastCol = col;
            if (hasMoreVlq(mappings, i, semi)) {
                i = decodeInteger(mappings, i, state, 1); // sourcesIndex
                i = decodeInteger(mappings, i, state, 2); // sourceLine
                i = decodeInteger(mappings, i, state, 3); // sourceColumn
                if (hasMoreVlq(mappings, i, semi)) {
                    i = decodeInteger(mappings, i, state, 4); // namesIndex
                    seg = [col, state[1], state[2], state[3], state[4]];
                }
                else {
                    seg = [col, state[1], state[2], state[3]];
                }
            }
            else {
                seg = [col];
            }
            line.push(seg);
        }
        if (!sorted)
            sort(line);
        decoded.push(line);
        index = semi + 1;
    } while (index <= mappings.length);
    return decoded;
}
function indexOf(mappings, index) {
    const idx = mappings.indexOf(';', index);
    return idx === -1 ? mappings.length : idx;
}
function decodeInteger(mappings, pos, state, j) {
    let value = 0;
    let shift = 0;
    let integer = 0;
    do {
        const c = mappings.charCodeAt(pos++);
        integer = charToInt[c];
        value |= (integer & 31) << shift;
        shift += 5;
    } while (integer & 32);
    const shouldNegate = value & 1;
    value >>>= 1;
    if (shouldNegate) {
        value = -0x80000000 | -value;
    }
    state[j] += value;
    return pos;
}
function hasMoreVlq(mappings, i, length) {
    if (i >= length)
        return false;
    return mappings.charCodeAt(i) !== comma;
}
function sort(line) {
    line.sort(sortComparator$1);
}
function sortComparator$1(a, b) {
    return a[0] - b[0];
}

// Matches the scheme of a URL, eg "http://"
const schemeRegex = /^[\w+.-]+:\/\//;
/**
 * Matches the parts of a URL:
 * 1. Scheme, including ":", guaranteed.
 * 2. User/password, including "@", optional.
 * 3. Host, guaranteed.
 * 4. Port, including ":", optional.
 * 5. Path, including "/", optional.
 * 6. Query, including "?", optional.
 * 7. Hash, including "#", optional.
 */
const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
/**
 * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
 * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
 *
 * 1. Host, optional.
 * 2. Path, which may include "/", guaranteed.
 * 3. Query, including "?", optional.
 * 4. Hash, including "#", optional.
 */
const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
var UrlType;
(function (UrlType) {
    UrlType[UrlType["Empty"] = 1] = "Empty";
    UrlType[UrlType["Hash"] = 2] = "Hash";
    UrlType[UrlType["Query"] = 3] = "Query";
    UrlType[UrlType["RelativePath"] = 4] = "RelativePath";
    UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath";
    UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative";
    UrlType[UrlType["Absolute"] = 7] = "Absolute";
})(UrlType || (UrlType = {}));
function isAbsoluteUrl(input) {
    return schemeRegex.test(input);
}
function isSchemeRelativeUrl(input) {
    return input.startsWith('//');
}
function isAbsolutePath(input) {
    return input.startsWith('/');
}
function isFileUrl(input) {
    return input.startsWith('file:');
}
function isRelative(input) {
    return /^[.?#]/.test(input);
}
function parseAbsoluteUrl(input) {
    const match = urlRegex.exec(input);
    return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || '');
}
function parseFileUrl(input) {
    const match = fileRegex.exec(input);
    const path = match[2];
    return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || '');
}
function makeUrl(scheme, user, host, port, path, query, hash) {
    return {
        scheme,
        user,
        host,
        port,
        path,
        query,
        hash,
        type: UrlType.Absolute,
    };
}
function parseUrl(input) {
    if (isSchemeRelativeUrl(input)) {
        const url = parseAbsoluteUrl('http:' + input);
        url.scheme = '';
        url.type = UrlType.SchemeRelative;
        return url;
    }
    if (isAbsolutePath(input)) {
        const url = parseAbsoluteUrl('http://foo.com' + input);
        url.scheme = '';
        url.host = '';
        url.type = UrlType.AbsolutePath;
        return url;
    }
    if (isFileUrl(input))
        return parseFileUrl(input);
    if (isAbsoluteUrl(input))
        return parseAbsoluteUrl(input);
    const url = parseAbsoluteUrl('http://foo.com/' + input);
    url.scheme = '';
    url.host = '';
    url.type = input
        ? input.startsWith('?')
            ? UrlType.Query
            : input.startsWith('#')
                ? UrlType.Hash
                : UrlType.RelativePath
        : UrlType.Empty;
    return url;
}
function stripPathFilename(path) {
    // If a path ends with a parent directory "..", then it's a relative path with excess parent
    // paths. It's not a file, so we can't strip it.
    if (path.endsWith('/..'))
        return path;
    const index = path.lastIndexOf('/');
    return path.slice(0, index + 1);
}
function mergePaths(url, base) {
    normalizePath(base, base.type);
    // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative
    // path).
    if (url.path === '/') {
        url.path = base.path;
    }
    else {
        // Resolution happens relative to the base path's directory, not the file.
        url.path = stripPathFilename(base.path) + url.path;
    }
}
/**
 * The path can have empty directories "//", unneeded parents "foo/..", or current directory
 * "foo/.". We need to normalize to a standard representation.
 */
function normalizePath(url, type) {
    const rel = type <= UrlType.RelativePath;
    const pieces = url.path.split('/');
    // We need to preserve the first piece always, so that we output a leading slash. The item at
    // pieces[0] is an empty string.
    let pointer = 1;
    // Positive is the number of real directories we've output, used for popping a parent directory.
    // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo".
    let positive = 0;
    // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will
    // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a
    // real directory, we won't need to append, unless the other conditions happen again.
    let addTrailingSlash = false;
    for (let i = 1; i < pieces.length; i++) {
        const piece = pieces[i];
        // An empty directory, could be a trailing slash, or just a double "//" in the path.
        if (!piece) {
            addTrailingSlash = true;
            continue;
        }
        // If we encounter a real directory, then we don't need to append anymore.
        addTrailingSlash = false;
        // A current directory, which we can always drop.
        if (piece === '.')
            continue;
        // A parent directory, we need to see if there are any real directories we can pop. Else, we
        // have an excess of parents, and we'll need to keep the "..".
        if (piece === '..') {
            if (positive) {
                addTrailingSlash = true;
                positive--;
                pointer--;
            }
            else if (rel) {
                // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute
                // URL, protocol relative URL, or an absolute path, we don't need to keep excess.
                pieces[pointer++] = piece;
            }
            continue;
        }
        // We've encountered a real directory. Move it to the next insertion pointer, which accounts for
        // any popped or dropped directories.
        pieces[pointer++] = piece;
        positive++;
    }
    let path = '';
    for (let i = 1; i < pointer; i++) {
        path += '/' + pieces[i];
    }
    if (!path || (addTrailingSlash && !path.endsWith('/..'))) {
        path += '/';
    }
    url.path = path;
}
/**
 * Attempts to resolve `input` URL/path relative to `base`.
 */
function resolve$1(input, base) {
    if (!input && !base)
        return '';
    const url = parseUrl(input);
    let inputType = url.type;
    if (base && inputType !== UrlType.Absolute) {
        const baseUrl = parseUrl(base);
        const baseType = baseUrl.type;
        switch (inputType) {
            case UrlType.Empty:
                url.hash = baseUrl.hash;
            // fall through
            case UrlType.Hash:
                url.query = baseUrl.query;
            // fall through
            case UrlType.Query:
            case UrlType.RelativePath:
                mergePaths(url, baseUrl);
            // fall through
            case UrlType.AbsolutePath:
                // The host, user, and port are joined, you can't copy one without the others.
                url.user = baseUrl.user;
                url.host = baseUrl.host;
                url.port = baseUrl.port;
            // fall through
            case UrlType.SchemeRelative:
                // The input doesn't have a schema at least, so we need to copy at least that over.
                url.scheme = baseUrl.scheme;
        }
        if (baseType > inputType)
            inputType = baseType;
    }
    normalizePath(url, inputType);
    const queryHash = url.query + url.hash;
    switch (inputType) {
        // This is impossible, because of the empty checks at the start of the function.
        // case UrlType.Empty:
        case UrlType.Hash:
        case UrlType.Query:
            return queryHash;
        case UrlType.RelativePath: {
            // The first char is always a "/", and we need it to be relative.
            const path = url.path.slice(1);
            if (!path)
                return queryHash || '.';
            if (isRelative(base || input) && !isRelative(path)) {
                // If base started with a leading ".", or there is no base and input started with a ".",
                // then we need to ensure that the relative path starts with a ".". We don't know if
                // relative starts with a "..", though, so check before prepending.
                return './' + path + queryHash;
            }
            return path + queryHash;
        }
        case UrlType.AbsolutePath:
            return url.path + queryHash;
        default:
            return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;
    }
}

function resolve(input, base) {
    // The base is always treated as a directory, if it's not empty.
    // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327
    // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401
    if (base && !base.endsWith('/'))
        base += '/';
    return resolve$1(input, base);
}

/**
 * Removes everything after the last "/", but leaves the slash.
 */
function stripFilename(path) {
    if (!path)
        return '';
    const index = path.lastIndexOf('/');
    return path.slice(0, index + 1);
}

const COLUMN$1 = 0;
const SOURCES_INDEX$1 = 1;
const SOURCE_LINE$1 = 2;
const SOURCE_COLUMN$1 = 3;
const NAMES_INDEX$1 = 4;

function maybeSort(mappings, owned) {
    const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
    if (unsortedIndex === mappings.length)
        return mappings;
    // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If
    // not, we do not want to modify the consumer's input array.
    if (!owned)
        mappings = mappings.slice();
    for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
        mappings[i] = sortSegments(mappings[i], owned);
    }
    return mappings;
}
function nextUnsortedSegmentLine(mappings, start) {
    for (let i = start; i < mappings.length; i++) {
        if (!isSorted(mappings[i]))
            return i;
    }
    return mappings.length;
}
function isSorted(line) {
    for (let j = 1; j < line.length; j++) {
        if (line[j][COLUMN$1] < line[j - 1][COLUMN$1]) {
            return false;
        }
    }
    return true;
}
function sortSegments(line, owned) {
    if (!owned)
        line = line.slice();
    return line.sort(sortComparator);
}
function sortComparator(a, b) {
    return a[COLUMN$1] - b[COLUMN$1];
}

let found = false;
/**
 * A binary search implementation that returns the index if a match is found.
 * If no match is found, then the left-index (the index associated with the item that comes just
 * before the desired index) is returned. To maintain proper sort order, a splice would happen at
 * the next index:
 *
 * ```js
 * const array = [1, 3];
 * const needle = 2;
 * const index = binarySearch(array, needle, (item, needle) => item - needle);
 *
 * assert.equal(index, 0);
 * array.splice(index + 1, 0, needle);
 * assert.deepEqual(array, [1, 2, 3]);
 * ```
 */
function binarySearch(haystack, needle, low, high) {
    while (low <= high) {
        const mid = low + ((high - low) >> 1);
        const cmp = haystack[mid][COLUMN$1] - needle;
        if (cmp === 0) {
            found = true;
            return mid;
        }
        if (cmp < 0) {
            low = mid + 1;
        }
        else {
            high = mid - 1;
        }
    }
    found = false;
    return low - 1;
}
function upperBound(haystack, needle, index) {
    for (let i = index + 1; i < haystack.length; index = i++) {
        if (haystack[i][COLUMN$1] !== needle)
            break;
    }
    return index;
}
function lowerBound(haystack, needle, index) {
    for (let i = index - 1; i >= 0; index = i--) {
        if (haystack[i][COLUMN$1] !== needle)
            break;
    }
    return index;
}
function memoizedState() {
    return {
        lastKey: -1,
        lastNeedle: -1,
        lastIndex: -1,
    };
}
/**
 * This overly complicated beast is just to record the last tested line/column and the resulting
 * index, allowing us to skip a few tests if mappings are monotonically increasing.
 */
function memoizedBinarySearch(haystack, needle, state, key) {
    const { lastKey, lastNeedle, lastIndex } = state;
    let low = 0;
    let high = haystack.length - 1;
    if (key === lastKey) {
        if (needle === lastNeedle) {
            found = lastIndex !== -1 && haystack[lastIndex][COLUMN$1] === needle;
            return lastIndex;
        }
        if (needle >= lastNeedle) {
            // lastIndex may be -1 if the previous needle was not found.
            low = lastIndex === -1 ? 0 : lastIndex;
        }
        else {
            high = lastIndex;
        }
    }
    state.lastKey = key;
    state.lastNeedle = needle;
    return (state.lastIndex = binarySearch(haystack, needle, low, high));
}

const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';
const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';
const LEAST_UPPER_BOUND = -1;
const GREATEST_LOWER_BOUND = 1;
/**
 * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
 */
let decodedMappings;
/**
 * A low-level API to find the segment associated with a generated line/column (think, from a
 * stack trace). Line and column here are 0-based, unlike `originalPositionFor`.
 */
let traceSegment;
/**
 * A higher-level API to find the source/line/column associated with a generated line/column
 * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in
 * `source-map` library.
 */
let originalPositionFor$1;
class TraceMap {
    constructor(map, mapUrl) {
        const isString = typeof map === 'string';
        if (!isString && map._decodedMemo)
            return map;
        const parsed = (isString ? JSON.parse(map) : map);
        const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
        this.version = version;
        this.file = file;
        this.names = names;
        this.sourceRoot = sourceRoot;
        this.sources = sources;
        this.sourcesContent = sourcesContent;
        const from = resolve(sourceRoot || '', stripFilename(mapUrl));
        this.resolvedSources = sources.map((s) => resolve(s || '', from));
        const { mappings } = parsed;
        if (typeof mappings === 'string') {
            this._encoded = mappings;
            this._decoded = undefined;
        }
        else {
            this._encoded = undefined;
            this._decoded = maybeSort(mappings, isString);
        }
        this._decodedMemo = memoizedState();
        this._bySources = undefined;
        this._bySourceMemos = undefined;
    }
}
(() => {
    decodedMappings = (map) => {
        return (map._decoded || (map._decoded = decode(map._encoded)));
    };
    traceSegment = (map, line, column) => {
        const decoded = decodedMappings(map);
        // It's common for parent source maps to have pointers to lines that have no
        // mapping (like a "//# sourceMappingURL=") at the end of the child file.
        if (line >= decoded.length)
            return null;
        const segments = decoded[line];
        const index = traceSegmentInternal(segments, map._decodedMemo, line, column, GREATEST_LOWER_BOUND);
        return index === -1 ? null : segments[index];
    };
    originalPositionFor$1 = (map, { line, column, bias }) => {
        line--;
        if (line < 0)
            throw new Error(LINE_GTR_ZERO);
        if (column < 0)
            throw new Error(COL_GTR_EQ_ZERO);
        const decoded = decodedMappings(map);
        // It's common for parent source maps to have pointers to lines that have no
        // mapping (like a "//# sourceMappingURL=") at the end of the child file.
        if (line >= decoded.length)
            return OMapping(null, null, null, null);
        const segments = decoded[line];
        const index = traceSegmentInternal(segments, map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
        if (index === -1)
            return OMapping(null, null, null, null);
        const segment = segments[index];
        if (segment.length === 1)
            return OMapping(null, null, null, null);
        const { names, resolvedSources } = map;
        return OMapping(resolvedSources[segment[SOURCES_INDEX$1]], segment[SOURCE_LINE$1] + 1, segment[SOURCE_COLUMN$1], segment.length === 5 ? names[segment[NAMES_INDEX$1]] : null);
    };
})();
function OMapping(source, line, column, name) {
    return { source, line, column, name };
}
function traceSegmentInternal(segments, memo, line, column, bias) {
    let index = memoizedBinarySearch(segments, column, memo, line);
    if (found) {
        index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
    }
    else if (bias === LEAST_UPPER_BOUND)
        index++;
    if (index === -1 || index === segments.length)
        return -1;
    return index;
}

/**
 * Gets the index associated with `key` in the backing array, if it is already present.
 */
let get;
/**
 * Puts `key` into the backing array, if it is not already present. Returns
 * the index of the `key` in the backing array.
 */
let put;
/**
 * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the
 * index of the `key` in the backing array.
 *
 * This is designed to allow synchronizing a second array with the contents of the backing array,
 * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`,
 * and there are never duplicates.
 */
class SetArray {
    constructor() {
        this._indexes = { __proto__: null };
        this.array = [];
    }
}
(() => {
    get = (strarr, key) => strarr._indexes[key];
    put = (strarr, key) => {
        // The key may or may not be present. If it is present, it's a number.
        const index = get(strarr, key);
        if (index !== undefined)
            return index;
        const { array, _indexes: indexes } = strarr;
        return (indexes[key] = array.push(key) - 1);
    };
})();

const COLUMN = 0;
const SOURCES_INDEX = 1;
const SOURCE_LINE = 2;
const SOURCE_COLUMN = 3;
const NAMES_INDEX = 4;

const NO_NAME = -1;
/**
 * Same as `addSegment`, but will only add the segment if it generates useful information in the
 * resulting map. This only works correctly if segments are added **in order**, meaning you should
 * not add a segment with a lower generated line/column than one that came before.
 */
let maybeAddSegment;
/**
 * Adds/removes the content of the source file to the source map.
 */
let setSourceContent;
/**
 * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects
 * a sourcemap, or to JSON.stringify.
 */
let toDecodedMap;
/**
 * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects
 * a sourcemap, or to JSON.stringify.
 */
let toEncodedMap;
// This split declaration is only so that terser can elminiate the static initialization block.
let addSegmentInternal;
/**
 * Provides the state to generate a sourcemap.
 */
class GenMapping {
    constructor({ file, sourceRoot } = {}) {
        this._names = new SetArray();
        this._sources = new SetArray();
        this._sourcesContent = [];
        this._mappings = [];
        this.file = file;
        this.sourceRoot = sourceRoot;
    }
}
(() => {
    maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
        return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content);
    };
    setSourceContent = (map, source, content) => {
        const { _sources: sources, _sourcesContent: sourcesContent } = map;
        sourcesContent[put(sources, source)] = content;
    };
    toDecodedMap = (map) => {
        const { file, sourceRoot, _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map;
        removeEmptyFinalLines(mappings);
        return {
            version: 3,
            file: file || undefined,
            names: names.array,
            sourceRoot: sourceRoot || undefined,
            sources: sources.array,
            sourcesContent,
            mappings,
        };
    };
    toEncodedMap = (map) => {
        const decoded = toDecodedMap(map);
        return Object.assign(Object.assign({}, decoded), { mappings: encode(decoded.mappings) });
    };
    // Internal helpers
    addSegmentInternal = (skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
        const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map;
        const line = getLine(mappings, genLine);
        const index = getColumnIndex(line, genColumn);
        if (!source) {
            if (skipable && skipSourceless(line, index))
                return;
            return insert(line, index, [genColumn]);
        }
        const sourcesIndex = put(sources, source);
        const namesIndex = name ? put(names, name) : NO_NAME;
        if (sourcesIndex === sourcesContent.length)
            sourcesContent[sourcesIndex] = content !== null && content !== void 0 ? content : null;
        if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {
            return;
        }
        return insert(line, index, name
            ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]
            : [genColumn, sourcesIndex, sourceLine, sourceColumn]);
    };
})();
function getLine(mappings, index) {
    for (let i = mappings.length; i <= index; i++) {
        mappings[i] = [];
    }
    return mappings[index];
}
function getColumnIndex(line, genColumn) {
    let index = line.length;
    for (let i = index - 1; i >= 0; index = i--) {
        const current = line[i];
        if (genColumn >= current[COLUMN])
            break;
    }
    return index;
}
function insert(array, index, value) {
    for (let i = array.length; i > index; i--) {
        array[i] = array[i - 1];
    }
    array[index] = value;
}
function removeEmptyFinalLines(mappings) {
    const { length } = mappings;
    let len = length;
    for (let i = len - 1; i >= 0; len = i, i--) {
        if (mappings[i].length > 0)
            break;
    }
    if (len < length)
        mappings.length = len;
}
function skipSourceless(line, index) {
    // The start of a line is already sourceless, so adding a sourceless segment to the beginning
    // doesn't generate any useful information.
    if (index === 0)
        return true;
    const prev = line[index - 1];
    // If the previous segment is also sourceless, then adding another sourceless segment doesn't
    // genrate any new information. Else, this segment will end the source/named segment and point to
    // a sourceless position, which is useful.
    return prev.length === 1;
}
function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
    // A source/named segment at the start of a line gives position at that genColumn
    if (index === 0)
        return false;
    const prev = line[index - 1];
    // If the previous segment is sourceless, then we're transitioning to a source.
    if (prev.length === 1)
        return false;
    // If the previous segment maps to the exact same source position, then this segment doesn't
    // provide any new position information.
    return (sourcesIndex === prev[SOURCES_INDEX] &&
        sourceLine === prev[SOURCE_LINE] &&
        sourceColumn === prev[SOURCE_COLUMN] &&
        namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME));
}

const SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null);
const EMPTY_SOURCES = [];
function SegmentObject(source, line, column, name, content) {
    return { source, line, column, name, content };
}
function Source(map, sources, source, content) {
    return {
        map,
        sources,
        source,
        content,
    };
}
/**
 * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes
 * (which may themselves be SourceMapTrees).
 */
function MapSource(map, sources) {
    return Source(map, sources, '', null);
}
/**
 * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive
 * segment tracing ends at the `OriginalSource`.
 */
function OriginalSource(source, content) {
    return Source(null, EMPTY_SOURCES, source, content);
}
/**
 * traceMappings is only called on the root level SourceMapTree, and begins the process of
 * resolving each mapping in terms of the original source files.
 */
function traceMappings(tree) {
    // TODO: Eventually support sourceRoot, which has to be removed because the sources are already
    // fully resolved. We'll need to make sources relative to the sourceRoot before adding them.
    const gen = new GenMapping({ file: tree.map.file });
    const { sources: rootSources, map } = tree;
    const rootNames = map.names;
    const rootMappings = decodedMappings(map);
    for (let i = 0; i < rootMappings.length; i++) {
        const segments = rootMappings[i];
        for (let j = 0; j < segments.length; j++) {
            const segment = segments[j];
            const genCol = segment[0];
            let traced = SOURCELESS_MAPPING;
            // 1-length segments only move the current generated column, there's no source information
            // to gather from it.
            if (segment.length !== 1) {
                const source = rootSources[segment[1]];
                traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : '');
                // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a
                // respective segment into an original source.
                if (traced == null)
                    continue;
            }
            const { column, line, name, content, source } = traced;
            maybeAddSegment(gen, i, genCol, source, line, column, name);
            if (source && content != null)
                setSourceContent(gen, source, content);
        }
    }
    return gen;
}
/**
 * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own
 * child SourceMapTrees, until we find the original source map.
 */
function originalPositionFor(source, line, column, name) {
    if (!source.map) {
        return SegmentObject(source.source, line, column, name, source.content);
    }
    const segment = traceSegment(source.map, line, column);
    // If we couldn't find a segment, then this doesn't exist in the sourcemap.
    if (segment == null)
        return null;
    // 1-length segments only move the current generated column, there's no source information
    // to gather from it.
    if (segment.length === 1)
        return SOURCELESS_MAPPING;
    return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name);
}

function asArray(value) {
    if (Array.isArray(value))
        return value;
    return [value];
}
/**
 * Recursively builds a tree structure out of sourcemap files, with each node
 * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of
 * `OriginalSource`s and `SourceMapTree`s.
 *
 * Every sourcemap is composed of a collection of source files and mappings
 * into locations of those source files. When we generate a `SourceMapTree` for
 * the sourcemap, we attempt to load each source file's own sourcemap. If it
 * does not have an associated sourcemap, it is considered an original,
 * unmodified source file.
 */
function buildSourceMapTree(input, loader) {
    const maps = asArray(input).map((m) => new TraceMap(m, ''));
    const map = maps.pop();
    for (let i = 0; i < maps.length; i++) {
        if (maps[i].sources.length > 1) {
            throw new Error(`Transformation map ${i} must have exactly one source file.\n` +
                'Did you specify these with the most recent transformation maps first?');
        }
    }
    let tree = build(map, loader, '', 0);
    for (let i = maps.length - 1; i >= 0; i--) {
        tree = MapSource(maps[i], [tree]);
    }
    return tree;
}
function build(map, loader, importer, importerDepth) {
    const { resolvedSources, sourcesContent } = map;
    const depth = importerDepth + 1;
    const children = resolvedSources.map((sourceFile, i) => {
        // The loading context gives the loader more information about why this file is being loaded
        // (eg, from which importer). It also allows the loader to override the location of the loaded
        // sourcemap/original source, or to override the content in the sourcesContent field if it's
        // an unmodified source file.
        const ctx = {
            importer,
            depth,
            source: sourceFile || '',
            content: undefined,
        };
        // Use the provided loader callback to retrieve the file's sourcemap.
        // TODO: We should eventually support async loading of sourcemap files.
        const sourceMap = loader(ctx.source, ctx);
        const { source, content } = ctx;
        // If there is a sourcemap, then we need to recurse into it to load its source files.
        if (sourceMap)
            return build(new TraceMap(sourceMap, source), loader, source, depth);
        // Else, it's an an unmodified source file.
        // The contents of this unmodified source file can be overridden via the loader context,
        // allowing it to be explicitly null or a string. If it remains undefined, we fall back to
        // the importing sourcemap's `sourcesContent` field.
        const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null;
        return OriginalSource(source, sourceContent);
    });
    return MapSource(map, children);
}

/**
 * A SourceMap v3 compatible sourcemap, which only includes fields that were
 * provided to it.
 */
let SourceMap$1 = class SourceMap {
    constructor(map, options) {
        const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);
        this.version = out.version; // SourceMap spec says this should be first.
        this.file = out.file;
        this.mappings = out.mappings;
        this.names = out.names;
        this.sourceRoot = out.sourceRoot;
        this.sources = out.sources;
        if (!options.excludeContent) {
            this.sourcesContent = out.sourcesContent;
        }
    }
    toString() {
        return JSON.stringify(this);
    }
};

/**
 * Traces through all the mappings in the root sourcemap, through the sources
 * (and their sourcemaps), all the way back to the original source location.
 *
 * `loader` will be called every time we encounter a source file. If it returns
 * a sourcemap, we will recurse into that sourcemap to continue the trace. If
 * it returns a falsey value, that source file is treated as an original,
 * unmodified source file.
 *
 * Pass `excludeContent` to exclude any self-containing source file content
 * from the output sourcemap.
 *
 * Pass `decodedMappings` to receive a SourceMap with decoded (instead of
 * VLQ encoded) mappings.
 */
function remapping(input, loader, options) {
    const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false };
    const tree = buildSourceMapTree(input, loader);
    return new SourceMap$1(traceMappings(tree), opts);
}

/**
 * @param {string} s
 */
function last_line_length(s) {
	return s.length - s.lastIndexOf('\n') - 1;
}
// mutate map in-place

/**
 * @param {import('@ampproject/remapping').DecodedSourceMap} map
 * @param {{ line: number; column: number; }} offset
 * @param {number} source_index
 */
function sourcemap_add_offset(map, offset, source_index) {
	if (map.mappings.length == 0) return;
	for (let line = 0; line < map.mappings.length; line++) {
		const segment_list = map.mappings[line];
		for (let segment = 0; segment < segment_list.length; segment++) {
			const seg = segment_list[segment];
			// shift only segments that belong to component source file
			if (seg[1] === source_index) {
				// also ensures that seg.length >= 4
				// shift column if it points at the first line
				if (seg[2] === 0) {
					seg[3] += offset.column;
				}
				// shift line
				seg[2] += offset.line;
			}
		}
	}
}

/**
 * @template T
 * @param {T[]} this_table
 * @param {T[]} other_table
 * @returns {[T[], number[], boolean, boolean]}
 */
function merge_tables(this_table, other_table) {
	const new_table = this_table.slice();
	const idx_map = [];
	other_table = other_table || [];
	let val_changed = false;
	for (const [other_idx, other_val] of other_table.entries()) {
		const this_idx = this_table.indexOf(other_val);
		if (this_idx >= 0) {
			idx_map[other_idx] = this_idx;
		} else {
			const new_idx = new_table.length;
			new_table[new_idx] = other_val;
			idx_map[other_idx] = new_idx;
			val_changed = true;
		}
	}
	let idx_changed = val_changed;
	if (val_changed) {
		if (idx_map.find((val, idx) => val != idx) === undefined) {
			// idx_map is identity map [0, 1, 2, 3, 4, ....]
			idx_changed = false;
		}
	}
	return [new_table, idx_map, val_changed, idx_changed];
}
const regex_line_token = /([^\d\w\s]|\s+)/g;
/** */
class MappedCode {
	/**
	 * @type {string}
	 */
	string = undefined;

	/**
	 * @type {import('@ampproject/remapping').DecodedSourceMap}
	 */
	map = undefined;
	constructor(string = '', map = null) {
		this.string = string;
		if (map) {
			this.map = map;
		} else {
			this.map = {
				version: 3,
				mappings: [],
				sources: [],
				names: []
			};
		}
	}
	/**
	 * concat in-place (mutable), return this (chainable)
	 * will also mutate the `other` object
	 * @param {MappedCode} other
	 * @returns {MappedCode}
	 */
	concat(other) {
		// noop: if one is empty, return the other
		if (other.string == '') return this;
		if (this.string == '') {
			this.string = other.string;
			this.map = other.map;
			return this;
		}
		// compute last line length before mutating
		const column_offset = last_line_length(this.string);
		this.string += other.string;
		const m1 = this.map;
		const m2 = other.map;
		if (m2.mappings.length == 0) return this;
		// combine sources and names
		const [sources, new_source_idx, sources_changed, sources_idx_changed] = merge_tables(
			m1.sources,
			m2.sources
		);
		const [names, new_name_idx, names_changed, names_idx_changed] = merge_tables(
			m1.names,
			m2.names
		);
		if (sources_changed) m1.sources = sources;
		if (names_changed) m1.names = names;
		// unswitched loops are faster
		if (sources_idx_changed && names_idx_changed) {
			for (let line = 0; line < m2.mappings.length; line++) {
				const segment_list = m2.mappings[line];
				for (let segment = 0; segment < segment_list.length; segment++) {
					const seg = segment_list[segment];
					if (seg[1] >= 0) seg[1] = new_source_idx[seg[1]];
					if (seg[4] >= 0) seg[4] = new_name_idx[seg[4]];
				}
			}
		} else if (sources_idx_changed) {
			for (let line = 0; line < m2.mappings.length; line++) {
				const segment_list = m2.mappings[line];
				for (let segment = 0; segment < segment_list.length; segment++) {
					const seg = segment_list[segment];
					if (seg[1] >= 0) seg[1] = new_source_idx[seg[1]];
				}
			}
		} else if (names_idx_changed) {
			for (let line = 0; line < m2.mappings.length; line++) {
				const segment_list = m2.mappings[line];
				for (let segment = 0; segment < segment_list.length; segment++) {
					const seg = segment_list[segment];
					if (seg[4] >= 0) seg[4] = new_name_idx[seg[4]];
				}
			}
		}
		// combine the mappings
		// combine
		// 1. last line of first map
		// 2. first line of second map
		// columns of 2 must be shifted
		if (m2.mappings.length > 0 && column_offset > 0) {
			const first_line = m2.mappings[0];
			for (let i = 0; i < first_line.length; i++) {
				first_line[i][0] += column_offset;
			}
		}
		// combine last line + first line
		push_array(m1.mappings[m1.mappings.length - 1], m2.mappings.shift());
		// append other lines
		push_array(m1.mappings, m2.mappings);
		return this;
	}

	/**
	 * @static
	 * @param {string} string
	 * @param {import('@ampproject/remapping').DecodedSourceMap} [map]
	 * @returns {MappedCode}
	 */
	static from_processed(string, map) {
		const line_count = string.split('\n').length;
		if (map) {
			// ensure that count of source map mappings lines
			// is equal to count of generated code lines
			// (some tools may produce less)
			const missing_lines = line_count - map.mappings.length;
			for (let i = 0; i < missing_lines; i++) {
				map.mappings.push([]);
			}
			return new MappedCode(string, map);
		}
		if (string == '') return new MappedCode();
		map = { version: 3, names: [], sources: [], mappings: [] };
		// add empty SourceMapSegment[] for every line
		for (let i = 0; i < line_count; i++) map.mappings.push([]);
		return new MappedCode(string, map);
	}

	/**
	 * @static
	 * @param {import('../preprocess/private.js').Source} opts
	 * @returns {MappedCode}
	 */
	static from_source({ source, file_basename, get_location }) {
		/**
		 * @type {{ line: number; column: number; }}
		 */
		let offset = get_location(0);
		if (!offset) offset = { line: 0, column: 0 };

		/**
		 * @type {import('@ampproject/remapping').DecodedSourceMap}
		 */
		const map = { version: 3, names: [], sources: [file_basename], mappings: [] };
		if (source == '') return new MappedCode(source, map);
		// we create a high resolution identity map here,
		// we know that it will eventually be merged with svelte's map,
		// at which stage the resolution will decrease.
		const line_list = source.split('\n');
		for (let line = 0; line < line_list.length; line++) {
			map.mappings.push([]);
			const token_list = line_list[line].split(regex_line_token);
			for (let token = 0, column = 0; token < token_list.length; token++) {
				if (token_list[token] == '') continue;
				map.mappings[line].push([column, 0, offset.line + line, column]);
				column += token_list[token].length;
			}
		}
		// shift columns in first line
		const segment_list = map.mappings[0];
		for (let segment = 0; segment < segment_list.length; segment++) {
			segment_list[segment][3] += offset.column;
		}
		return new MappedCode(source, map);
	}
}

/**
 * @param {string} filename
 * @param {Array<import('@ampproject/remapping').DecodedSourceMap | import('@ampproject/remapping').RawSourceMap>} sourcemap_list
 */
function combine_sourcemaps(filename, sourcemap_list) {
	if (sourcemap_list.length == 0) return null;
	let map_idx = 1;
	const map =
		sourcemap_list.slice(0, -1).find((m) => m.sources.length !== 1) === undefined
			? remapping(
					// use array interface
					// only the oldest sourcemap can have multiple sources
					sourcemap_list,
					() => null,
					true // skip optional field `sourcesContent`
			  )
			: remapping(
					// use loader interface
					sourcemap_list[0], // last map
					(sourcefile) => {
						if (sourcefile === filename && sourcemap_list[map_idx]) {
							return sourcemap_list[map_idx++]; // idx 1, 2, ...
							// bundle file = branch node
						} else {
							return null; // source file = leaf node
						}
					},
					true
			  );
	if (!map.file) delete map.file; // skip optional field `file`
	// When source maps are combined and the leading map is empty, sources is not set.
	// Add the filename to the empty array in this case.
	// Further improvements to remapping may help address this as well https://github.com/ampproject/remapping/issues/116
	if (!map.sources.length) map.sources = [filename];
	return map;
}

/**
 * @param {string} filename
 * @param {import('magic-string').SourceMap} svelte_map
 * @param {string | import('@ampproject/remapping').DecodedSourceMap | import('@ampproject/remapping').RawSourceMap} preprocessor_map_input
 * @returns {import('magic-string').SourceMap}
 */
function apply_preprocessor_sourcemap(filename, svelte_map, preprocessor_map_input) {
	if (!svelte_map || !preprocessor_map_input) return svelte_map;
	const preprocessor_map =
		typeof preprocessor_map_input === 'string'
			? JSON.parse(preprocessor_map_input)
			: preprocessor_map_input;
	const result_map = combine_sourcemaps(filename, [svelte_map, preprocessor_map]);
	// Svelte expects a SourceMap which includes toUrl and toString. Instead of wrapping our output in a class,
	// we just tack on the extra properties.
	Object.defineProperties(result_map, {
		toString: {
			enumerable: false,
			value: function toString() {
				return JSON.stringify(this);
			}
		},
		toUrl: {
			enumerable: false,
			value: function toUrl() {
				return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
			}
		}
	});
	return /** @type {import('magic-string').SourceMap} */ (result_map);
}
const regex_data_uri = /data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(\S*)/;
// parse attached sourcemap in processed.code

/**
 * @param {import('../preprocess/public.js').Processed} processed
 * @param {'script' | 'style'} tag_name
 * @returns {void}
 */
function parse_attached_sourcemap(processed, tag_name) {
	const r_in = '[#@]\\s*sourceMappingURL\\s*=\\s*(\\S*)';
	const regex =
		tag_name == 'script'
			? new RegExp('(?://' + r_in + ')|(?:/\\*' + r_in + '\\s*\\*/)$')
			: new RegExp('/\\*' + r_in + '\\s*\\*/$');

	/**
	 * @param {any} message
	 */
	function log_warning(message) {
		// code_start: help to find preprocessor
		const code_start =
			processed.code.length < 100 ? processed.code : processed.code.slice(0, 100) + ' [...]';
		console.warn(`warning: ${message}. processed.code = ${JSON.stringify(code_start)}`);
	}
	processed.code = processed.code.replace(regex, (_, match1, match2) => {
		const map_url = tag_name == 'script' ? match1 || match2 : match1;
		const map_data = (map_url.match(regex_data_uri) || [])[1];
		if (map_data) {
			// sourceMappingURL is data URL
			if (processed.map) {
				log_warning(
					'Not implemented. ' +
						'Found sourcemap in both processed.code and processed.map. ' +
						'Please update your preprocessor to return only one sourcemap.'
				);
				// ignore attached sourcemap
				return '';
			}
			processed.map = atob(map_data); // use attached sourcemap
			return ''; // remove from processed.code
		}
		// sourceMappingURL is path or URL
		if (!processed.map) {
			log_warning(
				`Found sourcemap path ${JSON.stringify(
					map_url
				)} in processed.code, but no sourcemap data. ` +
					'Please update your preprocessor to return sourcemap data directly.'
			);
		}
		// ignore sourcemap path
		return ''; // remove from processed.code
	});
}

/**
 * @param {import("../../interfaces.js").EnableSourcemap} enable_sourcemap
 * @param {keyof Exclude<import("../../interfaces.js").EnableSourcemap, boolean>} namespace
 */
function check_enable_sourcemap(enable_sourcemap, namespace) {
	return typeof enable_sourcemap === 'boolean' ? enable_sourcemap : enable_sourcemap[namespace];
}

/**
 * @param {import('../Component.js').default} component
 * @param {import('../../interfaces.js').CompileOptions} options
 * @returns {{ js: import('estree').Node[]; css: import('../../interfaces.js').CssResult; }}
 */
function dom(component, options) {
	const { name } = component;
	const renderer = new Renderer$1(component, options);
	const { block } = renderer;
	block.has_outro_method = true;
	/** @type {import('estree').Node[][]} */
	const body = [];
	if (renderer.file_var) {
		const file = component.file ? x$1`"${component.file}"` : x$1`undefined`;
		body.push(b$1`const ${renderer.file_var} = ${file};`);
	}
	const css = component.stylesheet.render(options.filename);
	const css_sourcemap_enabled = check_enable_sourcemap(options.enableSourcemap, 'css');
	if (css_sourcemap_enabled) {
		css.map = apply_preprocessor_sourcemap(
			options.filename,
			css.map,
			/** @type {string | import('@ampproject/remapping').RawSourceMap | import('@ampproject/remapping').DecodedSourceMap} */ (
				options.sourcemap
			)
		);
	} else {
		css.map = null;
	}
	const styles =
		css_sourcemap_enabled && component.stylesheet.has_styles && options.dev
			? `${css.code}\n/*# sourceMappingURL=${css.map.toUrl()} */`
			: css.code;
	const add_css = component.get_unique_name('add_css');
	const should_add_css = !!styles && (options.customElement || options.css === 'injected');
	if (should_add_css) {
		body.push(b$1`
			function ${add_css}(target) {
				@append_styles(target, "${component.stylesheet.id}", "${styles}");
			}
		`);
	}
	// fix order
	// TODO the deconflicted names of blocks are reversed... should set them here
	const blocks = renderer.blocks.slice().reverse();
	push_array(
		body,
		blocks.map((block) => {
			// TODO this is a horrible mess — renderer.blocks
			// contains a mixture of Blocks and Nodes
			if (/** @type {import('./Block.js').default} */ (block).render)
				return /** @type {import('./Block.js').default} */ (block).render();
			return block;
		})
	);
	if (options.dev && !options.hydratable) {
		block.chunks.claim.push(
			b$1`throw new @_Error("options.hydrate only works if the component was compiled with the \`hydratable: true\` option");`
		);
	}
	const uses_slots = component.var_lookup.has('$$slots');

	/** @type {import('estree').Node[] | undefined} */
	let compute_slots;
	if (uses_slots) {
		compute_slots = b$1`
			const $$slots = @compute_slots(#slots);
		`;
	}
	const uses_props = component.var_lookup.has('$$props');
	const uses_rest = component.var_lookup.has('$$restProps');
	const $$props = uses_props || uses_rest ? '$$new_props' : '$$props';
	const props = component.vars.filter((variable) => !variable.module && variable.export_name);
	const writable_props = props.filter((variable) => variable.writable);
	const omit_props_names = component.get_unique_name('omit_props_names');
	const compute_rest = x$1`@compute_rest_props($$props, ${omit_props_names.name})`;
	const rest = uses_rest
		? b$1`
		const ${omit_props_names.name} = [${props.map((prop) => `"${prop.export_name}"`).join(',')}];
		let $$restProps = ${compute_rest};
	`
		: null;
	const set =
		uses_props || uses_rest || writable_props.length > 0 || component.slots.size > 0
			? x$1`
			${$$props} => {
				${
					uses_props &&
					renderer.invalidate(
						'$$props',
						x$1`$$props = @assign(@assign({}, $$props), @exclude_internal_props($$new_props))`
					)
				}
				${
					uses_rest &&
					!uses_props &&
					x$1`$$props = @assign(@assign({}, $$props), @exclude_internal_props($$new_props))`
				}
				${uses_rest && renderer.invalidate('$$restProps', x$1`$$restProps = ${compute_rest}`)}
				${writable_props.map(
					(prop) =>
						b$1`if ('${prop.export_name}' in ${$$props}) ${renderer.invalidate(
							prop.name,
							x$1`${prop.name} = ${$$props}.${prop.export_name}`
						)};`
				)}
				${
					component.slots.size > 0 &&
					b$1`if ('$$scope' in ${$$props}) ${renderer.invalidate(
						'$$scope',
						x$1`$$scope = ${$$props}.$$scope`
					)};`
				}
			}
		`
			: null;
	const accessors = [];
	const not_equal = component.component_options.immutable ? x$1`@not_equal` : x$1`@safe_not_equal`;

	/** @type {import('estree').Node[] | import('estree').Node} */
	let missing_props_check;

	/** @type {import('estree').Expression} */
	let inject_state;

	/** @type {import('estree').Expression} */
	let capture_state;

	/** @type {import('estree').Node[] | import('estree').Node} */
	let props_inject;
	props.forEach((prop) => {
		const variable = component.var_lookup.get(prop.name);
		if (!variable.writable || component.component_options.accessors) {
			accessors.push({
				type: 'MethodDefinition',
				kind: 'get',
				key: { type: 'Identifier', name: prop.export_name },
				value: x$1`function() {
					return ${
						prop.hoistable
							? prop.name
							: x$1`this.$$.ctx[${renderer.context_lookup.get(prop.name).index}]`
					}
				}`
			});
		} else if (component.compile_options.dev) {
			accessors.push({
				type: 'MethodDefinition',
				kind: 'get',
				key: { type: 'Identifier', name: prop.export_name },
				value: x$1`function() {
					throw new @_Error("<${component.tag}>: Props cannot be read directly from the component instance unless compiling with 'accessors: true' or '<svelte:options accessors/>'");
				}`
			});
		}
		if (component.component_options.accessors) {
			if (variable.writable && !renderer.readonly.has(prop.name)) {
				accessors.push({
					type: 'MethodDefinition',
					kind: 'set',
					key: { type: 'Identifier', name: prop.export_name },
					value: x$1`function(${prop.name}) {
						this.$$set({ ${prop.export_name}: ${prop.name} });
						@flush();
					}`
				});
			} else if (component.compile_options.dev) {
				accessors.push({
					type: 'MethodDefinition',
					kind: 'set',
					key: { type: 'Identifier', name: prop.export_name },
					value: x$1`function(value) {
						throw new @_Error("<${component.tag}>: Cannot set read-only property '${prop.export_name}'");
					}`
				});
			}
		} else if (component.compile_options.dev) {
			accessors.push({
				type: 'MethodDefinition',
				kind: 'set',
				key: { type: 'Identifier', name: prop.export_name },
				value: x$1`function(value) {
					throw new @_Error("<${component.tag}>: Props cannot be set directly on the component instance unless compiling with 'accessors: true' or '<svelte:options accessors/>'");
				}`
			});
		}
	});
	component.instance_exports_from.forEach((exports_from) => {
		const import_declaration = {
			...exports_from,
			type: 'ImportDeclaration',
			specifiers: [],
			source: exports_from.source
		};
		component.imports.push(/** @type {import('estree').ImportDeclaration} */ (import_declaration));
		exports_from.specifiers.forEach((specifier) => {
			if (component.component_options.accessors) {
				const name = component.get_unique_name(specifier.exported.name);
				import_declaration.specifiers.push({
					...specifier,
					type: 'ImportSpecifier',
					imported: specifier.local,
					local: name
				});
				accessors.push({
					type: 'MethodDefinition',
					kind: 'get',
					key: { type: 'Identifier', name: specifier.exported.name },
					value: x$1`function() {
						return ${name}
					}`
				});
			} else if (component.compile_options.dev) {
				accessors.push({
					type: 'MethodDefinition',
					kind: 'get',
					key: { type: 'Identifier', name: specifier.exported.name },
					value: x$1`function() {
						throw new @_Error("<${component.tag}>: Props cannot be read directly from the component instance unless compiling with 'accessors: true' or '<svelte:options accessors/>'");
					}`
				});
			}
		});
	});
	if (component.compile_options.dev) {
		// checking that expected ones were passed
		const expected = props.filter((prop) => prop.writable && !prop.initialised);
		if (expected.length) {
			missing_props_check = b$1`
				$$self.$$.on_mount.push(function () {
					${expected.map(
						(prop) => b$1`
					if (${prop.name} === undefined && !(('${prop.export_name}' in $$props) || $$self.$$.bound[$$self.$$.props['${prop.export_name}']])) {
						@_console.warn("<${component.tag}> was created without expected prop '${prop.export_name}'");
					}`
					)}
				});
			`;
		}
		const capturable_vars = component.vars.filter(
			(v) => !v.internal && !v.global && !v.name.startsWith('$$')
		);
		if (capturable_vars.length > 0) {
			capture_state = x$1`() => ({ ${capturable_vars.map((prop) => p`${prop.name}`)} })`;
		}
		const injectable_vars = capturable_vars.filter(
			(v) => !v.module && v.writable && v.name[0] !== '$'
		);
		if (uses_props || injectable_vars.length > 0) {
			inject_state = x$1`
				${$$props} => {
					${
						uses_props &&
						renderer.invalidate('$$props', x$1`$$props = @assign(@assign({}, $$props), $$new_props)`)
					}
					${injectable_vars.map(
						(v) =>
							b$1`if ('${v.name}' in $$props) ${renderer.invalidate(
								v.name,
								x$1`${v.name} = ${$$props}.${v.name}`
							)};`
					)}
				}
			`;
			props_inject = b$1`
				if ($$props && "$$inject" in $$props) {
					$$self.$inject_state($$props.$$inject);
				}
			`;
		}
	}
	// instrument assignments
	if (component.ast.instance) {
		let scope = component.instance_scope;
		const map = component.instance_scope_map;

		/** @type {import('estree').Node | null} */
		let execution_context = null;
		walk(component.ast.instance.content, {
			enter(node) {
				if (map.has(node)) {
					scope = /** @type {import('periscopic').Scope} */ (map.get(node));
					if (!execution_context && !scope.block) {
						execution_context = node;
					}
				} else if (
					!execution_context &&
					node.type === 'LabeledStatement' &&
					node.label.name === '$'
				) {
					execution_context = node;
				}
			},
			leave(node) {
				if (map.has(node)) {
					scope = scope.parent;
				}
				if (execution_context === node) {
					execution_context = null;
				}
				if (node.type === 'AssignmentExpression' || node.type === 'UpdateExpression') {
					const assignee = node.type === 'AssignmentExpression' ? node.left : node.argument;
					// normally (`a = 1`, `b.c = 2`), there'll be a single name
					// (a or b). In destructuring cases (`[d, e] = [e, d]`) there
					// may be more, in which case we need to tack the extra ones
					// onto the initial function call
					const names = new Set(extract_names(/** @type {import('estree').Node} */ (assignee)));
					this.replace(invalidate(renderer, scope, node, names, execution_context === null));
				}
			}
		});
		component.rewrite_props(({ name, reassigned, export_name }) => {
			const value = `$${name}`;
			const i = renderer.context_lookup.get(`$${name}`).index;
			const insert =
				reassigned || export_name
					? b$1`${`$$subscribe_${name}`}()`
					: b$1`@component_subscribe($$self, ${name}, #value => $$invalidate(${i}, ${value} = #value))`;
			if (component.compile_options.dev) {
				return b$1`@validate_store(${name}, '${name}'); ${insert}`;
			}
			return insert;
		});
	}
	const args = [x$1`$$self`];
	const has_invalidate =
		props.length > 0 ||
		component.has_reactive_assignments ||
		component.slots.size > 0 ||
		capture_state ||
		inject_state;
	if (has_invalidate) {
		args.push(x$1`$$props`, x$1`$$invalidate`);
	} else if (component.compile_options.dev) {
		// $$props arg is still needed for unknown prop check
		args.push(x$1`$$props`);
	}
	// has_create_fragment is intentionally to be true in dev mode.
	const has_create_fragment = component.compile_options.dev || block.has_content();
	if (has_create_fragment) {
		body.push(b$1`
			function create_fragment(#ctx) {
				${block.get_contents()}
			}
		`);
	}
	body.push(b$1`
		${component.extract_javascript(component.ast.module)}

		${component.fully_hoisted}
	`);
	const filtered_props = props.filter((prop) => {
		const variable = component.var_lookup.get(prop.name);
		if (variable.hoistable) return false;
		return prop.name[0] !== '$';
	});
	const reactive_stores = component.vars.filter(
		(variable) => variable.name[0] === '$' && variable.name[1] !== '$'
	);
	const instance_javascript = component.extract_javascript(component.ast.instance);
	const has_definition =
		component.compile_options.dev ||
		(instance_javascript && instance_javascript.length > 0) ||
		filtered_props.length > 0 ||
		uses_props ||
		component.partly_hoisted.length > 0 ||
		renderer.initial_context.length > 0 ||
		component.reactive_declarations.length > 0 ||
		capture_state ||
		inject_state;
	const definition = has_definition
		? component.alias('instance')
		: { type: 'Literal', value: null };
	const reactive_store_subscriptions = reactive_stores
		.filter((store) => {
			const variable = component.var_lookup.get(store.name.slice(1));
			return !variable || variable.hoistable;
		})
		.map(
			({ name }) => b$1`
			${component.compile_options.dev && b$1`@validate_store(${name.slice(1)}, '${name.slice(1)}');`}
			@component_subscribe($$self, ${name.slice(1)}, $$value => $$invalidate(${
				renderer.context_lookup.get(name).index
			}, ${name} = $$value));
		`
		);
	const resubscribable_reactive_store_unsubscribers = reactive_stores
		.filter((store) => {
			const variable = component.var_lookup.get(store.name.slice(1));
			return variable && (variable.reassigned || variable.export_name);
		})
		.map(({ name }) => b$1`$$self.$$.on_destroy.push(() => ${`$$unsubscribe_${name.slice(1)}`}());`);
	if (has_definition) {
		/** @type {import('estree').Node | import('estree').Node[]} */
		const reactive_declarations = [];

		/** @type {import('estree').Node[]} */
		const fixed_reactive_declarations = []; // not really 'reactive' but whatever
		component.reactive_declarations.forEach((d) => {
			const dependencies = Array.from(d.dependencies);
			const uses_rest_or_props = !!dependencies.find((n) => n === '$$props' || n === '$$restProps');
			const writable = dependencies.filter((n) => {
				const variable = component.var_lookup.get(n);
				return variable && (variable.export_name || variable.mutated || variable.reassigned);
			});
			const condition =
				!uses_rest_or_props && writable.length > 0 && renderer.dirty(writable, true);
			let statement = d.node; // TODO remove label (use d.node.body) if it's not referenced
			if (condition)
				statement = /** @type {import('estree').Statement} */ (
					b$1`if (${condition}) { ${statement} }`[0]
				);
			if (condition || uses_rest_or_props) {
				reactive_declarations.push(statement);
			} else {
				fixed_reactive_declarations.push(statement);
			}
		});
		const injected = Array.from(component.injected_reactive_declaration_vars).filter((name) => {
			const variable = component.var_lookup.get(name);
			return variable.injected && variable.name[0] !== '$';
		});
		const reactive_store_declarations = reactive_stores.map((variable) => {
			const $name = variable.name;
			const name = $name.slice(1);
			const store = component.var_lookup.get(name);
			if (store && (store.reassigned || store.export_name)) {
				const unsubscribe = `$$unsubscribe_${name}`;
				const subscribe = `$$subscribe_${name}`;
				const i = renderer.context_lookup.get($name).index;
				return b$1`let ${$name}, ${unsubscribe} = @noop, ${subscribe} = () => (${unsubscribe}(), ${unsubscribe} = @subscribe(${name}, $$value => $$invalidate(${i}, ${$name} = $$value)), ${name})`;
			}
			return b$1`let ${$name};`;
		});

		/** @type {import('estree').Node[] | undefined} */
		let unknown_props_check;
		if (component.compile_options.dev && !(uses_props || uses_rest)) {
			unknown_props_check = b$1`
				const writable_props = [${writable_props.map((prop) => x$1`'${prop.export_name}'`)}];
				@_Object.keys($$props).forEach(key => {
					if (!~writable_props.indexOf(key) && key.slice(0, 2) !== '$$' && key !== 'slot') @_console.warn(\`<${
						component.tag
					}> was created with unknown prop '\${key}'\`);
				});
			`;
		}
		const return_value = {
			type: 'ArrayExpression',
			elements: renderer.initial_context.map(
				(member) =>
					/** @type {import('estree').Expression} */ ({
						type: 'Identifier',
						name: member.name
					})
			)
		};
		body.push(b$1`
			function ${definition}(${args}) {
				${injected.map((name) => b$1`let ${name};`)}

				${rest}

				${reactive_store_declarations}

				${reactive_store_subscriptions}

				${resubscribable_reactive_store_unsubscribers}

				${
					component.slots.size || component.compile_options.dev || uses_slots
						? b$1`let { $$slots: #slots = {}, $$scope } = $$props;`
						: null
				}
				${
					component.compile_options.dev &&
					b$1`@validate_slots('${component.tag}', #slots, [${[...component.slots.keys()]
						.map((key) => `'${key}'`)
						.join(',')}]);`
				}
				${compute_slots}

				${instance_javascript}

				${missing_props_check}
				${unknown_props_check}

				${
					renderer.binding_groups.size > 0 &&
					b$1`const $$binding_groups = [${[...renderer.binding_groups.keys()].map((_) => x$1`[]`)}];`
				}

				${component.partly_hoisted}

				${set && b$1`$$self.$$set = ${set};`}

				${capture_state && b$1`$$self.$capture_state = ${capture_state};`}

				${inject_state && b$1`$$self.$inject_state = ${inject_state};`}

				${/* before reactive declarations */ props_inject}

				${
					reactive_declarations.length > 0 &&
					b$1`
				$$self.$$.update = () => {
					${reactive_declarations}
				};
				`
				}

				${fixed_reactive_declarations}

				${uses_props && b$1`$$props = @exclude_internal_props($$props);`}

				return ${return_value};
			}
		`);
	}
	const prop_indexes = /** @type {import('estree').ObjectExpression} */ (
		x$1`{
		${props
			.filter((v) => v.export_name && !v.module)
			.map((v) => p`${v.export_name}: ${renderer.context_lookup.get(v.name).index}`)}
	}`
	);
	let dirty;
	if (renderer.context_overflow) {
		dirty = x$1`[]`;
		for (let i = 0; i < renderer.context.length; i += 31) {
			/** @type {any} */ (dirty).elements.push(x$1`-1`);
		}
	}
	const superclass = {
		type: 'Identifier',
		name: options.dev ? '@SvelteComponentDev' : '@SvelteComponent'
	};
	const optional_parameters = [];
	if (should_add_css) {
		optional_parameters.push(add_css);
	} else if (dirty) {
		optional_parameters.push(x$1`null`);
	}
	if (dirty) {
		optional_parameters.push(dirty);
	}
	const declaration = /** @type {import('estree').ClassDeclaration} */ (
		b$1`
		class ${name} extends ${superclass} {
			constructor(options) {
				super(${options.dev && 'options'});
				@init(this, options, ${definition}, ${
			has_create_fragment ? 'create_fragment' : 'null'
		}, ${not_equal}, ${prop_indexes}, ${optional_parameters});
				${
					options.dev &&
					b$1`@dispatch_dev("SvelteRegisterComponent", { component: this, tagName: "${name.name}", options, id: create_fragment.name });`
				}
			}
		}
	`[0]
	);
	push_array(declaration.body.body, accessors);
	body.push(/** @type {any} */ (declaration));
	if (options.customElement) {
		const props_str = writable_props.reduce((def, prop) => {
			def[prop.export_name] =
				component.component_options.customElement?.props?.[prop.export_name] || {};
			if (prop.is_boolean && !def[prop.export_name].type) {
				def[prop.export_name].type = 'Boolean';
			}
			return def;
		}, {});
		const slots_str = [...component.slots.keys()].map((key) => `"${key}"`).join(',');
		const accessors_str = accessors
			.filter((accessor) => !writable_props.some((prop) => prop.export_name === accessor.key.name))
			.map((accessor) => `"${accessor.key.name}"`)
			.join(',');
		const use_shadow_dom =
			component.component_options.customElement?.shadow !== 'none' ? 'true' : 'false';
		if (component.component_options.customElement?.tag) {
			body.push(
				b$1`@_customElements.define("${
					component.component_options.customElement.tag
				}", @create_custom_element(${name}, ${JSON.stringify(
					props_str
				)}, [${slots_str}], [${accessors_str}], ${use_shadow_dom}));`
			);
		} else {
			body.push(
				b$1`@create_custom_element(${name}, ${JSON.stringify(
					props_str
				)}, [${slots_str}], [${accessors_str}], ${use_shadow_dom});`
			);
		}
	}

	if (options.discloseVersion === true) {
		component.imports.unshift({
			type: 'ImportDeclaration',
			specifiers: [],
			source: {
				type: 'Literal',
				value: `${options.sveltePath ?? 'svelte'}/internal/disclose-version`
			}
		});
	}

	return { js: flatten$1(body), css };
}

/** @param {import('../../../nodes/ConstTag.js').default[]} const_tags */
function get_const_tags(const_tags) {
	if (const_tags.length === 0) return null;
	return {
		type: 'VariableDeclaration',
		kind: 'let',
		declarations: const_tags.map((const_tag) => {
			const assignment = const_tag.node.expression;
			return {
				type: 'VariableDeclarator',
				id: assignment.left,
				init: assignment.right
			};
		})
	};
}

/**
 * @param {import('../../nodes/AwaitBlock.js').default} node
 * @param {import('../Renderer.js').default} renderer
 * @param {import('../private.js').RenderOptions} options
 */
function AwaitBlock (node, renderer, options) {
	renderer.push();
	renderer.render(node.pending.children, options);

	const pending = renderer.pop();
	renderer.push();
	renderer.render(node.then.children, options);

	const then = renderer.pop();
	renderer.add_expression(x$1`
		function(__value) {
			if (@is_promise(__value)) {
				__value.then(null, @noop);
				return ${pending};
			}
			return (function(${node.then_node ? node.then_node : ''}) { ${get_const_tags(
		node.then.const_tags
	)}; return ${then}; }(__value));
		}(${node.expression.node})
	`);
}

/**
 * @param {import('../../nodes/Comment.js').default} node
 * @param {import('../Renderer.js').default} renderer
 * @param {import('../private.js').RenderOptions} options
 */
function Comment (node, renderer, options) {
	if (options.preserveComments) {
		renderer.add_string(`<!--${node.data}-->`);
	}
}

/**
 * @param {import('../../nodes/DebugTag.js').default} node
 * @param {import('../Renderer.js').default} renderer
 * @param {import('../private.js').RenderOptions} options
 */
function DebugTag (node, renderer, options) {
	if (!options.dev) return;
	const filename = options.filename || null;
	const { line, column } = options.locate(node.start + 1);
	const obj = x$1`{
		${node.expressions.map((e) => p`${/** @type {import('estree').Identifier} */ (e.node).name}`)}
	}`;
	renderer.add_expression(
		x$1`@debug(${filename ? x$1`"${filename}"` : x$1`null`}, ${line - 1}, ${column}, ${obj})`
	);
}

/**
 * @param {import('../../nodes/EachBlock.js').default} node
 * @param {import('../Renderer.js').default} renderer
 * @param {import('../private.js').RenderOptions} options
 */
function EachBlock (node, renderer, options) {
	const args = [node.context_node];
	if (node.index) args.push({ type: 'Identifier', name: node.index });
	renderer.push();
	renderer.render(node.children, options);
	const result = renderer.pop();
	const consequent = x$1`@each(${node.expression.node}, (${args}) => { ${get_const_tags(
		node.const_tags
	)}; return ${result} })`;
	if (node.else) {
		renderer.push();
		renderer.render(node.else.children, options);
		/** @type {import('estree').Node} */
		let alternate = renderer.pop();
		if (node.else.const_tags.length > 0)
			alternate = x$1`(() => { ${get_const_tags(node.else.const_tags)}; return ${alternate} })()`;
		renderer.add_expression(x$1`${node.expression.node}.length ? ${consequent} : ${alternate}`);
	} else {
		renderer.add_expression(consequent);
	}
}

/**
 * @param {import('../../../nodes/Attribute.js').default} attribute
 * @returns {import('estree').Expression}
 */
function get_class_attribute_value(attribute) {
	// handle special case — `class={possiblyUndefined}` with scoped CSS
	if (
		attribute.chunks.length === 2 &&
		/** @type {import('../../../nodes/Text.js').default} */ (attribute.chunks[1]).synthetic
	) {
		const value = /** @type {import('../../../nodes/shared/Expression.js').default} */ (
			attribute.chunks[0]
		).node;
		return x$1`@escape(@null_to_empty(${value}), true) + "${
			/** @type {import('../../../nodes/Text.js').default} */ (attribute.chunks[1]).data
		}"`;
	}
	return get_attribute_value(attribute);
}

/**
 * @param {import('../../../nodes/Attribute.js').default} attribute
 * @returns {import('estree').Expression}
 */
function get_attribute_value(attribute) {
	if (attribute.chunks.length === 0) return x$1`""`;
	/**
	 * For value attribute of textarea, it will render as child node of `<textarea>` element.
	 * Therefore, we need to escape as content (not attribute).
	 */
	const is_textarea_value =
		attribute.parent.name.toLowerCase() === 'textarea' && attribute.name.toLowerCase() === 'value';
	return attribute.chunks
		.map((chunk) => {
			return chunk.type === 'Text'
				? /** @type {import('estree').Expression} */ (
						string_literal(chunk.data.replace(regex_double_quotes, '&quot;'))
				  )
				: x$1`@escape(${chunk.node}, ${is_textarea_value ? 'false' : 'true'})`;
		})
		.reduce((lhs, rhs) => x$1`${lhs} + ${rhs}`);
}

/**
 * @param {import('../../../nodes/Attribute.js').default} attribute
 * @returns {import('estree').Expression}
 */
function get_attribute_expression(attribute) {
	if (attribute.chunks.length === 1 && attribute.chunks[0].type === 'Expression') {
		return /** @type {import('estree').Expression} */ (
			/** @type {import('../../../nodes/shared/Expression.js').default} */ (attribute.chunks[0])
				.node
		);
	}
	return get_attribute_value(attribute);
}

// similar logic from `compile/render_dom/wrappers/Fragment`
// We want to remove trailing whitespace inside an element/component/block,
// *unless* there is no whitespace between this node and its next sibling

/**
 * @param {import('../../../nodes/interfaces.js').INode[]} children
 * @param {import('../../../nodes/interfaces.js').INode} [next]
 * @returns {import('../../../nodes/interfaces.js').INode[]}
 */
function remove_whitespace_children(children, next) {
	/** @type {import('../../../nodes/interfaces.js').INode[]} */
	const nodes = [];

	/** @type {import('../../../nodes/interfaces.js').INode} */
	let last_child;
	let i = children.length;
	while (i--) {
		const child = children[i];
		if (child.type === 'Text') {
			if (child.should_skip()) {
				continue;
			}
			let { data } = child;
			if (nodes.length === 0) {
				const should_trim = next
					? next.type === 'Text' &&
					  regex_starts_with_whitespace.test(next.data) &&
					  trimmable_at(child, next)
					: !child.has_ancestor('EachBlock');
				if (should_trim && !child.keep_space()) {
					data = trim_end(data);
					if (!data) continue;
				}
			}
			// glue text nodes (which could e.g. be separated by comments) together
			if (last_child && last_child.type === 'Text') {
				last_child.data = data + last_child.data;
				continue;
			}
			child.data = data;
			nodes.unshift(child);
			link(last_child, (last_child = child));
		} else {
			nodes.unshift(child);
			link(last_child, (last_child = child));
		}
	}
	const first = nodes[0];
	if (first && first.type === 'Text' && !first.keep_space()) {
		first.data = trim_start(first.data);
		if (!first.data) {
			first.var = null;
			nodes.shift();
			if (nodes[0]) {
				nodes[0].prev = null;
			}
		}
	}
	return nodes;
}

/**
 * @param {import('../../../nodes/interfaces.js').INode} child
 * @param {import('../../../nodes/interfaces.js').INode} next_sibling
 * @returns {boolean}
 */
function trimmable_at(child, next_sibling) {
	// Whitespace is trimmable if one of the following is true:
	// The child and its sibling share a common nearest each block (not at an each block boundary)
	// The next sibling's previous node is an each block
	return (
		next_sibling.find_nearest(/EachBlock/) === child.find_nearest(/EachBlock/) ||
		next_sibling.prev.type === 'EachBlock'
	);
}

/**
 * @param {import('../../nodes/Element.js').default} node
 * @param {import('../Renderer.js').default} renderer
 * @param {import('../private.js').RenderOptions} options
 */
function Element (node, renderer, options) {
	const children = remove_whitespace_children(node.children, node.next);
	// awkward special case
	let node_contents;
	const contenteditable = is_contenteditable(node);
	if (node.is_dynamic_element) {
		renderer.push();
	}
	renderer.add_string('<');
	add_tag_name();
	const class_expression_list = node.classes.map((class_directive) => {
		const { expression, name } = class_directive;
		const snippet = expression ? expression.node : x$1`#ctx.${name}`; // TODO is this right?
		return x$1`${snippet} ? "${name}" : ""`;
	});
	if (node.needs_manual_style_scoping) {
		class_expression_list.push(x$1`"${node.component.stylesheet.id}"`);
	}
	const class_expression =
		class_expression_list.length > 0 &&
		class_expression_list.reduce((lhs, rhs) => x$1`${lhs} + ' ' + ${rhs}`);
	const style_expression_list = node.styles.map((style_directive) => {
		let {
			name,
			important,
			expression: { node: expression }
		} = style_directive;
		if (important) {
			expression = x$1`${expression} + ' !important'`;
		}
		return p`"${name}": ${expression}`;
	});
	const style_expression = style_expression_list.length > 0 && x$1`{ ${style_expression_list} }`;
	if (node.attributes.some((attr) => attr.is_spread)) {
		// TODO dry this out
		const args = [];
		node.attributes.forEach((attribute) => {
			if (attribute.is_spread) {
				args.push(x$1`@escape_object(${attribute.expression.node})`);
			} else {
				const attr_name =
					node.namespace === namespaces.foreign
						? attribute.name
						: fix_attribute_casing(attribute.name);
				const name = attribute.name.toLowerCase();
				if (name === 'value' && node.name.toLowerCase() === 'textarea') {
					node_contents = get_attribute_value(attribute);
				} else if (attribute.is_true) {
					args.push(x$1`{ ${attr_name}: true }`);
				} else if (
					boolean_attributes.has(name) &&
					attribute.chunks.length === 1 &&
					attribute.chunks[0].type !== 'Text'
				) {
					// a boolean attribute with one non-Text chunk
					args.push(
						x$1`{ ${attr_name}: ${
							/** @type {import('../../nodes/shared/Expression.js').default} */ (
								attribute.chunks[0]
							).node
						} || null }`
					);
				} else if (attribute.chunks.length === 1 && attribute.chunks[0].type !== 'Text') {
					const snippet = /** @type {import('../../nodes/shared/Expression.js').default} */ (
						attribute.chunks[0]
					).node;
					args.push(x$1`{ ${attr_name}: @escape_attribute_value(${snippet}) }`);
				} else {
					args.push(x$1`{ ${attr_name}: ${get_attribute_value(attribute)} }`);
				}
			}
		});
		renderer.add_expression(
			x$1`@spread([${args}], { classes: ${class_expression}, styles: ${style_expression} })`
		);
	} else {
		let add_class_attribute = !!class_expression;
		let add_style_attribute = !!style_expression;
		node.attributes.forEach((attribute) => {
			const name = attribute.name.toLowerCase();
			const attr_name =
				node.namespace === namespaces.foreign
					? attribute.name
					: fix_attribute_casing(attribute.name);
			if (name === 'value' && node.name.toLowerCase() === 'textarea') {
				node_contents = get_attribute_value(attribute);
			} else if (attribute.is_true) {
				renderer.add_string(` ${attr_name}`);
			} else if (
				boolean_attributes.has(name) &&
				attribute.chunks.length === 1 &&
				attribute.chunks[0].type !== 'Text'
			) {
				// a boolean attribute with one non-Text chunk
				renderer.add_string(' ');
				renderer.add_expression(
					x$1`${
						/** @type {import('../../nodes/shared/Expression.js').default} */ (attribute.chunks[0])
							.node
					} ? "${attr_name}" : ""`
				);
			} else if (name === 'class' && class_expression) {
				add_class_attribute = false;
				renderer.add_string(` ${attr_name}="`);
				renderer.add_expression(
					x$1`[${get_class_attribute_value(attribute)}, ${class_expression}].join(' ').trim()`
				);
				renderer.add_string('"');
			} else if (name === 'style' && style_expression) {
				add_style_attribute = false;
				renderer.add_expression(
					x$1`@add_styles(@merge_ssr_styles(${get_attribute_value(attribute)}, ${style_expression}))`
				);
			} else if (attribute.chunks.length === 1 && attribute.chunks[0].type !== 'Text') {
				const snippet = /** @type {import('../../nodes/shared/Expression.js').default} */ (
					attribute.chunks[0]
				).node;
				renderer.add_expression(
					x$1`@add_attribute("${attr_name}", ${snippet}, ${boolean_attributes.has(name) ? 1 : 0})`
				);
			} else {
				renderer.add_string(` ${attr_name}="`);
				renderer.add_expression(
					(name === 'class' ? get_class_attribute_value : get_attribute_value)(attribute)
				);
				renderer.add_string('"');
			}
		});
		if (add_class_attribute) {
			renderer.add_expression(x$1`@add_classes((${class_expression}).trim())`);
		}
		if (add_style_attribute) {
			renderer.add_expression(x$1`@add_styles(${style_expression})`);
		}
	}
	node.bindings.forEach((binding) => {
		const { name, expression } = binding;
		if (binding.is_readonly) {
			return;
		}
		if (name === 'group') {
			const value_attribute = node.attributes.find(({ name }) => name === 'value');
			if (value_attribute) {
				const value = get_attribute_expression(value_attribute);
				const type = node.get_static_attribute_value('type');
				const bound = expression.node;
				const condition =
					type === 'checkbox' ? x$1`~${bound}.indexOf(${value})` : x$1`${value} === ${bound}`;
				renderer.add_expression(x$1`${condition} ? @add_attribute("checked", true, 1) : ""`);
			}
		} else if (contenteditable && is_name_contenteditable(name)) {
			node_contents = expression.node;
			// TODO where was this used?
			// value = name === 'textContent' ? x`@escape($$value)` : x`$$value`;
		} else if (binding.name === 'value' && node.name === 'textarea') {
			const snippet = expression.node;
			node_contents = x$1`@escape(${snippet} || "")`;
		} else if (binding.name === 'value' && node.name === 'select') ; else {
			const snippet = expression.node;
			renderer.add_expression(
				x$1`@add_attribute("${name}", ${snippet}, ${boolean_attributes.has(name) ? 1 : 0})`
			);
		}
	});
	if (options.hydratable) {
		if (node.can_optimise_hydration && !options.has_added_svelte_hash) {
			renderer.add_string(` data-svelte-h="${node.hash()}"`);
			options = { ...options, has_added_svelte_hash: true };
		}
	}
	renderer.add_string('>');
	if (node_contents !== undefined) {
		if (contenteditable) {
			renderer.push();
			renderer.render(children, options);
			const result = renderer.pop();
			renderer.add_expression(
				x$1`($$value => $$value === void 0 ? ${result} : $$value)(${node_contents})`
			);
		} else {
			if (node.name === 'textarea') {
				// Two or more leading newlines are required to restore the leading newline immediately after `<textarea>`.
				// see https://html.spec.whatwg.org/multipage/syntax.html#element-restrictions
				const value_attribute = node.attributes.find(({ name }) => name === 'value');
				if (value_attribute) {
					const first = value_attribute.chunks[0];
					if (first && first.type === 'Text' && regex_starts_with_newline.test(first.data)) {
						renderer.add_string('\n');
					}
				}
			}
			renderer.add_expression(node_contents);
		}
		add_close_tag();
	} else {
		if (node.name === 'pre') {
			// Two or more leading newlines are required to restore the leading newline immediately after `<pre>`.
			// see https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
			// see https://html.spec.whatwg.org/multipage/syntax.html#element-restrictions
			const first = children[0];
			if (first && first.type === 'Text' && regex_starts_with_newline.test(first.data)) {
				renderer.add_string('\n');
			}
		}
		if (node.is_dynamic_element) renderer.push();
		renderer.render(children, options);
		if (node.is_dynamic_element) {
			const children = renderer.pop();
			renderer.add_expression(x$1`@is_void(#tag) ? '' : ${children}`);
		}
		add_close_tag();
	}
	if (node.is_dynamic_element) {
		/** @type {import('estree').Node} */
		let content = renderer.pop();
		if (options.dev && node.children.length > 0)
			content = x$1`(() => { @validate_void_dynamic_element(#tag); return ${content}; })()`;
		renderer.add_expression(x$1`((#tag) => {
			${options.dev && x$1`@validate_dynamic_element(#tag)`}
			return #tag ? ${content} : '';
		})(${node.tag_expr.node})`);
	}
	function add_close_tag() {
		if (node.tag_expr.node.type === 'Literal') {
			if (!is_void(/** @type {string} */ (node.tag_expr.node.value))) {
				renderer.add_string('</');
				add_tag_name();
				renderer.add_string('>');
			}
			return;
		}
		renderer.add_expression(x$1`@is_void(#tag) ? '' : \`</\${#tag}>\``);
	}
	function add_tag_name() {
		if (node.tag_expr.node.type === 'Literal') {
			renderer.add_string(/** @type {string} */ (node.tag_expr.node.value));
		} else {
			renderer.add_expression(/** @type {import('estree').Expression} */ (node.tag_expr.node));
		}
	}
}

/**
 * @param {import('../../nodes/Head.js').default} node
 * @param {import('../Renderer.js').default} renderer
 * @param {import('../private.js').RenderOptions} options
 */
function Head (node, renderer, options) {
	const head_options = {
		...options,
		head_id: node.id
	};
	renderer.push();
	renderer.render(node.children, head_options);
	const result = renderer.pop();

	/** @type {import('estree').Node} */
	let expression = result;
	if (options.hydratable) {
		const start_comment = `HEAD_${node.id}_START`;
		const end_comment = `HEAD_${node.id}_END`;
		expression = x$1`'<!-- ${start_comment} -->' + ${expression} + '<!-- ${end_comment} -->'`;
	}
	renderer.add_expression(x$1`$$result.head += ${expression}, ""`);
}

/**
 * @param {import('../../nodes/RawMustacheTag.js').default} node
 * @param {import('../Renderer.js').default} renderer
 * @param {import('../private.js').RenderOptions} options
 */
function HtmlTag (node, renderer, options) {
	if (options.hydratable) renderer.add_string('<!-- HTML_TAG_START -->');
	renderer.add_expression(/** @type {import('estree').Expression} */ (node.expression.node));
	if (options.hydratable) renderer.add_string('<!-- HTML_TAG_END -->');
}

/**
 * @param {import('../../nodes/IfBlock.js').default} node
 * @param {import('../Renderer.js').default} renderer
 * @param {import('../private.js').RenderOptions} options
 */
function IfBlock (node, renderer, options) {
	const condition = node.expression.node;
	renderer.push();
	renderer.render(node.children, options);

	/** @type {import('estree').Node} */
	let consequent = renderer.pop();
	if (node.const_tags.length > 0)
		consequent = x$1`(() => { ${get_const_tags(node.const_tags)}; return ${consequent} })()`;
	renderer.push();
	if (node.else) renderer.render(node.else.children, options);

	/** @type {import('estree').Node} */
	let alternate = renderer.pop();
	if (node.else && node.else.const_tags.length > 0)
		alternate = x$1`(() => { ${get_const_tags(node.else.const_tags)}; return ${alternate} })()`;
	renderer.add_expression(x$1`${condition} ? ${consequent} : ${alternate}`);
}

/** @param {any} attribute */
function get_prop_value(attribute) {
	if (attribute.is_true) return x$1`true`;
	if (attribute.chunks.length === 0) return x$1`''`;
	return attribute.chunks
		.map((chunk) => {
			if (chunk.type === 'Text') return string_literal(chunk.data);
			return chunk.node;
		})
		.reduce((lhs, rhs) => x$1`${lhs} + ${rhs}`);
}

/**
 * @param {import('../../nodes/InlineComponent.js').default} node
 * @param {import('../Renderer.js').default} renderer
 * @param {import('../private.js').RenderOptions} options
 */
function InlineComponent (node, renderer, options) {
	const binding_props = [];
	const binding_fns = [];
	node.bindings.forEach((binding) => {
		renderer.has_bindings = true;
		// TODO this probably won't work for contextual bindings
		const snippet = binding.expression.node;
		binding_props.push(p`${binding.name}: ${snippet}`);
		binding_fns.push(p`${binding.name}: $$value => { ${snippet} = $$value; $$settled = false }`);
	});
	const uses_spread = node.attributes.find((attr) => attr.is_spread);
	let props;
	if (uses_spread) {
		props = x$1`@_Object.assign({}, ${node.attributes
			.map((attribute) => {
				if (attribute.is_spread) {
					return attribute.expression.node;
				} else {
					return x$1`{ ${attribute.name}: ${get_prop_value(attribute)} }`;
				}
			})
			.concat(binding_props.map((p) => x$1`{ ${p} }`))})`;
	} else {
		props = x$1`{
			${node.attributes.map((attribute) => p`${attribute.name}: ${get_prop_value(attribute)}`)},
			${binding_props}
		}`;
	}
	const bindings = x$1`{
		${binding_fns}
	}`;
	const expression =
		node.name === 'svelte:self'
			? renderer.name
			: node.name === 'svelte:component'
			? x$1`(${node.expression.node}) || @missing_component`
			: node.name.split('.').reduce(/** @type {any} */ ((lhs, rhs) => x$1`${lhs}.${rhs}`));
	const slot_fns = [];
	const children = node.children;
	if (children.length) {
		const slot_scopes = new Map();
		renderer.render(
			children,
			Object.assign({}, options, {
				slot_scopes
			})
		);
		slot_scopes.forEach(({ input, output, statements }, name) => {
			slot_fns.push(p`${name}: (${input}) => { ${statements}; return ${output}; }`);
		});
	}
	const slots = x$1`{
		${slot_fns}
	}`;
	if (node.css_custom_properties.length > 0) {
		if (node.namespace === namespaces.svg) {
			renderer.add_string('<g style="');
		} else {
			renderer.add_string('<div style="display: contents; ');
		}
		node.css_custom_properties.forEach((attr, index) => {
			renderer.add_string(`${attr.name}:`);
			renderer.add_expression(get_attribute_value(attr));
			renderer.add_string(';');
			if (index < node.css_custom_properties.length - 1) renderer.add_string(' ');
		});
		renderer.add_string('">');
	}
	renderer.add_expression(
		x$1`@validate_component(${expression}, "${node.name}").$$render($$result, ${props}, ${bindings}, ${slots})`
	);
	if (node.css_custom_properties.length > 0) {
		if (node.namespace === namespaces.svg) {
			renderer.add_string('</g>');
		} else {
			renderer.add_string('</div>');
		}
	}
}

/**
 * @param {import('../../nodes/KeyBlock.js').default} node
 * @param {import('../Renderer.js').default} renderer
 * @param {import('../private.js').RenderOptions} options
 */
function KeyBlock (node, renderer, options) {
	renderer.render(node.children, options);
}

/**
 * @param {import('../../../nodes/Let.js').default[]} lets
 * @returns {import('estree').ObjectPattern}
 */
function get_slot_scope(lets) {
	if (lets.length === 0) return null;
	return {
		type: 'ObjectPattern',
		properties: lets.map((l) => {
			return {
				type: 'Property',
				kind: 'init',
				method: false,
				shorthand: false,
				computed: false,
				key: l.name,
				value: l.value || l.name
			};
		})
	};
}

/**
 * @param {import('../../nodes/Slot.js').default} node
 * @param {import('../Renderer.js').default} renderer
 * @param {import('../private.js').RenderOptions & {
 * 		slot_scopes: Map<any, any>;
 * 	}} options
 */
function Slot (node, renderer, options) {
	const slot_data = get_slot_data(node.values);
	const slot = node.get_static_attribute_value('slot');
	const nearest_inline_component = node.find_nearest(/InlineComponent/);
	if (slot && nearest_inline_component) {
		renderer.push();
	}
	renderer.push();
	renderer.render(node.children, options);
	const result = renderer.pop();
	renderer.add_expression(x$1`
		#slots.${node.slot_name}
			? #slots.${node.slot_name}(${slot_data})
			: ${result}
	`);
	if (slot && nearest_inline_component) {
		options.slot_scopes.set(slot, {
			input: get_slot_scope(node.lets),
			output: renderer.pop()
		});
	}
}

/**
 * @param {import('../../nodes/SlotTemplate.js').default} node
 * @param {import('../Renderer.js').default} renderer
 * @param {import('../private.js').RenderOptions & {
 * 		slot_scopes: Map<any, any>;
 * 	}} options
 */
function SlotTemplate (node, renderer, options) {
	const parent_inline_component = /** @type {import('../../nodes/InlineComponent.js').default} */ (
		node.parent
	);
	const children = remove_whitespace_children(
		node instanceof SlotTemplate$1 ? node.children : [node],
		node.next
	);
	renderer.push();
	renderer.render(children, options);

	const slot_fragment_content = renderer.pop();
	if (!is_empty_template_literal(slot_fragment_content)) {
		if (options.slot_scopes.has(node.slot_template_name)) {
			if (node.slot_template_name === 'default') {
				throw new Error('Found elements without slot attribute when using slot="default"');
			}
			throw new Error(
				`Duplicate slot name "${node.slot_template_name}" in <${parent_inline_component.name}>`
			);
		}
		options.slot_scopes.set(node.slot_template_name, {
			input: get_slot_scope(node.lets),
			output: slot_fragment_content,
			statements: get_const_tags(node.const_tags)
		});
	}
}

/** @param {any} template_literal */
function is_empty_template_literal(template_literal) {
	return (
		template_literal.expressions.length === 0 &&
		template_literal.quasis.length === 1 &&
		template_literal.quasis[0].value.raw === ''
	);
}

/**
 * @param {any} node
 * @param {import('../Renderer.js').default} renderer
 * @param {import('../private.js').RenderOptions} _options
 */
function Tag (node, renderer, _options) {
	const snippet = node.expression.node;
	renderer.add_expression(
		node.parent && node.parent.type === 'Element' && node.parent.name === 'style'
			? snippet
			: x$1`@escape(${snippet})`
	);
}

/**
 * @param {import('../../nodes/Text.js').default} node
 * @param {import('../Renderer.js').default} renderer
 * @param {import('../private.js').RenderOptions} _options
 */
function Text (node, renderer, _options) {
	let text = node.data;
	if (node.use_space()) {
		text = ' ';
	} else if (
		// prettier formats one of the type casts incorrectly, moving it outside the parens, therefore disable
		// prettier-ignore
		!node.parent ||
		node.parent.type !== 'Element' ||
		( /** @type {import('../../nodes/Element.js').default} */ (node.parent).name !== 'script' &&
			/** @type {import('../../nodes/Element.js').default} */ (node.parent).name !== 'style')
	) {
		// unless this Text node is inside a <script> or <style> element, escape &,<,>
		text = escape_html(text);
	}
	renderer.add_string(text);
}

/**
 * @param {import('../../nodes/Title.js').default} node
 * @param {import('../Renderer.js').default} renderer
 * @param {import('../private.js').RenderOptions} options
 */
function Title (node, renderer, options) {
	renderer.push();
	renderer.add_string('<title>');
	renderer.render(node.children, options);
	renderer.add_string('</title>');
	const result = renderer.pop();
	renderer.add_expression(x$1`$$result.title = ${result}, ""`);
}

/**
 * Collapse string literals together
 * @param {import('estree').TemplateLiteral} literal
 */
function collapse_template_literal(literal) {
	if (!literal.quasis.length) return;

	const collapsed_quasis = [];
	const collapsed_expressions = [];

	let cur_quasi = literal.quasis[0];

	// An expression always follows a quasi and vice versa, ending with a quasi
	for (let i = 0; i < literal.quasis.length; i++) {
		const expr = literal.expressions[i];
		const next_quasi = literal.quasis[i + 1];
		// If an expression is a simple string literal, combine it with its preceding
		// and following quasi
		if (next_quasi && expr && expr.type === 'Literal' && typeof expr.value === 'string') {
			cur_quasi.value.raw += escape_template(expr.value) + next_quasi.value.raw;
		} else {
			if (expr) {
				collapsed_expressions.push(expr);
			}
			collapsed_quasis.push(cur_quasi);
			cur_quasi = next_quasi;
		}
	}

	literal.quasis = collapsed_quasis;
	literal.expressions = collapsed_expressions;
}

function noop() {}

/** @type {Record<string, {(node: any, renderer: Renderer, options: import('../../interfaces.js').CompileOptions): void}>} */
const handlers = {
	AwaitBlock,
	Body: noop,
	Comment,
	DebugTag,
	Document: noop,
	EachBlock,
	Element,
	Head,
	IfBlock,
	InlineComponent,
	KeyBlock,
	MustacheTag: Tag,
	Options: noop,
	RawMustacheTag: HtmlTag,
	Slot,
	SlotTemplate,
	Text,
	Title,
	Window: noop
};

class Renderer {
	has_bindings = false;

	/** @type {import('estree').Identifier} */
	name = undefined;

	/** @type {Array<{ current: { value: string }; literal: import('estree').TemplateLiteral }>} */
	stack = [];

	/** @type {{ value: string }} */
	current = undefined; // TODO can it just be `current: string`?

	/** @type {import('estree').TemplateLiteral} */
	literal = undefined;

	/** @type {import('../../interfaces.js').AppendTarget[]} */
	targets = [];
	constructor({ name }) {
		this.name = name;
		this.push();
	}

	/** @param {string} str */
	add_string(str) {
		this.current.value += escape_template(str);
	}

	/** @param {import('estree').Expression} node */
	add_expression(node) {
		this.literal.quasis.push({
			type: 'TemplateElement',
			value: { raw: this.current.value, cooked: null },
			tail: false
		});
		this.literal.expressions.push(node);
		this.current.value = '';
	}
	push() {
		const current = (this.current = { value: '' });
		const literal = (this.literal = {
			type: 'TemplateLiteral',
			expressions: [],
			quasis: []
		});
		this.stack.push({ current, literal });
	}
	pop() {
		this.literal.quasis.push({
			type: 'TemplateElement',
			value: { raw: this.current.value, cooked: null },
			tail: true
		});
		const popped = this.stack.pop();
		const last = this.stack[this.stack.length - 1];
		if (last) {
			this.literal = last.literal;
			this.current = last.current;
		}
		// Optimize the TemplateLiteral to remove unnecessary nodes
		collapse_template_literal(popped.literal);
		return popped.literal;
	}

	/**
	 * @param {import('../nodes/interfaces.js').INode[]} nodes
	 * @param {import('./private.js').RenderOptions} options
	 */
	render(nodes, options) {
		nodes.forEach((node) => {
			const handler = handlers[node.type];
			if (!handler) {
				throw new Error(`No handler for '${node.type}' nodes`);
			}
			handler(node, this, options);
		});
	}
}

/**
 * @param {import('../Component.js').default} component
 * @param {import('../../interfaces.js').CompileOptions} options
 * @returns {{ js: import('estree').Node[]; css: import('../../interfaces.js').CssResult; }}
 */
function ssr(component, options) {
	const renderer = new Renderer({
		name: component.name
	});
	const { name } = component;
	// create $$render function
	renderer.render(
		trim(component.fragment.children),
		Object.assign(
			{
				locate: component.locate
			},
			options
		)
	);
	// TODO put this inside the Renderer class
	const literal = renderer.pop();
	// TODO concatenate CSS maps
	const css = options.customElement
		? { code: null, map: null }
		: component.stylesheet.render(options.filename);
	const uses_rest = component.var_lookup.has('$$restProps');
	const props = component.vars.filter((variable) => !variable.module && variable.export_name);
	const rest = uses_rest
		? b$1`let $$restProps = @compute_rest_props($$props, [${props
				.map((prop) => `"${prop.export_name}"`)
				.join(',')}]);`
		: null;
	const uses_slots = component.var_lookup.has('$$slots');
	const slots = uses_slots ? b$1`let $$slots = @compute_slots(#slots);` : null;
	const reactive_stores = component.vars.filter(
		(variable) => variable.name[0] === '$' && variable.name[1] !== '$'
	);
	const reactive_store_subscriptions = reactive_stores
		.filter((store) => {
			const variable = component.var_lookup.get(store.name.slice(1));
			return !variable || variable.hoistable;
		})
		.map(({ name }) => {
			const store_name = name.slice(1);
			return b$1`
				${component.compile_options.dev && b$1`@validate_store(${store_name}, '${store_name}');`}
				${`$$unsubscribe_${store_name}`} = @subscribe(${store_name}, #value => ${name} = #value)
			`;
		});
	const reactive_store_unsubscriptions = reactive_stores.map(
		({ name }) => b$1`${`$$unsubscribe_${name.slice(1)}`}()`
	);
	const reactive_store_declarations = reactive_stores.map(({ name }) => {
		const store_name = name.slice(1);
		const store = component.var_lookup.get(store_name);
		if (store && store.reassigned) {
			const unsubscribe = `$$unsubscribe_${store_name}`;
			const subscribe = `$$subscribe_${store_name}`;
			return b$1`let ${name}, ${unsubscribe} = @noop, ${subscribe} = () => (${unsubscribe}(), ${unsubscribe} = @subscribe(${store_name}, $$value => ${name} = $$value), ${store_name})`;
		}
		return b$1`let ${name}, ${`$$unsubscribe_${store_name}`};`;
	});
	// instrument get/set store value
	if (component.ast.instance) {
		let scope = component.instance_scope;
		const map = component.instance_scope_map;
		walk(component.ast.instance.content, {
			enter(node) {
				if (map.has(node)) {
					scope = map.get(node);
				}
			},
			leave(node) {
				if (map.has(node)) {
					scope = scope.parent;
				}
				if (node.type === 'AssignmentExpression' || node.type === 'UpdateExpression') {
					const assignee = node.type === 'AssignmentExpression' ? node.left : node.argument;
					const names = new Set(extract_names(/** @type {import('estree').Node} */ (assignee)));
					const to_invalidate = new Set();
					for (const name of names) {
						const variable = component.var_lookup.get(name);
						if (
							variable &&
							!variable.hoistable &&
							!variable.global &&
							!variable.module &&
							(variable.subscribable || variable.name[0] === '$')
						) {
							to_invalidate.add(variable.name);
						}
					}
					if (to_invalidate.size) {
						this.replace(
							invalidate(/** @type {any} */ ({ component }), scope, node, to_invalidate, true)
						);
					}
				}
			}
		});
	}
	component.rewrite_props(({ name, reassigned }) => {
		const value = `$${name}`;
		let insert = reassigned
			? b$1`${`$$subscribe_${name}`}()`
			: b$1`${`$$unsubscribe_${name}`} = @subscribe(${name}, #value => $${value} = #value)`;
		if (component.compile_options.dev) {
			insert = b$1`@validate_store(${name}, '${name}'); ${insert}`;
		}
		return insert;
	});
	const instance_javascript = component.extract_javascript(component.ast.instance);
	// TODO only do this for props with a default value
	const parent_bindings = instance_javascript
		? component.vars
				.filter((variable) => !variable.module && variable.export_name)
				.map((prop) => {
					return b$1`if ($$props.${prop.export_name} === void 0 && $$bindings.${prop.export_name} && ${prop.name} !== void 0) $$bindings.${prop.export_name}(${prop.name});`;
				})
		: [];
	const injected = Array.from(component.injected_reactive_declaration_vars).filter((name) => {
		const variable = component.var_lookup.get(name);
		return variable.injected;
	});
	const reactive_declarations = component.reactive_declarations.map((d) => {
		const body = /** @type {import('estree').LabeledStatement} */ (d.node).body;
		let statement = b$1`${body}`;
		if (!d.declaration) {
			// TODO do not add label if it's not referenced
			statement = b$1`$: { ${statement} }`;
		}
		return statement;
	});
	const main = renderer.has_bindings
		? b$1`
			let $$settled;
			let $$rendered;

			do {
				$$settled = true;

				${reactive_declarations}

				$$rendered = ${literal};
			} while (!$$settled);

			${reactive_store_unsubscriptions}

			return $$rendered;
		`
		: b$1`
			${reactive_declarations}

			${reactive_store_unsubscriptions}

			return ${literal};`;
	const blocks = [
		...injected.map((name) => b$1`let ${name};`),
		rest,
		slots,
		...reactive_store_declarations,
		...reactive_store_subscriptions,
		instance_javascript,
		...parent_bindings,
		css.code && b$1`$$result.css.add(#css);`,
		main
	].filter(Boolean);
	const css_sourcemap_enabled = check_enable_sourcemap(options.enableSourcemap, 'css');
	const js = b$1`
		${
			css.code
				? b$1`
		const #css = {
			code: "${css.code}",
			map: ${css_sourcemap_enabled && css.map ? string_literal(css.map.toString()) : 'null'}
		};`
				: null
		}

		${component.extract_javascript(component.ast.module)}

		${component.fully_hoisted}

		const ${name} = @create_ssr_component(($$result, $$props, $$bindings, #slots) => {
			${blocks}
		});
	`;
	return { js, css };
}

/** @param {import('../nodes/interfaces.js').INode[]} nodes */
function trim(nodes) {
	let start = 0;
	for (; start < nodes.length; start += 1) {
		const node = /** @type {import('../nodes/Text.js').default} */ (nodes[start]);
		if (node.type !== 'Text') break;
		node.data = node.data.replace(/^\s+/, '');
		if (node.data) break;
	}
	let end = nodes.length;
	for (; end > start; end -= 1) {
		const node = /** @type {import('../nodes/Text.js').default} */ (nodes[end - 1]);
		if (node.type !== 'Text') break;
		node.data = node.data.trimRight();
		if (node.data) break;
	}
	return nodes.slice(start, end);
}

/** ----------------------------------------------------------------------
This file is automatically generated by `scripts/globals-extractor.js`.
Generated At: 2023-05-24T13:16:20.777Z
---------------------------------------------------------------------- */

var globals = new Set([
	'AbortController',
	'AbortSignal',
	'AbstractRange',
	'ActiveXObject',
	'AggregateError',
	'AnalyserNode',
	'Animation',
	'AnimationEffect',
	'AnimationEvent',
	'AnimationPlaybackEvent',
	'AnimationTimeline',
	'Array',
	'ArrayBuffer',
	'Atomics',
	'Attr',
	'Audio',
	'AudioBuffer',
	'AudioBufferSourceNode',
	'AudioContext',
	'AudioDestinationNode',
	'AudioListener',
	'AudioNode',
	'AudioParam',
	'AudioParamMap',
	'AudioProcessingEvent',
	'AudioScheduledSourceNode',
	'AudioWorklet',
	'AudioWorkletNode',
	'AuthenticatorAssertionResponse',
	'AuthenticatorAttestationResponse',
	'AuthenticatorResponse',
	'BarProp',
	'BaseAudioContext',
	'BeforeUnloadEvent',
	'BigInt',
	'BigInt64Array',
	'BigUint64Array',
	'BiquadFilterNode',
	'Blob',
	'BlobEvent',
	'Boolean',
	'BroadcastChannel',
	'ByteLengthQueuingStrategy',
	'CDATASection',
	'CSS',
	'CSSAnimation',
	'CSSConditionRule',
	'CSSCounterStyleRule',
	'CSSFontFaceRule',
	'CSSGroupingRule',
	'CSSImportRule',
	'CSSKeyframeRule',
	'CSSKeyframesRule',
	'CSSMediaRule',
	'CSSNamespaceRule',
	'CSSPageRule',
	'CSSRule',
	'CSSRuleList',
	'CSSStyleDeclaration',
	'CSSStyleRule',
	'CSSStyleSheet',
	'CSSSupportsRule',
	'CSSTransition',
	'Cache',
	'CacheStorage',
	'CanvasCaptureMediaStreamTrack',
	'CanvasGradient',
	'CanvasPattern',
	'CanvasRenderingContext2D',
	'ChannelMergerNode',
	'ChannelSplitterNode',
	'CharacterData',
	'ClientRect',
	'Clipboard',
	'ClipboardEvent',
	'ClipboardItem',
	'CloseEvent',
	'Comment',
	'CompositionEvent',
	'ConstantSourceNode',
	'ConvolverNode',
	'CountQueuingStrategy',
	'Credential',
	'CredentialsContainer',
	'Crypto',
	'CryptoKey',
	'CustomElementRegistry',
	'CustomEvent',
	'DOMException',
	'DOMImplementation',
	'DOMMatrix',
	'DOMMatrixReadOnly',
	'DOMParser',
	'DOMPoint',
	'DOMPointReadOnly',
	'DOMQuad',
	'DOMRect',
	'DOMRectList',
	'DOMRectReadOnly',
	'DOMStringList',
	'DOMStringMap',
	'DOMTokenList',
	'DataTransfer',
	'DataTransferItem',
	'DataTransferItemList',
	'DataView',
	'Date',
	'DelayNode',
	'DeviceMotionEvent',
	'DeviceOrientationEvent',
	'Document',
	'DocumentFragment',
	'DocumentTimeline',
	'DocumentType',
	'DragEvent',
	'DynamicsCompressorNode',
	'Element',
	'ElementInternals',
	'Enumerator',
	'Error',
	'ErrorEvent',
	'EvalError',
	'Event',
	'EventCounts',
	'EventSource',
	'EventTarget',
	'External',
	'File',
	'FileList',
	'FileReader',
	'FileSystem',
	'FileSystemDirectoryEntry',
	'FileSystemDirectoryHandle',
	'FileSystemDirectoryReader',
	'FileSystemEntry',
	'FileSystemFileEntry',
	'FileSystemFileHandle',
	'FileSystemHandle',
	'FinalizationRegistry',
	'Float32Array',
	'Float64Array',
	'FocusEvent',
	'FontFace',
	'FontFaceSet',
	'FontFaceSetLoadEvent',
	'FormData',
	'FormDataEvent',
	'Function',
	'GainNode',
	'Gamepad',
	'GamepadButton',
	'GamepadEvent',
	'GamepadHapticActuator',
	'Geolocation',
	'GeolocationCoordinates',
	'GeolocationPosition',
	'GeolocationPositionError',
	'HTMLAllCollection',
	'HTMLAnchorElement',
	'HTMLAreaElement',
	'HTMLAudioElement',
	'HTMLBRElement',
	'HTMLBaseElement',
	'HTMLBodyElement',
	'HTMLButtonElement',
	'HTMLCanvasElement',
	'HTMLCollection',
	'HTMLDListElement',
	'HTMLDataElement',
	'HTMLDataListElement',
	'HTMLDetailsElement',
	'HTMLDialogElement',
	'HTMLDirectoryElement',
	'HTMLDivElement',
	'HTMLDocument',
	'HTMLElement',
	'HTMLEmbedElement',
	'HTMLFieldSetElement',
	'HTMLFontElement',
	'HTMLFormControlsCollection',
	'HTMLFormElement',
	'HTMLFrameElement',
	'HTMLFrameSetElement',
	'HTMLHRElement',
	'HTMLHeadElement',
	'HTMLHeadingElement',
	'HTMLHtmlElement',
	'HTMLIFrameElement',
	'HTMLImageElement',
	'HTMLInputElement',
	'HTMLLIElement',
	'HTMLLabelElement',
	'HTMLLegendElement',
	'HTMLLinkElement',
	'HTMLMapElement',
	'HTMLMarqueeElement',
	'HTMLMediaElement',
	'HTMLMenuElement',
	'HTMLMetaElement',
	'HTMLMeterElement',
	'HTMLModElement',
	'HTMLOListElement',
	'HTMLObjectElement',
	'HTMLOptGroupElement',
	'HTMLOptionElement',
	'HTMLOptionsCollection',
	'HTMLOutputElement',
	'HTMLParagraphElement',
	'HTMLParamElement',
	'HTMLPictureElement',
	'HTMLPreElement',
	'HTMLProgressElement',
	'HTMLQuoteElement',
	'HTMLScriptElement',
	'HTMLSelectElement',
	'HTMLSlotElement',
	'HTMLSourceElement',
	'HTMLSpanElement',
	'HTMLStyleElement',
	'HTMLTableCaptionElement',
	'HTMLTableCellElement',
	'HTMLTableColElement',
	'HTMLTableElement',
	'HTMLTableRowElement',
	'HTMLTableSectionElement',
	'HTMLTemplateElement',
	'HTMLTextAreaElement',
	'HTMLTimeElement',
	'HTMLTitleElement',
	'HTMLTrackElement',
	'HTMLUListElement',
	'HTMLUnknownElement',
	'HTMLVideoElement',
	'HashChangeEvent',
	'Headers',
	'History',
	'IDBCursor',
	'IDBCursorWithValue',
	'IDBDatabase',
	'IDBFactory',
	'IDBIndex',
	'IDBKeyRange',
	'IDBObjectStore',
	'IDBOpenDBRequest',
	'IDBRequest',
	'IDBTransaction',
	'IDBVersionChangeEvent',
	'IIRFilterNode',
	'IdleDeadline',
	'Image',
	'ImageBitmap',
	'ImageBitmapRenderingContext',
	'ImageData',
	'Infinity',
	'InputDeviceInfo',
	'InputEvent',
	'Int16Array',
	'Int32Array',
	'Int8Array',
	'InternalError',
	'IntersectionObserver',
	'IntersectionObserverEntry',
	'Intl',
	'JSON',
	'KeyboardEvent',
	'KeyframeEffect',
	'Location',
	'Lock',
	'LockManager',
	'Map',
	'Math',
	'MathMLElement',
	'MediaCapabilities',
	'MediaDeviceInfo',
	'MediaDevices',
	'MediaElementAudioSourceNode',
	'MediaEncryptedEvent',
	'MediaError',
	'MediaKeyMessageEvent',
	'MediaKeySession',
	'MediaKeyStatusMap',
	'MediaKeySystemAccess',
	'MediaKeys',
	'MediaList',
	'MediaMetadata',
	'MediaQueryList',
	'MediaQueryListEvent',
	'MediaRecorder',
	'MediaRecorderErrorEvent',
	'MediaSession',
	'MediaSource',
	'MediaStream',
	'MediaStreamAudioDestinationNode',
	'MediaStreamAudioSourceNode',
	'MediaStreamTrack',
	'MediaStreamTrackEvent',
	'MessageChannel',
	'MessageEvent',
	'MessagePort',
	'MimeType',
	'MimeTypeArray',
	'MouseEvent',
	'MutationEvent',
	'MutationObserver',
	'MutationRecord',
	'NaN',
	'NamedNodeMap',
	'NavigationPreloadManager',
	'Navigator',
	'NetworkInformation',
	'Node',
	'NodeFilter',
	'NodeIterator',
	'NodeList',
	'Notification',
	'Number',
	'Object',
	'OfflineAudioCompletionEvent',
	'OfflineAudioContext',
	'Option',
	'OscillatorNode',
	'OverconstrainedError',
	'PageTransitionEvent',
	'PannerNode',
	'Path2D',
	'PaymentAddress',
	'PaymentMethodChangeEvent',
	'PaymentRequest',
	'PaymentRequestUpdateEvent',
	'PaymentResponse',
	'Performance',
	'PerformanceEntry',
	'PerformanceEventTiming',
	'PerformanceMark',
	'PerformanceMeasure',
	'PerformanceNavigation',
	'PerformanceNavigationTiming',
	'PerformanceObserver',
	'PerformanceObserverEntryList',
	'PerformancePaintTiming',
	'PerformanceResourceTiming',
	'PerformanceServerTiming',
	'PerformanceTiming',
	'PeriodicWave',
	'PermissionStatus',
	'Permissions',
	'PictureInPictureWindow',
	'Plugin',
	'PluginArray',
	'PointerEvent',
	'PopStateEvent',
	'ProcessingInstruction',
	'ProgressEvent',
	'Promise',
	'PromiseRejectionEvent',
	'Proxy',
	'PublicKeyCredential',
	'PushManager',
	'PushSubscription',
	'PushSubscriptionOptions',
	'RTCCertificate',
	'RTCDTMFSender',
	'RTCDTMFToneChangeEvent',
	'RTCDataChannel',
	'RTCDataChannelEvent',
	'RTCDtlsTransport',
	'RTCEncodedAudioFrame',
	'RTCEncodedVideoFrame',
	'RTCError',
	'RTCErrorEvent',
	'RTCIceCandidate',
	'RTCIceTransport',
	'RTCPeerConnection',
	'RTCPeerConnectionIceErrorEvent',
	'RTCPeerConnectionIceEvent',
	'RTCRtpReceiver',
	'RTCRtpSender',
	'RTCRtpTransceiver',
	'RTCSctpTransport',
	'RTCSessionDescription',
	'RTCStatsReport',
	'RTCTrackEvent',
	'RadioNodeList',
	'Range',
	'RangeError',
	'ReadableByteStreamController',
	'ReadableStream',
	'ReadableStreamBYOBReader',
	'ReadableStreamBYOBRequest',
	'ReadableStreamDefaultController',
	'ReadableStreamDefaultReader',
	'ReferenceError',
	'Reflect',
	'RegExp',
	'RemotePlayback',
	'Request',
	'ResizeObserver',
	'ResizeObserverEntry',
	'ResizeObserverSize',
	'Response',
	'SVGAElement',
	'SVGAngle',
	'SVGAnimateElement',
	'SVGAnimateMotionElement',
	'SVGAnimateTransformElement',
	'SVGAnimatedAngle',
	'SVGAnimatedBoolean',
	'SVGAnimatedEnumeration',
	'SVGAnimatedInteger',
	'SVGAnimatedLength',
	'SVGAnimatedLengthList',
	'SVGAnimatedNumber',
	'SVGAnimatedNumberList',
	'SVGAnimatedPreserveAspectRatio',
	'SVGAnimatedRect',
	'SVGAnimatedString',
	'SVGAnimatedTransformList',
	'SVGAnimationElement',
	'SVGCircleElement',
	'SVGClipPathElement',
	'SVGComponentTransferFunctionElement',
	'SVGCursorElement',
	'SVGDefsElement',
	'SVGDescElement',
	'SVGElement',
	'SVGEllipseElement',
	'SVGFEBlendElement',
	'SVGFEColorMatrixElement',
	'SVGFEComponentTransferElement',
	'SVGFECompositeElement',
	'SVGFEConvolveMatrixElement',
	'SVGFEDiffuseLightingElement',
	'SVGFEDisplacementMapElement',
	'SVGFEDistantLightElement',
	'SVGFEDropShadowElement',
	'SVGFEFloodElement',
	'SVGFEFuncAElement',
	'SVGFEFuncBElement',
	'SVGFEFuncGElement',
	'SVGFEFuncRElement',
	'SVGFEGaussianBlurElement',
	'SVGFEImageElement',
	'SVGFEMergeElement',
	'SVGFEMergeNodeElement',
	'SVGFEMorphologyElement',
	'SVGFEOffsetElement',
	'SVGFEPointLightElement',
	'SVGFESpecularLightingElement',
	'SVGFESpotLightElement',
	'SVGFETileElement',
	'SVGFETurbulenceElement',
	'SVGFilterElement',
	'SVGForeignObjectElement',
	'SVGGElement',
	'SVGGeometryElement',
	'SVGGradientElement',
	'SVGGraphicsElement',
	'SVGImageElement',
	'SVGLength',
	'SVGLengthList',
	'SVGLineElement',
	'SVGLinearGradientElement',
	'SVGMPathElement',
	'SVGMarkerElement',
	'SVGMaskElement',
	'SVGMatrix',
	'SVGMetadataElement',
	'SVGNumber',
	'SVGNumberList',
	'SVGPathElement',
	'SVGPatternElement',
	'SVGPoint',
	'SVGPointList',
	'SVGPolygonElement',
	'SVGPolylineElement',
	'SVGPreserveAspectRatio',
	'SVGRadialGradientElement',
	'SVGRect',
	'SVGRectElement',
	'SVGSVGElement',
	'SVGScriptElement',
	'SVGSetElement',
	'SVGStopElement',
	'SVGStringList',
	'SVGStyleElement',
	'SVGSwitchElement',
	'SVGSymbolElement',
	'SVGTSpanElement',
	'SVGTextContentElement',
	'SVGTextElement',
	'SVGTextPathElement',
	'SVGTextPositioningElement',
	'SVGTitleElement',
	'SVGTransform',
	'SVGTransformList',
	'SVGUnitTypes',
	'SVGUseElement',
	'SVGViewElement',
	'SafeArray',
	'Screen',
	'ScreenOrientation',
	'ScriptProcessorNode',
	'SecurityPolicyViolationEvent',
	'Selection',
	'ServiceWorker',
	'ServiceWorkerContainer',
	'ServiceWorkerRegistration',
	'Set',
	'ShadowRoot',
	'SharedArrayBuffer',
	'SharedWorker',
	'SourceBuffer',
	'SourceBufferList',
	'SpeechRecognitionAlternative',
	'SpeechRecognitionErrorEvent',
	'SpeechRecognitionResult',
	'SpeechRecognitionResultList',
	'SpeechSynthesis',
	'SpeechSynthesisErrorEvent',
	'SpeechSynthesisEvent',
	'SpeechSynthesisUtterance',
	'SpeechSynthesisVoice',
	'StaticRange',
	'StereoPannerNode',
	'Storage',
	'StorageEvent',
	'StorageManager',
	'String',
	'StyleMedia',
	'StyleSheet',
	'StyleSheetList',
	'SubmitEvent',
	'SubtleCrypto',
	'Symbol',
	'SyntaxError',
	'Text',
	'TextDecoder',
	'TextDecoderStream',
	'TextEncoder',
	'TextEncoderStream',
	'TextMetrics',
	'TextTrack',
	'TextTrackCue',
	'TextTrackCueList',
	'TextTrackList',
	'TimeRanges',
	'Touch',
	'TouchEvent',
	'TouchList',
	'TrackEvent',
	'TransformStream',
	'TransformStreamDefaultController',
	'TransitionEvent',
	'TreeWalker',
	'TypeError',
	'UIEvent',
	'URIError',
	'URL',
	'URLSearchParams',
	'Uint16Array',
	'Uint32Array',
	'Uint8Array',
	'Uint8ClampedArray',
	'VBArray',
	'VTTCue',
	'VTTRegion',
	'ValidityState',
	'VarDate',
	'VideoColorSpace',
	'VideoPlaybackQuality',
	'VisualViewport',
	'WSH',
	'WScript',
	'WaveShaperNode',
	'WeakMap',
	'WeakRef',
	'WeakSet',
	'WebAssembly',
	'WebGL2RenderingContext',
	'WebGLActiveInfo',
	'WebGLBuffer',
	'WebGLContextEvent',
	'WebGLFramebuffer',
	'WebGLProgram',
	'WebGLQuery',
	'WebGLRenderbuffer',
	'WebGLRenderingContext',
	'WebGLSampler',
	'WebGLShader',
	'WebGLShaderPrecisionFormat',
	'WebGLSync',
	'WebGLTexture',
	'WebGLTransformFeedback',
	'WebGLUniformLocation',
	'WebGLVertexArrayObject',
	'WebKitCSSMatrix',
	'WebSocket',
	'WheelEvent',
	'Window',
	'Worker',
	'Worklet',
	'WritableStream',
	'WritableStreamDefaultController',
	'WritableStreamDefaultWriter',
	'XMLDocument',
	'XMLHttpRequest',
	'XMLHttpRequestEventTarget',
	'XMLHttpRequestUpload',
	'XMLSerializer',
	'XPathEvaluator',
	'XPathExpression',
	'XPathResult',
	'XSLTProcessor',
	'addEventListener',
	'alert',
	'atob',
	'blur',
	'btoa',
	'caches',
	'cancelAnimationFrame',
	'cancelIdleCallback',
	'captureEvents',
	'clearInterval',
	'clearTimeout',
	'clientInformation',
	'close',
	'closed',
	'confirm',
	'console',
	'createImageBitmap',
	'crossOriginIsolated',
	'crypto',
	'customElements',
	'decodeURI',
	'decodeURIComponent',
	'devicePixelRatio',
	'dispatchEvent',
	'document',
	'encodeURI',
	'encodeURIComponent',
	'escape',
	'eval',
	'event',
	'external',
	'fetch',
	'focus',
	'frameElement',
	'frames',
	'getComputedStyle',
	'getSelection',
	'global',
	'globalThis',
	'history',
	'importScripts',
	'indexedDB',
	'innerHeight',
	'innerWidth',
	'isFinite',
	'isNaN',
	'isSecureContext',
	'length',
	'localStorage',
	'location',
	'locationbar',
	'matchMedia',
	'menubar',
	'moveBy',
	'moveTo',
	'name',
	'navigator',
	'onabort',
	'onafterprint',
	'onanimationcancel',
	'onanimationend',
	'onanimationiteration',
	'onanimationstart',
	'onauxclick',
	'onbeforeprint',
	'onbeforeunload',
	'onblur',
	'oncanplay',
	'oncanplaythrough',
	'onchange',
	'onclick',
	'onclose',
	'oncontextmenu',
	'oncuechange',
	'ondblclick',
	'ondevicemotion',
	'ondeviceorientation',
	'ondrag',
	'ondragend',
	'ondragenter',
	'ondragleave',
	'ondragover',
	'ondragstart',
	'ondrop',
	'ondurationchange',
	'onemptied',
	'onended',
	'onerror',
	'onfocus',
	'onformdata',
	'ongamepadconnected',
	'ongamepaddisconnected',
	'ongotpointercapture',
	'onhashchange',
	'oninput',
	'oninvalid',
	'onkeydown',
	'onkeypress',
	'onkeyup',
	'onlanguagechange',
	'onload',
	'onloadeddata',
	'onloadedmetadata',
	'onloadstart',
	'onlostpointercapture',
	'onmessage',
	'onmessageerror',
	'onmousedown',
	'onmouseenter',
	'onmouseleave',
	'onmousemove',
	'onmouseout',
	'onmouseover',
	'onmouseup',
	'onoffline',
	'ononline',
	'onorientationchange',
	'onpagehide',
	'onpageshow',
	'onpause',
	'onplay',
	'onplaying',
	'onpointercancel',
	'onpointerdown',
	'onpointerenter',
	'onpointerleave',
	'onpointermove',
	'onpointerout',
	'onpointerover',
	'onpointerup',
	'onpopstate',
	'onprogress',
	'onratechange',
	'onrejectionhandled',
	'onreset',
	'onresize',
	'onscroll',
	'onsecuritypolicyviolation',
	'onseeked',
	'onseeking',
	'onselect',
	'onselectionchange',
	'onselectstart',
	'onslotchange',
	'onstalled',
	'onstorage',
	'onsubmit',
	'onsuspend',
	'ontimeupdate',
	'ontoggle',
	'ontouchcancel',
	'ontouchend',
	'ontouchmove',
	'ontouchstart',
	'ontransitioncancel',
	'ontransitionend',
	'ontransitionrun',
	'ontransitionstart',
	'onunhandledrejection',
	'onunload',
	'onvolumechange',
	'onwaiting',
	'onwebkitanimationend',
	'onwebkitanimationiteration',
	'onwebkitanimationstart',
	'onwebkittransitionend',
	'onwheel',
	'open',
	'opener',
	'orientation',
	'origin',
	'outerHeight',
	'outerWidth',
	'pageXOffset',
	'pageYOffset',
	'parent',
	'parseFloat',
	'parseInt',
	'performance',
	'personalbar',
	'postMessage',
	'print',
	'process',
	'prompt',
	'queueMicrotask',
	'releaseEvents',
	'removeEventListener',
	'reportError',
	'requestAnimationFrame',
	'requestIdleCallback',
	'resizeBy',
	'resizeTo',
	'screen',
	'screenLeft',
	'screenTop',
	'screenX',
	'screenY',
	'scroll',
	'scrollBy',
	'scrollTo',
	'scrollX',
	'scrollY',
	'scrollbars',
	'self',
	'sessionStorage',
	'setInterval',
	'setTimeout',
	'speechSynthesis',
	'status',
	'statusbar',
	'stop',
	'structuredClone',
	'toString',
	'toolbar',
	'top',
	'undefined',
	'unescape',
	'visualViewport',
	'webkitURL',
	'window'
]);

/**
 * @param {any} program
 * @param {import('estree').Identifier} name
 * @param {string} banner
 * @param {any} sveltePath
 * @param {Array<{ name: string; alias: import('estree').Identifier }>} helpers
 * @param {Array<{ name: string; alias: import('estree').Identifier }>} globals
 * @param {import('estree').ImportDeclaration[]} imports
 * @param {Export[]} module_exports
 * @param {import('estree').ExportNamedDeclaration[]} exports_from
 */
function create_module(
	program,
	name,
	banner,
	sveltePath = 'svelte',
	helpers,
	globals,
	imports,
	module_exports,
	exports_from
) {
	const internal_path = `${sveltePath}/internal`;
	helpers.sort(
		/**
		 * @param {any} a
		 * @param {any} b
		 */ (a, b) => (a.name < b.name ? -1 : 1)
	);
	globals.sort(
		/**
		 * @param {any} a
		 * @param {any} b
		 */ (a, b) => (a.name < b.name ? -1 : 1)
	);
	return esm(
		program,
		name,
		banner,
		sveltePath,
		internal_path,
		helpers,
		globals,
		imports,
		module_exports,
		exports_from
	);
}

/**
 * @param {any} source
 * @param {any} sveltePath
 */
function edit_source(source, sveltePath) {
	return source === 'svelte' || source.startsWith('svelte/')
		? source.replace('svelte', sveltePath)
		: source;
}

/**
 * @param {Array<{ name: string; alias: import('estree').Identifier }>} globals
 * @param {Array<{ name: string; alias: import('estree').Identifier }>} helpers
 */
function get_internal_globals(globals, helpers) {
	return (
		globals.length > 0 && {
			type: 'VariableDeclaration',
			kind: 'const',
			declarations: [
				{
					type: 'VariableDeclarator',
					id: {
						type: 'ObjectPattern',
						properties: globals.map(
							/** @param {any} g */ (g) => ({
								type: 'Property',
								method: false,
								shorthand: false,
								computed: false,
								key: { type: 'Identifier', name: g.name },
								value: g.alias,
								kind: 'init'
							})
						)
					},
					init: helpers.find(/** @param {any}params_0 */ ({ name }) => name === 'globals').alias
				}
			]
		}
	);
}

/**
 * @param {any} program
 * @param {import('estree').Identifier} name
 * @param {string} banner
 * @param {string} sveltePath
 * @param {string} internal_path
 * @param {Array<{ name: string; alias: import('estree').Identifier }>} helpers
 * @param {Array<{ name: string; alias: import('estree').Identifier }>} globals
 * @param {import('estree').ImportDeclaration[]} imports
 * @param {Export[]} module_exports
 * @param {import('estree').ExportNamedDeclaration[]} exports_from
 */
function esm(
	program,
	name,
	banner,
	sveltePath,
	internal_path,
	helpers,
	globals,
	imports,
	module_exports,
	exports_from
) {
	const import_declaration = {
		type: 'ImportDeclaration',
		specifiers: helpers.map(
			/** @param {any} h */ (h) => ({
				type: 'ImportSpecifier',
				local: h.alias,
				imported: { type: 'Identifier', name: h.name }
			})
		),
		source: { type: 'Literal', value: internal_path }
	};
	const internal_globals = get_internal_globals(globals, helpers);
	// edit user imports

	/** @param {any} node */
	function rewrite_import(node) {
		const value = edit_source(node.source.value, sveltePath);
		if (node.source.value !== value) {
			node.source.value = value;
			node.source.raw = null;
		}
	}
	imports.forEach(rewrite_import);
	exports_from.forEach(rewrite_import);
	const exports = module_exports.length > 0 && {
		type: 'ExportNamedDeclaration',
		specifiers: module_exports.map(
			/** @param {any} x */ (x) => ({
				type: 'Specifier',
				local: { type: 'Identifier', name: x.name },
				exported: { type: 'Identifier', name: x.as }
			})
		)
	};
	program.body = b$1`
		/* ${banner} */

		${import_declaration}
		${internal_globals}
		${imports}
		${exports_from}

		${program.body}

		export default ${name};
		${exports}
	`;
}

/**
 * @typedef {Object} Export
 * @property {string} name
 * @property {string} as
 */

class BitSet {
	constructor(arg) {
		this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
	}

	add(n) {
		this.bits[n >> 5] |= 1 << (n & 31);
	}

	has(n) {
		return !!(this.bits[n >> 5] & (1 << (n & 31)));
	}
}

class Chunk {
	constructor(start, end, content) {
		this.start = start;
		this.end = end;
		this.original = content;

		this.intro = '';
		this.outro = '';

		this.content = content;
		this.storeName = false;
		this.edited = false;

		{
			this.previous = null;
			this.next = null;
		}
	}

	appendLeft(content) {
		this.outro += content;
	}

	appendRight(content) {
		this.intro = this.intro + content;
	}

	clone() {
		const chunk = new Chunk(this.start, this.end, this.original);

		chunk.intro = this.intro;
		chunk.outro = this.outro;
		chunk.content = this.content;
		chunk.storeName = this.storeName;
		chunk.edited = this.edited;

		return chunk;
	}

	contains(index) {
		return this.start < index && index < this.end;
	}

	eachNext(fn) {
		let chunk = this;
		while (chunk) {
			fn(chunk);
			chunk = chunk.next;
		}
	}

	eachPrevious(fn) {
		let chunk = this;
		while (chunk) {
			fn(chunk);
			chunk = chunk.previous;
		}
	}

	edit(content, storeName, contentOnly) {
		this.content = content;
		if (!contentOnly) {
			this.intro = '';
			this.outro = '';
		}
		this.storeName = storeName;

		this.edited = true;

		return this;
	}

	prependLeft(content) {
		this.outro = content + this.outro;
	}

	prependRight(content) {
		this.intro = content + this.intro;
	}

	split(index) {
		const sliceIndex = index - this.start;

		const originalBefore = this.original.slice(0, sliceIndex);
		const originalAfter = this.original.slice(sliceIndex);

		this.original = originalBefore;

		const newChunk = new Chunk(index, this.end, originalAfter);
		newChunk.outro = this.outro;
		this.outro = '';

		this.end = index;

		if (this.edited) {
			// TODO is this block necessary?...
			newChunk.edit('', false);
			this.content = '';
		} else {
			this.content = originalBefore;
		}

		newChunk.next = this.next;
		if (newChunk.next) newChunk.next.previous = newChunk;
		newChunk.previous = this;
		this.next = newChunk;

		return newChunk;
	}

	toString() {
		return this.intro + this.content + this.outro;
	}

	trimEnd(rx) {
		this.outro = this.outro.replace(rx, '');
		if (this.outro.length) return true;

		const trimmed = this.content.replace(rx, '');

		if (trimmed.length) {
			if (trimmed !== this.content) {
				this.split(this.start + trimmed.length).edit('', undefined, true);
			}
			return true;
		} else {
			this.edit('', undefined, true);

			this.intro = this.intro.replace(rx, '');
			if (this.intro.length) return true;
		}
	}

	trimStart(rx) {
		this.intro = this.intro.replace(rx, '');
		if (this.intro.length) return true;

		const trimmed = this.content.replace(rx, '');

		if (trimmed.length) {
			if (trimmed !== this.content) {
				this.split(this.end - trimmed.length);
				this.edit('', undefined, true);
			}
			return true;
		} else {
			this.edit('', undefined, true);

			this.outro = this.outro.replace(rx, '');
			if (this.outro.length) return true;
		}
	}
}

function getBtoa () {
	if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
		return (str) => window.btoa(unescape(encodeURIComponent(str)));
	} else if (typeof Buffer === 'function') {
		return (str) => Buffer.from(str, 'utf-8').toString('base64');
	} else {
		return () => {
			throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
		};
	}
}

const btoa$1 = /*#__PURE__*/ getBtoa();

class SourceMap {
	constructor(properties) {
		this.version = 3;
		this.file = properties.file;
		this.sources = properties.sources;
		this.sourcesContent = properties.sourcesContent;
		this.names = properties.names;
		this.mappings = encode(properties.mappings);
		if (typeof properties.x_google_ignoreList !== 'undefined') {
			this.x_google_ignoreList = properties.x_google_ignoreList;
		}
	}

	toString() {
		return JSON.stringify(this);
	}

	toUrl() {
		return 'data:application/json;charset=utf-8;base64,' + btoa$1(this.toString());
	}
}

function guessIndent(code) {
	const lines = code.split('\n');

	const tabbed = lines.filter((line) => /^\t+/.test(line));
	const spaced = lines.filter((line) => /^ {2,}/.test(line));

	if (tabbed.length === 0 && spaced.length === 0) {
		return null;
	}

	// More lines tabbed than spaced? Assume tabs, and
	// default to tabs in the case of a tie (or nothing
	// to go on)
	if (tabbed.length >= spaced.length) {
		return '\t';
	}

	// Otherwise, we need to guess the multiple
	const min = spaced.reduce((previous, current) => {
		const numSpaces = /^ +/.exec(current)[0].length;
		return Math.min(numSpaces, previous);
	}, Infinity);

	return new Array(min + 1).join(' ');
}

function getRelativePath(from, to) {
	const fromParts = from.split(/[/\\]/);
	const toParts = to.split(/[/\\]/);

	fromParts.pop(); // get dirname

	while (fromParts[0] === toParts[0]) {
		fromParts.shift();
		toParts.shift();
	}

	if (fromParts.length) {
		let i = fromParts.length;
		while (i--) fromParts[i] = '..';
	}

	return fromParts.concat(toParts).join('/');
}

const toString = Object.prototype.toString;

function isObject(thing) {
	return toString.call(thing) === '[object Object]';
}

function getLocator(source) {
	const originalLines = source.split('\n');
	const lineOffsets = [];

	for (let i = 0, pos = 0; i < originalLines.length; i++) {
		lineOffsets.push(pos);
		pos += originalLines[i].length + 1;
	}

	return function locate(index) {
		let i = 0;
		let j = lineOffsets.length;
		while (i < j) {
			const m = (i + j) >> 1;
			if (index < lineOffsets[m]) {
				j = m;
			} else {
				i = m + 1;
			}
		}
		const line = i - 1;
		const column = index - lineOffsets[line];
		return { line, column };
	};
}

class Mappings {
	constructor(hires) {
		this.hires = hires;
		this.generatedCodeLine = 0;
		this.generatedCodeColumn = 0;
		this.raw = [];
		this.rawSegments = this.raw[this.generatedCodeLine] = [];
		this.pending = null;
	}

	addEdit(sourceIndex, content, loc, nameIndex) {
		if (content.length) {
			const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
			if (nameIndex >= 0) {
				segment.push(nameIndex);
			}
			this.rawSegments.push(segment);
		} else if (this.pending) {
			this.rawSegments.push(this.pending);
		}

		this.advance(content);
		this.pending = null;
	}

	addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
		let originalCharIndex = chunk.start;
		let first = true;

		while (originalCharIndex < chunk.end) {
			if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
				this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
			}

			if (original[originalCharIndex] === '\n') {
				loc.line += 1;
				loc.column = 0;
				this.generatedCodeLine += 1;
				this.raw[this.generatedCodeLine] = this.rawSegments = [];
				this.generatedCodeColumn = 0;
				first = true;
			} else {
				loc.column += 1;
				this.generatedCodeColumn += 1;
				first = false;
			}

			originalCharIndex += 1;
		}

		this.pending = null;
	}

	advance(str) {
		if (!str) return;

		const lines = str.split('\n');

		if (lines.length > 1) {
			for (let i = 0; i < lines.length - 1; i++) {
				this.generatedCodeLine++;
				this.raw[this.generatedCodeLine] = this.rawSegments = [];
			}
			this.generatedCodeColumn = 0;
		}

		this.generatedCodeColumn += lines[lines.length - 1].length;
	}
}

const n = '\n';

const warned = {
	insertLeft: false,
	insertRight: false,
	storeName: false,
};

class MagicString {
	constructor(string, options = {}) {
		const chunk = new Chunk(0, string.length, string);

		Object.defineProperties(this, {
			original: { writable: true, value: string },
			outro: { writable: true, value: '' },
			intro: { writable: true, value: '' },
			firstChunk: { writable: true, value: chunk },
			lastChunk: { writable: true, value: chunk },
			lastSearchedChunk: { writable: true, value: chunk },
			byStart: { writable: true, value: {} },
			byEnd: { writable: true, value: {} },
			filename: { writable: true, value: options.filename },
			indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
			sourcemapLocations: { writable: true, value: new BitSet() },
			storedNames: { writable: true, value: {} },
			indentStr: { writable: true, value: undefined },
			ignoreList: { writable: true, value: options.ignoreList },
		});

		this.byStart[0] = chunk;
		this.byEnd[string.length] = chunk;
	}

	addSourcemapLocation(char) {
		this.sourcemapLocations.add(char);
	}

	append(content) {
		if (typeof content !== 'string') throw new TypeError('outro content must be a string');

		this.outro += content;
		return this;
	}

	appendLeft(index, content) {
		if (typeof content !== 'string') throw new TypeError('inserted content must be a string');

		this._split(index);

		const chunk = this.byEnd[index];

		if (chunk) {
			chunk.appendLeft(content);
		} else {
			this.intro += content;
		}
		return this;
	}

	appendRight(index, content) {
		if (typeof content !== 'string') throw new TypeError('inserted content must be a string');

		this._split(index);

		const chunk = this.byStart[index];

		if (chunk) {
			chunk.appendRight(content);
		} else {
			this.outro += content;
		}
		return this;
	}

	clone() {
		const cloned = new MagicString(this.original, { filename: this.filename });

		let originalChunk = this.firstChunk;
		let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());

		while (originalChunk) {
			cloned.byStart[clonedChunk.start] = clonedChunk;
			cloned.byEnd[clonedChunk.end] = clonedChunk;

			const nextOriginalChunk = originalChunk.next;
			const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();

			if (nextClonedChunk) {
				clonedChunk.next = nextClonedChunk;
				nextClonedChunk.previous = clonedChunk;

				clonedChunk = nextClonedChunk;
			}

			originalChunk = nextOriginalChunk;
		}

		cloned.lastChunk = clonedChunk;

		if (this.indentExclusionRanges) {
			cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
		}

		cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);

		cloned.intro = this.intro;
		cloned.outro = this.outro;

		return cloned;
	}

	generateDecodedMap(options) {
		options = options || {};

		const sourceIndex = 0;
		const names = Object.keys(this.storedNames);
		const mappings = new Mappings(options.hires);

		const locate = getLocator(this.original);

		if (this.intro) {
			mappings.advance(this.intro);
		}

		this.firstChunk.eachNext((chunk) => {
			const loc = locate(chunk.start);

			if (chunk.intro.length) mappings.advance(chunk.intro);

			if (chunk.edited) {
				mappings.addEdit(
					sourceIndex,
					chunk.content,
					loc,
					chunk.storeName ? names.indexOf(chunk.original) : -1
				);
			} else {
				mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
			}

			if (chunk.outro.length) mappings.advance(chunk.outro);
		});

		return {
			file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
			sources: [options.source ? getRelativePath(options.file || '', options.source) : (options.file || '')],
			sourcesContent: options.includeContent ? [this.original] : undefined,
			names,
			mappings: mappings.raw,
			x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined
		};
	}

	generateMap(options) {
		return new SourceMap(this.generateDecodedMap(options));
	}

	_ensureindentStr() {
		if (this.indentStr === undefined) {
			this.indentStr = guessIndent(this.original);
		}
	}

	_getRawIndentString() {
		this._ensureindentStr();
		return this.indentStr;
	}

	getIndentString() {
		this._ensureindentStr();
		return this.indentStr === null ? '\t' : this.indentStr;
	}

	indent(indentStr, options) {
		const pattern = /^[^\r\n]/gm;

		if (isObject(indentStr)) {
			options = indentStr;
			indentStr = undefined;
		}

		if (indentStr === undefined) {
			this._ensureindentStr();
			indentStr = this.indentStr || '\t';
		}

		if (indentStr === '') return this; // noop

		options = options || {};

		// Process exclusion ranges
		const isExcluded = {};

		if (options.exclude) {
			const exclusions =
				typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
			exclusions.forEach((exclusion) => {
				for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
					isExcluded[i] = true;
				}
			});
		}

		let shouldIndentNextCharacter = options.indentStart !== false;
		const replacer = (match) => {
			if (shouldIndentNextCharacter) return `${indentStr}${match}`;
			shouldIndentNextCharacter = true;
			return match;
		};

		this.intro = this.intro.replace(pattern, replacer);

		let charIndex = 0;
		let chunk = this.firstChunk;

		while (chunk) {
			const end = chunk.end;

			if (chunk.edited) {
				if (!isExcluded[charIndex]) {
					chunk.content = chunk.content.replace(pattern, replacer);

					if (chunk.content.length) {
						shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
					}
				}
			} else {
				charIndex = chunk.start;

				while (charIndex < end) {
					if (!isExcluded[charIndex]) {
						const char = this.original[charIndex];

						if (char === '\n') {
							shouldIndentNextCharacter = true;
						} else if (char !== '\r' && shouldIndentNextCharacter) {
							shouldIndentNextCharacter = false;

							if (charIndex === chunk.start) {
								chunk.prependRight(indentStr);
							} else {
								this._splitChunk(chunk, charIndex);
								chunk = chunk.next;
								chunk.prependRight(indentStr);
							}
						}
					}

					charIndex += 1;
				}
			}

			charIndex = chunk.end;
			chunk = chunk.next;
		}

		this.outro = this.outro.replace(pattern, replacer);

		return this;
	}

	insert() {
		throw new Error(
			'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)'
		);
	}

	insertLeft(index, content) {
		if (!warned.insertLeft) {
			console.warn(
				'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'
			); // eslint-disable-line no-console
			warned.insertLeft = true;
		}

		return this.appendLeft(index, content);
	}

	insertRight(index, content) {
		if (!warned.insertRight) {
			console.warn(
				'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'
			); // eslint-disable-line no-console
			warned.insertRight = true;
		}

		return this.prependRight(index, content);
	}

	move(start, end, index) {
		if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');

		this._split(start);
		this._split(end);
		this._split(index);

		const first = this.byStart[start];
		const last = this.byEnd[end];

		const oldLeft = first.previous;
		const oldRight = last.next;

		const newRight = this.byStart[index];
		if (!newRight && last === this.lastChunk) return this;
		const newLeft = newRight ? newRight.previous : this.lastChunk;

		if (oldLeft) oldLeft.next = oldRight;
		if (oldRight) oldRight.previous = oldLeft;

		if (newLeft) newLeft.next = first;
		if (newRight) newRight.previous = last;

		if (!first.previous) this.firstChunk = last.next;
		if (!last.next) {
			this.lastChunk = first.previous;
			this.lastChunk.next = null;
		}

		first.previous = newLeft;
		last.next = newRight || null;

		if (!newLeft) this.firstChunk = first;
		if (!newRight) this.lastChunk = last;
		return this;
	}

	overwrite(start, end, content, options) {
		options = options || {};
		return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
	}

	update(start, end, content, options) {
		if (typeof content !== 'string') throw new TypeError('replacement content must be a string');

		while (start < 0) start += this.original.length;
		while (end < 0) end += this.original.length;

		if (end > this.original.length) throw new Error('end is out of bounds');
		if (start === end)
			throw new Error(
				'Cannot overwrite a zero-length range – use appendLeft or prependRight instead'
			);

		this._split(start);
		this._split(end);

		if (options === true) {
			if (!warned.storeName) {
				console.warn(
					'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'
				); // eslint-disable-line no-console
				warned.storeName = true;
			}

			options = { storeName: true };
		}
		const storeName = options !== undefined ? options.storeName : false;
		const overwrite = options !== undefined ? options.overwrite : false;

		if (storeName) {
			const original = this.original.slice(start, end);
			Object.defineProperty(this.storedNames, original, {
				writable: true,
				value: true,
				enumerable: true,
			});
		}

		const first = this.byStart[start];
		const last = this.byEnd[end];

		if (first) {
			let chunk = first;
			while (chunk !== last) {
				if (chunk.next !== this.byStart[chunk.end]) {
					throw new Error('Cannot overwrite across a split point');
				}
				chunk = chunk.next;
				chunk.edit('', false);
			}

			first.edit(content, storeName, !overwrite);
		} else {
			// must be inserting at the end
			const newChunk = new Chunk(start, end, '').edit(content, storeName);

			// TODO last chunk in the array may not be the last chunk, if it's moved...
			last.next = newChunk;
			newChunk.previous = last;
		}
		return this;
	}

	prepend(content) {
		if (typeof content !== 'string') throw new TypeError('outro content must be a string');

		this.intro = content + this.intro;
		return this;
	}

	prependLeft(index, content) {
		if (typeof content !== 'string') throw new TypeError('inserted content must be a string');

		this._split(index);

		const chunk = this.byEnd[index];

		if (chunk) {
			chunk.prependLeft(content);
		} else {
			this.intro = content + this.intro;
		}
		return this;
	}

	prependRight(index, content) {
		if (typeof content !== 'string') throw new TypeError('inserted content must be a string');

		this._split(index);

		const chunk = this.byStart[index];

		if (chunk) {
			chunk.prependRight(content);
		} else {
			this.outro = content + this.outro;
		}
		return this;
	}

	remove(start, end) {
		while (start < 0) start += this.original.length;
		while (end < 0) end += this.original.length;

		if (start === end) return this;

		if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
		if (start > end) throw new Error('end must be greater than start');

		this._split(start);
		this._split(end);

		let chunk = this.byStart[start];

		while (chunk) {
			chunk.intro = '';
			chunk.outro = '';
			chunk.edit('');

			chunk = end > chunk.end ? this.byStart[chunk.end] : null;
		}
		return this;
	}

	lastChar() {
		if (this.outro.length) return this.outro[this.outro.length - 1];
		let chunk = this.lastChunk;
		do {
			if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
			if (chunk.content.length) return chunk.content[chunk.content.length - 1];
			if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
		} while ((chunk = chunk.previous));
		if (this.intro.length) return this.intro[this.intro.length - 1];
		return '';
	}

	lastLine() {
		let lineIndex = this.outro.lastIndexOf(n);
		if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
		let lineStr = this.outro;
		let chunk = this.lastChunk;
		do {
			if (chunk.outro.length > 0) {
				lineIndex = chunk.outro.lastIndexOf(n);
				if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
				lineStr = chunk.outro + lineStr;
			}

			if (chunk.content.length > 0) {
				lineIndex = chunk.content.lastIndexOf(n);
				if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
				lineStr = chunk.content + lineStr;
			}

			if (chunk.intro.length > 0) {
				lineIndex = chunk.intro.lastIndexOf(n);
				if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
				lineStr = chunk.intro + lineStr;
			}
		} while ((chunk = chunk.previous));
		lineIndex = this.intro.lastIndexOf(n);
		if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
		return this.intro + lineStr;
	}

	slice(start = 0, end = this.original.length) {
		while (start < 0) start += this.original.length;
		while (end < 0) end += this.original.length;

		let result = '';

		// find start chunk
		let chunk = this.firstChunk;
		while (chunk && (chunk.start > start || chunk.end <= start)) {
			// found end chunk before start
			if (chunk.start < end && chunk.end >= end) {
				return result;
			}

			chunk = chunk.next;
		}

		if (chunk && chunk.edited && chunk.start !== start)
			throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);

		const startChunk = chunk;
		while (chunk) {
			if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
				result += chunk.intro;
			}

			const containsEnd = chunk.start < end && chunk.end >= end;
			if (containsEnd && chunk.edited && chunk.end !== end)
				throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);

			const sliceStart = startChunk === chunk ? start - chunk.start : 0;
			const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;

			result += chunk.content.slice(sliceStart, sliceEnd);

			if (chunk.outro && (!containsEnd || chunk.end === end)) {
				result += chunk.outro;
			}

			if (containsEnd) {
				break;
			}

			chunk = chunk.next;
		}

		return result;
	}

	// TODO deprecate this? not really very useful
	snip(start, end) {
		const clone = this.clone();
		clone.remove(0, start);
		clone.remove(end, clone.original.length);

		return clone;
	}

	_split(index) {
		if (this.byStart[index] || this.byEnd[index]) return;

		let chunk = this.lastSearchedChunk;
		const searchForward = index > chunk.end;

		while (chunk) {
			if (chunk.contains(index)) return this._splitChunk(chunk, index);

			chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
		}
	}

	_splitChunk(chunk, index) {
		if (chunk.edited && chunk.content.length) {
			// zero-length edited chunks are a special case (overlapping replacements)
			const loc = getLocator(this.original)(index);
			throw new Error(
				`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`
			);
		}

		const newChunk = chunk.split(index);

		this.byEnd[index] = chunk;
		this.byStart[index] = newChunk;
		this.byEnd[newChunk.end] = newChunk;

		if (chunk === this.lastChunk) this.lastChunk = newChunk;

		this.lastSearchedChunk = chunk;
		return true;
	}

	toString() {
		let str = this.intro;

		let chunk = this.firstChunk;
		while (chunk) {
			str += chunk.toString();
			chunk = chunk.next;
		}

		return str + this.outro;
	}

	isEmpty() {
		let chunk = this.firstChunk;
		do {
			if (
				(chunk.intro.length && chunk.intro.trim()) ||
				(chunk.content.length && chunk.content.trim()) ||
				(chunk.outro.length && chunk.outro.trim())
			)
				return false;
		} while ((chunk = chunk.next));
		return true;
	}

	length() {
		let chunk = this.firstChunk;
		let length = 0;
		do {
			length += chunk.intro.length + chunk.content.length + chunk.outro.length;
		} while ((chunk = chunk.next));
		return length;
	}

	trimLines() {
		return this.trim('[\\r\\n]');
	}

	trim(charType) {
		return this.trimStart(charType).trimEnd(charType);
	}

	trimEndAborted(charType) {
		const rx = new RegExp((charType || '\\s') + '+$');

		this.outro = this.outro.replace(rx, '');
		if (this.outro.length) return true;

		let chunk = this.lastChunk;

		do {
			const end = chunk.end;
			const aborted = chunk.trimEnd(rx);

			// if chunk was trimmed, we have a new lastChunk
			if (chunk.end !== end) {
				if (this.lastChunk === chunk) {
					this.lastChunk = chunk.next;
				}

				this.byEnd[chunk.end] = chunk;
				this.byStart[chunk.next.start] = chunk.next;
				this.byEnd[chunk.next.end] = chunk.next;
			}

			if (aborted) return true;
			chunk = chunk.previous;
		} while (chunk);

		return false;
	}

	trimEnd(charType) {
		this.trimEndAborted(charType);
		return this;
	}
	trimStartAborted(charType) {
		const rx = new RegExp('^' + (charType || '\\s') + '+');

		this.intro = this.intro.replace(rx, '');
		if (this.intro.length) return true;

		let chunk = this.firstChunk;

		do {
			const end = chunk.end;
			const aborted = chunk.trimStart(rx);

			if (chunk.end !== end) {
				// special case...
				if (chunk === this.lastChunk) this.lastChunk = chunk.next;

				this.byEnd[chunk.end] = chunk;
				this.byStart[chunk.next.start] = chunk.next;
				this.byEnd[chunk.next.end] = chunk.next;
			}

			if (aborted) return true;
			chunk = chunk.next;
		} while (chunk);

		return false;
	}

	trimStart(charType) {
		this.trimStartAborted(charType);
		return this;
	}

	hasChanged() {
		return this.original !== this.toString();
	}

	_replaceRegexp(searchValue, replacement) {
		function getReplacement(match, str) {
			if (typeof replacement === 'string') {
				return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
					// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
					if (i === '$') return '$';
					if (i === '&') return match[0];
					const num = +i;
					if (num < match.length) return match[+i];
					return `$${i}`;
				});
			} else {
				return replacement(...match, match.index, str, match.groups);
			}
		}
		function matchAll(re, str) {
			let match;
			const matches = [];
			while ((match = re.exec(str))) {
				matches.push(match);
			}
			return matches;
		}
		if (searchValue.global) {
			const matches = matchAll(searchValue, this.original);
			matches.forEach((match) => {
				if (match.index != null)
					this.overwrite(
						match.index,
						match.index + match[0].length,
						getReplacement(match, this.original)
					);
			});
		} else {
			const match = this.original.match(searchValue);
			if (match && match.index != null)
				this.overwrite(
					match.index,
					match.index + match[0].length,
					getReplacement(match, this.original)
				);
		}
		return this;
	}

	_replaceString(string, replacement) {
		const { original } = this;
		const index = original.indexOf(string);

		if (index !== -1) {
			this.overwrite(index, index + string.length, replacement);
		}

		return this;
	}

	replace(searchValue, replacement) {
		if (typeof searchValue === 'string') {
			return this._replaceString(searchValue, replacement);
		}

		return this._replaceRegexp(searchValue, replacement);
	}

	_replaceAllString(string, replacement) {
		const { original } = this;
		const stringLength = string.length;
		for (
			let index = original.indexOf(string);
			index !== -1;
			index = original.indexOf(string, index + stringLength)
		) {
			this.overwrite(index, index + stringLength, replacement);
		}

		return this;
	}

	replaceAll(searchValue, replacement) {
		if (typeof searchValue === 'string') {
			return this._replaceAllString(searchValue, replacement);
		}

		if (!searchValue.global) {
			throw new TypeError(
				'MagicString.prototype.replaceAll called with a non-global RegExp argument'
			);
		}

		return this._replaceRegexp(searchValue, replacement);
	}
}

const UNKNOWN = {};

/**
 * @param {import("estree").Node} node
 * @param {Set<string | {}>} set
 */
function gather_possible_values(node, set) {
	if (node.type === 'Literal') {
		set.add(node.value);
	} else if (node.type === 'ConditionalExpression') {
		gather_possible_values(node.consequent, set);
		gather_possible_values(node.alternate, set);
	} else {
		set.add(UNKNOWN);
	}
}

const BlockAppliesToNode = /** @type {const} */ ({
	NotPossible: 0,
	Possible: 1,
	UnknownSelectorType: 2
});

const NodeExist = /** @type {const} */ ({
	Probably: 0,
	Definitely: 1
});

/** @typedef {typeof NodeExist[keyof typeof NodeExist]} NodeExistsValue */

const whitelist_attribute_selector = new Map([
	['details', new Set(['open'])],
	['dialog', new Set(['open'])]
]);
const regex_is_single_css_selector = /[^\\],(?!([^([]+[^\\]|[^([\\])[)\]])/;

class Selector {
	/** @type {import('./private.js').CssNode} */
	node;

	/** @type {import('./Stylesheet.js').default} */
	stylesheet;

	/** @type {Block[]} */
	blocks;

	/** @type {Block[]} */
	local_blocks;

	/** @type {boolean} */
	used;

	/**
	 * @param {import('./private.js').CssNode} node
	 * @param {import('./Stylesheet.js').default} stylesheet
	 */
	constructor(node, stylesheet) {
		this.node = node;
		this.stylesheet = stylesheet;
		this.blocks = group_selectors(node);
		// take trailing :global(...) selectors out of consideration
		let i = this.blocks.length;
		while (i > 0) {
			if (!this.blocks[i - 1].global) break;
			i -= 1;
		}
		this.local_blocks = this.blocks.slice(0, i);
		const host_only = this.blocks.length === 1 && this.blocks[0].host;
		const root_only = this.blocks.length === 1 && this.blocks[0].root;
		this.used = this.local_blocks.length === 0 || host_only || root_only;
	}

	/** @param {import('../nodes/Element.js').default} node */
	apply(node) {
		/** @type {Array<{ node: import('../nodes/Element.js').default; block: Block }>} */
		const to_encapsulate = [];
		apply_selector(this.local_blocks.slice(), node, to_encapsulate);
		if (to_encapsulate.length > 0) {
			to_encapsulate.forEach(({ node, block }) => {
				this.stylesheet.nodes_with_css_class.add(node);
				block.should_encapsulate = true;
			});
			this.used = true;
		}
	}

	/** @param {import('magic-string').default} code */
	minify(code) {
		/** @type {number} */
		let c = null;
		this.blocks.forEach((block, i) => {
			if (i > 0) {
				if (block.start - c > 1) {
					code.update(c, block.start, block.combinator.name || ' ');
				}
			}
			c = block.end;
		});
	}

	/**
	 * @param {import('magic-string').default} code
	 * @param {string} attr
	 * @param {number} max_amount_class_specificity_increased
	 */
	transform(code, attr, max_amount_class_specificity_increased) {
		const amount_class_specificity_to_increase =
			max_amount_class_specificity_increased -
			this.blocks.filter((block) => block.should_encapsulate).length;

		/** @param {import('./private.js').CssNode} selector */
		function remove_global_pseudo_class(selector) {
			const first = selector.children[0];
			const last = selector.children[selector.children.length - 1];
			code.remove(selector.start, first.start).remove(last.end, selector.end);
		}

		/**
		 * @param {Block} block
		 * @param {string} attr
		 */
		function encapsulate_block(block, attr) {
			for (const selector of block.selectors) {
				if (selector.type === 'PseudoClassSelector' && selector.name === 'global') {
					remove_global_pseudo_class(selector);
				}
			}
			let i = block.selectors.length;
			while (i--) {
				const selector = block.selectors[i];
				if (selector.type === 'PseudoElementSelector' || selector.type === 'PseudoClassSelector') {
					if (selector.name !== 'root' && selector.name !== 'host') {
						if (i === 0) code.prependRight(selector.start, attr);
					}
					continue;
				}
				if (selector.type === 'TypeSelector' && selector.name === '*') {
					code.update(selector.start, selector.end, attr);
				} else {
					code.appendLeft(selector.end, attr);
				}
				break;
			}
		}
		this.blocks.forEach((block, index) => {
			if (block.global) {
				remove_global_pseudo_class(block.selectors[0]);
			}
			if (block.should_encapsulate)
				encapsulate_block(
					block,
					index === this.blocks.length - 1
						? attr.repeat(amount_class_specificity_to_increase + 1)
						: attr
				);
		});
	}

	/** @param {import('../Component.js').default} component */
	validate(component) {
		let start = 0;
		let end = this.blocks.length;
		for (; start < end; start += 1) {
			if (!this.blocks[start].global) break;
		}
		for (; end > start; end -= 1) {
			if (!this.blocks[end - 1].global) break;
		}
		for (let i = start; i < end; i += 1) {
			if (this.blocks[i].global) {
				return component.error(this.blocks[i].selectors[0], compiler_errors.css_invalid_global);
			}
		}
		this.validate_global_with_multiple_selectors(component);
		this.validate_global_compound_selector(component);
		this.validate_invalid_combinator_without_selector(component);
	}

	/** @param {import('../Component.js').default} component */
	validate_global_with_multiple_selectors(component) {
		if (this.blocks.length === 1 && this.blocks[0].selectors.length === 1) {
			// standalone :global() with multiple selectors is OK
			return;
		}
		for (const block of this.blocks) {
			for (const selector of block.selectors) {
				if (selector.type === 'PseudoClassSelector' && selector.name === 'global') {
					if (regex_is_single_css_selector.test(selector.children[0].value)) {
						component.error(selector, compiler_errors.css_invalid_global_selector);
					}
				}
			}
		}
	}

	/** @param {import('../Component.js').default} component */
	validate_invalid_combinator_without_selector(component) {
		for (let i = 0; i < this.blocks.length; i++) {
			const block = this.blocks[i];
			if (block.combinator && block.selectors.length === 0) {
				component.error(
					this.node,
					compiler_errors.css_invalid_selector(
						component.source.slice(this.node.start, this.node.end)
					)
				);
			}
			if (!block.combinator && block.selectors.length === 0) {
				component.error(
					this.node,
					compiler_errors.css_invalid_selector(
						component.source.slice(this.node.start, this.node.end)
					)
				);
			}
		}
	}

	/** @param {import('../Component.js').default} component */
	validate_global_compound_selector(component) {
		for (const block of this.blocks) {
			for (let index = 0; index < block.selectors.length; index++) {
				const selector = block.selectors[index];
				if (
					selector.type === 'PseudoClassSelector' &&
					selector.name === 'global' &&
					index !== 0 &&
					selector.children &&
					selector.children.length > 0 &&
					!/[.:#\s]/.test(selector.children[0].value[0])
				) {
					component.error(selector, compiler_errors.css_invalid_global_selector_position);
				}
			}
		}
	}

	get_amount_class_specificity_increased() {
		let count = 0;
		for (const block of this.blocks) {
			if (block.should_encapsulate) {
				count++;
			}
		}
		return count;
	}
}

/**
 * @param {Block[]} blocks
 * @param {import('../nodes/Element.js').default} node
 * @param {Array<{ node: import('../nodes/Element.js').default; block: Block }>} to_encapsulate
 * @returns {boolean}
 */
function apply_selector(blocks, node, to_encapsulate) {
	const block = blocks.pop();
	if (!block) return false;
	if (!node) {
		return (
			(block.global && blocks.every((block) => block.global)) || (block.host && blocks.length === 0)
		);
	}
	switch (block_might_apply_to_node(block, node)) {
		case BlockAppliesToNode.NotPossible:
			return false;
		case BlockAppliesToNode.UnknownSelectorType:
			// bail. TODO figure out what these could be
			to_encapsulate.push({ node, block });
			return true;
	}
	if (block.combinator) {
		if (block.combinator.type === 'Combinator' && block.combinator.name === ' ') {
			for (const ancestor_block of blocks) {
				if (ancestor_block.global) {
					continue;
				}
				if (ancestor_block.host) {
					to_encapsulate.push({ node, block });
					return true;
				}
				let parent = node;
				while ((parent = get_element_parent(parent))) {
					if (
						block_might_apply_to_node(ancestor_block, parent) !== BlockAppliesToNode.NotPossible
					) {
						to_encapsulate.push({ node: parent, block: ancestor_block });
					}
				}
				if (to_encapsulate.length) {
					to_encapsulate.push({ node, block });
					return true;
				}
			}
			if (blocks.every((block) => block.global)) {
				to_encapsulate.push({ node, block });
				return true;
			}
			return false;
		} else if (block.combinator.name === '>') {
			const has_global_parent = blocks.every((block) => block.global);
			if (has_global_parent || apply_selector(blocks, get_element_parent(node), to_encapsulate)) {
				to_encapsulate.push({ node, block });
				return true;
			}
			return false;
		} else if (block.combinator.name === '+' || block.combinator.name === '~') {
			const siblings = get_possible_element_siblings(node, block.combinator.name === '+');
			let has_match = false;
			// NOTE: if we have :global(), we couldn't figure out what is selected within `:global` due to the
			// css-tree limitation that does not parse the inner selector of :global
			// so unless we are sure there will be no sibling to match, we will consider it as matched
			const has_global = blocks.some((block) => block.global);
			if (has_global) {
				if (siblings.size === 0 && get_element_parent(node) !== null) {
					return false;
				}
				to_encapsulate.push({ node, block });
				return true;
			}
			for (const possible_sibling of siblings.keys()) {
				if (apply_selector(blocks.slice(), possible_sibling, to_encapsulate)) {
					to_encapsulate.push({ node, block });
					has_match = true;
				}
			}
			return has_match;
		}
		// TODO other combinators
		to_encapsulate.push({ node, block });
		return true;
	}
	to_encapsulate.push({ node, block });
	return true;
}

const regex_backslash_and_following_character = /\\(.)/g;

/**
 * @param {Block} block
 * @param {import('../nodes/Element.js').default} node
 * @returns {typeof BlockAppliesToNode[keyof typeof BlockAppliesToNode]}
 */
function block_might_apply_to_node(block, node) {
	let i = block.selectors.length;
	while (i--) {
		const selector = block.selectors[i];
		const name =
			typeof selector.name === 'string' &&
			selector.name.replace(regex_backslash_and_following_character, '$1');
		if (selector.type === 'PseudoClassSelector' && (name === 'host' || name === 'root')) {
			return BlockAppliesToNode.NotPossible;
		}
		if (
			block.selectors.length === 1 &&
			selector.type === 'PseudoClassSelector' &&
			name === 'global'
		) {
			return BlockAppliesToNode.NotPossible;
		}
		if (selector.type === 'PseudoClassSelector' || selector.type === 'PseudoElementSelector') {
			continue;
		}
		if (selector.type === 'ClassSelector') {
			if (
				!attribute_matches(node, 'class', name, '~=', false) &&
				!node.classes.some((c) => c.name === name)
			)
				return BlockAppliesToNode.NotPossible;
		} else if (selector.type === 'IdSelector') {
			if (!attribute_matches(node, 'id', name, '=', false)) return BlockAppliesToNode.NotPossible;
		} else if (selector.type === 'AttributeSelector') {
			if (
				!(
					whitelist_attribute_selector.has(node.name.toLowerCase()) &&
					whitelist_attribute_selector
						.get(node.name.toLowerCase())
						.has(selector.name.name.toLowerCase())
				) &&
				!attribute_matches(
					node,
					selector.name.name,
					selector.value && unquote(selector.value),
					selector.matcher,
					selector.flags
				)
			) {
				return BlockAppliesToNode.NotPossible;
			}
		} else if (selector.type === 'TypeSelector') {
			if (
				node.name.toLowerCase() !== name.toLowerCase() &&
				name !== '*' &&
				!node.is_dynamic_element
			)
				return BlockAppliesToNode.NotPossible;
		} else {
			return BlockAppliesToNode.UnknownSelectorType;
		}
	}
	return BlockAppliesToNode.Possible;
}

/**
 * @param {any} operator
 * @param {any} expected_value
 * @param {any} case_insensitive
 * @param {any} value
 */
function test_attribute(operator, expected_value, case_insensitive, value) {
	if (case_insensitive) {
		expected_value = expected_value.toLowerCase();
		value = value.toLowerCase();
	}
	switch (operator) {
		case '=':
			return value === expected_value;
		case '~=':
			return value.split(/\s/).includes(expected_value);
		case '|=':
			return `${value}-`.startsWith(`${expected_value}-`);
		case '^=':
			return value.startsWith(expected_value);
		case '$=':
			return value.endsWith(expected_value);
		case '*=':
			return value.includes(expected_value);
		default:
			throw new Error("this shouldn't happen");
	}
}

/**
 * @param {import('./private.js').CssNode} node
 * @param {string} name
 * @param {string} expected_value
 * @param {string} operator
 * @param {boolean} case_insensitive
 */
function attribute_matches(node, name, expected_value, operator, case_insensitive) {
	const spread = node.attributes.find((attr) => attr.type === 'Spread');
	if (spread) return true;
	if (node.bindings.some((binding) => binding.name === name)) return true;
	const attr = node.attributes.find((attr) => attr.name === name);
	if (!attr) return false;
	if (attr.is_true) return operator === null;
	if (expected_value == null) return true;
	if (attr.chunks.length === 1) {
		const value = attr.chunks[0];
		if (!value) return false;
		if (value.type === 'Text')
			return test_attribute(operator, expected_value, case_insensitive, value.data);
	}
	const possible_values = new Set();
	let prev_values = [];
	for (const chunk of attr.chunks) {
		const current_possible_values = new Set();
		if (chunk.type === 'Text') {
			current_possible_values.add(chunk.data);
		} else {
			gather_possible_values(chunk.node, current_possible_values);
		}
		// impossible to find out all combinations
		if (current_possible_values.has(UNKNOWN)) return true;
		if (prev_values.length > 0) {
			const start_with_space = [];
			const remaining = [];
			current_possible_values.forEach((current_possible_value) => {
				if (regex_starts_with_whitespace.test(current_possible_value)) {
					start_with_space.push(current_possible_value);
				} else {
					remaining.push(current_possible_value);
				}
			});
			if (remaining.length > 0) {
				if (start_with_space.length > 0) {
					prev_values.forEach((prev_value) => possible_values.add(prev_value));
				}
				const combined = [];
				prev_values.forEach((prev_value) => {
					remaining.forEach((value) => {
						combined.push(prev_value + value);
					});
				});
				prev_values = combined;
				start_with_space.forEach((value) => {
					if (regex_ends_with_whitespace.test(value)) {
						possible_values.add(value);
					} else {
						prev_values.push(value);
					}
				});
				continue;
			} else {
				prev_values.forEach((prev_value) => possible_values.add(prev_value));
				prev_values = [];
			}
		}
		current_possible_values.forEach((current_possible_value) => {
			if (regex_ends_with_whitespace.test(current_possible_value)) {
				possible_values.add(current_possible_value);
			} else {
				prev_values.push(current_possible_value);
			}
		});
		if (prev_values.length < current_possible_values.size) {
			prev_values.push(' ');
		}
		if (prev_values.length > 20) {
			// might grow exponentially, bail out
			return true;
		}
	}
	prev_values.forEach((prev_value) => possible_values.add(prev_value));
	if (possible_values.has(UNKNOWN)) return true;
	for (const value of possible_values) {
		if (test_attribute(operator, expected_value, case_insensitive, value)) return true;
	}
	return false;
}

/** @param {import('./private.js').CssNode} value */
function unquote(value) {
	if (value.type === 'Identifier') return value.name;
	const str = value.value;
	if ((str[0] === str[str.length - 1] && str[0] === "'") || str[0] === '"') {
		return str.slice(1, str.length - 1);
	}
	return str;
}

/**
 * @param {import('../nodes/Element.js').default} node
 * @returns {any}
 */
function get_element_parent(node) {
	/** @type {import('../nodes/interfaces.js').INode} */
	let parent = node;
	while ((parent = parent.parent) && parent.type !== 'Element');
	return /** @type {import('../nodes/Element.js').default | null} */ (parent);
}

/**
 * Finds the given node's previous sibling in the DOM
 *
 * The Svelte <slot> is just a placeholder and is not actually real. Any children nodes
 * in <slot> are 'flattened' and considered as the same level as the <slot>'s siblings
 *
 * e.g.
 * <h1>Heading 1</h1>
 * <slot>
 *   <h2>Heading 2</h2>
 * </slot>
 *
 * is considered to look like:
 * <h1>Heading 1</h1>
 * <h2>Heading 2</h2>
 * @param {import('../nodes/interfaces.js').INode} node
 * @returns {import('../nodes/interfaces.js').INode}
 */
function find_previous_sibling(node) {
	/** @type {import('../nodes/interfaces.js').INode} */
	let current_node = node;
	do {
		if (current_node.type === 'Slot') {
			const slot_children = current_node.children;
			if (slot_children.length > 0) {
				current_node = slot_children.slice(-1)[0]; // go to its last child first
				continue;
			}
		}
		while (!current_node.prev && current_node.parent && current_node.parent.type === 'Slot') {
			current_node = current_node.parent;
		}
		current_node = current_node.prev;
	} while (current_node && current_node.type === 'Slot');
	return current_node;
}

/**
 * @param {import('../nodes/interfaces.js').INode} node
 * @param {boolean} adjacent_only
 * @returns {Map<import('../nodes/Element.js').default, NodeExistsValue>}
 */
function get_possible_element_siblings(node, adjacent_only) {
	/** @type {Map<import('../nodes/Element.js').default, NodeExistsValue>} */
	const result = new Map();

	/** @type {import('../nodes/interfaces.js').INode} */
	let prev = node;
	while ((prev = find_previous_sibling(prev))) {
		if (prev.type === 'Element') {
			if (
				!prev.attributes.find(
					(attr) => attr.type === 'Attribute' && attr.name.toLowerCase() === 'slot'
				)
			) {
				result.set(prev, NodeExist.Definitely);
			}
			if (adjacent_only) {
				break;
			}
		} else if (prev.type === 'EachBlock' || prev.type === 'IfBlock' || prev.type === 'AwaitBlock') {
			const possible_last_child = get_possible_last_child(prev, adjacent_only);
			add_to_map(possible_last_child, result);
			if (adjacent_only && has_definite_elements(possible_last_child)) {
				return result;
			}
		}
	}
	if (!prev || !adjacent_only) {
		/** @type {import('../nodes/interfaces.js').INode} */
		let parent = node;
		let skip_each_for_last_child = node.type === 'ElseBlock';
		while (
			(parent = parent.parent) &&
			(parent.type === 'EachBlock' ||
				parent.type === 'IfBlock' ||
				parent.type === 'ElseBlock' ||
				parent.type === 'AwaitBlock')
		) {
			const possible_siblings = get_possible_element_siblings(parent, adjacent_only);
			add_to_map(possible_siblings, result);
			if (parent.type === 'EachBlock') {
				// first child of each block can select the last child of each block as previous sibling
				if (skip_each_for_last_child) {
					skip_each_for_last_child = false;
				} else {
					add_to_map(get_possible_last_child(parent, adjacent_only), result);
				}
			} else if (parent.type === 'ElseBlock') {
				skip_each_for_last_child = true;
				parent = parent.parent;
			}
			if (adjacent_only && has_definite_elements(possible_siblings)) {
				break;
			}
		}
	}
	return result;
}

/**
 * @param {import('../nodes/EachBlock.js').default | import('../nodes/IfBlock.js').default | import('../nodes/AwaitBlock.js').default} block
 * @param {boolean} adjacent_only
 * @returns {Map<import('../nodes/Element.js').default, NodeExistsValue>}
 */
function get_possible_last_child(block, adjacent_only) {
	/** @typedef {Map<import('../nodes/Element.js').default, NodeExistsValue>} NodeMap */

	/** @type {NodeMap} */
	const result = new Map();
	if (block.type === 'EachBlock') {
		/** @type {NodeMap} */
		const each_result = loop_child(block.children, adjacent_only);

		/** @type {NodeMap} */
		const else_result = block.else ? loop_child(block.else.children, adjacent_only) : new Map();
		const not_exhaustive = !has_definite_elements(else_result);
		if (not_exhaustive) {
			mark_as_probably(each_result);
			mark_as_probably(else_result);
		}
		add_to_map(each_result, result);
		add_to_map(else_result, result);
	} else if (block.type === 'IfBlock') {
		/** @type {NodeMap} */
		const if_result = loop_child(block.children, adjacent_only);

		/** @type {NodeMap} */
		const else_result = block.else ? loop_child(block.else.children, adjacent_only) : new Map();
		const not_exhaustive = !has_definite_elements(if_result) || !has_definite_elements(else_result);
		if (not_exhaustive) {
			mark_as_probably(if_result);
			mark_as_probably(else_result);
		}
		add_to_map(if_result, result);
		add_to_map(else_result, result);
	} else if (block.type === 'AwaitBlock') {
		/** @type {NodeMap} */
		const pending_result = block.pending
			? loop_child(block.pending.children, adjacent_only)
			: new Map();

		/** @type {NodeMap} */
		const then_result = block.then ? loop_child(block.then.children, adjacent_only) : new Map();

		/** @type {NodeMap} */
		const catch_result = block.catch ? loop_child(block.catch.children, adjacent_only) : new Map();
		const not_exhaustive =
			!has_definite_elements(pending_result) ||
			!has_definite_elements(then_result) ||
			!has_definite_elements(catch_result);
		if (not_exhaustive) {
			mark_as_probably(pending_result);
			mark_as_probably(then_result);
			mark_as_probably(catch_result);
		}
		add_to_map(pending_result, result);
		add_to_map(then_result, result);
		add_to_map(catch_result, result);
	}
	return result;
}

/**
 * @param {Map<import('../nodes/Element.js').default, NodeExistsValue>} result
 * @returns {boolean}
 */
function has_definite_elements(result) {
	if (result.size === 0) return false;
	for (const exist of result.values()) {
		if (exist === NodeExist.Definitely) {
			return true;
		}
	}
	return false;
}

/**
 * @param {Map<import('../nodes/Element.js').default, NodeExistsValue>} from
 * @param {Map<import('../nodes/Element.js').default, NodeExistsValue>} to
 * @returns {void}
 */
function add_to_map(from, to) {
	from.forEach((exist, element) => {
		to.set(element, higher_existence(exist, to.get(element)));
	});
}

/**
 * @param {NodeExistsValue | null} exist1
 * @param {NodeExistsValue | null} exist2
 * @returns {NodeExistsValue}
 */
function higher_existence(exist1, exist2) {
	if (exist1 === undefined || exist2 === undefined) return exist1 || exist2;
	return exist1 > exist2 ? exist1 : exist2;
}

/** @param {Map<import('../nodes/Element.js').default, NodeExistsValue>} result */
function mark_as_probably(result) {
	for (const key of result.keys()) {
		result.set(key, NodeExist.Probably);
	}
}

/**
 * @param {import('../nodes/interfaces.js').INode[]} children
 * @param {boolean} adjacent_only
 */
function loop_child(children, adjacent_only) {
	/** @type {Map<import('../nodes/Element.js').default, NodeExistsValue>} */
	const result = new Map();
	for (let i = children.length - 1; i >= 0; i--) {
		const child = children[i];
		if (child.type === 'Element') {
			result.set(child, NodeExist.Definitely);
			if (adjacent_only) {
				break;
			}
		} else if (
			child.type === 'EachBlock' ||
			child.type === 'IfBlock' ||
			child.type === 'AwaitBlock'
		) {
			const child_result = get_possible_last_child(child, adjacent_only);
			add_to_map(child_result, result);
			if (adjacent_only && has_definite_elements(child_result)) {
				break;
			}
		}
	}
	return result;
}

class Block {
	/** @type {boolean} */
	host;

	/** @type {boolean} */
	root;

	/** @type {import('./private.js').CssNode} */
	combinator;

	/** @type {import('./private.js').CssNode[]} */
	selectors;

	/** @type {number} */
	start;

	/** @type {number} */
	end;

	/** @type {boolean} */
	should_encapsulate;

	/** @param {import('./private.js').CssNode} combinator */
	constructor(combinator) {
		this.combinator = combinator;
		this.host = false;
		this.root = false;
		this.selectors = [];
		this.start = null;
		this.end = null;
		this.should_encapsulate = false;
	}

	/** @param {import('./private.js').CssNode} selector */
	add(selector) {
		if (this.selectors.length === 0) {
			this.start = selector.start;
			this.host = selector.type === 'PseudoClassSelector' && selector.name === 'host';
		}
		this.root = this.root || (selector.type === 'PseudoClassSelector' && selector.name === 'root');
		this.selectors.push(selector);
		this.end = selector.end;
	}
	get global() {
		return (
			this.selectors.length >= 1 &&
			this.selectors[0].type === 'PseudoClassSelector' &&
			this.selectors[0].name === 'global' &&
			this.selectors.every(
				(selector) =>
					selector.type === 'PseudoClassSelector' || selector.type === 'PseudoElementSelector'
			)
		);
	}
}

/** @param {import('./private.js').CssNode} selector */
function group_selectors(selector) {
	/** @type {Block} */
	let block = new Block(null);
	const blocks = [block];
	selector.children.forEach((child) => {
		if (child.type === 'WhiteSpace' || child.type === 'Combinator') {
			block = new Block(child);
			blocks.push(block);
		} else {
			block.add(child);
		}
	});
	return blocks;
}

const regex_css_browser_prefix = /^-((webkit)|(moz)|(o)|(ms))-/;

/**
 * @param {string} name
 * @returns {string}
 */
function remove_css_prefix(name) {
	return name.replace(regex_css_browser_prefix, '');
}

/** @param {import('./private.js').CssNode} node */
const is_keyframes_node = (node) => remove_css_prefix(node.name) === 'keyframes';

/**
 * @param {import('./private.js').CssNode} param
 * @returns {true}
 */
const at_rule_has_declaration = ({ block }) =>
	block && block.children && block.children.find((node) => node.type === 'Declaration');

/**
 * @param {import('magic-string').default} code
 * @param {number} start
 * @param {Declaration[]} declarations
 * @returns {number}
 */
function minify_declarations(code, start, declarations) {
	let c = start;
	declarations.forEach((declaration, i) => {
		const separator = i > 0 ? ';' : '';
		if (declaration.node.start - c > separator.length) {
			code.update(c, declaration.node.start, separator);
		}
		declaration.minify(code);
		c = declaration.node.end;
	});
	return c;
}
class Rule {
	/** @type {import('./Selector.js').default[]} */
	selectors;

	/** @type {Declaration[]} */
	declarations;

	/** @type {import('./private.js').CssNode} */
	node;

	/** @type {Atrule} */
	parent;

	/**
	 * @param {import('./private.js').CssNode} node
	 * @param {any} stylesheet
	 * @param {Atrule} [parent]
	 */
	constructor(node, stylesheet, parent) {
		this.node = node;
		this.parent = parent;
		this.selectors = node.prelude.children.map((node) => new Selector(node, stylesheet));
		this.declarations = node.block.children.map((node) => new Declaration(node));
	}

	/** @param {import('../nodes/Element.js').default} node */
	apply(node) {
		this.selectors.forEach((selector) => selector.apply(node)); // TODO move the logic in here?
	}

	/** @param {boolean} dev */
	is_used(dev) {
		if (this.parent && this.parent.node.type === 'Atrule' && is_keyframes_node(this.parent.node))
			return true;
		if (this.declarations.length === 0) return dev;
		return this.selectors.some((s) => s.used);
	}

	/**
	 * @param {import('magic-string').default} code
	 * @param {boolean} _dev
	 */
	minify(code, _dev) {
		let c = this.node.start;
		let started = false;
		this.selectors.forEach((selector) => {
			if (selector.used) {
				const separator = started ? ',' : '';
				if (selector.node.start - c > separator.length) {
					code.update(c, selector.node.start, separator);
				}
				selector.minify(code);
				c = selector.node.end;
				started = true;
			}
		});
		code.remove(c, this.node.block.start);
		c = this.node.block.start + 1;
		c = minify_declarations(code, c, this.declarations);
		code.remove(c, this.node.block.end - 1);
	}

	/**
	 * @param {import('magic-string').default} code
	 * @param {string} id
	 * @param {Map<string, string>} keyframes
	 * @param {number} max_amount_class_specificity_increased
	 */
	transform(code, id, keyframes, max_amount_class_specificity_increased) {
		if (this.parent && this.parent.node.type === 'Atrule' && is_keyframes_node(this.parent.node))
			return true;
		const attr = `.${id}`;
		this.selectors.forEach((selector) =>
			selector.transform(code, attr, max_amount_class_specificity_increased)
		);
		this.declarations.forEach((declaration) => declaration.transform(code, keyframes));
	}

	/** @param {import('../Component.js').default} component */
	validate(component) {
		this.selectors.forEach((selector) => {
			selector.validate(component);
		});
	}

	/** @param {(selector: import('./Selector.js').default) => void} handler */
	warn_on_unused_selector(handler) {
		this.selectors.forEach((selector) => {
			if (!selector.used) handler(selector);
		});
	}
	get_max_amount_class_specificity_increased() {
		return Math.max(
			...this.selectors.map((selector) => selector.get_amount_class_specificity_increased())
		);
	}
}
class Declaration {
	/** @type {import('./private.js').CssNode} */
	node;

	/** @param {import('./private.js').CssNode} node */
	constructor(node) {
		this.node = node;
	}

	/**
	 * @param {import('magic-string').default} code
	 * @param {Map<string, string>} keyframes
	 */
	transform(code, keyframes) {
		const property = this.node.property && remove_css_prefix(this.node.property.toLowerCase());
		if (property === 'animation' || property === 'animation-name') {
			this.node.value.children.forEach((block) => {
				if (block.type === 'Identifier') {
					const name = block.name;
					if (keyframes.has(name)) {
						code.update(block.start, block.end, keyframes.get(name));
					}
				}
			});
		}
	}

	/** @param {import('magic-string').default} code */
	minify(code) {
		if (!this.node.property) return; // @apply, and possibly other weird cases?
		const c = this.node.start + this.node.property.length;
		const first = this.node.value.children ? this.node.value.children[0] : this.node.value;
		// Don't minify whitespace in custom properties, since some browsers (Chromium < 99)
		// treat --foo: ; and --foo:; differently
		if (first.type === 'Raw' && regex_only_whitespaces.test(first.value)) return;
		let start = first.start;
		while (regex_whitespace.test(code.original[start])) start += 1;
		if (start - c > 1) {
			code.update(c, start, ':');
		}
	}
}
class Atrule {
	/** @type {import('./private.js').CssNode} */
	node;

	/** @type {Array<Atrule | Rule>} */
	children;

	/** @type {Declaration[]} */
	declarations;

	/** @param {import('./private.js').CssNode} node */
	constructor(node) {
		this.node = node;
		this.children = [];
		this.declarations = [];
	}

	/** @param {import('../nodes/Element.js').default} node */
	apply(node) {
		if (
			this.node.name === 'container' ||
			this.node.name === 'media' ||
			this.node.name === 'supports' ||
			this.node.name === 'layer'
		) {
			this.children.forEach((child) => {
				child.apply(node);
			});
		} else if (is_keyframes_node(this.node)) {
			this.children.forEach((/** @type {Rule} */ rule) => {
				rule.selectors.forEach((selector) => {
					selector.used = true;
				});
			});
		}
	}

	/** @param {boolean} _dev */
	is_used(_dev) {
		return true; // TODO
	}

	/**
	 * @param {import('magic-string').default} code
	 * @param {boolean} dev
	 */
	minify(code, dev) {
		if (this.node.name === 'media') {
			const expression_char = code.original[this.node.prelude.start];
			let c = this.node.start + (expression_char === '(' ? 6 : 7);
			if (this.node.prelude.start > c) code.remove(c, this.node.prelude.start);
			this.node.prelude.children.forEach((query) => {
				// TODO minify queries
				c = query.end;
			});
			code.remove(c, this.node.block.start);
		} else if (this.node.name === 'supports') {
			let c = this.node.start + 9;
			if (this.node.prelude.start - c > 1) code.update(c, this.node.prelude.start, ' ');
			this.node.prelude.children.forEach((query) => {
				// TODO minify queries
				c = query.end;
			});
			code.remove(c, this.node.block.start);
		} else {
			let c = this.node.start + this.node.name.length + 1;
			if (this.node.prelude) {
				if (this.node.prelude.start - c > 1) code.update(c, this.node.prelude.start, ' ');
				c = this.node.prelude.end;
			}
			if (this.node.block && this.node.block.start - c > 0) {
				code.remove(c, this.node.block.start);
			}
		}
		// TODO other atrules
		if (this.node.block) {
			let c = this.node.block.start + 1;
			if (this.declarations.length) {
				c = minify_declarations(code, c, this.declarations);
				// if the atrule has children, leave the last declaration semicolon alone
				if (this.children.length) c++;
			}
			this.children.forEach((child) => {
				if (child.is_used(dev)) {
					code.remove(c, child.node.start);
					child.minify(code, dev);
					c = child.node.end;
				}
			});
			code.remove(c, this.node.block.end - 1);
		}
	}

	/**
	 * @param {import('magic-string').default} code
	 * @param {string} id
	 * @param {Map<string, string>} keyframes
	 * @param {number} max_amount_class_specificity_increased
	 */
	transform(code, id, keyframes, max_amount_class_specificity_increased) {
		if (is_keyframes_node(this.node)) {
			this.node.prelude.children.forEach(({ type, name, start, end }) => {
				if (type === 'Identifier') {
					if (name.startsWith('-global-')) {
						code.remove(start, start + 8);
						this.children.forEach((/** @type {Rule} */ rule) => {
							rule.selectors.forEach((selector) => {
								selector.used = true;
							});
						});
					} else {
						code.update(start, end, keyframes.get(name));
					}
				}
			});
		}
		this.children.forEach((child) => {
			child.transform(code, id, keyframes, max_amount_class_specificity_increased);
		});
	}

	/** @param {import('../Component.js').default} component */
	validate(component) {
		this.children.forEach((child) => {
			child.validate(component);
		});
	}

	/** @param {(selector: import('./Selector.js').default) => void} handler */
	warn_on_unused_selector(handler) {
		if (this.node.name !== 'media') return;
		this.children.forEach((child) => {
			child.warn_on_unused_selector(handler);
		});
	}
	get_max_amount_class_specificity_increased() {
		return Math.max(
			...this.children.map((rule) => rule.get_max_amount_class_specificity_increased())
		);
	}
}

/** @param {any} params */
const get_default_css_hash = ({ css, hash }) => {
	return `svelte-${hash(css)}`;
};
class Stylesheet {
	/** @type {string} */
	source;

	/** @type {import('../../interfaces.js').Ast} */
	ast;

	/** @type {string} */
	filename;

	/** @type {boolean} */
	dev;

	/** @type {boolean} */
	has_styles;

	/** @type {string} */
	id;

	/** @type {Array<Rule | Atrule>} */
	children = [];

	/** @type {Map<string, string>} */
	keyframes = new Map();

	/** @type {Set<import('./private.js').CssNode>} */
	nodes_with_css_class = new Set();

	/**
	 * @param {{
	 * 		source: string;
	 * 		ast: import('../../interfaces.js').Ast;
	 * 		filename: string | undefined;
	 * 		component_name: string | undefined;
	 * 		dev: boolean;
	 * 		get_css_hash: import('../../interfaces.js').CssHashGetter;
	 * 	}} params
	 */
	constructor({ source, ast, component_name, filename, dev, get_css_hash = get_default_css_hash }) {
		this.source = source;
		this.ast = ast;
		this.filename = filename;
		this.dev = dev;
		if (ast.css && ast.css.children.length) {
			this.id = get_css_hash({
				filename,
				name: component_name,
				css: ast.css.content.styles,
				hash
			});
			this.has_styles = true;

			/** @type {Atrule[]} */
			const stack = [];
			let depth = 0;

			/** @type {Atrule} */
			let current_atrule = null;
			walk(/** @type {any} */ (ast.css), {
				enter: (/** @type {any} */ node) => {
					if (node.type === 'Atrule') {
						const atrule = new Atrule(node);
						stack.push(atrule);
						if (current_atrule) {
							current_atrule.children.push(atrule);
						} else if (depth <= 1) {
							this.children.push(atrule);
						}
						if (is_keyframes_node(node)) {
							node.prelude.children.forEach((expression) => {
								if (expression.type === 'Identifier' && !expression.name.startsWith('-global-')) {
									this.keyframes.set(expression.name, `${this.id}-${expression.name}`);
								}
							});
						} else if (at_rule_has_declaration(node)) {
							const at_rule_declarations = node.block.children
								.filter((node) => node.type === 'Declaration')
								.map((node) => new Declaration(node));
							push_array(atrule.declarations, at_rule_declarations);
						}
						current_atrule = atrule;
					}
					if (node.type === 'Rule') {
						const rule = new Rule(node, this, current_atrule);
						if (current_atrule) {
							current_atrule.children.push(rule);
						} else if (depth <= 1) {
							this.children.push(rule);
						}
					}
					depth += 1;
				},
				leave: (/** @type {any} */ node) => {
					if (node.type === 'Atrule') {
						stack.pop();
						current_atrule = stack[stack.length - 1];
					}
					depth -= 1;
				}
			});
		} else {
			this.has_styles = false;
		}
	}

	/** @param {import('../nodes/Element.js').default} node */
	apply(node) {
		if (!this.has_styles) return;
		for (let i = 0; i < this.children.length; i += 1) {
			const child = this.children[i];
			child.apply(node);
		}
	}
	reify() {
		this.nodes_with_css_class.forEach((node) => {
			node.add_css_class();
		});
	}

	/** @param {string} file */
	render(file) {
		if (!this.has_styles) {
			return { code: null, map: null };
		}
		const code = new MagicString(this.source);
		walk(/** @type {any} */ (this.ast.css), {
			enter: (/** @type {any} */ node) => {
				code.addSourcemapLocation(node.start);
				code.addSourcemapLocation(node.end);
			}
		});
		const max = Math.max(
			...this.children.map((rule) => rule.get_max_amount_class_specificity_increased())
		);
		this.children.forEach((child) => {
			child.transform(code, this.id, this.keyframes, max);
		});
		let c = 0;
		this.children.forEach((child) => {
			if (child.is_used(this.dev)) {
				code.remove(c, child.node.start);
				child.minify(code, this.dev);
				c = child.node.end;
			}
		});
		code.remove(c, this.source.length);
		return {
			code: code.toString(),
			map: code.generateMap({
				includeContent: true,
				source: this.filename,
				file
			})
		};
	}

	/** @param {import('../Component.js').default} component */
	validate(component) {
		this.children.forEach((child) => {
			child.validate(component);
		});
	}

	/** @param {import('../Component.js').default} component */
	warn_on_unused_selectors(component) {
		const ignores = !this.ast.css
			? []
			: extract_ignores_above_position(this.ast.css.start, this.ast.html.children);
		component.push_ignores(ignores);
		this.children.forEach((child) => {
			child.warn_on_unused_selector((selector) => {
				component.warn(
					selector.node,
					compiler_warnings.css_unused_selector(
						this.source.slice(selector.node.start, selector.node.end)
					)
				);
			});
		});
		component.pop_ignores();
	}
}

class TemplateScope {
	/**
	 * @typedef {import('../EachBlock').default
	 * 	| import('../ThenBlock').default
	 * 	| import('../CatchBlock').default
	 * 	| import('../InlineComponent').default
	 * 	| import('../Element').default
	 * 	| import('../SlotTemplate').default
	 * 	| import('../ConstTag').default} NodeWithScope
	 */

	/** @type {Set<string>} */
	names;

	/** @type {Map<string, Set<string>>} */
	dependencies_for_name;

	/** @type {Map<string, NodeWithScope>} */
	owners = new Map();

	/** @type {TemplateScope} */
	parent;

	/** @param {TemplateScope} [parent]  undefined */
	constructor(parent) {
		this.parent = parent;
		this.names = new Set(parent ? parent.names : []);
		this.dependencies_for_name = new Map(parent ? parent.dependencies_for_name : []);
	}

	/**
	 * @param {any} name
	 * @param {Set<string>} dependencies
	 * @param {any} owner
	 */
	add(name, dependencies, owner) {
		this.names.add(name);
		this.dependencies_for_name.set(name, dependencies);
		this.owners.set(name, owner);
		return this;
	}
	child() {
		const child = new TemplateScope(this);
		return child;
	}

	/** @param {string} name */
	is_top_level(name) {
		return !this.parent || (!this.names.has(name) && this.parent.is_top_level(name));
	}

	/**
	 * @param {string} name
	 * @returns {NodeWithScope}
	 */
	get_owner(name) {
		return this.owners.get(name) || (this.parent && this.parent.get_owner(name));
	}

	/** @param {string} name */
	is_let(name) {
		const owner = this.get_owner(name);
		return (
			owner &&
			(owner.type === 'Element' ||
				owner.type === 'InlineComponent' ||
				owner.type === 'SlotTemplate')
		);
	}

	/** @param {string} name */
	is_await(name) {
		const owner = this.get_owner(name);
		return owner && (owner.type === 'ThenBlock' || owner.type === 'CatchBlock');
	}

	/** @param {string} name */
	is_const(name) {
		const owner = this.get_owner(name);
		return owner && owner.type === 'ConstTag';
	}
}

/** @extends Node<'Fragment'> */
class Fragment extends Node {
	/** @type {import('../render_dom/Block.js').default} */
	block;

	/** @type {import('./interfaces.js').INode[]} */
	children;

	/** @type {import('./shared/TemplateScope.js').default} */
	scope;

	/**
	 * @param {import('../Component.js').default} component
	 * @param {import('../../interfaces.js').TemplateNode} info
	 */
	constructor(component, info) {
		const scope = new TemplateScope();
		super(component, null, scope, info);
		this.scope = scope;
		this.children = map_children(component, this, scope, info.children);
	}
}

// This file is automatically generated
var internal_exports = new Set(["HtmlTag","HtmlTagHydration","ResizeObserverSingleton","SvelteComponent","SvelteComponentDev","SvelteComponentTyped","SvelteElement","action_destroyer","add_attribute","add_classes","add_flush_callback","add_iframe_resize_listener","add_location","add_render_callback","add_styles","add_transform","afterUpdate","append","append_dev","append_empty_stylesheet","append_hydration","append_hydration_dev","append_styles","assign","attr","attr_dev","attribute_to_object","beforeUpdate","bind","binding_callbacks","blank_object","bubble","check_outros","children","claim_comment","claim_component","claim_element","claim_html_tag","claim_space","claim_svg_element","claim_text","clear_loops","comment","component_subscribe","compute_rest_props","compute_slots","construct_svelte_component","construct_svelte_component_dev","contenteditable_truthy_values","createEventDispatcher","create_animation","create_bidirectional_transition","create_component","create_custom_element","create_in_transition","create_out_transition","create_slot","create_ssr_component","current_component","custom_event","dataset_dev","debug","destroy_block","destroy_component","destroy_each","detach","detach_after_dev","detach_before_dev","detach_between_dev","detach_dev","dirty_components","dispatch_dev","each","element","element_is","empty","end_hydrating","ensure_array_like","ensure_array_like_dev","escape","escape_attribute_value","escape_object","exclude_internal_props","fix_and_destroy_block","fix_and_outro_and_destroy_block","fix_position","flush","flush_render_callbacks","getAllContexts","getContext","get_all_dirty_from_scope","get_binding_group_value","get_current_component","get_custom_elements_slots","get_root_for_style","get_slot_changes","get_spread_object","get_spread_update","get_store_value","get_svelte_dataset","globals","group_outros","handle_promise","hasContext","has_prop","head_selector","identity","init","init_binding_group","init_binding_group_dynamic","insert","insert_dev","insert_hydration","insert_hydration_dev","intros","invalid_attribute_name_character","is_client","is_crossorigin","is_empty","is_function","is_promise","is_void","listen","listen_dev","loop","loop_guard","merge_ssr_styles","missing_component","mount_component","noop","not_equal","now","null_to_empty","object_without_properties","onDestroy","onMount","once","outro_and_destroy_block","prevent_default","prop_dev","query_selector_all","raf","resize_observer_border_box","resize_observer_content_box","resize_observer_device_pixel_content_box","run","run_all","safe_not_equal","schedule_update","select_multiple_value","select_option","select_options","select_value","self","setContext","set_attributes","set_current_component","set_custom_element_data","set_custom_element_data_map","set_data","set_data_contenteditable","set_data_contenteditable_dev","set_data_dev","set_data_maybe_contenteditable","set_data_maybe_contenteditable_dev","set_dynamic_element_data","set_input_type","set_input_value","set_now","set_raf","set_store_value","set_style","set_svg_attributes","space","split_css_unit","spread","src_url_equal","srcset_url_equal","start_hydrating","stop_immediate_propagation","stop_propagation","subscribe","svg_element","text","tick","time_ranges_to_array","to_number","toggle_class","transition_in","transition_out","trusted","update_await_block_branch","update_keyed_each","update_slot","update_slot_base","validate_component","validate_dynamic_element","validate_each_keys","validate_slots","validate_store","validate_void_dynamic_element","xlink_attr"]);

/**
 *
 * @param {import('estree').Node} node
 * @param {import('estree').Node} parent
 * @returns {boolean}
 */
function is_used_as_reference(node, parent) {
	if (
		!is_reference(
			/** @type {import('is-reference').NodeWithPropertyDefinition} */ (node),
			/** @type {import('is-reference').NodeWithPropertyDefinition} */ (parent)
		)
	) {
		return false;
	}
	if (!parent) {
		return true;
	}

	/* eslint-disable no-fallthrough */
	switch (parent.type) {
		// disregard the `foo` in `const foo = bar`
		case 'VariableDeclarator':
			return node !== parent.id;
		// disregard the `foo`, `bar` in `function foo(bar){}`
		case 'FunctionDeclaration':
		// disregard the `foo` in `import { foo } from 'foo'`
		case 'ImportSpecifier':
		// disregard the `foo` in `import foo from 'foo'`
		case 'ImportDefaultSpecifier':
		// disregard the `foo` in `import * as foo from 'foo'`
		case 'ImportNamespaceSpecifier':
		// disregard the `foo` in `export { foo }`
		case 'ExportSpecifier':
			return false;
		default:
			return true;
	}
}

// generated during release, do not modify

/**
 * The current version, as set in package.json.
 *
 * https://svelte.dev/docs/svelte-compiler#svelte-version
 * @type {string}
 */
const VERSION = '4.0.5';

const regex_leading_directory_separator = /^[/\\]/;
const regex_starts_with_term_export = /^Export/;
const regex_contains_term_function = /Function/;

class Component {
	/** @type {import('../Stats.js').default} */
	stats;

	/** @type {import('../interfaces.js').Warning[]} */
	warnings;

	/** @type {Set<string>} */
	ignores;

	/** @type {Array<Set<string>>} */
	ignore_stack = [];

	/** @type {import('../interfaces.js').Ast} */
	ast;

	/** @type {import('../interfaces.js').Ast} */
	original_ast;

	/** @type {string} */
	source;

	/** @type {import('estree').Identifier} */
	name;

	/** @type {import('../interfaces.js').CompileOptions} */
	compile_options;

	/** @type {import('./nodes/Fragment.js').default} */
	fragment;

	/** @type {import('./utils/scope.js').Scope} */
	module_scope;

	/** @type {import('./utils/scope.js').Scope} */
	instance_scope;

	/** @type {WeakMap<import('estree').Node, import('./utils/scope.js').Scope>} */
	instance_scope_map;

	/** @type {ComponentOptions} */
	component_options;

	/** @type {string} */
	namespace;

	/** @type {string} */
	tag;

	/** @type {boolean} */
	accessors;

	/** @type {import('../interfaces.js').Var[]} */
	vars = [];

	/** @type {Map<string, import('../interfaces.js').Var>} */
	var_lookup = new Map();

	/** @type {import('estree').ImportDeclaration[]} */
	imports = [];

	/** @type {import('estree').ExportNamedDeclaration[]} */
	exports_from = [];

	/** @type {import('estree').ExportNamedDeclaration[]} */
	instance_exports_from = [];

	/** @type {Set<import('estree').Node>} */
	hoistable_nodes = new Set();

	/** @type {Map<string, import('estree').Node>} */
	node_for_declaration = new Map();

	/** @type {Array<import('estree').Node | import('estree').Node[]>} */
	partly_hoisted = [];

	/** @type {Array<import('estree').Node | import('estree').Node[]>} */
	fully_hoisted = [];
	/**
	 * @type {Array<{
	 * 		assignees: Set<string>;
	 * 		dependencies: Set<string>;
	 * 		node: import('estree').Node;
	 * 		declaration: import('estree').Node;
	 * 	}>}
	 */
	reactive_declarations = [];

	/** @type {Set<import('estree').Node>} */
	reactive_declaration_nodes = new Set();
	/** */
	has_reactive_assignments = false;

	/** @type {Set<string>} */
	injected_reactive_declaration_vars = new Set();

	/** @type {Map<string, import('estree').Identifier>} */
	helpers = new Map();

	/** @type {Map<string, import('estree').Identifier>} */
	globals = new Map();

	/** @type {Map<string, Set<string>>} */
	indirect_dependencies = new Map();

	/** @type {string} */
	file;

	/**
	 * Use this for stack traces. It is 1-based and acts on pre-processed sources.
	 * Use `meta_locate` for metadata on DOM elements.
	 * @type {(c: number) => { line: number; column: number }}
	 */
	locate;

	/**
	 * Use this for metadata on DOM elements. It is 1-based and acts on sources that have not been pre-processed.
	 * Use `locate` for source mappings.
	 * @type {(c: number) => { line: number; column: number }}
	 */
	meta_locate;

	/** @type {import('./nodes/Element.js').default[]} */
	elements = [];

	/** @type {import('./css/Stylesheet.js').default} */
	stylesheet;

	/** @type {Map<string, import('estree').Identifier>} */
	aliases = new Map();

	/** @type {Set<string>} */
	used_names = new Set();

	/** @type {Set<string>} */
	globally_used_names = new Set();

	/** @type {Map<string, import('./nodes/Slot.js').default>} */
	slots = new Map();

	/** @type {Set<string>} */
	slot_outlets = new Set();

	/** @type {import('./nodes/shared/Tag.js').default[]} */
	tags = [];

	/**
	 * @param {import('../interfaces.js').Ast} ast
	 * @param {string} source
	 * @param {string} name
	 * @param {import('../interfaces.js').CompileOptions} compile_options
	 * @param {import('../Stats.js').default} stats
	 * @param {import('../interfaces.js').Warning[]} warnings
	 */
	constructor(ast, source, name, compile_options, stats, warnings) {
		this.name = { type: 'Identifier', name };
		this.stats = stats;
		this.warnings = warnings;
		this.ast = ast;
		this.source = source;
		this.compile_options = compile_options;
		// the instance JS gets mutated, so we park
		// a copy here for later. TODO this feels gross
		this.original_ast = clone({
			html: ast.html,
			css: ast.css,
			instance: ast.instance,
			module: ast.module
		});
		this.file =
			compile_options.filename &&
			(typeof process !== 'undefined'
				? compile_options.filename
						.replace(process.cwd(), '')
						.replace(regex_leading_directory_separator, '')
				: compile_options.filename);

		// line numbers in stack trace frames are 1-based. source maps are 0-based
		this.locate = getLocator$1(this.source, { offsetLine: 1 });
		/** @type {TraceMap | null | undefined} initialise lazy because only used in dev mode */
		let tracer;
		this.meta_locate = (c) => {
			/** @type {{ line: number, column: number }} */
			let location = this.locate(c);
			if (tracer === undefined) {
				// @ts-expect-error - fix the type of CompileOptions.sourcemap
				tracer = compile_options.sourcemap ? new TraceMap(compile_options.sourcemap) : null;
			}
			if (tracer) {
				// originalPositionFor returns 1-based lines like locator
				location = originalPositionFor$1(tracer, location);
			}
			return location;
		};

		// styles
		this.stylesheet = new Stylesheet({
			source,
			ast,
			filename: compile_options.filename,
			component_name: name,
			dev: compile_options.dev,
			get_css_hash: compile_options.cssHash
		});
		this.stylesheet.validate(this);
		this.component_options = process_component_options(this, this.ast.html.children);
		this.namespace =
			namespaces[this.component_options.namespace] || this.component_options.namespace;
		if (compile_options.customElement) {
			this.tag = this.component_options.customElement?.tag || compile_options.tag || this.name.name;
		} else {
			this.tag = this.name.name;
		}
		this.walk_module_js();
		this.push_ignores(
			this.ast.instance
				? extract_ignores_above_position(this.ast.instance.start, this.ast.html.children)
				: []
		);
		this.walk_instance_js_pre_template();
		this.pop_ignores();
		this.fragment = new Fragment(this, ast.html);
		this.name = this.get_unique_name(name);
		this.push_ignores(
			this.ast.instance
				? extract_ignores_above_position(this.ast.instance.start, this.ast.html.children)
				: []
		);
		this.walk_instance_js_post_template();
		this.pop_ignores();
		this.elements.forEach(/** @param {any} element */ (element) => this.stylesheet.apply(element));
		this.stylesheet.reify();
		this.stylesheet.warn_on_unused_selectors(this);
	}

	/**
	 * @param {import('estree').Node} node
	 * @param {import('../interfaces.js').Var} variable
	 * @param {any} add_to_lookup
	 */
	add_var(node, variable, add_to_lookup = true) {
		this.vars.push(variable);
		if (add_to_lookup) {
			if (this.var_lookup.has(variable.name)) {
				const exists_var = this.var_lookup.get(variable.name);
				if (exists_var.module && exists_var.imported) {
					this.error(/** @type {any} */ (node), compiler_errors.illegal_variable_declaration);
				}
			}
			this.var_lookup.set(variable.name, variable);
		}
	}

	/**
	 * @param {import('estree').Node} node
	 * @param {string} name
	 */
	add_reference(node, name) {
		const variable = this.var_lookup.get(name);
		if (variable) {
			variable.referenced = true;
		} else if (is_reserved_keyword(name)) {
			this.add_var(node, {
				name,
				injected: true,
				referenced: true
			});
		} else if (name[0] === '$') {
			this.add_var(node, {
				name,
				injected: true,
				referenced: true,
				mutated: true,
				writable: true
			});
			const subscribable_name = name.slice(1);
			const variable = this.var_lookup.get(subscribable_name);
			if (variable) {
				variable.referenced = true;
				variable.subscribable = true;
			}
		} else {
			if (this.compile_options.varsReport === 'full') {
				this.add_var(node, { name, referenced: true }, false);
			}
			this.used_names.add(name);
		}
	}

	/** @param {string} name */
	alias(name) {
		if (!this.aliases.has(name)) {
			this.aliases.set(name, this.get_unique_name(name));
		}
		return this.aliases.get(name);
	}

	/** @param {import('./nodes/Element.js').default} element */
	apply_stylesheet(element) {
		this.elements.push(element);
	}

	/** @param {string} name */
	global(name) {
		const alias = this.alias(name);
		this.globals.set(name, alias);
		return alias;
	}

	/**
	 * @param {{ js: import('estree').Node[]; css: import('../interfaces.js').CssResult }} [result]
	 * @returns {import('../interfaces.js').CompileResult}
	 */
	generate(result) {
		let js = null;
		let css = null;
		if (result) {
			const { compile_options, name } = this;
			const banner = `${this.file ? `${this.file} ` : ''}generated by Svelte v${VERSION}`;

			/** @type {any} */
			const program = { type: 'Program', body: result.js };
			walk(program, {
				enter: /**
				 * @param {import('estree').Node} node
				 * @param {import('estree').Node} parent
				 * @param {any} key
				 */ (node, parent, key) => {
					if (node.type === 'Identifier') {
						if (node.name[0] === '@') {
							if (node.name[1] === '_') {
								const alias = this.global(node.name.slice(2));
								node.name = alias.name;
							} else {
								let name = node.name.slice(1);
								if (compile_options.hydratable) {
									if (internal_exports.has(`${name}_hydration`)) {
										name += '_hydration';
									} else if (internal_exports.has(`${name}Hydration`)) {
										name += 'Hydration';
									}
								}
								if (compile_options.dev) {
									if (internal_exports.has(`${name}_dev`)) {
										name += '_dev';
									} else if (internal_exports.has(`${name}Dev`)) {
										name += 'Dev';
									}
								}
								const alias = this.alias(name);
								this.helpers.set(name, alias);
								node.name = alias.name;
							}
						} else if (node.name[0] !== '#' && !is_valid(node.name)) {
							// this hack allows x`foo.${bar}` where bar could be invalid

							/** @type {import('estree').Literal} */
							const literal = { type: 'Literal', value: node.name };
							if (parent.type === 'Property' && key === 'key') {
								parent.key = literal;
							} else if (parent.type === 'MemberExpression' && key === 'property') {
								parent.property = literal;
								parent.computed = true;
							}
						}
					}
				}
			});
			const referenced_globals = Array.from(
				this.globals,
				/** @param {any}params_0 */
				([name, alias]) => name !== alias.name && { name, alias }
			).filter(Boolean);
			if (referenced_globals.length) {
				this.helpers.set('globals', this.alias('globals'));
			}
			const imported_helpers = Array.from(
				this.helpers,
				/** @param {any}params_0 */ ([name, alias]) => ({
					name,
					alias
				})
			);
			create_module(
				program,
				name,
				banner,
				compile_options.sveltePath,
				imported_helpers,
				referenced_globals,
				this.imports,
				this.vars
					.filter(
						/** @param {any} variable */ (variable) => variable.module && variable.export_name
					)
					.map(
						/** @param {any} variable */ (variable) => ({
							name: variable.name,
							as: variable.export_name
						})
					),
				this.exports_from
			);
			css = compile_options.customElement ? { code: null, map: null } : result.css;
			const js_sourcemap_enabled = check_enable_sourcemap(compile_options.enableSourcemap, 'js');
			if (!js_sourcemap_enabled) {
				js = print(program);
				js.map = null;
			} else {
				const sourcemap_source_filename = get_sourcemap_source_filename(compile_options);
				js = print(program, {
					sourceMapSource: sourcemap_source_filename
				});
				js.map.sources = [sourcemap_source_filename];
				js.map.sourcesContent = [this.source];
				js.map = apply_preprocessor_sourcemap(
					sourcemap_source_filename,
					js.map,
					/** @type {string | import('@ampproject/remapping').RawSourceMap | import('@ampproject/remapping').DecodedSourceMap} */ (
						compile_options.sourcemap
					)
				);
			}
		}
		return {
			js,
			css,
			ast: this.original_ast,
			warnings: this.warnings,
			vars: this.get_vars_report(),
			stats: this.stats.render()
		};
	}

	/**
	 * @param {string} name
	 * @param {import('./utils/scope.js').Scope} [scope]
	 * @returns {import('estree').Identifier}
	 */
	get_unique_name(name, scope) {
		let alias = name;
		for (
			let i = 1;
			reserved.has(alias) ||
			this.var_lookup.has(alias) ||
			this.used_names.has(alias) ||
			this.globally_used_names.has(alias) ||
			(scope && scope.has(alias));

		) {
			alias = `${name}_${i++}`;
		}
		this.used_names.add(alias);
		return { type: 'Identifier', name: alias };
	}
	get_unique_name_maker() {
		const local_used_names = new Set();

		/** @param {string} name */
		function add(name) {
			local_used_names.add(name);
		}
		reserved.forEach(add);
		internal_exports.forEach(add);
		this.var_lookup.forEach(
			/**
			 * @param {any} _value
			 * @param {any} key
			 */ (_value, key) => add(key)
		);

		/**
		 * @param {string} name
		 * @returns {import('estree').Identifier}
		 */
		return (name) => {
			let alias = name;
			for (
				let i = 1;
				this.used_names.has(alias) || local_used_names.has(alias);
				alias = `${name}_${i++}`
			);
			local_used_names.add(alias);
			this.globally_used_names.add(alias);
			return {
				type: 'Identifier',
				name: alias
			};
		};
	}

	/** @returns {import('../interfaces.js').Var[]} */
	get_vars_report() {
		const { compile_options, vars } = this;
		const vars_report =
			compile_options.varsReport === false
				? []
				: compile_options.varsReport === 'full'
				? vars
				: vars.filter(/** @param {any} v */ (v) => !v.global && !v.internal);
		return vars_report.map(
			/** @param {any} v */ (v) => ({
				name: v.name,
				export_name: v.export_name || null,
				injected: v.injected || false,
				module: v.module || false,
				mutated: v.mutated || false,
				reassigned: v.reassigned || false,
				referenced: v.referenced || false,
				writable: v.writable || false,
				referenced_from_script: v.referenced_from_script || false
			})
		);
	}
	/**
	 * @param {{
	 * 			start: number;
	 * 			end: number;
	 * 		}} pos
	 * @param {{
	 * 			code: string;
	 * 			message: string;
	 * 		}} e
	 */
	error(pos, e) {
		if (this.compile_options.errorMode === 'warn') {
			this.warn(pos, e);
		} else {
			error(e.message, {
				name: 'ValidationError',
				code: e.code,
				source: this.source,
				start: pos.start,
				end: pos.end,
				filename: this.compile_options.filename
			});
		}
	}
	/**
	 * @param {{
	 * 			start: number;
	 * 			end: number;
	 * 		}} pos
	 * @param {{
	 * 			code: string;
	 * 			message: string;
	 * 		}} warning
	 */
	warn(pos, warning) {
		if (this.ignores && this.ignores.has(warning.code)) {
			return;
		}
		const start = this.locate(pos.start);
		const end = this.locate(pos.end);
		const frame = get_code_frame(this.source, start.line - 1, start.column);
		this.warnings.push({
			code: warning.code,
			message: warning.message,
			frame,
			start,
			end,
			pos: pos.start,
			filename: this.compile_options.filename,
			toString: () => `${warning.message} (${start.line}:${start.column})\n${frame}`
		});
	}

	/** @param {any} node */
	extract_imports(node) {
		this.imports.push(node);
	}

	/**
	 * @param {any} node
	 * @param {any} module_script
	 */
	extract_exports(node, module_script = false) {
		const ignores = extract_svelte_ignore_from_comments(node);
		if (ignores.length) this.push_ignores(ignores);
		const result = this._extract_exports(node, module_script);
		if (ignores.length) this.pop_ignores();
		return result;
	}

	/**
	 * @private
	 * @param {import('estree').ExportDefaultDeclaration | import('estree').ExportNamedDeclaration | import('estree').ExportAllDeclaration} node
	 * @param {boolean} module_script
	 */
	_extract_exports(node, module_script) {
		if (node.type === 'ExportDefaultDeclaration') {
			return this.error(/** @type {any} */ (node), compiler_errors.default_export);
		}
		if (node.type === 'ExportNamedDeclaration') {
			if (node.source) {
				if (module_script) {
					this.exports_from.push(node);
				} else {
					this.instance_exports_from.push(node);
				}
				return null;
			}
			if (node.declaration) {
				if (node.declaration.type === 'VariableDeclaration') {
					node.declaration.declarations.forEach(
						/** @param {any} declarator */ (declarator) => {
							extract_names(declarator.id).forEach(
								/** @param {any} name */ (name) => {
									const variable = this.var_lookup.get(name);
									variable.export_name = name;
									if (
										declarator.init?.type === 'Literal' &&
										typeof declarator.init.value === 'boolean'
									) {
										variable.is_boolean = true;
									}
									if (
										!module_script &&
										variable.writable &&
										!(
											variable.referenced ||
											variable.referenced_from_script ||
											variable.subscribable
										)
									) {
										this.warn(
											/** @type {any} */ (declarator),
											compiler_warnings.unused_export_let(this.name.name, name)
										);
									}
								}
							);
						}
					);
				} else {
					const { name } = node.declaration.id;
					const variable = this.var_lookup.get(name);
					variable.export_name = name;
				}
				return node.declaration;
			} else {
				node.specifiers.forEach(
					/** @param {any} specifier */ (specifier) => {
						const variable = this.var_lookup.get(specifier.local.name);
						if (variable) {
							variable.export_name = specifier.exported.name;
							if (
								!module_script &&
								variable.writable &&
								!(variable.referenced || variable.referenced_from_script || variable.subscribable)
							) {
								this.warn(
									/** @type {any} */ (specifier),
									compiler_warnings.unused_export_let(this.name.name, specifier.exported.name)
								);
							}
						}
					}
				);
				return null;
			}
		}
	}

	/** @param {any} script */
	extract_javascript(script) {
		if (!script) return null;
		return script.content.body.filter(
			/** @param {any} node */ (node) => {
				if (!node) return false;
				if (this.hoistable_nodes.has(node)) return false;
				if (this.reactive_declaration_nodes.has(node)) return false;
				if (node.type === 'ImportDeclaration') return false;
				if (node.type === 'ExportDeclaration' && node.specifiers.length > 0) return false;
				return true;
			}
		);
	}
	walk_module_js() {
		const component = this;
		const script = this.ast.module;
		if (!script) return;
		walk(script.content, {
			/** @param {import('estree').Node} node */
			enter(node) {
				if (node.type === 'LabeledStatement' && node.label.name === '$') {
					component.warn(
						/** @type {any} */ (node),
						compiler_warnings.module_script_reactive_declaration
					);
				}
			}
		});
		const { scope, globals } = create_scopes(script.content);
		this.module_scope = scope;
		scope.declarations.forEach(
			/**
			 * @param {any} node
			 * @param {any} name
			 */ (node, name) => {
				if (name[0] === '$') {
					return this.error(/** @type {any} */ (node), compiler_errors.illegal_declaration);
				}
				const writable =
					node.type === 'VariableDeclaration' && (node.kind === 'var' || node.kind === 'let');
				const imported = node.type.startsWith('Import');
				this.add_var(node, {
					name,
					module: true,
					hoistable: true,
					writable,
					imported
				});
			}
		);
		globals.forEach(
			/**
			 * @param {any} node
			 * @param {any} name
			 */ (node, name) => {
				if (name[0] === '$') {
					return this.error(/** @type {any} */ (node), compiler_errors.illegal_subscription);
				} else {
					this.add_var(node, {
						name,
						global: true,
						hoistable: true
					});
				}
			}
		);
		const { body } = script.content;
		let i = body.length;
		while (--i >= 0) {
			const node = body[i];
			if (node.type === 'ImportDeclaration') {
				this.extract_imports(node);
				body.splice(i, 1);
			}
			if (regex_starts_with_term_export.test(node.type)) {
				const replacement = this.extract_exports(node, true);
				if (replacement) {
					body[i] = replacement;
				} else {
					body.splice(i, 1);
				}
			}
		}
	}
	walk_instance_js_pre_template() {
		const script = this.ast.instance;
		if (!script) return;
		// inject vars for reactive declarations
		script.content.body.forEach(
			/** @param {any} node */ (node) => {
				if (node.type !== 'LabeledStatement') return;
				if (node.body.type !== 'ExpressionStatement') return;
				const { expression } = node.body;
				if (expression.type !== 'AssignmentExpression') return;
				if (expression.left.type === 'MemberExpression') return;
				extract_names(expression.left).forEach(
					/** @param {any} name */ (name) => {
						if (!this.var_lookup.has(name) && name[0] !== '$') {
							this.injected_reactive_declaration_vars.add(name);
						}
					}
				);
			}
		);
		const { scope: instance_scope, map, globals } = create_scopes(script.content);
		this.instance_scope = instance_scope;
		this.instance_scope_map = map;
		instance_scope.declarations.forEach(
			/**
			 * @param {any} node
			 * @param {any} name
			 */ (node, name) => {
				if (name[0] === '$') {
					return this.error(/** @type {any} */ (node), compiler_errors.illegal_declaration);
				}
				const writable =
					node.type === 'VariableDeclaration' && (node.kind === 'var' || node.kind === 'let');
				const imported = node.type.startsWith('Import');
				this.add_var(node, {
					name,
					initialised: instance_scope.initialised_declarations.has(name),
					writable,
					imported
				});
				this.node_for_declaration.set(name, node);
			}
		);
		// NOTE: add store variable first, then only $store value
		// as `$store` will mark `store` variable as referenced and subscribable
		const global_keys = Array.from(globals.keys());
		const sorted_globals = [
			...global_keys.filter(/** @param {any} key */ (key) => key[0] !== '$'),
			...global_keys.filter(/** @param {any} key */ (key) => key[0] === '$')
		];
		sorted_globals.forEach(
			/** @param {any} name */ (name) => {
				if (this.var_lookup.has(name)) return;
				const node = globals.get(name);
				if (this.injected_reactive_declaration_vars.has(name)) {
					this.add_var(node, {
						name,
						injected: true,
						writable: true,
						reassigned: true,
						initialised: true
					});
				} else if (is_reserved_keyword(name)) {
					this.add_var(node, {
						name,
						injected: true
					});
				} else if (name[0] === '$') {
					if (name === '$' || name[1] === '$') {
						return this.error(/** @type {any} */ (node), compiler_errors.illegal_global(name));
					}
					this.add_var(node, {
						name,
						injected: true,
						mutated: true,
						writable: true
					});
					this.add_reference(node, name.slice(1));
					const variable = this.var_lookup.get(name.slice(1));
					if (variable) {
						variable.subscribable = true;
						variable.referenced_from_script = true;
					}
				} else {
					this.add_var(node, {
						name,
						global: true,
						hoistable: true
					});
				}
			}
		);
		this.track_references_and_mutations();
	}
	walk_instance_js_post_template() {
		const script = this.ast.instance;
		if (!script) return;
		this.post_template_walk();
		this.hoist_instance_declarations();
		this.extract_reactive_declarations();
		this.check_if_tags_content_dynamic();
	}
	post_template_walk() {
		const script = this.ast.instance;
		if (!script) return;
		const component = this;
		const { content } = script;
		const { instance_scope, instance_scope_map: map } = this;
		let scope = instance_scope;
		const to_remove = [];

		/**
		 * @param {any} parent
		 * @param {any} prop
		 * @param {any} index
		 */
		const remove = (parent, prop, index) => {
			to_remove.unshift([parent, prop, index]);
		};
		let scope_updated = false;
		const current_function_stack = [];

		/** @type {import('estree').FunctionDeclaration | import('estree').FunctionExpression} */
		let current_function = null;
		walk(content, {
			/**
			 * @param {import('estree').Node} node
			 * @param {import('estree').Node} parent
			 * @param {any} prop
			 * @param {any} index
			 */
			enter(node, parent, prop, index) {
				if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression') {
					current_function_stack.push((current_function = node));
				}
				if (map.has(node)) {
					scope = map.get(node);
				}
				let deep = false;

				/** @type {string[]} */
				let names = [];
				if (node.type === 'AssignmentExpression') {
					if (node.left.type === 'ArrayPattern') {
						walk(node.left, {
							/**
							 * @param {import('estree').Node} node
							 * @param {import('estree').Node} parent
							 */
							enter(node, parent) {
								if (
									node.type === 'Identifier' &&
									parent.type !== 'MemberExpression' &&
									(parent.type !== 'AssignmentPattern' || parent.right !== node)
								) {
									names.push(node.name);
								}
							}
						});
					} else {
						deep = node.left.type === 'MemberExpression';
						names = deep ? [get_object(node.left).name] : extract_names(node.left);
					}
				} else if (node.type === 'UpdateExpression') {
					deep = node.argument.type === 'MemberExpression';
					const { name } = get_object(node.argument);
					names.push(name);
				}
				if (names.length > 0) {
					names.forEach(
						/** @param {any} name */ (name) => {
							let current_scope = scope;
							let declaration;
							while (current_scope) {
								if (current_scope.declarations.has(name)) {
									declaration = current_scope.declarations.get(name);
									break;
								}
								current_scope = current_scope.parent;
							}
							if (declaration && /** @type {any} */ (declaration).kind === 'const' && !deep) {
								component.error(/** @type {any} */ (node), {
									code: 'assignment-to-const',
									message: 'You are assigning to a const'
								});
							}
						}
					);
				}
				if (node.type === 'ImportDeclaration') {
					component.extract_imports(node);
					// TODO: to use actual remove
					remove(parent, prop, index);
					return this.skip();
				}
				if (regex_starts_with_term_export.test(node.type)) {
					const replacement = component.extract_exports(node);
					if (replacement) {
						this.replace(replacement);
					} else {
						// TODO: to use actual remove
						remove(parent, prop, index);
					}
					return this.skip();
				}
				component.warn_on_undefined_store_value_references(node, parent, prop, scope);
			},

			/** @param {import('estree').Node} node */
			leave(node) {
				if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression') {
					current_function_stack.pop();
					current_function = current_function_stack[current_function_stack.length - 1];
				}
				// do it on leave, to prevent infinite loop
				if (
					component.compile_options.dev &&
					component.compile_options.loopGuardTimeout > 0 &&
					(!current_function || (!current_function.generator && !current_function.async))
				) {
					const to_replace_for_loop_protect = component.loop_protect(
						node,
						scope,
						component.compile_options.loopGuardTimeout
					);
					if (to_replace_for_loop_protect) {
						this.replace(to_replace_for_loop_protect);
						scope_updated = true;
					}
				}
				if (map.has(node)) {
					scope = scope.parent;
				}
			}
		});
		for (const [parent, prop, index] of to_remove) {
			if (parent) {
				if (index !== null) {
					parent[prop].splice(index, 1);
				} else {
					delete parent[prop];
				}
			}
		}
		if (scope_updated) {
			const { scope, map } = create_scopes(script.content);
			this.instance_scope = scope;
			this.instance_scope_map = map;
		}
	}
	track_references_and_mutations() {
		const script = this.ast.instance;
		if (!script) return;
		const component = this;
		const { content } = script;
		const { instance_scope, module_scope, instance_scope_map: map } = this;
		let scope = instance_scope;
		walk(content, {
			/**
			 * @param {import('estree').Node} node
			 * @param {import('estree').Node} parent
			 */
			enter(node, parent) {
				if (map.has(node)) {
					scope = map.get(node);
				}
				if (node.type === 'AssignmentExpression' || node.type === 'UpdateExpression') {
					const assignee = node.type === 'AssignmentExpression' ? node.left : node.argument;
					const names = extract_names(/** @type {import('estree').Node} */ (assignee));
					const deep = assignee.type === 'MemberExpression';
					names.forEach(
						/** @param {any} name */ (name) => {
							const scope_owner = scope.find_owner(name);
							if (
								scope_owner !== null
									? scope_owner === instance_scope
									: module_scope && module_scope.has(name)
							) {
								const variable = component.var_lookup.get(name);
								variable[deep ? 'mutated' : 'reassigned'] = true;
							}
						}
					);
				}
				if (is_used_as_reference(node, parent)) {
					const object = get_object(node);
					if (scope.find_owner(object.name) === instance_scope) {
						const variable = component.var_lookup.get(object.name);
						variable.referenced_from_script = true;
					}
				}
			},

			/** @param {import('estree').Node} node */
			leave(node) {
				if (map.has(node)) {
					scope = scope.parent;
				}
			}
		});
	}

	/**
	 * @param {import('estree').Node} node
	 * @param {import('estree').Node} parent
	 * @param {string | number | symbol} prop
	 * @param {import('./utils/scope.js').Scope} scope
	 */
	warn_on_undefined_store_value_references(node, parent, prop, scope) {
		if (node.type === 'LabeledStatement' && node.label.name === '$' && parent.type !== 'Program') {
			this.warn(/** @type {any} */ (node), compiler_warnings.non_top_level_reactive_declaration);
		}
		if (
			is_reference(
				/** @type {import('is-reference').NodeWithPropertyDefinition} */ (node),
				/** @type {import('is-reference').NodeWithPropertyDefinition} */ (parent)
			)
		) {
			const object = get_object(node);
			const { name } = object;
			if (name[0] === '$') {
				if (!scope.has(name)) {
					this.warn_if_undefined(name, object, null);
				}
				if (
					name[1] !== '$' &&
					scope.has(name.slice(1)) &&
					scope.find_owner(name.slice(1)) !== this.instance_scope
				) {
					if (
						!(
							(regex_contains_term_function.test(parent.type) && prop === 'params') ||
							(parent.type === 'VariableDeclarator' && prop === 'id')
						)
					) {
						return this.error(/** @type {any} */ (node), compiler_errors.contextual_store);
					}
				}
			}
		}
	}

	/**
	 * @param {any} node
	 * @param {import('./utils/scope.js').Scope} scope
	 * @param {number} timeout
	 * @returns {import('estree').Node}
	 */
	loop_protect(node, scope, timeout) {
		if (
			node.type === 'WhileStatement' ||
			node.type === 'ForStatement' ||
			node.type === 'DoWhileStatement'
		) {
			const guard = this.get_unique_name('guard', scope);
			this.used_names.add(guard.name);
			const before = b$1`const ${guard} = @loop_guard(${timeout})`;
			const inside = b$1`${guard}();`;
			// wrap expression statement with BlockStatement
			if (node.body.type !== 'BlockStatement') {
				node.body = {
					type: 'BlockStatement',
					body: [node.body]
				};
			}
			node.body.body.push(inside[0]);
			return {
				type: 'BlockStatement',
				body: [before[0], node]
			};
		}
		return null;
	}

	/** @param {(variable: import('../interfaces.js').Var) => import('estree').Node[]} get_insert */
	rewrite_props(get_insert) {
		if (!this.ast.instance) return;
		const component = this;
		const { instance_scope, instance_scope_map: map } = this;
		let scope = instance_scope;
		walk(this.ast.instance.content, {
			/** @param {import('estree').Node} node */
			enter(node) {
				if (regex_contains_term_function.test(node.type)) {
					return this.skip();
				}
				if (map.has(node)) {
					scope = map.get(node);
				}
				if (node.type === 'ExportNamedDeclaration' && node.declaration) {
					return this.replace(node.declaration);
				}
				if (node.type === 'VariableDeclaration') {
					// NOTE: `var` does not follow block scoping
					if (node.kind === 'var' || scope === instance_scope) {
						const inserts = [];
						const props = [];

						/**
						 * @param {import('estree').Identifier} exported
						 * @param {import('estree').Pattern} local
						 * @param {import('estree').Expression} default_value
						 */
						function add_new_props(exported, local, default_value) {
							props.push({
								type: 'Property',
								method: false,
								shorthand: false,
								computed: false,
								kind: 'init',
								key: exported,
								value: default_value
									? {
											type: 'AssignmentPattern',
											left: local,
											right: default_value
									  }
									: local
							});
						}
						// transform
						// ```
						// export let { x, y = 123 } = OBJ, z = 456
						// ```
						// into
						// ```
						// let { x: x$, y: y$ = 123 } = OBJ;
						// let { x = x$, y = y$, z = 456 } = $$props;
						// ```
						for (let index = 0; index < node.declarations.length; index++) {
							const declarator = node.declarations[index];
							if (declarator.id.type !== 'Identifier') {
								/**
								 * @param {import('estree').Identifier} local
								 * @returns {import('estree').Identifier}
								 */
								function get_new_name(local) {
									const variable = component.var_lookup.get(local.name);
									if (variable.subscribable) {
										inserts.push(get_insert(variable));
									}
									if (variable.export_name && variable.writable) {
										const alias_name = component.get_unique_name(local.name);
										add_new_props(
											{ type: 'Identifier', name: variable.export_name },
											local,
											alias_name
										);
										return alias_name;
									}
									return local;
								}

								/** @param {import('estree').Pattern} param */
								function rename_identifiers(param) {
									switch (param.type) {
										case 'ObjectPattern': {
											/** @param {import('estree').Property | import('estree').RestElement} prop */
											const handle_prop = (prop) => {
												if (prop.type === 'RestElement') {
													rename_identifiers(prop);
												} else if (prop.value.type === 'Identifier') {
													prop.value = get_new_name(prop.value);
												} else {
													rename_identifiers(/** @type {import('estree').Pattern} */ (prop.value));
												}
											};
											param.properties.forEach(handle_prop);
											break;
										}
										case 'ArrayPattern': {
											/**
											 * @param {import('estree').Pattern | null} element
											 * @param {number} index
											 * @param {Array<import('estree').Pattern | null>} array
											 */
											const handle_element = (element, index, array) => {
												if (element) {
													if (element.type === 'Identifier') {
														array[index] = get_new_name(element);
													} else {
														rename_identifiers(element);
													}
												}
											};
											param.elements.forEach(handle_element);
											break;
										}
										case 'RestElement':
											if (param.argument.type === 'Identifier') {
												param.argument = get_new_name(param.argument);
											} else {
												rename_identifiers(param.argument);
											}
											break;
										case 'AssignmentPattern':
											if (param.left.type === 'Identifier') {
												param.left = get_new_name(param.left);
											} else {
												rename_identifiers(param.left);
											}
											break;
									}
								}
								rename_identifiers(declarator.id);
							} else {
								const { name } = declarator.id;
								const variable = component.var_lookup.get(name);
								const is_props = variable.export_name && variable.writable;
								if (is_props) {
									add_new_props(
										{ type: 'Identifier', name: variable.export_name },
										declarator.id,
										declarator.init
									);
									node.declarations.splice(index--, 1);
								}
								if (variable.subscribable && (is_props || declarator.init)) {
									inserts.push(get_insert(variable));
								}
							}
						}
						this.replace(
							/** @type {any} */ (
								b$1`
							${node.declarations.length ? node : null}
							${props.length > 0 && b$1`let { ${props} } = $$props;`}
							${inserts}
						`
							)
						);
						return this.skip();
					}
				}
			},

			/** @param {import('estree').Node} node */
			leave(node) {
				if (map.has(node)) {
					scope = scope.parent;
				}
			}
		});
	}
	hoist_instance_declarations() {
		// we can safely hoist variable declarations that are
		// initialised to literals, and functions that don't
		// reference instance variables other than other
		// hoistable functions. TODO others?
		const { hoistable_nodes, var_lookup, injected_reactive_declaration_vars, imports } = this;
		const top_level_function_declarations = new Map();
		const { body } = this.ast.instance.content;
		for (let i = 0; i < body.length; i += 1) {
			const node = body[i];
			if (node.type === 'VariableDeclaration') {
				const all_hoistable = node.declarations.every(
					/** @param {any} d */ (d) => {
						if (!d.init) return false;
						if (d.init.type !== 'Literal') return false;
						// everything except const values can be changed by e.g. svelte devtools
						// which means we can't hoist it
						if (node.kind !== 'const' && this.compile_options.dev) return false;
						const { name } = /** @type {import('estree').Identifier} */ (d.id);
						const v = this.var_lookup.get(name);
						if (v.reassigned) return false;
						if (v.export_name) return false;
						if (this.var_lookup.get(name).reassigned) return false;
						if (
							this.vars.find(
								/** @param {any} variable */ (variable) => variable.name === name && variable.module
							)
						) {
							return false;
						}
						return true;
					}
				);
				if (all_hoistable) {
					node.declarations.forEach(
						/** @param {any} d */ (d) => {
							const variable = this.var_lookup.get(
								/** @type {import('estree').Identifier} */ (d.id).name
							);
							variable.hoistable = true;
						}
					);
					hoistable_nodes.add(node);
					body.splice(i--, 1);
					this.fully_hoisted.push(node);
				}
			}
			if (
				node.type === 'ExportNamedDeclaration' &&
				node.declaration &&
				node.declaration.type === 'FunctionDeclaration'
			) {
				top_level_function_declarations.set(node.declaration.id.name, node);
			}
			if (node.type === 'FunctionDeclaration') {
				top_level_function_declarations.set(node.id.name, node);
			}
		}
		const checked = new Set();
		const walking = new Set();

		/** @param {any} fn_declaration */
		const is_hoistable = (fn_declaration) => {
			if (fn_declaration.type === 'ExportNamedDeclaration') {
				fn_declaration = fn_declaration.declaration;
			}
			const instance_scope = this.instance_scope;
			let scope = this.instance_scope;
			const map = this.instance_scope_map;
			let hoistable = true;
			// handle cycles
			walking.add(fn_declaration);
			walk(fn_declaration, {
				/**
				 * @param {import('estree').Node} node
				 * @param {any} parent
				 */
				enter(node, parent) {
					if (!hoistable) return this.skip();
					if (map.has(node)) {
						scope = map.get(node);
					}
					if (
						is_reference(
							/** @type {import('is-reference').NodeWithPropertyDefinition} */ (node),
							/** @type {import('is-reference').NodeWithPropertyDefinition} */ (parent)
						)
					) {
						const { name } = flatten_reference(node);
						const owner = scope.find_owner(name);
						if (injected_reactive_declaration_vars.has(name)) {
							hoistable = false;
						} else if (name[0] === '$' && !owner) {
							hoistable = false;
						} else if (owner === instance_scope) {
							const variable = var_lookup.get(name);
							if (variable.reassigned || variable.mutated) hoistable = false;
							if (name === fn_declaration.id.name) return;
							if (variable.hoistable) return;
							if (top_level_function_declarations.has(name)) {
								const other_declaration = top_level_function_declarations.get(name);
								if (walking.has(other_declaration)) {
									hoistable = false;
								} else if (
									other_declaration.type === 'ExportNamedDeclaration' &&
									walking.has(other_declaration.declaration)
								) {
									hoistable = false;
								} else if (!is_hoistable(other_declaration)) {
									hoistable = false;
								}
							} else {
								hoistable = false;
							}
						}
						this.skip();
					}
				},

				/** @param {import('estree').Node} node */
				leave(node) {
					if (map.has(node)) {
						scope = scope.parent;
					}
				}
			});
			checked.add(fn_declaration);
			walking.delete(fn_declaration);
			return hoistable;
		};
		for (const [name, node] of top_level_function_declarations) {
			if (is_hoistable(node)) {
				const variable = this.var_lookup.get(name);
				variable.hoistable = true;
				hoistable_nodes.add(node);
				const i = body.indexOf(node);
				body.splice(i, 1);
				this.fully_hoisted.push(node);
			}
		}
		for (const { specifiers } of imports) {
			for (const specifier of specifiers) {
				const variable = var_lookup.get(specifier.local.name);
				if (!variable.mutated || variable.subscribable) {
					variable.hoistable = true;
				}
			}
		}
	}
	extract_reactive_declarations() {
		const component = this;
		/**
		 * @type {Array<{
		 * 			assignees: Set<string>;
		 * 			dependencies: Set<string>;
		 * 			node: import('estree').Node;
		 * 			declaration: import('estree').Node;
		 * 		}>}
		 */
		const unsorted_reactive_declarations = [];
		this.ast.instance.content.body.forEach(
			/** @param {any} node */ (node) => {
				const ignores = extract_svelte_ignore_from_comments(node);
				if (ignores.length) this.push_ignores(ignores);
				if (node.type === 'LabeledStatement' && node.label.name === '$') {
					this.reactive_declaration_nodes.add(node);
					const assignees = new Set();
					const assignee_nodes = new Set();
					const dependencies = new Set();
					const module_dependencies = new Set();
					let scope = this.instance_scope;
					const { declarations: outset_scope_decalarations } = this.instance_scope;
					const map = this.instance_scope_map;
					walk(node.body, {
						/**
						 * @param {import('estree').Node} node
						 * @param {any} parent
						 */
						enter(node, parent) {
							if (node.type === 'VariableDeclaration' && node.kind === 'var') {
								const is_var_in_outset = node.declarations.some(
									/** @param {import('estree').VariableDeclarator} declaration */ (declaration) => {
										/** @type {string[]} */
										const names = extract_names(declaration.id);
										return !!names.find(
											/** @param {string} name */ (name) => {
												const var_node = outset_scope_decalarations.get(name);
												return var_node === node;
											}
										);
									}
								);
								if (is_var_in_outset) {
									return component.error(
										/** @type {any} */ (node),
										compiler_errors.invalid_var_declaration
									);
								}
							}
							if (map.has(node)) {
								scope = map.get(node);
							}
							if (node.type === 'AssignmentExpression') {
								const left = get_object(node.left);
								extract_identifiers(left).forEach(
									/** @param {any} node */ (node) => {
										assignee_nodes.add(node);
										assignees.add(node.name);
									}
								);
								if (node.operator !== '=') {
									dependencies.add(left.name);
								}
							} else if (node.type === 'UpdateExpression') {
								const identifier = get_object(node.argument);
								assignees.add(identifier.name);
							} else if (
								is_reference(
									/** @type {import('is-reference').NodeWithPropertyDefinition} */ (node),
									/** @type {import('is-reference').NodeWithPropertyDefinition} */ (parent)
								)
							) {
								const identifier = get_object(node);
								if (!assignee_nodes.has(identifier)) {
									const { name } = identifier;
									const owner = scope.find_owner(name);
									const variable = component.var_lookup.get(name);
									let should_add_as_dependency = true;
									if (variable) {
										variable.is_reactive_dependency = true;
										if (variable.module && variable.writable) {
											should_add_as_dependency = false;
											module_dependencies.add(name);
										}
									}
									const is_writable_or_mutated =
										variable && (variable.writable || variable.mutated);
									if (
										should_add_as_dependency &&
										(!owner || owner === component.instance_scope) &&
										(name[0] === '$' || is_writable_or_mutated)
									) {
										dependencies.add(name);
									}
								}
								this.skip();
							}
						},

						/** @param {import('estree').Node} node */
						leave(node) {
							if (map.has(node)) {
								scope = scope.parent;
							}
						}
					});
					if (module_dependencies.size > 0 && dependencies.size === 0) {
						component.warn(
							/** @type {any} */ (node.body),
							compiler_warnings.module_script_variable_reactive_declaration(
								Array.from(module_dependencies)
							)
						);
					}
					const { expression } = /** @type {import('estree').ExpressionStatement} */ (node.body);
					const declaration =
						expression && /** @type {import('estree').AssignmentExpression} */ (expression).left;
					unsorted_reactive_declarations.push({
						assignees,
						dependencies,
						node,
						declaration
					});
				}
				if (ignores.length) this.pop_ignores();
			}
		);
		const lookup = new Map();
		unsorted_reactive_declarations.forEach(
			/** @param {any} declaration */ (declaration) => {
				declaration.assignees.forEach(
					/** @param {any} name */ (name) => {
						if (!lookup.has(name)) {
							lookup.set(name, []);
						}
						// TODO warn or error if a name is assigned to in
						// multiple reactive declarations?
						lookup.get(name).push(declaration);
					}
				);
			}
		);
		const cycle = check_graph_for_cycles(
			unsorted_reactive_declarations.reduce(
				/**
				 * @param {any} acc
				 * @param {any} declaration
				 */ (acc, declaration) => {
					declaration.assignees.forEach(
						/** @param {any} v */ (v) => {
							declaration.dependencies.forEach(
								/** @param {any} w */ (w) => {
									if (!declaration.assignees.has(w)) {
										acc.push([v, w]);
									}
								}
							);
						}
					);
					return acc;
				},
				[]
			)
		);
		if (cycle && cycle.length) {
			const declarationList = lookup.get(cycle[0]);
			const declaration = declarationList[0];
			return this.error(declaration.node, compiler_errors.cyclical_reactive_declaration(cycle));
		}

		/** @param {any} declaration */
		const add_declaration = (declaration) => {
			if (this.reactive_declarations.includes(declaration)) return;
			declaration.dependencies.forEach(
				/** @param {any} name */ (name) => {
					if (declaration.assignees.has(name)) return;
					const earlier_declarations = lookup.get(name);
					if (earlier_declarations) {
						earlier_declarations.forEach(add_declaration);
					}
				}
			);
			this.reactive_declarations.push(declaration);
		};
		unsorted_reactive_declarations.forEach(add_declaration);
	}
	check_if_tags_content_dynamic() {
		this.tags.forEach((tag) => {
			tag.check_if_content_dynamic();
		});
	}

	/**
	 * @param {string} name
	 * @param {any} node
	 * @param {import('./nodes/shared/TemplateScope.js').default} template_scope
	 * @param {import("./nodes/shared/Node.js").default} [owner]
	 */
	warn_if_undefined(name, node, template_scope, owner) {
		if (name[0] === '$') {
			if (name === '$' || (name[1] === '$' && !is_reserved_keyword(name))) {
				return this.error(node, compiler_errors.illegal_global(name));
			}
			this.has_reactive_assignments = true; // TODO does this belong here?
			if (is_reserved_keyword(name)) return;
			name = name.slice(1);
		}
		if (this.var_lookup.has(name) && !this.var_lookup.get(name).global) return;
		if (template_scope && template_scope.names.has(name)) return;
		if (globals.has(name) && node.type !== 'InlineComponent') return;

		function has_out_of_scope_let() {
			for (let parent = owner.parent; parent; parent = parent.parent) {
				if (parent.type === 'InlineComponent') {
					const { let_attributes } = parent;

					for (const attr of let_attributes) {
						if (
							// @ts-expect-error
							// TODO extract_names only considers patterns but let attributes return expressions
							(attr.expression && extract_names(attr.expression).includes(name)) ||
							attr.name === name
						)
							return true;
					}
				}
			}

			return false;
		}

		if (owner && has_out_of_scope_let()) {
			return this.warn(node, {
				code: 'missing-declaration',
				message: `let:${name} declared on parent component cannot be used inside named slot`
			});
		}

		this.warn(node, compiler_warnings.missing_declaration(name, !!this.ast.instance));
	}

	/** @param {any} ignores */
	push_ignores(ignores) {
		this.ignores = new Set(this.ignores || []);
		add_to_set(this.ignores, ignores);
		this.ignore_stack.push(this.ignores);
	}
	pop_ignores() {
		this.ignore_stack.pop();
		this.ignores = this.ignore_stack[this.ignore_stack.length - 1];
	}
}
const regex_valid_tag_name = /^[a-zA-Z][a-zA-Z0-9]*-[a-zA-Z0-9-]+$/;

/**
 * @param {Component} component
 * @param {any} nodes
 */
function process_component_options(component, nodes) {
	/** @type {ComponentOptions} */
	const component_options = {
		immutable: component.compile_options.immutable || false,
		accessors:
			'accessors' in component.compile_options
				? component.compile_options.accessors
				: !!component.compile_options.customElement,
		preserveWhitespace: !!component.compile_options.preserveWhitespace,
		namespace: component.compile_options.namespace
	};
	const node = nodes.find(/** @param {any} node */ (node) => node.name === 'svelte:options');

	/**
	 * @param {any} attribute
	 * @param {any}params_0
	 */
	function get_value(attribute, { code, message }) {
		const { value } = attribute;
		const chunk = value[0];
		if (!chunk) return true;
		if (value.length > 1) {
			return component.error(attribute, { code, message });
		}
		if (chunk.type === 'Text') return chunk.data;
		if (chunk.expression.type !== 'Literal') {
			return component.error(attribute, { code, message });
		}
		return chunk.expression.value;
	}
	if (node) {
		node.attributes.forEach(
			/** @param {any} attribute */ (attribute) => {
				if (attribute.type === 'Attribute') {
					const { name } = attribute;

					/**
					 * @param {import('../interfaces.js').Attribute} attribute
					 * @param {string} tag
					 */
					function parse_tag(attribute, tag) {
						if (typeof tag !== 'string' && tag !== null) {
							return component.error(attribute, compiler_errors.invalid_tag_attribute);
						}
						if (tag && !regex_valid_tag_name.test(tag)) {
							return component.error(attribute, compiler_errors.invalid_tag_property);
						}
						if (tag && !component.compile_options.customElement) {
							component.warn(attribute, compiler_warnings.missing_custom_element_compile_options);
						}
						component_options.customElement =
							component_options.customElement || /** @type {any} */ ({});
						component_options.customElement.tag = tag;
					}
					switch (name) {
						case 'tag': {
							component.warn(attribute, compiler_warnings.tag_option_deprecated);
							parse_tag(attribute, get_value(attribute, compiler_errors.invalid_tag_attribute));
							break;
						}
						case 'customElement': {
							component_options.customElement =
								component_options.customElement || /** @type {any} */ ({});
							const { value } = attribute;
							if (value[0].type === 'MustacheTag' && value[0].expression?.value === null) {
								component_options.customElement.tag = null;
								break;
							} else if (value[0].type === 'Text') {
								parse_tag(attribute, get_value(attribute, compiler_errors.invalid_tag_attribute));
								break;
							} else if (value[0].expression.type !== 'ObjectExpression') {
								return component.error(attribute, compiler_errors.invalid_customElement_attribute);
							}
							const tag = value[0].expression.properties.find(
								/** @param {any} prop */ (prop) => prop.key.name === 'tag'
							);
							if (tag) {
								parse_tag(tag, tag.value?.value);
							} else {
								return component.error(attribute, compiler_errors.invalid_customElement_attribute);
							}
							const props = value[0].expression.properties.find(
								/** @param {any} prop */
								(prop) => prop.key.name === 'props'
							);
							if (props) {
								const error = () =>
									component.error(attribute, compiler_errors.invalid_props_attribute);
								if (props.value?.type !== 'ObjectExpression') {
									return error();
								}
								component_options.customElement.props = {};
								for (const property of /** @type {import('estree').ObjectExpression} */ (
									props.value
								).properties) {
									if (
										property.type !== 'Property' ||
										property.computed ||
										property.key.type !== 'Identifier' ||
										property.value.type !== 'ObjectExpression'
									) {
										return error();
									}
									component_options.customElement.props[property.key.name] = {};
									for (const prop of property.value.properties) {
										if (
											prop.type !== 'Property' ||
											prop.computed ||
											prop.key.type !== 'Identifier' ||
											prop.value.type !== 'Literal'
										) {
											return error();
										}
										if (
											['reflect', 'attribute', 'type'].indexOf(prop.key.name) === -1 ||
											(prop.key.name === 'type' &&
												['String', 'Number', 'Boolean', 'Array', 'Object'].indexOf(
													/** @type {string} */ (prop.value.value)
												) === -1) ||
											(prop.key.name === 'reflect' && typeof prop.value.value !== 'boolean') ||
											(prop.key.name === 'attribute' && typeof prop.value.value !== 'string')
										) {
											return error();
										}
										component_options.customElement.props[property.key.name][prop.key.name] =
											prop.value.value;
									}
								}
							}
							const shadow = value[0].expression.properties.find(
								/** @param {any} prop */
								(prop) => prop.key.name === 'shadow'
							);
							if (shadow) {
								const shadowdom = shadow.value?.value;
								if (shadowdom !== 'open' && shadowdom !== 'none') {
									return component.error(shadow, compiler_errors.invalid_shadow_attribute);
								}
								component_options.customElement.shadow = shadowdom;
							}
							break;
						}
						case 'namespace': {
							const ns = get_value(attribute, compiler_errors.invalid_namespace_attribute);
							if (typeof ns !== 'string') {
								return component.error(attribute, compiler_errors.invalid_namespace_attribute);
							}
							if (valid_namespaces.indexOf(ns) === -1) {
								const match = fuzzymatch(ns, valid_namespaces);
								return component.error(
									attribute,
									compiler_errors.invalid_namespace_property(ns, match)
								);
							}
							component_options.namespace = ns;
							break;
						}
						case 'accessors':
						case 'immutable':
						case 'preserveWhitespace': {
							const value = get_value(attribute, compiler_errors.invalid_attribute_value(name));
							if (typeof value !== 'boolean') {
								return component.error(attribute, compiler_errors.invalid_attribute_value(name));
							}
							component_options[name] = value;
							break;
						}
						default:
							return component.error(
								attribute,
								compiler_errors.invalid_options_attribute_unknown(name)
							);
					}
				} else {
					return component.error(attribute, compiler_errors.invalid_options_attribute);
				}
			}
		);
	}
	return component_options;
}

/**
 * @param {string} from
 * @param {string} to
 */
function get_relative_path(from, to) {
	const from_parts = from.split(/[/\\]/);
	const to_parts = to.split(/[/\\]/);
	from_parts.pop(); // get dirname
	while (from_parts[0] === to_parts[0]) {
		from_parts.shift();
		to_parts.shift();
	}
	if (from_parts.length) {
		let i = from_parts.length;
		while (i--) from_parts[i] = '..';
	}
	return from_parts.concat(to_parts).join('/');
}

/** @param {string} filename */
function get_basename(filename) {
	return filename.split(/[/\\]/).pop();
}

/** @param {import('../interfaces.js').CompileOptions} compile_options */
function get_sourcemap_source_filename(compile_options) {
	if (!compile_options.filename) return null;
	return compile_options.outputFilename
		? get_relative_path(compile_options.outputFilename, compile_options.filename)
		: get_basename(compile_options.filename);
}

/** @typedef {Object} ComponentOptions
 * @property {string} [namespace]
 * @property {boolean} [immutable]
 * @property {boolean} [accessors]
 * @property {boolean} [preserveWhitespace]
 * @property {Object} [customElement]
 * @property {string|null} customElement.tag
 * @property {'open'|'none'} [customElement.shadow]
 * @property {Record<string,{attribute?:string;reflect?:boolean;type?:'String'|'Boolean'|'Number'|'Array'|'Object';}>} [customElement.props]
 */

const regex_percentage_characters = /%/g;
const regex_file_ending = /\.[^.]+$/;
const regex_repeated_invalid_variable_identifier_characters = /[^a-zA-Z_$0-9]+/g;
const regex_starts_with_digit = /^(\d)/;
const regex_may_starts_or_ends_with_underscore = /^_?(.+?)_?$/;

/**
 * @param {string} filename
 */
function get_name_from_filename(filename) {
	if (!filename) return null;

	const parts = filename.split(/[/\\]/).map(encodeURI);

	if (parts.length > 1) {
		const index_match = parts[parts.length - 1].match(/^index(\.\w+)/);
		if (index_match) {
			parts.pop();
			parts[parts.length - 1] += index_match[1];
		}
	}

	const base = parts
		.pop()
		.replace(regex_percentage_characters, 'u')
		.replace(regex_file_ending, '')
		.replace(regex_repeated_invalid_variable_identifier_characters, '_')
		.replace(regex_may_starts_or_ends_with_underscore, '$1')
		.replace(regex_starts_with_digit, '_$1');

	if (!base) {
		throw new Error(`Could not derive component name from file ${filename}`);
	}

	return base[0].toUpperCase() + base.slice(1);
}

const valid_options = [
	'name',
	'filename',
	'sourcemap',
	'enableSourcemap',
	'generate',
	'errorMode',
	'varsReport',
	'outputFilename',
	'cssOutputFilename',
	'sveltePath',
	'dev',
	'accessors',
	'immutable',
	'hydratable',
	'legacy',
	'customElement',
	'namespace',
	'tag',
	'css',
	'loopGuardTimeout',
	'preserveComments',
	'preserveWhitespace',
	'cssHash',
	'discloseVersion'
];
const valid_css_values = [true, false, 'injected', 'external', 'none'];
const regex_valid_identifier = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/;
const regex_starts_with_lowercase_character = /^[a-z]/;

let warned_of_format = false;
let warned_boolean_css = false;

/**
 * @param {import('../interfaces.js').CompileOptions} options
 * @param {import('../interfaces.js').Warning[]} warnings
 */
function validate_options(options, warnings) {
	if (/** @type {any} */ (options).format) {
		if (!warned_of_format) {
			warned_of_format = true;
			console.warn(
				'The format option has been removed in Svelte 4, the compiler only outputs ESM now. Remove "format" from your compiler options. ' +
					'If you did not set this yourself, bump the version of your bundler plugin (vite-plugin-svelte/rollup-plugin-svelte/svelte-loader)'
			);
		}
		delete (/** @type {any} */ (options).format);
	}

	const { name, filename, loopGuardTimeout, dev, namespace, css } = options;
	Object.keys(options).forEach(
		/** @param {any} key */ (key) => {
			if (!valid_options.includes(key)) {
				const match = fuzzymatch(key, valid_options);
				let message = `Unrecognized option '${key}'`;
				if (match) message += ` (did you mean '${match}'?)`;
				throw new Error(message);
			}
		}
	);
	if (name && !regex_valid_identifier.test(name)) {
		throw new Error(`options.name must be a valid identifier (got '${name}')`);
	}
	if (name && regex_starts_with_lowercase_character.test(name)) {
		const message = 'options.name should be capitalised';
		warnings.push({
			code: 'options-lowercase-name',
			message,
			filename,
			toString: () => message
		});
	}
	if (loopGuardTimeout && !dev) {
		const message = 'options.loopGuardTimeout is for options.dev = true only';
		warnings.push({
			code: 'options-loop-guard-timeout',
			message,
			filename,
			toString: () => message
		});
	}

	if (css === true || css === false) {
		options.css = css === true ? 'injected' : 'external';
		if (!warned_boolean_css) {
			console.warn(
				`compilerOptions.css as a boolean is deprecated. Use '${options.css}' instead of ${css}.`
			);
			warned_boolean_css = true;
		}
	}

	if (!valid_css_values.includes(options.css)) {
		throw new Error(
			`compilerOptions.css must be 'injected', 'external' or 'none' (got '${options.css}').`
		);
	}

	if (namespace && valid_namespaces.indexOf(namespace) === -1) {
		const match = fuzzymatch(namespace, valid_namespaces);
		if (match) {
			throw new Error(`Invalid namespace '${namespace}' (did you mean '${match}'?)`);
		} else {
			throw new Error(`Invalid namespace '${namespace}'`);
		}
	}

	if (options.discloseVersion == undefined) {
		options.discloseVersion = true;
	}
}

/**
 * `compile` takes your component source code, and turns it into a JavaScript module that exports a class.
 *
 * https://svelte.dev/docs/svelte-compiler#svelte-compile
 * @param {string} source
 * @param {import('../interfaces.js').CompileOptions} options
 */
function compile(source, options = {}) {
	options = Object.assign(
		{ generate: 'dom', dev: false, enableSourcemap: true, css: 'injected' },
		options
	);
	const stats = new Stats();
	const warnings = [];
	validate_options(options, warnings);
	stats.start('parse');
	const ast = parse(source, options);
	stats.stop('parse');
	stats.start('create component');
	const component = new Component(
		ast,
		source,
		options.name || get_name_from_filename(options.filename) || 'Component',
		options,
		stats,
		warnings
	);
	stats.stop('create component');
	const result =
		options.generate === false
			? null
			: options.generate === 'ssr'
			? ssr(component, options)
			: dom(component, options);
	return component.generate(result);
}

/**
 * Import decoded sourcemap from mozilla/source-map/SourceMapGenerator
 * Forked from source-map/lib/source-map-generator.js
 * from methods _serializeMappings and toJSON.
 * We cannot use source-map.d.ts types, because we access hidden properties.
 * @param {any} generator
 */
function decoded_sourcemap_from_generator(generator) {
	let previous_generated_line = 1;
	const converted_mappings = [[]];
	let result_line;
	let result_segment;
	let mapping;
	const source_idx = generator._sources
		.toArray()
		.reduce((acc, val, idx) => ((acc[val] = idx), acc), {});
	const name_idx = generator._names
		.toArray()
		.reduce((acc, val, idx) => ((acc[val] = idx), acc), {});
	const mappings = generator._mappings.toArray();
	result_line = converted_mappings[0];
	for (let i = 0, len = mappings.length; i < len; i++) {
		mapping = mappings[i];
		if (mapping.generatedLine > previous_generated_line) {
			while (mapping.generatedLine > previous_generated_line) {
				converted_mappings.push([]);
				previous_generated_line++;
			}
			result_line = converted_mappings[mapping.generatedLine - 1]; // line is one-based
		} else if (i > 0) {
			const previous_mapping = mappings[i - 1];
			if (
				// sorted by selectivity
				mapping.generatedColumn === previous_mapping.generatedColumn &&
				mapping.originalColumn === previous_mapping.originalColumn &&
				mapping.name === previous_mapping.name &&
				mapping.generatedLine === previous_mapping.generatedLine &&
				mapping.originalLine === previous_mapping.originalLine &&
				mapping.source === previous_mapping.source
			) {
				continue;
			}
		}
		result_line.push([mapping.generatedColumn]);
		result_segment = result_line[result_line.length - 1];
		if (mapping.source != null) {
			result_segment.push(
				...[source_idx[mapping.source], mapping.originalLine - 1, mapping.originalColumn]
			);
			if (mapping.name != null) {
				result_segment.push(name_idx[mapping.name]);
			}
		}
	}
	const map = {
		version: generator._version,
		sources: generator._sources.toArray(),
		names: generator._names.toArray(),
		mappings: converted_mappings
	};
	if (generator._file != null) {
		map.file = generator._file;
	}
	// not needed: map.sourcesContent and map.sourceRoot
	return map;
}

/**
 * @param {import('./public.js').Processed} processed
 */
function decode_map(processed) {
	let decoded_map = typeof processed.map === 'string' ? JSON.parse(processed.map) : processed.map;
	if (typeof decoded_map.mappings === 'string') {
		decoded_map.mappings = decode$1(decoded_map.mappings);
	}
	if (decoded_map._mappings && decoded_map.constructor.name === 'SourceMapGenerator') {
		// import decoded sourcemap from mozilla/source-map/SourceMapGenerator
		decoded_map = decoded_sourcemap_from_generator(decoded_map);
	}
	return decoded_map;
}

/**
 * @param {string} code_slice
 * @param {number} offset
 * @param {import('./private.js').Source} opts
 * @returns {import('./private.js').Source}
 */
function slice_source(code_slice, offset, { file_basename, filename, get_location }) {
	return {
		source: code_slice,
		get_location: (index) => get_location(index + offset),
		file_basename,
		filename
	};
}

/**
 * @param {RegExp} re
 * @param {(...match: any[]) => Promise<MappedCode>} get_replacement
 * @param {string} source
 */
function calculate_replacements(re, get_replacement, source) {
	/**
	 * @type {Array<Promise<import('./private.js').Replacement>>}
	 */
	const replacements = [];
	source.replace(re, (...match) => {
		replacements.push(
			get_replacement(...match).then((replacement) => {
				const matched_string = match[0];
				const offset = match[match.length - 2];
				return { offset, length: matched_string.length, replacement };
			})
		);
		return '';
	});
	return Promise.all(replacements);
}

/**
 * @param {import('./private.js').Replacement[]} replacements
 * @param {import('./private.js').Source} source
 * @returns {MappedCode}
 */
function perform_replacements(replacements, source) {
	const out = new MappedCode();
	let last_end = 0;
	for (const { offset, length, replacement } of replacements) {
		const unchanged_prefix = MappedCode.from_source(
			slice_source(source.source.slice(last_end, offset), last_end, source)
		);
		out.concat(unchanged_prefix).concat(replacement);
		last_end = offset + length;
	}
	const unchanged_suffix = MappedCode.from_source(
		slice_source(source.source.slice(last_end), last_end, source)
	);
	return out.concat(unchanged_suffix);
}

/**
 * @param {RegExp} regex
 * @param {(...match: any[]) => Promise<MappedCode>} get_replacement
 * @param {import('./private.js').Source} location
 * @returns {Promise<MappedCode>}
 */
async function replace_in_code(regex, get_replacement, location) {
	const replacements = await calculate_replacements(regex, get_replacement, location.source);
	return perform_replacements(replacements, location);
}

const regex_filepath_separator = /[/\\]/;

/**
 * @param {string} filename
 */
function get_file_basename(filename) {
	return filename.split(regex_filepath_separator).pop();
}

/**
 * Represents intermediate states of the preprocessing.
 */
class PreprocessResult {
	/** @type {string} */
	source;
	/** @type {string | undefined} */
	filename;

	// sourcemap_list is sorted in reverse order from last map (index 0) to first map (index -1)
	// so we use sourcemap_list.unshift() to add new maps
	// https://github.com/ampproject/remapping#multiple-transformations-of-a-file

	/**
	 * @default []
	 * @type {Array<import('@ampproject/remapping').DecodedSourceMap | import('@ampproject/remapping').RawSourceMap>}
	 */
	sourcemap_list = [];

	/**
	 * @default []
	 * @type {string[]}
	 */
	dependencies = [];

	/**
	 * @type {string}
	 */
	file_basename = undefined;

	/**
	 * @type {ReturnType<typeof getLocator>}
	 */
	get_location = undefined;

	/**
	 *
	 * @param {string} source
	 * @param {string} [filename]
	 */
	constructor(source, filename) {
		this.source = source;
		this.filename = filename;
		this.update_source({ string: source });
		// preprocess source must be relative to itself or equal null
		this.file_basename = filename == null ? null : get_file_basename(filename);
	}

	/**
	 * @param {import('./private.js').SourceUpdate} opts
	 */
	update_source({ string: source, map, dependencies }) {
		if (source != null) {
			this.source = source;
			this.get_location = getLocator$1(source);
		}
		if (map) {
			this.sourcemap_list.unshift(map);
		}
		if (dependencies) {
			this.dependencies.push(...dependencies);
		}
	}

	/**
	 * @returns {import('./public.js').Processed}
	 */
	to_processed() {
		// Combine all the source maps for each preprocessor function into one
		const map = combine_sourcemaps(this.file_basename, this.sourcemap_list);
		return {
			// TODO return separated output, in future version where svelte.compile supports it:
			// style: { code: styleCode, map: styleMap },
			// script { code: scriptCode, map: scriptMap },
			// markup { code: markupCode, map: markupMap },
			code: this.source,
			dependencies: [...new Set(this.dependencies)],
			map,
			toString: () => this.source
		};
	}
}
/**
 * Convert preprocessor output for the tag content into MappedCode
 * @param {import('./public.js').Processed} processed
 * @param {{ line: number; column: number; }} location
 * @param {string} file_basename
 * @returns {MappedCode}
 */
function processed_content_to_code(processed, location, file_basename) {
	// Convert the preprocessed code and its sourcemap to a MappedCode

	/**
	 * @type {import('@ampproject/remapping').DecodedSourceMap}
	 */
	let decoded_map;
	if (processed.map) {
		decoded_map = decode_map(processed);
		// decoded map may not have sources for empty maps like `{ mappings: '' }`
		if (decoded_map.sources) {
			// offset only segments pointing at original component source
			const source_index = decoded_map.sources.indexOf(file_basename);
			if (source_index !== -1) {
				sourcemap_add_offset(decoded_map, location, source_index);
			}
		}
	}
	return MappedCode.from_processed(processed.code, decoded_map);
}
/**
 * Given the whole tag including content, return a `MappedCode`
 * representing the tag content replaced with `processed`.
 * @param {import('./public.js').Processed} processed
 * @param {'style' | 'script'} tag_name
 * @param {string} original_attributes
 * @param {string} generated_attributes
 * @param {import('./private.js').Source} source
 * @returns {MappedCode}
 */
function processed_tag_to_code(
	processed,
	tag_name,
	original_attributes,
	generated_attributes,
	source
) {
	const { file_basename, get_location } = source;

	/**
	 * @param {string} code
	 * @param {number} offset
	 */
	const build_mapped_code = (code, offset) =>
		MappedCode.from_source(slice_source(code, offset, source));

	// To map the open/close tag and content starts positions correctly, we need to
	// differentiate between the original attributes and the generated attributes:
	// `source` contains the original attributes and its get_location maps accordingly.
	const original_tag_open = `<${tag_name}${original_attributes}>`;
	const tag_open = `<${tag_name}${generated_attributes}>`;
	/** @type {MappedCode} */
	let tag_open_code;

	if (original_tag_open.length !== tag_open.length) {
		// Generate a source map for the open tag
		/** @type {import('@ampproject/remapping').DecodedSourceMap['mappings']} */
		const mappings = [
			[
				// start of tag
				[0, 0, 0, 0],
				// end of tag start
				[`<${tag_name}`.length, 0, 0, `<${tag_name}`.length]
			]
		];

		const line = tag_open.split('\n').length - 1;
		const column = tag_open.length - (line === 0 ? 0 : tag_open.lastIndexOf('\n')) - 1;

		while (mappings.length <= line) {
			// end of tag start again, if this is a multi line mapping
			mappings.push([[0, 0, 0, `<${tag_name}`.length]]);
		}

		// end of tag
		mappings[line].push([
			column,
			0,
			original_tag_open.split('\n').length - 1,
			original_tag_open.length - original_tag_open.lastIndexOf('\n') - 1
		]);

		/** @type {import('@ampproject/remapping').DecodedSourceMap} */
		const map = {
			version: 3,
			names: [],
			sources: [file_basename],
			mappings
		};
		sourcemap_add_offset(map, get_location(0), 0);
		tag_open_code = MappedCode.from_processed(tag_open, map);
	} else {
		tag_open_code = build_mapped_code(tag_open, 0);
	}

	const tag_close = `</${tag_name}>`;
	const tag_close_code = build_mapped_code(
		tag_close,
		original_tag_open.length + source.source.length
	);

	parse_attached_sourcemap(processed, tag_name);
	const content_code = processed_content_to_code(
		processed,
		get_location(original_tag_open.length),
		file_basename
	);

	return tag_open_code.concat(content_code).concat(tag_close_code);
}

const attribute_pattern = /([\w-$]+\b)(?:=(?:"([^"]*)"|'([^']*)'|(\S+)))?/g;

/**
 * @param {string} str
 */
function parse_tag_attributes(str) {
	/** @type {Record<string, string | boolean>} */
	const attrs = {};

	/** @type {RegExpMatchArray} */
	let match;
	while ((match = attribute_pattern.exec(str)) !== null) {
		const name = match[1];
		const value = match[2] || match[3] || match[4];
		attrs[name] = !value || value;
	}

	return attrs;
}

/**
 * @param {Record<string, string | boolean> | undefined} attributes
 */
function stringify_tag_attributes(attributes) {
	if (!attributes) return;

	let value = Object.entries(attributes)
		.map(([key, value]) => (value === true ? key : `${key}="${value}"`))
		.join(' ');
	if (value) {
		value = ' ' + value;
	}
	return value;
}

const regex_style_tags = /<!--[^]*?-->|<style(\s[^]*?)?(?:>([^]*?)<\/style>|\/>)/gi;
const regex_script_tags = /<!--[^]*?-->|<script(\s[^]*?)?(?:>([^]*?)<\/script>|\/>)/gi;

/**
 * Calculate the updates required to process all instances of the specified tag.
 * @param {'style' | 'script'} tag_name
 * @param {import('./public.js').Preprocessor} preprocessor
 * @param {import('./private.js').Source} source
 * @returns {Promise<import('./private.js').SourceUpdate>}
 */
async function process_tag(tag_name, preprocessor, source) {
	const { filename, source: markup } = source;
	const tag_regex = tag_name === 'style' ? regex_style_tags : regex_script_tags;

	/**
	 * @type {string[]}
	 */
	const dependencies = [];

	/**
	 * @param {string} tag_with_content
	 * @param {number} tag_offset
	 * @returns {Promise<MappedCode>}
	 */
	async function process_single_tag(tag_with_content, attributes = '', content = '', tag_offset) {
		const no_change = () =>
			MappedCode.from_source(slice_source(tag_with_content, tag_offset, source));
		if (!attributes && !content) return no_change();
		const processed = await preprocessor({
			content: content || '',
			attributes: parse_tag_attributes(attributes || ''),
			markup,
			filename
		});
		if (!processed) return no_change();
		if (processed.dependencies) dependencies.push(...processed.dependencies);
		if (!processed.map && processed.code === content) return no_change();
		return processed_tag_to_code(
			processed,
			tag_name,
			attributes,
			stringify_tag_attributes(processed.attributes) ?? attributes,
			slice_source(content, tag_offset, source)
		);
	}
	const { string, map } = await replace_in_code(tag_regex, process_single_tag, source);
	return { string, map, dependencies };
}

/**
 * @param {import('./public.js').MarkupPreprocessor} process
 * @param {import('./private.js').Source} source
 */
async function process_markup(process, source) {
	const processed = await process({
		content: source.source,
		filename: source.filename
	});
	if (processed) {
		return {
			string: processed.code,
			map: processed.map
				? // TODO: can we use decode_sourcemap?
				  typeof processed.map === 'string'
					? JSON.parse(processed.map)
					: processed.map
				: undefined,
			dependencies: processed.dependencies
		};
	} else {
		return {};
	}
}

/**
 * The preprocess function provides convenient hooks for arbitrarily transforming component source code.
 * For example, it can be used to convert a <style lang="sass"> block into vanilla CSS.
 *
 * https://svelte.dev/docs/svelte-compiler#svelte-preprocess
 * @param {string} source
 * @param {import('./public.js').PreprocessorGroup | import('./public.js').PreprocessorGroup[]} preprocessor
 * @param {{ filename?: string }} [options]
 * @returns {Promise<import('./public.js').Processed>}
 */
async function preprocess(source, preprocessor, options) {
	/**
	 * @type {string | undefined}
	 */
	const filename = (options && options.filename) || /** @type {any} */ (preprocessor).filename; // legacy
	const preprocessors = preprocessor
		? Array.isArray(preprocessor)
			? preprocessor
			: [preprocessor]
		: [];
	const result = new PreprocessResult(source, filename);

	// TODO keep track: what preprocessor generated what sourcemap?
	// to make debugging easier = detect low-resolution sourcemaps in fn combine_mappings
	for (const preprocessor of preprocessors) {
		if (preprocessor.markup) {
			result.update_source(await process_markup(preprocessor.markup, result));
		}
		if (preprocessor.script) {
			result.update_source(await process_tag('script', preprocessor.script, result));
		}
		if (preprocessor.style) {
			result.update_source(await process_tag('style', preprocessor.style, result));
		}
	}

	return result.to_processed();
}

exports.VERSION = VERSION;
exports.compile = compile;
exports.parse = parse;
exports.preprocess = preprocess;
exports.walk = walk;

}));
