frontend/.pnpm-store/v3/files/af/d72da5b6b2a3a33946ad6a6e3bfc3578151d18e0f8bf189c35078182506876a3b84bd8484e27e300c02ca9ddc91de7a86a8aaee3949bd7f218c59fb2e723da

47748 lines
1.5 MiB
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.svelte = {}));
}(this, (function (exports) { 'use strict';
const now = (typeof process !== 'undefined' && process.hrtime)
? () => {
const t = process.hrtime();
return t[0] * 1e3 + t[1] / 1e6;
}
: () => self.performance.now();
function collapse_timings(timings) {
const result = {};
timings.forEach(timing => {
result[timing.label] = Object.assign({
total: timing.end - timing.start
}, timing.children && collapse_timings(timing.children));
});
return result;
}
class Stats {
constructor() {
this.start_time = now();
this.stack = [];
this.current_children = this.timings = [];
}
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;
}
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
// 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 = ref.toString;
var hasOwn = Object.hasOwn || (function (obj, propName) { return (
hasOwnProperty$1.call(obj, propName)
); });
var isArray = Array.isArray || (function (obj) { return (
toString.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 = 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.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.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.parse = function parse (input, options) {
return new this(options, input).parse()
};
Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
var parser = new this(options, input, pos);
parser.nextToken();
return parser.parseExpression()
};
Parser.tokenizer = function tokenizer (input, options) {
return new this(options, input)
};
Object.defineProperties( Parser.prototype, prototypeAccessors );
var pp$9 = Parser.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.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.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.parseBindingAtom();
var simple = clause.param.type === "Identifier";
this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
this.expect(types$1.parenR);
} 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) {
this.next();
this.parseVar(node, false, kind);
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) {
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 (kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
this.unexpected();
} else if (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.raise(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.parseExport = function(node, exports) {
this.next();
// export * from '...'
if (this.eat(types$1.star)) {
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")
}
if (this.eat(types$1._default)) { // export default ...
this.checkExport(exports, "default", this.lastTokStart);
var isAsync;
if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {
var fNode = this.startNode();
this.next();
if (isAsync) { this.next(); }
node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
} else if (this.type === types$1._class) {
var cNode = this.startNode();
node.declaration = this.parseClass(cNode, "nullableID");
} else {
node.declaration = this.parseMaybeAssign();
this.semicolon();
}
return this.finishNode(node, "ExportDefaultDeclaration")
}
// export var|const|let|function|class ...
if (this.shouldParseExportStatement()) {
node.declaration = this.parseStatement(null);
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.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.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; }
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
);
nodes.push(this.finishNode(node, "ExportSpecifier"));
}
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.parseImportSpecifiers = function() {
var nodes = [], first = true;
if (this.type === types$1.name) {
// import defaultObj, { x, y as z } from '...'
var node = this.startNode();
node.local = this.parseIdent();
this.checkLValSimple(node.local, BIND_LEXICAL);
nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
if (!this.eat(types$1.comma)) { return nodes }
}
if (this.type === types$1.star) {
var node$1 = this.startNode();
this.next();
this.expectContextual("as");
node$1.local = this.parseIdent();
this.checkLValSimple(node$1.local, BIND_LEXICAL);
nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
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; }
var node$2 = this.startNode();
node$2.imported = this.parseModuleExportName();
if (this.eatContextual("as")) {
node$2.local = this.parseIdent();
} else {
this.checkUnreserved(node$2.imported);
node$2.local = node$2.imported;
}
this.checkLValSimple(node$2.local, BIND_LEXICAL);
nodes.push(this.finishNode(node$2, "ImportSpecifier"));
}
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.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) {
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.raise(this.start, "Comma is not permitted after the rest element"); }
this.expect(close);
break
} else {
var elem = this.parseMaybeDefault(this.start, this.startLoc);
this.parseBindingListItem(elem);
elts.push(elem);
}
}
return elts
};
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
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.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
var pp$5 = Parser.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.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.canInsertSemicolon() && this.eat(types$1.arrow)) {
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.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, 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) {
// 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()
} else {
return this.unexpected()
}
default:
this.unexpected();
}
};
pp$5.parseExprImport = function() {
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);
switch (this.type) {
case types$1.parenL:
return this.parseDynamicImport(node)
case types$1.dot:
node.meta = meta;
return this.parseImportMeta(node)
default:
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.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.raise(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.canInsertSemicolon() && 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, isImport = this.type === types$1._import;
node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false);
if (isImport && node.callee.type === "ImportExpression") {
this.raise(startPos, "Cannot use new with import()");
}
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.raise(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.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(); }
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"); }
}
} 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.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();
}
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.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.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.prototype;
var Scope = 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(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 = 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.prototype;
pp$2.startNode = function() {
return new Node(this, this.start, this.startLoc)
};
pp$2.startNodeAt = function(pos, loc) {
return new Node(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(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-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 + " Kawi Nag_Mundari Nagm";
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),
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 = 0, list = [9, 10, 11, 12, 13, 14]; i < list.length; i += 1) {
var ecmaVersion = list[i];
buildUnicodeData(ecmaVersion);
}
var pp$1 = Parser.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" : "");
this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion];
this.source = "";
this.flags = "";
this.start = 0;
this.switchU = 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 unicode = flags.indexOf("u") !== -1;
this.start = start | 0;
this.source = pattern + "";
this.flags = flags;
this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
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
};
/**
* 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;
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");
}
}
};
/**
* 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
};
// 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 true
}
if (
state.switchU &&
this.options.ecmaVersion >= 9 &&
(ch === 0x50 /* P */ || ch === 0x70 /* p */)
) {
state.lastIntValue = -1;
state.advance();
if (
state.eat(0x7B /* { */) &&
this.regexp_eatUnicodePropertyValueExpression(state) &&
state.eat(0x7D /* } */)
) {
return true
}
state.raise("Invalid property name");
}
return false
};
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 true
}
}
state.pos = start;
// LoneUnicodePropertyNameOrValue
if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
var nameOrValue = state.lastStringValue;
this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
return true
}
return false
};
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))
{ 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 /* [ */)) {
state.eat(0x5E /* ^ */);
this.regexp_classRanges(state);
if (state.eat(0x5D /* ] */)) {
return true
}
// Unreachable since it threw "unterminated regular expression" error before.
state.raise("Unterminated character class");
}
return false
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
// 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_classRanges = 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://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 = Parser.prototype;
// Move to the next token
pp.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.getToken = function() {
this.next();
return new Token(this)
};
// If we're in an ES6 environment, make parsers iterable
if (typeof Symbol !== "undefined")
{ pp[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.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.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.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.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.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.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.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.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.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.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.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.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.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.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.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.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.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.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.finishOp = function(type, size) {
var str = this.input.slice(this.pos, this.pos + size);
this.pos += size;
return this.finishToken(type, str)
};
pp.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.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.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.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.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.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.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.invalidStringToken = function(position, message) {
if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
throw INVALID_TEMPLATE_ESCAPE_ERROR
} else {
this.raise(position, message);
}
};
pp.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.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.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.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.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.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.
var version = "8.8.2";
Parser.acorn = {
Parser: Parser,
version: version,
defaultOptions: defaultOptions,
Position: Position,
SourceLocation: SourceLocation,
getLineInfo: getLineInfo,
Node: Node,
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(input, options) {
return Parser.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(input, pos, options) {
return Parser.parseExpressionAt(input, pos, options)
}
function flatten(nodes, target = []) {
for (let i = 0; i < nodes.length; i += 1) {
const node = nodes[i];
if (Array.isArray(node)) {
flatten(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 = /^\s+$/;
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_svelte_ignore = /^\s*svelte-ignore\s+([\s\S]+)\s*$/m;
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) : [];
}
function extract_svelte_ignore_from_comments(node) {
return flatten((node.leadingComments || []).map(comment => extract_svelte_ignore(comment.value)));
}
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 [];
}
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 [];
}
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
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
function levenshtein(str1, str2) {
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, ]+/;
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;
}
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;
}
function sort_descending(a, b) {
return b[0] - a[0];
}
class FuzzySet {
constructor(arr) {
this.exact_set = {};
this.match_dict = {};
this.items = {};
// 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]);
}
}
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);
}
}
_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;
}
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;
}
__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 = /^(?: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)$/;
function is_void(name) {
return void_element_names.test(name) || name.toLowerCase() === '!doctype';
}
function is_html(name) {
return html_element_names.test(name);
}
function is_svg(name) {
return svg.test(name);
}
function list$1(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 = {
css_syntax_error: (message) => ({
code: 'css-syntax-error',
message
}),
duplicate_attribute: {
code: 'duplicate-attribute',
message: 'Attributes need to be unique'
},
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'
},
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'
},
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'
},
invalid_closing_tag_unopened: (name) => ({
code: 'invalid-closing-tag',
message: `</${name}> attempted to close an element that was not open`
}),
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'
},
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'
},
invalid_else_placement_unclosed_block: (block) => ({
code: 'invalid-else-placement',
message: `Expected to close ${block} before seeing {:else} block`
}),
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'
},
invalid_element_placement: (slug, name) => ({
code: `invalid-${slug}-placement`,
message: `<${name}> tags cannot be inside elements or blocks`
}),
invalid_logic_block_placement: (location, name) => ({
code: 'invalid-logic-block-placement',
message: `{#${name}} logic block cannot be ${location}`
}),
invalid_tag_placement: (location, name) => ({
code: 'invalid-tag-placement',
message: `{@${name}} tag cannot be ${location}`
}),
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'
},
invalid_tag_name_svelte_element: (tags, match) => ({
code: 'invalid-tag-name',
message: `Valid <svelte:...> tag names are ${list$1(tags)}${match ? ' (did you mean ' + match + '?)' : ''}`
}),
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'
},
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 -->'
},
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'
},
unexpected_eof_token: (token) => ({
code: 'unexpected-eof',
message: `Unexpected ${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 = 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,
(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$1(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$1(current_scope, false));
} else {
map.set(node, current_scope = new Scope$1(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$1(current_scope, true));
break;
case 'BlockStatement':
map.set(node, current_scope = new Scope$1(current_scope, true));
break;
case 'ClassDeclaration':
case 'VariableDeclaration':
current_scope.add_declaration(node);
break;
case 'CatchClause':
map.set(node, current_scope = new Scope$1(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$1 {
/**
* @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(array, items) {
for (let i = 0; i < items.length; i++) {
array.push(items[i]);
}
}
// heavily based on https://github.com/davidbonnet/astring
/** @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[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 = (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(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(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(chunks, join(declarators, separator));
return chunks;
};
/** @type {Record<string, Handler>} */
const handlers = {
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(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(
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(
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(chunks, handle(node.handler.param, state));
chunks.push(c(') '));
} else {
chunks.push(c(' catch '));
}
push_array(chunks, handle(node.handler.body, state));
}
if (node.finalizer) {
chunks.push(c(' finally '));
push_array(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(chunks, handle_var_declaration(node.init, state));
} else {
push_array(chunks, handle(node.init, state));
}
}
chunks.push(c('; '));
if (node.test) push_array(chunks, handle(node.test, state));
chunks.push(c('; '));
if (node.update) push_array(chunks, handle(node.update, state));
chunks.push(c(') '));
push_array(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(chunks, handle_var_declaration(node.left, state));
} else {
push_array(chunks, handle(node.left, state));
}
chunks.push(c(node.type === 'ForInStatement' ? ` in ` : ` of `));
push_array(chunks, handle(node.right, state));
chunks.push(c(') '));
push_array(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(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(chunks, join(params, separator));
chunks.push(c(`\n${state.indent}`));
} else {
push_array(chunks, join(params, separator));
}
chunks.push(c(') '));
push_array(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(chunks, handle(node.id, state));
chunks.push(c(' '));
}
if (node.superClass) {
chunks.push(c('extends '));
push_array(chunks, handle(node.superClass, state));
chunks.push(c(' '));
}
push_array(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(chunks, join(specifiers, c(',\n\t')));
chunks.push(c('\n}'));
} else {
chunks.push(c(`{ `));
push_array(chunks, join(specifiers, c(', ')));
chunks.push(c(' }'));
}
}
chunks.push(c(' from '));
}
push_array(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(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(chunks, join(specifiers, c(',\n\t')));
chunks.push(c('\n}'));
} else {
chunks.push(c('{ '));
push_array(chunks, join(specifiers, c(', ')));
chunks.push(c(' }'));
}
if (node.source) {
chunks.push(c(' from '));
push_array(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(chunks, handle(node.key, state));
chunks.push(c(']'));
} else {
push_array(chunks, handle(node.key, state));
}
chunks.push(c('('));
const { params } = node.value;
for (let i = 0; i < params.length; i += 1) {
push_array(chunks, handle(params[i], state));
if (i < params.length - 1) chunks.push(c(', '));
}
chunks.push(c(') '));
push_array(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(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(chunks, join(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(chunks, handle(node.body, state));
chunks.push(c(')'));
} else {
push_array(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(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(chunks, join(elements, c(`,\n${state.indent}\t`)));
chunks.push(c(`\n${state.indent}`));
push_array(chunks, sparse_commas);
} else {
push_array(chunks, join(elements, c(', ')));
push_array(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(
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(chunks, node.computed ? [c('['), ...key, c(']')] : key);
chunks.push(c('('));
push_array(
chunks,
join(
node.value.params.map((/** @type {Pattern} */ param) =>
handle(param, state)
),
c(', ')
)
);
chunks.push(c(') '));
push_array(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(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(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(chunks, handle(node.argument, state));
chunks.push(c(')'));
} else {
push_array(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(chunks, handle(node.left, state));
chunks.push(c(')'));
} else {
push_array(chunks, handle(node.left, state));
}
chunks.push(c(` ${node.operator} `));
if (needs_parens(node.right, node, true)) {
chunks.push(c('('));
push_array(chunks, handle(node.right, state));
chunks.push(c(')'));
} else {
push_array(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(chunks, handle(node.test, state));
} else {
chunks.push(c('('));
push_array(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(chunks, consequent);
chunks.push(c(`\n${state.indent}: `));
push_array(chunks, alternate);
} else {
chunks.push(c(` ? `));
push_array(chunks, consequent);
chunks.push(c(` : `));
push_array(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(chunks, handle(node.callee, state));
chunks.push(c(')'));
} else {
push_array(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(chunks, join(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(chunks, handle(node.callee, state));
chunks.push(c(')'));
} else {
push_array(chunks, handle(node.callee, state));
}
if (/** @type {SimpleCallExpression} */ (node).optional) {
chunks.push(c('?.'));
}
const args = node.arguments.map((arg) => handle(arg, state));
const multiple_lines = args.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) =>
handle(arg, {
...state,
indent: `${state.indent}\t`
})
);
chunks.push(c(`(\n${state.indent}\t`));
push_array(chunks, join(args, c(`,\n${state.indent}\t`)));
chunks.push(c(`\n${state.indent})`));
} else {
chunks.push(c('('));
push_array(chunks, join(args, 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(chunks, handle(node.object, state));
chunks.push(c(')'));
} else {
push_array(chunks, handle(node.object, state));
}
if (node.computed) {
if (node.optional) {
chunks.push(c('?.'));
}
chunks.push(c('['));
push_array(chunks, handle(node.property, state));
chunks.push(c(']'));
} else {
chunks.push(c(node.optional ? '?.' : '.'));
push_array(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,
(_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(chunks, handlers.BlockStatement(node, state));
return chunks;
},
PrivateIdentifier(/** @type {PrivateIdenifier} */ node, state) {
const chunks = [c('#')];
push_array(chunks, [c(node.name, node)]);
return chunks;
}
};
handlers.ForOfStatement = handlers.ForInStatement;
handlers.FunctionExpression = handlers.FunctionDeclaration;
handlers.ClassExpression = handlers.ClassDeclaration;
handlers.ClassBody = handlers.BlockStatement;
handlers.SpreadElement = handlers.RestElement;
handlers.ArrayPattern = handlers.ArrayExpression;
handlers.LogicalExpression = handlers.BinaryExpression;
handlers.AssignmentPattern = handlers.AssignmentExpression;
const comma = ','.charCodeAt(0);
const semicolon = ';'.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;
}
// 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(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);
}
function sortComparator(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;
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[clamped];
} while (num > 0);
return pos;
}
/** @type {(str?: string) => string} str */
let btoa$1 = () => {
throw new Error(
'Unsupported environment: `window.btoa` or `Buffer` should be supported.'
);
};
if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
btoa$1 = (str) => window.btoa(unescape(encodeURIComponent(str)));
} else if (typeof Buffer === 'function') {
btoa$1 = (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$1(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$1 = (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$1 = (nodes, target) => {
for (let i = 0; i < nodes.length; i += 1) {
const node = nodes[i];
if (node === EMPTY) continue;
if (Array.isArray(node)) {
flatten$1(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, (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.lastIndex = 0;
const match = re.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.lastIndex = 0;
const new_value = /** @type {string} */ (node.value).replace(
re,
(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.lastIndex = 0;
node.value.raw = /** @type {string} */ (node.value.raw).replace(
re,
(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$1(node.elements, []);
}
if (
node.type === 'FunctionExpression' ||
node.type === 'FunctionDeclaration' ||
node.type === 'ArrowFunctionExpression'
) {
node.params = flatten$1(node.params, []);
}
if (node.type === 'CallExpression' || node.type === 'NewExpression') {
node.arguments = flatten$1(node.arguments, []);
}
if (
node.type === 'ImportDeclaration' ||
node.type === 'ExportNamedDeclaration'
) {
node.specifiers = flatten$1(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(strings, ...values) {
const str = join$1(strings);
/** @type {CommentWithLocation[]} */
const comments = [];
try {
let ast = /** @type {any} */ (parse(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(strings, ...values) {
const str = join$1(strings);
/** @type {CommentWithLocation[]} */
const comments = [];
try {
let expression =
/** @type {Expression & { start: Number, end: number }} */ (
parseExpressionAt(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$1(strings)}}`;
/** @type {CommentWithLocation[]} */
const comments = [];
try {
let expression = /** @type {any} */ (
parseExpressionAt(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.lastIndex = 0;
str = str.replace(re, (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$1 = (source, opts) => {
/** @type {CommentWithLocation[]} */
const comments = [];
const { onComment, enter, leave } = get_comment_handlers(comments, source);
const ast = /** @type {any} */ (parse(source, { onComment, ...opts }));
walk(ast, { enter, leave });
return ast;
};
/**
* @param {string} source
* @param {number} index
* @param {any} opts
*/
const parseExpressionAt$1 = (source, index, opts) => {
/** @type {CommentWithLocation[]} */
const comments = [];
const { onComment, enter, leave } = get_comment_handlers(comments, source);
const ast = /** @type {any} */ (
parseExpressionAt(source, index, { onComment, ...opts })
);
walk(ast, { enter, leave });
return ast;
};
const parse$2 = (source) => parse$1(source, {
sourceType: 'module',
ecmaVersion: 12,
locations: true
});
const parse_expression_at = (source, index) => parseExpressionAt$1(source, index, {
sourceType: 'module',
ecmaVersion: 12,
locations: true
});
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*>/;
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;
}
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);
let ast;
try {
ast = parse$2(source);
}
catch (err) {
parser.acorn_error(err);
}
// TODO is this necessary?
ast.start = script_start;
return {
type: 'Script',
start,
end: parser.index,
context: get_context(parser, attributes, start),
content: ast
};
}
//
// list
// ┌──────┐
// ┌──────────────┼─head │
// │ │ tail─┼──────────────┐
// │ └──────┘ │
// ▼ ▼
// item item item item
// ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐
// null ◀──┼─prev │◀───┼─prev │◀───┼─prev │◀───┼─prev │
// │ next─┼───▶│ next─┼───▶│ next─┼───▶│ next─┼──▶ null
// ├──────┤ ├──────┤ ├──────┤ ├──────┤
// │ data │ │ data │ │ data │ │ data │
// └──────┘ └──────┘ └──────┘ └──────┘
//
let releasedCursors = null;
class List {
static createItem(data) {
return {
prev: null,
next: null,
data
};
}
constructor() {
this.head = null;
this.tail = null;
this.cursor = null;
}
createItem(data) {
return List.createItem(data);
}
// cursor helpers
allocateCursor(prev, next) {
let cursor;
if (releasedCursors !== null) {
cursor = releasedCursors;
releasedCursors = releasedCursors.cursor;
cursor.prev = prev;
cursor.next = next;
cursor.cursor = this.cursor;
} else {
cursor = {
prev,
next,
cursor: this.cursor
};
}
this.cursor = cursor;
return cursor;
}
releaseCursor() {
const { cursor } = this;
this.cursor = cursor.cursor;
cursor.prev = null;
cursor.next = null;
cursor.cursor = releasedCursors;
releasedCursors = cursor;
}
updateCursors(prevOld, prevNew, nextOld, nextNew) {
let { cursor } = this;
while (cursor !== null) {
if (cursor.prev === prevOld) {
cursor.prev = prevNew;
}
if (cursor.next === nextOld) {
cursor.next = nextNew;
}
cursor = cursor.cursor;
}
}
*[Symbol.iterator]() {
for (let cursor = this.head; cursor !== null; cursor = cursor.next) {
yield cursor.data;
}
}
// getters
get size() {
let size = 0;
for (let cursor = this.head; cursor !== null; cursor = cursor.next) {
size++;
}
return size;
}
get isEmpty() {
return this.head === null;
}
get first() {
return this.head && this.head.data;
}
get last() {
return this.tail && this.tail.data;
}
// convertors
fromArray(array) {
let cursor = null;
this.head = null;
for (let data of array) {
const item = List.createItem(data);
if (cursor !== null) {
cursor.next = item;
} else {
this.head = item;
}
item.prev = cursor;
cursor = item;
}
this.tail = cursor;
return this;
}
toArray() {
return [...this];
}
toJSON() {
return [...this];
}
// array-like methods
forEach(fn, thisArg = this) {
// push cursor
const cursor = this.allocateCursor(null, this.head);
while (cursor.next !== null) {
const item = cursor.next;
cursor.next = item.next;
fn.call(thisArg, item.data, item, this);
}
// pop cursor
this.releaseCursor();
}
forEachRight(fn, thisArg = this) {
// push cursor
const cursor = this.allocateCursor(this.tail, null);
while (cursor.prev !== null) {
const item = cursor.prev;
cursor.prev = item.prev;
fn.call(thisArg, item.data, item, this);
}
// pop cursor
this.releaseCursor();
}
reduce(fn, initialValue, thisArg = this) {
// push cursor
let cursor = this.allocateCursor(null, this.head);
let acc = initialValue;
let item;
while (cursor.next !== null) {
item = cursor.next;
cursor.next = item.next;
acc = fn.call(thisArg, acc, item.data, item, this);
}
// pop cursor
this.releaseCursor();
return acc;
}
reduceRight(fn, initialValue, thisArg = this) {
// push cursor
let cursor = this.allocateCursor(this.tail, null);
let acc = initialValue;
let item;
while (cursor.prev !== null) {
item = cursor.prev;
cursor.prev = item.prev;
acc = fn.call(thisArg, acc, item.data, item, this);
}
// pop cursor
this.releaseCursor();
return acc;
}
some(fn, thisArg = this) {
for (let cursor = this.head; cursor !== null; cursor = cursor.next) {
if (fn.call(thisArg, cursor.data, cursor, this)) {
return true;
}
}
return false;
}
map(fn, thisArg = this) {
const result = new List();
for (let cursor = this.head; cursor !== null; cursor = cursor.next) {
result.appendData(fn.call(thisArg, cursor.data, cursor, this));
}
return result;
}
filter(fn, thisArg = this) {
const result = new List();
for (let cursor = this.head; cursor !== null; cursor = cursor.next) {
if (fn.call(thisArg, cursor.data, cursor, this)) {
result.appendData(cursor.data);
}
}
return result;
}
nextUntil(start, fn, thisArg = this) {
if (start === null) {
return;
}
// push cursor
const cursor = this.allocateCursor(null, start);
while (cursor.next !== null) {
const item = cursor.next;
cursor.next = item.next;
if (fn.call(thisArg, item.data, item, this)) {
break;
}
}
// pop cursor
this.releaseCursor();
}
prevUntil(start, fn, thisArg = this) {
if (start === null) {
return;
}
// push cursor
const cursor = this.allocateCursor(start, null);
while (cursor.prev !== null) {
const item = cursor.prev;
cursor.prev = item.prev;
if (fn.call(thisArg, item.data, item, this)) {
break;
}
}
// pop cursor
this.releaseCursor();
}
// mutation
clear() {
this.head = null;
this.tail = null;
}
copy() {
const result = new List();
for (let data of this) {
result.appendData(data);
}
return result;
}
prepend(item) {
// head
// ^
// item
this.updateCursors(null, item, this.head, item);
// insert to the beginning of the list
if (this.head !== null) {
// new item <- first item
this.head.prev = item;
// new item -> first item
item.next = this.head;
} else {
// if list has no head, then it also has no tail
// in this case tail points to the new item
this.tail = item;
}
// head always points to new item
this.head = item;
return this;
}
prependData(data) {
return this.prepend(List.createItem(data));
}
append(item) {
return this.insert(item);
}
appendData(data) {
return this.insert(List.createItem(data));
}
insert(item, before = null) {
if (before !== null) {
// prev before
// ^
// item
this.updateCursors(before.prev, item, before, item);
if (before.prev === null) {
// insert to the beginning of list
if (this.head !== before) {
throw new Error('before doesn\'t belong to list');
}
// since head points to before therefore list doesn't empty
// no need to check tail
this.head = item;
before.prev = item;
item.next = before;
this.updateCursors(null, item);
} else {
// insert between two items
before.prev.next = item;
item.prev = before.prev;
before.prev = item;
item.next = before;
}
} else {
// tail
// ^
// item
this.updateCursors(this.tail, item, null, item);
// insert to the ending of the list
if (this.tail !== null) {
// last item -> new item
this.tail.next = item;
// last item <- new item
item.prev = this.tail;
} else {
// if list has no tail, then it also has no head
// in this case head points to new item
this.head = item;
}
// tail always points to new item
this.tail = item;
}
return this;
}
insertData(data, before) {
return this.insert(List.createItem(data), before);
}
remove(item) {
// item
// ^
// prev next
this.updateCursors(item, item.prev, item, item.next);
if (item.prev !== null) {
item.prev.next = item.next;
} else {
if (this.head !== item) {
throw new Error('item doesn\'t belong to list');
}
this.head = item.next;
}
if (item.next !== null) {
item.next.prev = item.prev;
} else {
if (this.tail !== item) {
throw new Error('item doesn\'t belong to list');
}
this.tail = item.prev;
}
item.prev = null;
item.next = null;
return item;
}
push(data) {
this.insert(List.createItem(data));
}
pop() {
return this.tail !== null ? this.remove(this.tail) : null;
}
unshift(data) {
this.prepend(List.createItem(data));
}
shift() {
return this.head !== null ? this.remove(this.head) : null;
}
prependList(list) {
return this.insertList(list, this.head);
}
appendList(list) {
return this.insertList(list);
}
insertList(list, before) {
// ignore empty lists
if (list.head === null) {
return this;
}
if (before !== undefined && before !== null) {
this.updateCursors(before.prev, list.tail, before, list.head);
// insert in the middle of dist list
if (before.prev !== null) {
// before.prev <-> list.head
before.prev.next = list.head;
list.head.prev = before.prev;
} else {
this.head = list.head;
}
before.prev = list.tail;
list.tail.next = before;
} else {
this.updateCursors(this.tail, list.tail, null, list.head);
// insert to end of the list
if (this.tail !== null) {
// if destination list has a tail, then it also has a head,
// but head doesn't change
// dest tail -> source head
this.tail.next = list.head;
// dest tail <- source head
list.head.prev = this.tail;
} else {
// if list has no a tail, then it also has no a head
// in this case points head to new item
this.head = list.head;
}
// tail always start point to new item
this.tail = list.tail;
}
list.head = null;
list.tail = null;
return this;
}
replace(oldItem, newItemOrList) {
if ('head' in newItemOrList) {
this.insertList(newItemOrList, oldItem);
} else {
this.insert(newItemOrList, oldItem);
}
this.remove(oldItem);
}
}
function createCustomError(name, message) {
// use Object.create(), because some VMs prevent setting line/column otherwise
// (iOS Safari 10 even throws an exception)
const error = Object.create(SyntaxError.prototype);
const errorStack = new Error();
return Object.assign(error, {
name,
message,
get stack() {
return (errorStack.stack || '').replace(/^(.+\n){1,3}/, `${name}: ${message}\n`);
}
});
}
const MAX_LINE_LENGTH = 100;
const OFFSET_CORRECTION = 60;
const TAB_REPLACEMENT = ' ';
function sourceFragment({ source, line, column }, extraLines) {
function processLines(start, end) {
return lines
.slice(start, end)
.map((line, idx) =>
String(start + idx + 1).padStart(maxNumLength) + ' |' + line
).join('\n');
}
const lines = source.split(/\r\n?|\n|\f/);
const startLine = Math.max(1, line - extraLines) - 1;
const endLine = Math.min(line + extraLines, lines.length + 1);
const maxNumLength = Math.max(4, String(endLine).length) + 1;
let cutLeft = 0;
// column correction according to replaced tab before column
column += (TAB_REPLACEMENT.length - 1) * (lines[line - 1].substr(0, column - 1).match(/\t/g) || []).length;
if (column > MAX_LINE_LENGTH) {
cutLeft = column - OFFSET_CORRECTION + 3;
column = OFFSET_CORRECTION - 2;
}
for (let i = startLine; i <= endLine; i++) {
if (i >= 0 && i < lines.length) {
lines[i] = lines[i].replace(/\t/g, TAB_REPLACEMENT);
lines[i] =
(cutLeft > 0 && lines[i].length > cutLeft ? '\u2026' : '') +
lines[i].substr(cutLeft, MAX_LINE_LENGTH - 2) +
(lines[i].length > cutLeft + MAX_LINE_LENGTH - 1 ? '\u2026' : '');
}
}
return [
processLines(startLine, line),
new Array(column + maxNumLength + 2).join('-') + '^',
processLines(line, endLine)
].filter(Boolean).join('\n');
}
function SyntaxError$1(message, source, offset, line, column) {
const error = Object.assign(createCustomError('SyntaxError', message), {
source,
offset,
line,
column,
sourceFragment(extraLines) {
return sourceFragment({ source, line, column }, isNaN(extraLines) ? 0 : extraLines);
},
get formattedMessage() {
return (
`Parse error: ${message}\n` +
sourceFragment({ source, line, column }, 2)
);
}
});
return error;
}
// 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 AtKeyword = 3; // <at-keyword-token>
const Hash = 4; // <hash-token>
const String$1 = 5; // <string-token>
const BadString = 6; // <bad-string-token>
const Url = 7; // <url-token>
const BadUrl = 8; // <bad-url-token>
const Delim = 9; // <delim-token>
const Number$1 = 10; // <number-token>
const Percentage = 11; // <percentage-token>
const Dimension = 12; // <dimension-token>
const WhiteSpace = 13; // <whitespace-token>
const CDO = 14; // <CDO-token>
const CDC = 15; // <CDC-token>
const Colon = 16; // <colon-token> :
const Semicolon = 17; // <semicolon-token> ;
const Comma = 18; // <comma-token> ,
const LeftSquareBracket = 19; // <[-token>
const RightSquareBracket = 20; // <]-token>
const LeftParenthesis = 21; // <(-token>
const RightParenthesis = 22; // <)-token>
const LeftCurlyBracket = 23; // <{-token>
const RightCurlyBracket = 24; // <}-token>
const Comment = 25;
const EOF$1 = 0;
// 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;
}
// hex digit
// A digit, or a code point between U+0041 LATIN CAPITAL LETTER A (A) and U+0046 LATIN CAPITAL LETTER F (F),
// or a code point between U+0061 LATIN SMALL LETTER A (a) and U+0066 LATIN SMALL LETTER F (f).
function isHexDigit$1(code) {
return (
isDigit(code) || // 0 .. 9
(code >= 0x0041 && code <= 0x0046) || // A .. F
(code >= 0x0061 && code <= 0x0066) // a .. f
);
}
// 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;
}
// name code point
// A name-start code point, a digit, or U+002D HYPHEN-MINUS (-).
function isName(code) {
return isNameStart(code) || isDigit(code) || code === 0x002D;
}
// 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;
}
// § 4.3.8. Check if two code points are a valid escape
function isValidEscape(first, second) {
// If the first code point is not U+005C REVERSE SOLIDUS (\), return false.
if (first !== 0x005C) {
return false;
}
// Otherwise, if the second code point is a newline or EOF, return false.
if (isNewline(second) || second === EOF$1) {
return false;
}
// Otherwise, return true.
return true;
}
// § 4.3.9. Check if three code points would start an identifier
function isIdentifierStart$1(first, second, third) {
// Look at the first code point:
// U+002D HYPHEN-MINUS
if (first === 0x002D) {
// If the second code point is a name-start code point or a U+002D HYPHEN-MINUS,
// or the second and third code points are a valid escape, return true. Otherwise, return false.
return (
isNameStart(second) ||
second === 0x002D ||
isValidEscape(second, third)
);
}
// name-start code point
if (isNameStart(first)) {
// Return true.
return true;
}
// U+005C REVERSE SOLIDUS (\)
if (first === 0x005C) {
// If the first and second code points are a valid escape, return true. Otherwise, return false.
return isValidEscape(first, second);
}
// anything else
// Return false.
return false;
}
// § 4.3.10. Check if three code points would start a number
function isNumberStart(first, second, third) {
// Look at the first code point:
// U+002B PLUS SIGN (+)
// U+002D HYPHEN-MINUS (-)
if (first === 0x002B || first === 0x002D) {
// If the second code point is a digit, return true.
if (isDigit(second)) {
return 2;
}
// Otherwise, if the second code point is a U+002E FULL STOP (.)
// and the third code point is a digit, return true.
// Otherwise, return false.
return second === 0x002E && isDigit(third) ? 3 : 0;
}
// U+002E FULL STOP (.)
if (first === 0x002E) {
// If the second code point is a digit, return true. Otherwise, return false.
return isDigit(second) ? 2 : 0;
}
// digit
if (isDigit(first)) {
// Return true.
return 1;
}
// anything else
// Return false.
return 0;
}
//
// Misc
//
// detect BOM (https://en.wikipedia.org/wiki/Byte_order_mark)
function isBOM(code) {
// UTF-16BE
if (code === 0xFEFF) {
return 1;
}
// UTF-16LE
if (code === 0xFFFE) {
return 1;
}
return 0;
}
// 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;
}
function charCodeCategory(code) {
return code < 0x80 ? CATEGORY[code] : NameStartCategory;
}
function getCharCode(source, offset) {
return offset < source.length ? source.charCodeAt(offset) : 0;
}
function getNewlineLength(source, offset, code) {
if (code === 13 /* \r */ && getCharCode(source, offset + 1) === 10 /* \n */) {
return 2;
}
return 1;
}
function cmpChar(testStr, offset, referenceCode) {
let code = testStr.charCodeAt(offset);
// code.toLowerCase() for A..Z
if (isUppercaseLetter(code)) {
code = code | 32;
}
return code === referenceCode;
}
function cmpStr(testStr, start, end, referenceStr) {
if (end - start !== referenceStr.length) {
return false;
}
if (start < 0 || end > testStr.length) {
return false;
}
for (let i = start; i < end; i++) {
const referenceCode = referenceStr.charCodeAt(i - start);
let testCode = testStr.charCodeAt(i);
// testCode.toLowerCase() for A..Z
if (isUppercaseLetter(testCode)) {
testCode = testCode | 32;
}
if (testCode !== referenceCode) {
return false;
}
}
return true;
}
function findWhiteSpaceStart(source, offset) {
for (; offset >= 0; offset--) {
if (!isWhiteSpace(source.charCodeAt(offset))) {
break;
}
}
return offset + 1;
}
function findWhiteSpaceEnd(source, offset) {
for (; offset < source.length; offset++) {
if (!isWhiteSpace(source.charCodeAt(offset))) {
break;
}
}
return offset;
}
function findDecimalNumberEnd(source, offset) {
for (; offset < source.length; offset++) {
if (!isDigit(source.charCodeAt(offset))) {
break;
}
}
return offset;
}
// § 4.3.7. Consume an escaped code point
function consumeEscaped(source, offset) {
// It assumes that the U+005C REVERSE SOLIDUS (\) has already been consumed and
// that the next input code point has already been verified to be part of a valid escape.
offset += 2;
// hex digit
if (isHexDigit$1(getCharCode(source, offset - 1))) {
// Consume as many hex digits as possible, but no more than 5.
// Note that this means 1-6 hex digits have been consumed in total.
for (const maxOffset = Math.min(source.length, offset + 5); offset < maxOffset; offset++) {
if (!isHexDigit$1(getCharCode(source, offset))) {
break;
}
}
// If the next input code point is whitespace, consume it as well.
const code = getCharCode(source, offset);
if (isWhiteSpace(code)) {
offset += getNewlineLength(source, offset, code);
}
}
return offset;
}
// §4.3.11. Consume a name
// Note: This algorithm does not do the verification of the first few code points that are necessary
// to ensure the returned code points would constitute an <ident-token>. If that is the intended use,
// ensure that the stream starts with an identifier before calling this algorithm.
function consumeName(source, offset) {
// Let result initially be an empty string.
// Repeatedly consume the next input code point from the stream:
for (; offset < source.length; offset++) {
const code = source.charCodeAt(offset);
// name code point
if (isName(code)) {
// Append the code point to result.
continue;
}
// the stream starts with a valid escape
if (isValidEscape(code, getCharCode(source, offset + 1))) {
// Consume an escaped code point. Append the returned code point to result.
offset = consumeEscaped(source, offset) - 1;
continue;
}
// anything else
// Reconsume the current input code point. Return result.
break;
}
return offset;
}
// §4.3.12. Consume a number
function consumeNumber(source, offset) {
let code = source.charCodeAt(offset);
// 2. If the next input code point is U+002B PLUS SIGN (+) or U+002D HYPHEN-MINUS (-),
// consume it and append it to repr.
if (code === 0x002B || code === 0x002D) {
code = source.charCodeAt(offset += 1);
}
// 3. While the next input code point is a digit, consume it and append it to repr.
if (isDigit(code)) {
offset = findDecimalNumberEnd(source, offset + 1);
code = source.charCodeAt(offset);
}
// 4. If the next 2 input code points are U+002E FULL STOP (.) followed by a digit, then:
if (code === 0x002E && isDigit(source.charCodeAt(offset + 1))) {
// 4.1 Consume them.
// 4.2 Append them to repr.
offset += 2;
// 4.3 Set type to "number".
// TODO
// 4.4 While the next input code point is a digit, consume it and append it to repr.
offset = findDecimalNumberEnd(source, offset);
}
// 5. If the next 2 or 3 input code points are U+0045 LATIN CAPITAL LETTER E (E)
// or U+0065 LATIN SMALL LETTER E (e), ... , followed by a digit, then:
if (cmpChar(source, offset, 101 /* e */)) {
let sign = 0;
code = source.charCodeAt(offset + 1);
// ... optionally followed by U+002D HYPHEN-MINUS (-) or U+002B PLUS SIGN (+) ...
if (code === 0x002D || code === 0x002B) {
sign = 1;
code = source.charCodeAt(offset + 2);
}
// ... followed by a digit
if (isDigit(code)) {
// 5.1 Consume them.
// 5.2 Append them to repr.
// 5.3 Set type to "number".
// TODO
// 5.4 While the next input code point is a digit, consume it and append it to repr.
offset = findDecimalNumberEnd(source, offset + 1 + sign + 1);
}
}
return offset;
}
// § 4.3.14. Consume the remnants of a bad url
// ... its sole use is to consume enough of the input stream to reach a recovery point
// where normal tokenizing can resume.
function consumeBadUrlRemnants(source, offset) {
// Repeatedly consume the next input code point from the stream:
for (; offset < source.length; offset++) {
const code = source.charCodeAt(offset);
// U+0029 RIGHT PARENTHESIS ())
// EOF
if (code === 0x0029) {
// Return.
offset++;
break;
}
if (isValidEscape(code, getCharCode(source, offset + 1))) {
// Consume an escaped code point.
// Note: This allows an escaped right parenthesis ("\)") to be encountered
// without ending the <bad-url-token>. This is otherwise identical to
// the "anything else" clause.
offset = consumeEscaped(source, offset);
}
}
return offset;
}
// § 4.3.7. Consume an escaped code point
// Note: This algorithm assumes that escaped is valid without leading U+005C REVERSE SOLIDUS (\)
function decodeEscaped(escaped) {
// Single char escaped that's not a hex digit
if (escaped.length === 1 && !isHexDigit$1(escaped.charCodeAt(0))) {
return escaped[0];
}
// Interpret the hex digits as a hexadecimal number.
let code = parseInt(escaped, 16);
if (
(code === 0) || // If this number is zero,
(code >= 0xD800 && code <= 0xDFFF) || // or is for a surrogate,
(code > 0x10FFFF) // or is greater than the maximum allowed code point
) {
// ... return U+FFFD REPLACEMENT CHARACTER
code = 0xFFFD;
}
// Otherwise, return the code point with that value.
return String.fromCodePoint(code);
}
var tokenNames = [
'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'
];
const MIN_SIZE = 16 * 1024;
function adoptBuffer(buffer = null, size) {
if (buffer === null || buffer.length < size) {
return new Uint32Array(Math.max(size + 1024, MIN_SIZE));
}
return buffer;
}
const N = 10;
const F = 12;
const R = 13;
function computeLinesAndColumns(host) {
const source = host.source;
const sourceLength = source.length;
const startOffset = source.length > 0 ? isBOM(source.charCodeAt(0)) : 0;
const lines = adoptBuffer(host.lines, sourceLength);
const columns = adoptBuffer(host.columns, sourceLength);
let line = host.startLine;
let column = host.startColumn;
for (let i = startOffset; i < sourceLength; i++) {
const code = source.charCodeAt(i);
lines[i] = line;
columns[i] = column++;
if (code === N || code === R || code === F) {
if (code === R && i + 1 < sourceLength && source.charCodeAt(i + 1) === N) {
i++;
lines[i] = line;
columns[i] = column;
}
line++;
column = 1;
}
}
lines[sourceLength] = line;
columns[sourceLength] = column;
host.lines = lines;
host.columns = columns;
host.computed = true;
}
class OffsetToLocation {
constructor() {
this.lines = null;
this.columns = null;
this.computed = false;
}
setSource(source, startOffset = 0, startLine = 1, startColumn = 1) {
this.source = source;
this.startOffset = startOffset;
this.startLine = startLine;
this.startColumn = startColumn;
this.computed = false;
}
getLocation(offset, filename) {
if (!this.computed) {
computeLinesAndColumns(this);
}
return {
source: filename,
offset: this.startOffset + offset,
line: this.lines[offset],
column: this.columns[offset]
};
}
getLocationRange(start, end, filename) {
if (!this.computed) {
computeLinesAndColumns(this);
}
return {
source: filename,
start: {
offset: this.startOffset + start,
line: this.lines[start],
column: this.columns[start]
},
end: {
offset: this.startOffset + end,
line: this.lines[end],
column: this.columns[end]
}
};
}
}
const OFFSET_MASK = 0x00FFFFFF;
const TYPE_SHIFT = 24;
const balancePair = new Map([
[Function$1, RightParenthesis],
[LeftParenthesis, RightParenthesis],
[LeftSquareBracket, RightSquareBracket],
[LeftCurlyBracket, RightCurlyBracket]
]);
class TokenStream {
constructor(source, tokenize) {
this.setSource(source, tokenize);
}
reset() {
this.eof = false;
this.tokenIndex = -1;
this.tokenType = 0;
this.tokenStart = this.firstCharOffset;
this.tokenEnd = this.firstCharOffset;
}
setSource(source = '', tokenize = () => {}) {
source = String(source || '');
const sourceLength = source.length;
const offsetAndType = adoptBuffer(this.offsetAndType, source.length + 1); // +1 because of eof-token
const balance = adoptBuffer(this.balance, source.length + 1);
let tokenCount = 0;
let balanceCloseType = 0;
let balanceStart = 0;
let firstCharOffset = -1;
// capture buffers
this.offsetAndType = null;
this.balance = null;
tokenize(source, (type, start, end) => {
switch (type) {
default:
balance[tokenCount] = sourceLength;
break;
case balanceCloseType: {
let balancePrev = balanceStart & OFFSET_MASK;
balanceStart = balance[balancePrev];
balanceCloseType = balanceStart >> TYPE_SHIFT;
balance[tokenCount] = balancePrev;
balance[balancePrev++] = tokenCount;
for (; balancePrev < tokenCount; balancePrev++) {
if (balance[balancePrev] === sourceLength) {
balance[balancePrev] = tokenCount;
}
}
break;
}
case LeftParenthesis:
case Function$1:
case LeftSquareBracket:
case LeftCurlyBracket:
balance[tokenCount] = balanceStart;
balanceCloseType = balancePair.get(type);
balanceStart = (balanceCloseType << TYPE_SHIFT) | tokenCount;
break;
}
offsetAndType[tokenCount++] = (type << TYPE_SHIFT) | end;
if (firstCharOffset === -1) {
firstCharOffset = start;
}
});
// finalize buffers
offsetAndType[tokenCount] = (EOF << TYPE_SHIFT) | sourceLength; // <EOF-token>
balance[tokenCount] = sourceLength;
balance[sourceLength] = sourceLength; // prevents false positive balance match with any token
while (balanceStart !== 0) {
const balancePrev = balanceStart & OFFSET_MASK;
balanceStart = balance[balancePrev];
balance[balancePrev] = sourceLength;
}
this.source = source;
this.firstCharOffset = firstCharOffset === -1 ? 0 : firstCharOffset;
this.tokenCount = tokenCount;
this.offsetAndType = offsetAndType;
this.balance = balance;
this.reset();
this.next();
}
lookupType(offset) {
offset += this.tokenIndex;
if (offset < this.tokenCount) {
return this.offsetAndType[offset] >> TYPE_SHIFT;
}
return EOF;
}
lookupOffset(offset) {
offset += this.tokenIndex;
if (offset < this.tokenCount) {
return this.offsetAndType[offset - 1] & OFFSET_MASK;
}
return this.source.length;
}
lookupValue(offset, referenceStr) {
offset += this.tokenIndex;
if (offset < this.tokenCount) {
return cmpStr(
this.source,
this.offsetAndType[offset - 1] & OFFSET_MASK,
this.offsetAndType[offset] & OFFSET_MASK,
referenceStr
);
}
return false;
}
getTokenStart(tokenIndex) {
if (tokenIndex === this.tokenIndex) {
return this.tokenStart;
}
if (tokenIndex > 0) {
return tokenIndex < this.tokenCount
? this.offsetAndType[tokenIndex - 1] & OFFSET_MASK
: this.offsetAndType[this.tokenCount] & OFFSET_MASK;
}
return this.firstCharOffset;
}
substrToCursor(start) {
return this.source.substring(start, this.tokenStart);
}
isBalanceEdge(pos) {
return this.balance[this.tokenIndex] < pos;
}
isDelim(code, offset) {
if (offset) {
return (
this.lookupType(offset) === Delim &&
this.source.charCodeAt(this.lookupOffset(offset)) === code
);
}
return (
this.tokenType === Delim &&
this.source.charCodeAt(this.tokenStart) === code
);
}
skip(tokenCount) {
let next = this.tokenIndex + tokenCount;
if (next < this.tokenCount) {
this.tokenIndex = next;
this.tokenStart = this.offsetAndType[next - 1] & OFFSET_MASK;
next = this.offsetAndType[next];
this.tokenType = next >> TYPE_SHIFT;
this.tokenEnd = next & OFFSET_MASK;
} else {
this.tokenIndex = this.tokenCount;
this.next();
}
}
next() {
let next = this.tokenIndex + 1;
if (next < this.tokenCount) {
this.tokenIndex = next;
this.tokenStart = this.tokenEnd;
next = this.offsetAndType[next];
this.tokenType = next >> TYPE_SHIFT;
this.tokenEnd = next & OFFSET_MASK;
} else {
this.eof = true;
this.tokenIndex = this.tokenCount;
this.tokenType = EOF;
this.tokenStart = this.tokenEnd = this.source.length;
}
}
skipSC() {
while (this.tokenType === WhiteSpace || this.tokenType === Comment) {
this.next();
}
}
skipUntilBalanced(startToken, stopConsume) {
let cursor = startToken;
let balanceEnd;
let offset;
loop:
for (; cursor < this.tokenCount; cursor++) {
balanceEnd = this.balance[cursor];
// stop scanning on balance edge that points to offset before start token
if (balanceEnd < startToken) {
break loop;
}
offset = cursor > 0 ? this.offsetAndType[cursor - 1] & OFFSET_MASK : this.firstCharOffset;
// check stop condition
switch (stopConsume(this.source.charCodeAt(offset))) {
case 1: // just stop
break loop;
case 2: // stop & included
cursor++;
break loop;
default:
// fast forward to the end of balanced block
if (this.balance[balanceEnd] === cursor) {
cursor = balanceEnd;
}
}
}
this.skip(cursor - this.tokenIndex);
}
forEachToken(fn) {
for (let i = 0, offset = this.firstCharOffset; i < this.tokenCount; i++) {
const start = offset;
const item = this.offsetAndType[i];
const end = item & OFFSET_MASK;
const type = item >> TYPE_SHIFT;
offset = end;
fn(type, start, end, i);
}
}
dump() {
const tokens = new Array(this.tokenCount);
this.forEachToken((type, start, end, index) => {
tokens[index] = {
idx: index,
type: tokenNames[type],
chunk: this.source.substring(start, end),
balance: this.balance[index]
};
});
return tokens;
}
}
function tokenize(source, onToken) {
function getCharCode(offset) {
return offset < sourceLength ? source.charCodeAt(offset) : 0;
}
// § 4.3.3. Consume a numeric token
function consumeNumericToken() {
// Consume a number and let number be the result.
offset = consumeNumber(source, offset);
// If the next 3 input code points would start an identifier, then:
if (isIdentifierStart$1(getCharCode(offset), getCharCode(offset + 1), getCharCode(offset + 2))) {
// Create a <dimension-token> with the same value and type flag as number, and a unit set initially to the empty string.
// Consume a name. Set the <dimension-token>s unit to the returned value.
// Return the <dimension-token>.
type = Dimension;
offset = consumeName(source, offset);
return;
}
// Otherwise, if the next input code point is U+0025 PERCENTAGE SIGN (%), consume it.
if (getCharCode(offset) === 0x0025) {
// Create a <percentage-token> with the same value as number, and return it.
type = Percentage;
offset++;
return;
}
// Otherwise, create a <number-token> with the same value and type flag as number, and return it.
type = Number$1;
}
// § 4.3.4. Consume an ident-like token
function consumeIdentLikeToken() {
const nameStartOffset = offset;
// Consume a name, and let string be the result.
offset = consumeName(source, offset);
// If strings value is an ASCII case-insensitive match for "url",
// and the next input code point is U+0028 LEFT PARENTHESIS ((), consume it.
if (cmpStr(source, nameStartOffset, offset, 'url') && getCharCode(offset) === 0x0028) {
// While the next two input code points are whitespace, consume the next input code point.
offset = findWhiteSpaceEnd(source, offset + 1);
// If the next one or two input code points are U+0022 QUOTATION MARK ("), U+0027 APOSTROPHE ('),
// or whitespace followed by U+0022 QUOTATION MARK (") or U+0027 APOSTROPHE ('),
// then create a <function-token> with its value set to string and return it.
if (getCharCode(offset) === 0x0022 ||
getCharCode(offset) === 0x0027) {
type = Function$1;
offset = nameStartOffset + 4;
return;
}
// Otherwise, consume a url token, and return it.
consumeUrlToken();
return;
}
// Otherwise, if the next input code point is U+0028 LEFT PARENTHESIS ((), consume it.
// Create a <function-token> with its value set to string and return it.
if (getCharCode(offset) === 0x0028) {
type = Function$1;
offset++;
return;
}
// Otherwise, create an <ident-token> with its value set to string and return it.
type = Ident;
}
// § 4.3.5. Consume a string token
function consumeStringToken(endingCodePoint) {
// This algorithm may be called with an ending code point, which denotes the code point
// that ends the string. If an ending code point is not specified,
// the current input code point is used.
if (!endingCodePoint) {
endingCodePoint = getCharCode(offset++);
}
// Initially create a <string-token> with its value set to the empty string.
type = String$1;
// Repeatedly consume the next input code point from the stream:
for (; offset < source.length; offset++) {
const code = source.charCodeAt(offset);
switch (charCodeCategory(code)) {
// ending code point
case endingCodePoint:
// Return the <string-token>.
offset++;
return;
// EOF
// case EofCategory:
// This is a parse error. Return the <string-token>.
// return;
// newline
case WhiteSpaceCategory:
if (isNewline(code)) {
// This is a parse error. Reconsume the current input code point,
// create a <bad-string-token>, and return it.
offset += getNewlineLength(source, offset, code);
type = BadString;
return;
}
break;
// U+005C REVERSE SOLIDUS (\)
case 0x005C:
// If the next input code point is EOF, do nothing.
if (offset === source.length - 1) {
break;
}
const nextCode = getCharCode(offset + 1);
// Otherwise, if the next input code point is a newline, consume it.
if (isNewline(nextCode)) {
offset += getNewlineLength(source, offset + 1, nextCode);
} else if (isValidEscape(code, nextCode)) {
// Otherwise, (the stream starts with a valid escape) consume
// an escaped code point and append the returned code point to
// the <string-token>s value.
offset = consumeEscaped(source, offset) - 1;
}
break;
// anything else
// Append the current input code point to the <string-token>s value.
}
}
}
// § 4.3.6. Consume a url token
// Note: This algorithm assumes that the initial "url(" has already been consumed.
// This algorithm also assumes that its being called to consume an "unquoted" value, like url(foo).
// A quoted value, like url("foo"), is parsed as a <function-token>. Consume an ident-like token
// automatically handles this distinction; this algorithm shouldnt be called directly otherwise.
function consumeUrlToken() {
// Initially create a <url-token> with its value set to the empty string.
type = Url;
// Consume as much whitespace as possible.
offset = findWhiteSpaceEnd(source, offset);
// Repeatedly consume the next input code point from the stream:
for (; offset < source.length; offset++) {
const code = source.charCodeAt(offset);
switch (charCodeCategory(code)) {
// U+0029 RIGHT PARENTHESIS ())
case 0x0029:
// Return the <url-token>.
offset++;
return;
// EOF
// case EofCategory:
// This is a parse error. Return the <url-token>.
// return;
// whitespace
case WhiteSpaceCategory:
// Consume as much whitespace as possible.
offset = findWhiteSpaceEnd(source, offset);
// If the next input code point is U+0029 RIGHT PARENTHESIS ()) or EOF,
// consume it and return the <url-token>
// (if EOF was encountered, this is a parse error);
if (getCharCode(offset) === 0x0029 || offset >= source.length) {
if (offset < source.length) {
offset++;
}
return;
}
// otherwise, consume the remnants of a bad url, create a <bad-url-token>,
// and return it.
offset = consumeBadUrlRemnants(source, offset);
type = BadUrl;
return;
// U+0022 QUOTATION MARK (")
// U+0027 APOSTROPHE (')
// U+0028 LEFT PARENTHESIS (()
// non-printable code point
case 0x0022:
case 0x0027:
case 0x0028:
case NonPrintableCategory:
// This is a parse error. Consume the remnants of a bad url,
// create a <bad-url-token>, and return it.
offset = consumeBadUrlRemnants(source, offset);
type = BadUrl;
return;
// U+005C REVERSE SOLIDUS (\)
case 0x005C:
// If the stream starts with a valid escape, consume an escaped code point and
// append the returned code point to the <url-token>s value.
if (isValidEscape(code, getCharCode(offset + 1))) {
offset = consumeEscaped(source, offset) - 1;
break;
}
// Otherwise, this is a parse error. Consume the remnants of a bad url,
// create a <bad-url-token>, and return it.
offset = consumeBadUrlRemnants(source, offset);
type = BadUrl;
return;
// anything else
// Append the current input code point to the <url-token>s value.
}
}
}
// ensure source is a string
source = String(source || '');
const sourceLength = source.length;
let start = isBOM(getCharCode(0));
let offset = start;
let type;
// https://drafts.csswg.org/css-syntax-3/#consume-token
// § 4.3.1. Consume a token
while (offset < sourceLength) {
const code = source.charCodeAt(offset);
switch (charCodeCategory(code)) {
// whitespace
case WhiteSpaceCategory:
// Consume as much whitespace as possible. Return a <whitespace-token>.
type = WhiteSpace;
offset = findWhiteSpaceEnd(source, offset + 1);
break;
// U+0022 QUOTATION MARK (")
case 0x0022:
// Consume a string token and return it.
consumeStringToken();
break;
// U+0023 NUMBER SIGN (#)
case 0x0023:
// If the next input code point is a name code point or the next two input code points are a valid escape, then:
if (isName(getCharCode(offset + 1)) || isValidEscape(getCharCode(offset + 1), getCharCode(offset + 2))) {
// Create a <hash-token>.
type = Hash;
// If the next 3 input code points would start an identifier, set the <hash-token>s type flag to "id".
// if (isIdentifierStart(getCharCode(offset + 1), getCharCode(offset + 2), getCharCode(offset + 3))) {
// // TODO: set id flag
// }
// Consume a name, and set the <hash-token>s value to the returned string.
offset = consumeName(source, offset + 1);
// Return the <hash-token>.
} else {
// Otherwise, return a <delim-token> with its value set to the current input code point.
type = Delim;
offset++;
}
break;
// U+0027 APOSTROPHE (')
case 0x0027:
// Consume a string token and return it.
consumeStringToken();
break;
// U+0028 LEFT PARENTHESIS (()
case 0x0028:
// Return a <(-token>.
type = LeftParenthesis;
offset++;
break;
// U+0029 RIGHT PARENTHESIS ())
case 0x0029:
// Return a <)-token>.
type = RightParenthesis;
offset++;
break;
// U+002B PLUS SIGN (+)
case 0x002B:
// If the input stream starts with a number, ...
if (isNumberStart(code, getCharCode(offset + 1), getCharCode(offset + 2))) {
// ... reconsume the current input code point, consume a numeric token, and return it.
consumeNumericToken();
} else {
// Otherwise, return a <delim-token> with its value set to the current input code point.
type = Delim;
offset++;
}
break;
// U+002C COMMA (,)
case 0x002C:
// Return a <comma-token>.
type = Comma;
offset++;
break;
// U+002D HYPHEN-MINUS (-)
case 0x002D:
// If the input stream starts with a number, reconsume the current input code point, consume a numeric token, and return it.
if (isNumberStart(code, getCharCode(offset + 1), getCharCode(offset + 2))) {
consumeNumericToken();
} else {
// Otherwise, if the next 2 input code points are U+002D HYPHEN-MINUS U+003E GREATER-THAN SIGN (->), consume them and return a <CDC-token>.
if (getCharCode(offset + 1) === 0x002D &&
getCharCode(offset + 2) === 0x003E) {
type = CDC;
offset = offset + 3;
} else {
// Otherwise, if the input stream starts with an identifier, ...
if (isIdentifierStart$1(code, getCharCode(offset + 1), getCharCode(offset + 2))) {
// ... reconsume the current input code point, consume an ident-like token, and return it.
consumeIdentLikeToken();
} else {
// Otherwise, return a <delim-token> with its value set to the current input code point.
type = Delim;
offset++;
}
}
}
break;
// U+002E FULL STOP (.)
case 0x002E:
// If the input stream starts with a number, ...
if (isNumberStart(code, getCharCode(offset + 1), getCharCode(offset + 2))) {
// ... reconsume the current input code point, consume a numeric token, and return it.
consumeNumericToken();
} else {
// Otherwise, return a <delim-token> with its value set to the current input code point.
type = Delim;
offset++;
}
break;
// U+002F SOLIDUS (/)
case 0x002F:
// If the next two input code point are U+002F SOLIDUS (/) followed by a U+002A ASTERISK (*),
if (getCharCode(offset + 1) === 0x002A) {
// ... consume them and all following code points up to and including the first U+002A ASTERISK (*)
// followed by a U+002F SOLIDUS (/), or up to an EOF code point.
type = Comment;
offset = source.indexOf('*/', offset + 2);
offset = offset === -1 ? source.length : offset + 2;
} else {
type = Delim;
offset++;
}
break;
// U+003A COLON (:)
case 0x003A:
// Return a <colon-token>.
type = Colon;
offset++;
break;
// U+003B SEMICOLON (;)
case 0x003B:
// Return a <semicolon-token>.
type = Semicolon;
offset++;
break;
// U+003C LESS-THAN SIGN (<)
case 0x003C:
// If the next 3 input code points are U+0021 EXCLAMATION MARK U+002D HYPHEN-MINUS U+002D HYPHEN-MINUS (!--), ...
if (getCharCode(offset + 1) === 0x0021 &&
getCharCode(offset + 2) === 0x002D &&
getCharCode(offset + 3) === 0x002D) {
// ... consume them and return a <CDO-token>.
type = CDO;
offset = offset + 4;
} else {
// Otherwise, return a <delim-token> with its value set to the current input code point.
type = Delim;
offset++;
}
break;
// U+0040 COMMERCIAL AT (@)
case 0x0040:
// If the next 3 input code points would start an identifier, ...
if (isIdentifierStart$1(getCharCode(offset + 1), getCharCode(offset + 2), getCharCode(offset + 3))) {
// ... consume a name, create an <at-keyword-token> with its value set to the returned value, and return it.
type = AtKeyword;
offset = consumeName(source, offset + 1);
} else {
// Otherwise, return a <delim-token> with its value set to the current input code point.
type = Delim;
offset++;
}
break;
// U+005B LEFT SQUARE BRACKET ([)
case 0x005B:
// Return a <[-token>.
type = LeftSquareBracket;
offset++;
break;
// U+005C REVERSE SOLIDUS (\)
case 0x005C:
// If the input stream starts with a valid escape, ...
if (isValidEscape(code, getCharCode(offset + 1))) {
// ... reconsume the current input code point, consume an ident-like token, and return it.
consumeIdentLikeToken();
} else {
// Otherwise, this is a parse error. Return a <delim-token> with its value set to the current input code point.
type = Delim;
offset++;
}
break;
// U+005D RIGHT SQUARE BRACKET (])
case 0x005D:
// Return a <]-token>.
type = RightSquareBracket;
offset++;
break;
// U+007B LEFT CURLY BRACKET ({)
case 0x007B:
// Return a <{-token>.
type = LeftCurlyBracket;
offset++;
break;
// U+007D RIGHT CURLY BRACKET (})
case 0x007D:
// Return a <}-token>.
type = RightCurlyBracket;
offset++;
break;
// digit
case DigitCategory:
// Reconsume the current input code point, consume a numeric token, and return it.
consumeNumericToken();
break;
// name-start code point
case NameStartCategory:
// Reconsume the current input code point, consume an ident-like token, and return it.
consumeIdentLikeToken();
break;
// EOF
// case EofCategory:
// Return an <EOF-token>.
// break;
// anything else
default:
// Return a <delim-token> with its value set to the current input code point.
type = Delim;
offset++;
}
// put token to stream
onToken(type, start, start = offset);
}
}
function readSequence(recognizer) {
const children = this.createList();
let space = false;
const context = {
recognizer
};
while (!this.eof) {
switch (this.tokenType) {
case Comment:
this.next();
continue;
case WhiteSpace:
space = true;
this.next();
continue;
}
let child = recognizer.getNode.call(this, context);
if (child === undefined) {
break;
}
if (space) {
if (recognizer.onWhiteSpace) {
recognizer.onWhiteSpace.call(this, child, children, context);
}
space = false;
}
children.push(child);
}
if (space && recognizer.onWhiteSpace) {
recognizer.onWhiteSpace.call(this, null, children, context);
}
return children;
}
const NOOP = () => {};
const EXCLAMATIONMARK = 0x0021; // U+0021 EXCLAMATION MARK (!)
const NUMBERSIGN = 0x0023; // U+0023 NUMBER SIGN (#)
const SEMICOLON = 0x003B; // U+003B SEMICOLON (;)
const LEFTCURLYBRACKET = 0x007B; // U+007B LEFT CURLY BRACKET ({)
const NULL = 0;
function createParseContext(name) {
return function() {
return this[name]();
};
}
function fetchParseValues(dict) {
const result = Object.create(null);
for (const name in dict) {
const item = dict[name];
const fn = item.parse || item;
if (fn) {
result[name] = fn;
}
}
return result;
}
function processConfig(config) {
const parseConfig = {
context: Object.create(null),
scope: Object.assign(Object.create(null), config.scope),
atrule: fetchParseValues(config.atrule),
pseudo: fetchParseValues(config.pseudo),
node: fetchParseValues(config.node)
};
for (const name in config.parseContext) {
switch (typeof config.parseContext[name]) {
case 'function':
parseConfig.context[name] = config.parseContext[name];
break;
case 'string':
parseConfig.context[name] = createParseContext(config.parseContext[name]);
break;
}
}
return {
config: parseConfig,
...parseConfig,
...parseConfig.node
};
}
function createParser(config) {
let source = '';
let filename = '<unknown>';
let needPositions = false;
let onParseError = NOOP;
let onParseErrorThrow = false;
const locationMap = new OffsetToLocation();
const parser = Object.assign(new TokenStream(), processConfig(config || {}), {
parseAtrulePrelude: true,
parseRulePrelude: true,
parseValue: true,
parseCustomProperty: false,
readSequence,
consumeUntilBalanceEnd: () => 0,
consumeUntilLeftCurlyBracket(code) {
return code === LEFTCURLYBRACKET ? 1 : 0;
},
consumeUntilLeftCurlyBracketOrSemicolon(code) {
return code === LEFTCURLYBRACKET || code === SEMICOLON ? 1 : 0;
},
consumeUntilExclamationMarkOrSemicolon(code) {
return code === EXCLAMATIONMARK || code === SEMICOLON ? 1 : 0;
},
consumeUntilSemicolonIncluded(code) {
return code === SEMICOLON ? 2 : 0;
},
createList() {
return new List();
},
createSingleNodeList(node) {
return new List().appendData(node);
},
getFirstListNode(list) {
return list && list.first;
},
getLastListNode(list) {
return list && list.last;
},
parseWithFallback(consumer, fallback) {
const startToken = this.tokenIndex;
try {
return consumer.call(this);
} catch (e) {
if (onParseErrorThrow) {
throw e;
}
const fallbackNode = fallback.call(this, startToken);
onParseErrorThrow = true;
onParseError(e, fallbackNode);
onParseErrorThrow = false;
return fallbackNode;
}
},
lookupNonWSType(offset) {
let type;
do {
type = this.lookupType(offset++);
if (type !== WhiteSpace) {
return type;
}
} while (type !== NULL);
return NULL;
},
charCodeAt(offset) {
return offset >= 0 && offset < source.length ? source.charCodeAt(offset) : 0;
},
substring(offsetStart, offsetEnd) {
return source.substring(offsetStart, offsetEnd);
},
substrToCursor(start) {
return this.source.substring(start, this.tokenStart);
},
cmpChar(offset, charCode) {
return cmpChar(source, offset, charCode);
},
cmpStr(offsetStart, offsetEnd, str) {
return cmpStr(source, offsetStart, offsetEnd, str);
},
consume(tokenType) {
const start = this.tokenStart;
this.eat(tokenType);
return this.substrToCursor(start);
},
consumeFunctionName() {
const name = source.substring(this.tokenStart, this.tokenEnd - 1);
this.eat(Function$1);
return name;
},
consumeNumber(type) {
const number = source.substring(this.tokenStart, consumeNumber(source, this.tokenStart));
this.eat(type);
return number;
},
eat(tokenType) {
if (this.tokenType !== tokenType) {
const tokenName = tokenNames[tokenType].slice(0, -6).replace(/-/g, ' ').replace(/^./, m => m.toUpperCase());
let message = `${/[[\](){}]/.test(tokenName) ? `"${tokenName}"` : tokenName} is expected`;
let offset = this.tokenStart;
// tweak message and offset
switch (tokenType) {
case Ident:
// when identifier is expected but there is a function or url
if (this.tokenType === Function$1 || this.tokenType === Url) {
offset = this.tokenEnd - 1;
message = 'Identifier is expected but function found';
} else {
message = 'Identifier is expected';
}
break;
case Hash:
if (this.isDelim(NUMBERSIGN)) {
this.next();
offset++;
message = 'Name is expected';
}
break;
case Percentage:
if (this.tokenType === Number$1) {
offset = this.tokenEnd;
message = 'Percent sign is expected';
}
break;
}
this.error(message, offset);
}
this.next();
},
eatIdent(name) {
if (this.tokenType !== Ident || this.lookupValue(0, name) === false) {
this.error(`Identifier "${name}" is expected`);
}
this.next();
},
eatDelim(code) {
if (!this.isDelim(code)) {
this.error(`Delim "${String.fromCharCode(code)}" is expected`);
}
this.next();
},
getLocation(start, end) {
if (needPositions) {
return locationMap.getLocationRange(
start,
end,
filename
);
}
return null;
},
getLocationFromList(list) {
if (needPositions) {
const head = this.getFirstListNode(list);
const tail = this.getLastListNode(list);
return locationMap.getLocationRange(
head !== null ? head.loc.start.offset - locationMap.startOffset : this.tokenStart,
tail !== null ? tail.loc.end.offset - locationMap.startOffset : this.tokenStart,
filename
);
}
return null;
},
error(message, offset) {
const location = typeof offset !== 'undefined' && offset < source.length
? locationMap.getLocation(offset)
: this.eof
? locationMap.getLocation(findWhiteSpaceStart(source, source.length - 1))
: locationMap.getLocation(this.tokenStart);
throw new SyntaxError$1(
message || 'Unexpected input',
source,
location.offset,
location.line,
location.column
);
}
});
const parse = function(source_, options) {
source = source_;
options = options || {};
parser.setSource(source, tokenize);
locationMap.setSource(
source,
options.offset,
options.line,
options.column
);
filename = options.filename || '<unknown>';
needPositions = Boolean(options.positions);
onParseError = typeof options.onParseError === 'function' ? options.onParseError : NOOP;
onParseErrorThrow = false;
parser.parseAtrulePrelude = 'parseAtrulePrelude' in options ? Boolean(options.parseAtrulePrelude) : true;
parser.parseRulePrelude = 'parseRulePrelude' in options ? Boolean(options.parseRulePrelude) : true;
parser.parseValue = 'parseValue' in options ? Boolean(options.parseValue) : true;
parser.parseCustomProperty = 'parseCustomProperty' in options ? Boolean(options.parseCustomProperty) : false;
const { context = 'default', onComment } = options;
if (context in parser.context === false) {
throw new Error('Unknown context `' + context + '`');
}
if (typeof onComment === 'function') {
parser.forEachToken((type, start, end) => {
if (type === Comment) {
const loc = parser.getLocation(start, end);
const value = cmpStr(source, end - 2, end, '*/')
? source.slice(start + 2, end - 2)
: source.slice(start + 2, end);
onComment(value, loc);
}
});
}
const ast = parser.context[context].call(parser, options);
if (!parser.eof) {
parser.error();
}
return ast;
};
return Object.assign(parse, {
SyntaxError: SyntaxError$1,
config: parser.config
});
}
const NUMBERSIGN$1 = 0x0023; // U+0023 NUMBER SIGN (#)
const ASTERISK = 0x002A; // U+002A ASTERISK (*)
const PLUSSIGN = 0x002B; // U+002B PLUS SIGN (+)
const HYPHENMINUS = 0x002D; // U+002D HYPHEN-MINUS (-)
const SOLIDUS = 0x002F; // U+002F SOLIDUS (/)
const U = 0x0075; // U+0075 LATIN SMALL LETTER U (u)
function defaultRecognizer(context) {
switch (this.tokenType) {
case Hash:
return this.Hash();
case Comma:
return this.Operator();
case LeftParenthesis:
return this.Parentheses(this.readSequence, context.recognizer);
case LeftSquareBracket:
return this.Brackets(this.readSequence, context.recognizer);
case String$1:
return this.String();
case Dimension:
return this.Dimension();
case Percentage:
return this.Percentage();
case Number$1:
return this.Number();
case Function$1:
return this.cmpStr(this.tokenStart, this.tokenEnd, 'url(')
? this.Url()
: this.Function(this.readSequence, context.recognizer);
case Url:
return this.Url();
case Ident:
// check for unicode range, it should start with u+ or U+
if (this.cmpChar(this.tokenStart, U) &&
this.cmpChar(this.tokenStart + 1, PLUSSIGN)) {
return this.UnicodeRange();
} else {
return this.Identifier();
}
case Delim: {
const code = this.charCodeAt(this.tokenStart);
if (code === SOLIDUS ||
code === ASTERISK ||
code === PLUSSIGN ||
code === HYPHENMINUS) {
return this.Operator(); // TODO: replace with Delim
}
// TODO: produce a node with Delim node type
if (code === NUMBERSIGN$1) {
this.error('Hex or identifier is expected', this.tokenStart + 1);
}
break;
}
}
}
var atrulePrelude = {
getNode: defaultRecognizer
};
const NUMBERSIGN$2 = 0x0023; // U+0023 NUMBER SIGN (#)
const AMPERSAND = 0x0026; // U+0026 AMPERSAND (&)
const ASTERISK$1 = 0x002A; // U+002A ASTERISK (*)
const PLUSSIGN$1 = 0x002B; // U+002B PLUS SIGN (+)
const SOLIDUS$1 = 0x002F; // U+002F SOLIDUS (/)
const FULLSTOP = 0x002E; // U+002E FULL STOP (.)
const GREATERTHANSIGN = 0x003E; // U+003E GREATER-THAN SIGN (>)
const VERTICALLINE = 0x007C; // U+007C VERTICAL LINE (|)
const TILDE = 0x007E; // U+007E TILDE (~)
function onWhiteSpace(next, children) {
if (children.last !== null && children.last.type !== 'Combinator' &&
next !== null && next.type !== 'Combinator') {
children.push({ // FIXME: this.Combinator() should be used instead
type: 'Combinator',
loc: null,
name: ' '
});
}
}
function getNode() {
switch (this.tokenType) {
case LeftSquareBracket:
return this.AttributeSelector();
case Hash:
return this.IdSelector();
case Colon:
if (this.lookupType(1) === Colon) {
return this.PseudoElementSelector();
} else {
return this.PseudoClassSelector();
}
case Ident:
return this.TypeSelector();
case Number$1:
case Percentage:
return this.Percentage();
case Dimension:
// throws when .123ident
if (this.charCodeAt(this.tokenStart) === FULLSTOP) {
this.error('Identifier is expected', this.tokenStart + 1);
}
break;
case Delim: {
const code = this.charCodeAt(this.tokenStart);
switch (code) {
case PLUSSIGN$1:
case GREATERTHANSIGN:
case TILDE:
case SOLIDUS$1: // /deep/
return this.Combinator();
case FULLSTOP:
return this.ClassSelector();
case ASTERISK$1:
case VERTICALLINE:
return this.TypeSelector();
case NUMBERSIGN$2:
return this.IdSelector();
case AMPERSAND:
return this.NestingSelector();
}
break;
}
}
}
var selector = {
onWhiteSpace,
getNode
};
// legacy IE function
// expression( <any-value> )
function expressionFn() {
return this.createSingleNodeList(
this.Raw(this.tokenIndex, null, false)
);
}
// var( <ident> , <value>? )
function varFn() {
const children = this.createList();
this.skipSC();
// NOTE: Don't check more than a first argument is an ident, rest checks are for lexer
children.push(this.Identifier());
this.skipSC();
if (this.tokenType === Comma) {
children.push(this.Operator());
const startIndex = this.tokenIndex;
const value = this.parseCustomProperty
? this.Value(null)
: this.Raw(this.tokenIndex, this.consumeUntilExclamationMarkOrSemicolon, false);
if (value.type === 'Value' && value.children.isEmpty) {
for (let offset = startIndex - this.tokenIndex; offset <= 0; offset++) {
if (this.lookupType(offset) === WhiteSpace) {
value.children.appendData({
type: 'WhiteSpace',
loc: null,
value: ' '
});
break;
}
}
}
children.push(value);
}
return children;
}
function isPlusMinusOperator(node) {
return (
node !== null &&
node.type === 'Operator' &&
(node.value[node.value.length - 1] === '-' || node.value[node.value.length - 1] === '+')
);
}
var value = {
getNode: defaultRecognizer,
onWhiteSpace(next, children) {
if (isPlusMinusOperator(next)) {
next.value = ' ' + next.value;
}
if (isPlusMinusOperator(children.last)) {
children.last.value += ' ';
}
},
'expression': expressionFn,
'var': varFn
};
var scope = /*#__PURE__*/Object.freeze({
__proto__: null,
AtrulePrelude: atrulePrelude,
Selector: selector,
Value: value
});
var fontFace = {
parse: {
prelude: null,
block() {
return this.Block(true);
}
}
};
var importAtrule = {
parse: {
prelude() {
const children = this.createList();
this.skipSC();
switch (this.tokenType) {
case String$1:
children.push(this.String());
break;
case Url:
case Function$1:
children.push(this.Url());
break;
default:
this.error('String or url() is expected');
}
if (this.lookupNonWSType(0) === Ident ||
this.lookupNonWSType(0) === LeftParenthesis) {
children.push(this.MediaQueryList());
}
return children;
},
block: null
}
};
var media = {
parse: {
prelude() {
return this.createSingleNodeList(
this.MediaQueryList()
);
},
block(isStyleBlock = false) {
return this.Block(isStyleBlock);
}
}
};
var nest = {
parse: {
prelude() {
return this.createSingleNodeList(
this.SelectorList()
);
},
block() {
return this.Block(true);
}
}
};
var page = {
parse: {
prelude() {
return this.createSingleNodeList(
this.SelectorList()
);
},
block() {
return this.Block(true);
}
}
};
function consumeRaw() {
return this.createSingleNodeList(
this.Raw(this.tokenIndex, null, false)
);
}
function parentheses() {
this.skipSC();
if (this.tokenType === Ident &&
this.lookupNonWSType(1) === Colon) {
return this.createSingleNodeList(
this.Declaration()
);
}
return readSequence$1.call(this);
}
function readSequence$1() {
const children = this.createList();
let child;
this.skipSC();
scan:
while (!this.eof) {
switch (this.tokenType) {
case Comment:
case WhiteSpace:
this.next();
continue;
case Function$1:
child = this.Function(consumeRaw, this.scope.AtrulePrelude);
break;
case Ident:
child = this.Identifier();
break;
case LeftParenthesis:
child = this.Parentheses(parentheses, this.scope.AtrulePrelude);
break;
default:
break scan;
}
children.push(child);
}
return children;
}
var supports = {
parse: {
prelude() {
const children = readSequence$1.call(this);
if (this.getFirstListNode(children) === null) {
this.error('Condition is expected');
}
return children;
},
block(isStyleBlock = false) {
return this.Block(isStyleBlock);
}
}
};
var atrule = {
'font-face': fontFace,
'import': importAtrule,
media,
nest,
page,
supports
};
const selectorList = {
parse() {
return this.createSingleNodeList(
this.SelectorList()
);
}
};
const selector$1 = {
parse() {
return this.createSingleNodeList(
this.Selector()
);
}
};
const identList = {
parse() {
return this.createSingleNodeList(
this.Identifier()
);
}
};
const nth = {
parse() {
return this.createSingleNodeList(
this.Nth()
);
}
};
var pseudo = {
'dir': identList,
'has': selectorList,
'lang': identList,
'matches': selectorList,
'is': selectorList,
'-moz-any': selectorList,
'-webkit-any': selectorList,
'where': selectorList,
'not': selectorList,
'nth-child': nth,
'nth-last-child': nth,
'nth-last-of-type': nth,
'nth-of-type': nth,
'slotted': selector$1,
'host': selector$1,
'host-context': selector$1
};
const PLUSSIGN$2 = 0x002B; // U+002B PLUS SIGN (+)
const HYPHENMINUS$1 = 0x002D; // U+002D HYPHEN-MINUS (-)
const N$1 = 0x006E; // U+006E LATIN SMALL LETTER N (n)
const DISALLOW_SIGN = true;
const ALLOW_SIGN = false;
function checkInteger(offset, disallowSign) {
let pos = this.tokenStart + offset;
const code = this.charCodeAt(pos);
if (code === PLUSSIGN$2 || code === HYPHENMINUS$1) {
if (disallowSign) {
this.error('Number sign is not allowed');
}
pos++;
}
for (; pos < this.tokenEnd; pos++) {
if (!isDigit(this.charCodeAt(pos))) {
this.error('Integer is expected', pos);
}
}
}
function checkTokenIsInteger(disallowSign) {
return checkInteger.call(this, 0, disallowSign);
}
function expectCharCode(offset, code) {
if (!this.cmpChar(this.tokenStart + offset, code)) {
let msg = '';
switch (code) {
case N$1:
msg = 'N is expected';
break;
case HYPHENMINUS$1:
msg = 'HyphenMinus is expected';
break;
}
this.error(msg, this.tokenStart + offset);
}
}
// ... <signed-integer>
// ... ['+' | '-'] <signless-integer>
function consumeB() {
let offset = 0;
let sign = 0;
let type = this.tokenType;
while (type === WhiteSpace || type === Comment) {
type = this.lookupType(++offset);
}
if (type !== Number$1) {
if (this.isDelim(PLUSSIGN$2, offset) ||
this.isDelim(HYPHENMINUS$1, offset)) {
sign = this.isDelim(PLUSSIGN$2, offset) ? PLUSSIGN$2 : HYPHENMINUS$1;
do {
type = this.lookupType(++offset);
} while (type === WhiteSpace || type === Comment);
if (type !== Number$1) {
this.skip(offset);
checkTokenIsInteger.call(this, DISALLOW_SIGN);
}
} else {
return null;
}
}
if (offset > 0) {
this.skip(offset);
}
if (sign === 0) {
type = this.charCodeAt(this.tokenStart);
if (type !== PLUSSIGN$2 && type !== HYPHENMINUS$1) {
this.error('Number sign is expected');
}
}
checkTokenIsInteger.call(this, sign !== 0);
return sign === HYPHENMINUS$1 ? '-' + this.consume(Number$1) : this.consume(Number$1);
}
function parse$3() {
/* eslint-disable brace-style*/
const start = this.tokenStart;
let a = null;
let b = null;
// <integer>
if (this.tokenType === Number$1) {
checkTokenIsInteger.call(this, ALLOW_SIGN);
b = this.consume(Number$1);
}
// -n
// -n <signed-integer>
// -n ['+' | '-'] <signless-integer>
// -n- <signless-integer>
// <dashndashdigit-ident>
else if (this.tokenType === Ident && this.cmpChar(this.tokenStart, HYPHENMINUS$1)) {
a = '-1';
expectCharCode.call(this, 1, N$1);
switch (this.tokenEnd - this.tokenStart) {
// -n
// -n <signed-integer>
// -n ['+' | '-'] <signless-integer>
case 2:
this.next();
b = consumeB.call(this);
break;
// -n- <signless-integer>
case 3:
expectCharCode.call(this, 2, HYPHENMINUS$1);
this.next();
this.skipSC();
checkTokenIsInteger.call(this, DISALLOW_SIGN);
b = '-' + this.consume(Number$1);
break;
// <dashndashdigit-ident>
default:
expectCharCode.call(this, 2, HYPHENMINUS$1);
checkInteger.call(this, 3, DISALLOW_SIGN);
this.next();
b = this.substrToCursor(start + 2);
}
}
// '+'? n
// '+'? n <signed-integer>
// '+'? n ['+' | '-'] <signless-integer>
// '+'? n- <signless-integer>
// '+'? <ndashdigit-ident>
else if (this.tokenType === Ident || (this.isDelim(PLUSSIGN$2) && this.lookupType(1) === Ident)) {
let sign = 0;
a = '1';
// just ignore a plus
if (this.isDelim(PLUSSIGN$2)) {
sign = 1;
this.next();
}
expectCharCode.call(this, 0, N$1);
switch (this.tokenEnd - this.tokenStart) {
// '+'? n
// '+'? n <signed-integer>
// '+'? n ['+' | '-'] <signless-integer>
case 1:
this.next();
b = consumeB.call(this);
break;
// '+'? n- <signless-integer>
case 2:
expectCharCode.call(this, 1, HYPHENMINUS$1);
this.next();
this.skipSC();
checkTokenIsInteger.call(this, DISALLOW_SIGN);
b = '-' + this.consume(Number$1);
break;
// '+'? <ndashdigit-ident>
default:
expectCharCode.call(this, 1, HYPHENMINUS$1);
checkInteger.call(this, 2, DISALLOW_SIGN);
this.next();
b = this.substrToCursor(start + sign + 1);
}
}
// <ndashdigit-dimension>
// <ndash-dimension> <signless-integer>
// <n-dimension>
// <n-dimension> <signed-integer>
// <n-dimension> ['+' | '-'] <signless-integer>
else if (this.tokenType === Dimension) {
const code = this.charCodeAt(this.tokenStart);
const sign = code === PLUSSIGN$2 || code === HYPHENMINUS$1;
let i = this.tokenStart + sign;
for (; i < this.tokenEnd; i++) {
if (!isDigit(this.charCodeAt(i))) {
break;
}
}
if (i === this.tokenStart + sign) {
this.error('Integer is expected', this.tokenStart + sign);
}
expectCharCode.call(this, i - this.tokenStart, N$1);
a = this.substring(start, i);
// <n-dimension>
// <n-dimension> <signed-integer>
// <n-dimension> ['+' | '-'] <signless-integer>
if (i + 1 === this.tokenEnd) {
this.next();
b = consumeB.call(this);
} else {
expectCharCode.call(this, i - this.tokenStart + 1, HYPHENMINUS$1);
// <ndash-dimension> <signless-integer>
if (i + 2 === this.tokenEnd) {
this.next();
this.skipSC();
checkTokenIsInteger.call(this, DISALLOW_SIGN);
b = '-' + this.consume(Number$1);
}
// <ndashdigit-dimension>
else {
checkInteger.call(this, i - this.tokenStart + 2, DISALLOW_SIGN);
this.next();
b = this.substrToCursor(i + 1);
}
}
} else {
this.error();
}
if (a !== null && a.charCodeAt(0) === PLUSSIGN$2) {
a = a.substr(1);
}
if (b !== null && b.charCodeAt(0) === PLUSSIGN$2) {
b = b.substr(1);
}
return {
type: 'AnPlusB',
loc: this.getLocation(start, this.tokenStart),
a,
b
};
}
function consumeRaw$1(startToken) {
return this.Raw(startToken, this.consumeUntilLeftCurlyBracketOrSemicolon, true);
}
function isDeclarationBlockAtrule() {
for (let offset = 1, type; type = this.lookupType(offset); offset++) {
if (type === RightCurlyBracket) {
return true;
}
if (type === LeftCurlyBracket ||
type === AtKeyword) {
return false;
}
}
return false;
}
function parse$4(isDeclaration = false) {
const start = this.tokenStart;
let name;
let nameLowerCase;
let prelude = null;
let block = null;
this.eat(AtKeyword);
name = this.substrToCursor(start + 1);
nameLowerCase = name.toLowerCase();
this.skipSC();
// parse prelude
if (this.eof === false &&
this.tokenType !== LeftCurlyBracket &&
this.tokenType !== Semicolon) {
if (this.parseAtrulePrelude) {
prelude = this.parseWithFallback(this.AtrulePrelude.bind(this, name, isDeclaration), consumeRaw$1);
} else {
prelude = consumeRaw$1.call(this, this.tokenIndex);
}
this.skipSC();
}
switch (this.tokenType) {
case Semicolon:
this.next();
break;
case LeftCurlyBracket:
if (hasOwnProperty.call(this.atrule, nameLowerCase) &&
typeof this.atrule[nameLowerCase].block === 'function') {
block = this.atrule[nameLowerCase].block.call(this, isDeclaration);
} else {
// TODO: should consume block content as Raw?
block = this.Block(isDeclarationBlockAtrule.call(this));
}
break;
}
return {
type: 'Atrule',
loc: this.getLocation(start, this.tokenStart),
name,
prelude,
block
};
}
function parse$5(name) {
let children = null;
if (name !== null) {
name = name.toLowerCase();
}
this.skipSC();
if (hasOwnProperty.call(this.atrule, name) &&
typeof this.atrule[name].prelude === 'function') {
// custom consumer
children = this.atrule[name].prelude.call(this);
} else {
// default consumer
children = this.readSequence(this.scope.AtrulePrelude);
}
this.skipSC();
if (this.eof !== true &&
this.tokenType !== LeftCurlyBracket &&
this.tokenType !== Semicolon) {
this.error('Semicolon or block is expected');
}
return {
type: 'AtrulePrelude',
loc: this.getLocationFromList(children),
children
};
}
const DOLLARSIGN = 0x0024; // U+0024 DOLLAR SIGN ($)
const ASTERISK$2 = 0x002A; // U+002A ASTERISK (*)
const EQUALSSIGN = 0x003D; // U+003D EQUALS SIGN (=)
const CIRCUMFLEXACCENT = 0x005E; // U+005E (^)
const VERTICALLINE$1 = 0x007C; // U+007C VERTICAL LINE (|)
const TILDE$1 = 0x007E; // U+007E TILDE (~)
function getAttributeName() {
if (this.eof) {
this.error('Unexpected end of input');
}
const start = this.tokenStart;
let expectIdent = false;
if (this.isDelim(ASTERISK$2)) {
expectIdent = true;
this.next();
} else if (!this.isDelim(VERTICALLINE$1)) {
this.eat(Ident);
}
if (this.isDelim(VERTICALLINE$1)) {
if (this.charCodeAt(this.tokenStart + 1) !== EQUALSSIGN) {
this.next();
this.eat(Ident);
} else if (expectIdent) {
this.error('Identifier is expected', this.tokenEnd);
}
} else if (expectIdent) {
this.error('Vertical line is expected');
}
return {
type: 'Identifier',
loc: this.getLocation(start, this.tokenStart),
name: this.substrToCursor(start)
};
}
function getOperator() {
const start = this.tokenStart;
const code = this.charCodeAt(start);
if (code !== EQUALSSIGN && // =
code !== TILDE$1 && // ~=
code !== CIRCUMFLEXACCENT && // ^=
code !== DOLLARSIGN && // $=
code !== ASTERISK$2 && // *=
code !== VERTICALLINE$1 // |=
) {
this.error('Attribute selector (=, ~=, ^=, $=, *=, |=) is expected');
}
this.next();
if (code !== EQUALSSIGN) {
if (!this.isDelim(EQUALSSIGN)) {
this.error('Equal sign is expected');
}
this.next();
}
return this.substrToCursor(start);
}
function parse$6() {
const start = this.tokenStart;
let name;
let matcher = null;
let value = null;
let flags = null;
this.eat(LeftSquareBracket);
this.skipSC();
name = getAttributeName.call(this);
this.skipSC();
if (this.tokenType !== RightSquareBracket) {
// avoid case `[name i]`
if (this.tokenType !== Ident) {
matcher = getOperator.call(this);
this.skipSC();
value = this.tokenType === String$1
? this.String()
: this.Identifier();
this.skipSC();
}
// attribute flags
if (this.tokenType === Ident) {
flags = this.consume(Ident);
this.skipSC();
}
}
this.eat(RightSquareBracket);
return {
type: 'AttributeSelector',
loc: this.getLocation(start, this.tokenStart),
name,
matcher,
value,
flags
};
}
const AMPERSAND$1 = 0x0026; // U+0026 AMPERSAND (&)
function consumeRaw$2(startToken) {
return this.Raw(startToken, null, true);
}
function consumeRule() {
return this.parseWithFallback(this.Rule, consumeRaw$2);
}
function consumeRawDeclaration(startToken) {
return this.Raw(startToken, this.consumeUntilSemicolonIncluded, true);
}
function consumeDeclaration() {
if (this.tokenType === Semicolon) {
return consumeRawDeclaration.call(this, this.tokenIndex);
}
const node = this.parseWithFallback(this.Declaration, consumeRawDeclaration);
if (this.tokenType === Semicolon) {
this.next();
}
return node;
}
function parse$7(isStyleBlock) {
const consumer = isStyleBlock ? consumeDeclaration : consumeRule;
const start = this.tokenStart;
let children = this.createList();
this.eat(LeftCurlyBracket);
scan:
while (!this.eof) {
switch (this.tokenType) {
case RightCurlyBracket:
break scan;
case WhiteSpace:
case Comment:
this.next();
break;
case AtKeyword:
children.push(this.parseWithFallback(this.Atrule.bind(this, isStyleBlock), consumeRaw$2));
break;
default:
if (isStyleBlock && this.isDelim(AMPERSAND$1)) {
children.push(consumeRule.call(this));
} else {
children.push(consumer.call(this));
}
}
}
if (!this.eof) {
this.eat(RightCurlyBracket);
}
return {
type: 'Block',
loc: this.getLocation(start, this.tokenStart),
children
};
}
function parse$8(readSequence, recognizer) {
const start = this.tokenStart;
let children = null;
this.eat(LeftSquareBracket);
children = readSequence.call(this, recognizer);
if (!this.eof) {
this.eat(RightSquareBracket);
}
return {
type: 'Brackets',
loc: this.getLocation(start, this.tokenStart),
children
};
}
function parse$9() {
const start = this.tokenStart;
this.eat(CDC); // -->
return {
type: 'CDC',
loc: this.getLocation(start, this.tokenStart)
};
}
function parse$a() {
const start = this.tokenStart;
this.eat(CDO); // <!--
return {
type: 'CDO',
loc: this.getLocation(start, this.tokenStart)
};
}
const FULLSTOP$1 = 0x002E; // U+002E FULL STOP (.)
function parse$b() {
this.eatDelim(FULLSTOP$1);
return {
type: 'ClassSelector',
loc: this.getLocation(this.tokenStart - 1, this.tokenEnd),
name: this.consume(Ident)
};
}
const PLUSSIGN$3 = 0x002B; // U+002B PLUS SIGN (+)
const SOLIDUS$2 = 0x002F; // U+002F SOLIDUS (/)
const GREATERTHANSIGN$1 = 0x003E; // U+003E GREATER-THAN SIGN (>)
const TILDE$2 = 0x007E; // U+007E TILDE (~)
// + | > | ~ | /deep/
function parse$c() {
const start = this.tokenStart;
let name;
switch (this.tokenType) {
case WhiteSpace:
name = ' ';
break;
case Delim:
switch (this.charCodeAt(this.tokenStart)) {
case GREATERTHANSIGN$1:
case PLUSSIGN$3:
case TILDE$2:
this.next();
break;
case SOLIDUS$2:
this.next();
this.eatIdent('deep');
this.eatDelim(SOLIDUS$2);
break;
default:
this.error('Combinator is expected');
}
name = this.substrToCursor(start);
break;
}
return {
type: 'Combinator',
loc: this.getLocation(start, this.tokenStart),
name
};
}
const ASTERISK$3 = 0x002A; // U+002A ASTERISK (*)
const SOLIDUS$3 = 0x002F; // U+002F SOLIDUS (/)
function parse$d() {
const start = this.tokenStart;
let end = this.tokenEnd;
this.eat(Comment);
if ((end - start + 2) >= 2 &&
this.charCodeAt(end - 2) === ASTERISK$3 &&
this.charCodeAt(end - 1) === SOLIDUS$3) {
end -= 2;
}
return {
type: 'Comment',
loc: this.getLocation(start, this.tokenStart),
value: this.substring(start + 2, end)
};
}
const HYPHENMINUS$2 = 45; // '-'.charCodeAt()
function isCustomProperty(str, offset) {
offset = offset || 0;
return str.length - offset >= 2 &&
str.charCodeAt(offset) === HYPHENMINUS$2 &&
str.charCodeAt(offset + 1) === HYPHENMINUS$2;
}
const EXCLAMATIONMARK$1 = 0x0021; // U+0021 EXCLAMATION MARK (!)
const NUMBERSIGN$3 = 0x0023; // U+0023 NUMBER SIGN (#)
const DOLLARSIGN$1 = 0x0024; // U+0024 DOLLAR SIGN ($)
const AMPERSAND$2 = 0x0026; // U+0026 AMPERSAND (&)
const ASTERISK$4 = 0x002A; // U+002A ASTERISK (*)
const PLUSSIGN$4 = 0x002B; // U+002B PLUS SIGN (+)
const SOLIDUS$4 = 0x002F; // U+002F SOLIDUS (/)
function consumeValueRaw(startToken) {
return this.Raw(startToken, this.consumeUntilExclamationMarkOrSemicolon, true);
}
function consumeCustomPropertyRaw(startToken) {
return this.Raw(startToken, this.consumeUntilExclamationMarkOrSemicolon, false);
}
function consumeValue() {
const startValueToken = this.tokenIndex;
const value = this.Value();
if (value.type !== 'Raw' &&
this.eof === false &&
this.tokenType !== Semicolon &&
this.isDelim(EXCLAMATIONMARK$1) === false &&
this.isBalanceEdge(startValueToken) === false) {
this.error();
}
return value;
}
function parse$e() {
const start = this.tokenStart;
const startToken = this.tokenIndex;
const property = readProperty.call(this);
const customProperty = isCustomProperty(property);
const parseValue = customProperty ? this.parseCustomProperty : this.parseValue;
const consumeRaw = customProperty ? consumeCustomPropertyRaw : consumeValueRaw;
let important = false;
let value;
this.skipSC();
this.eat(Colon);
const valueStart = this.tokenIndex;
if (!customProperty) {
this.skipSC();
}
if (parseValue) {
value = this.parseWithFallback(consumeValue, consumeRaw);
} else {
value = consumeRaw.call(this, this.tokenIndex);
}
if (customProperty && value.type === 'Value' && value.children.isEmpty) {
for (let offset = valueStart - this.tokenIndex; offset <= 0; offset++) {
if (this.lookupType(offset) === WhiteSpace) {
value.children.appendData({
type: 'WhiteSpace',
loc: null,
value: ' '
});
break;
}
}
}
if (this.isDelim(EXCLAMATIONMARK$1)) {
important = getImportant.call(this);
this.skipSC();
}
// Do not include semicolon to range per spec
// https://drafts.csswg.org/css-syntax/#declaration-diagram
if (this.eof === false &&
this.tokenType !== Semicolon &&
this.isBalanceEdge(startToken) === false) {
this.error();
}
return {
type: 'Declaration',
loc: this.getLocation(start, this.tokenStart),
important,
property,
value
};
}
function readProperty() {
const start = this.tokenStart;
// hacks
if (this.tokenType === Delim) {
switch (this.charCodeAt(this.tokenStart)) {
case ASTERISK$4:
case DOLLARSIGN$1:
case PLUSSIGN$4:
case NUMBERSIGN$3:
case AMPERSAND$2:
this.next();
break;
// TODO: not sure we should support this hack
case SOLIDUS$4:
this.next();
if (this.isDelim(SOLIDUS$4)) {
this.next();
}
break;
}
}
if (this.tokenType === Hash) {
this.eat(Hash);
} else {
this.eat(Ident);
}
return this.substrToCursor(start);
}
// ! ws* important
function getImportant() {
this.eat(Delim);
this.skipSC();
const important = this.consume(Ident);
// store original value in case it differ from `important`
// for better original source restoring and hacks like `!ie` support
return important === 'important' ? true : important;
}
const AMPERSAND$3 = 0x0026; // U+0026 AMPERSAND (&)
function consumeRaw$3(startToken) {
return this.Raw(startToken, this.consumeUntilSemicolonIncluded, true);
}
function parse$f() {
const children = this.createList();
while (!this.eof) {
switch (this.tokenType) {
case WhiteSpace:
case Comment:
case Semicolon:
this.next();
break;
case AtKeyword:
children.push(this.parseWithFallback(this.Atrule.bind(this, true), consumeRaw$3));
break;
default:
if (this.isDelim(AMPERSAND$3)) {
children.push(this.parseWithFallback(this.Rule, consumeRaw$3));
} else {
children.push(this.parseWithFallback(this.Declaration, consumeRaw$3));
}
}
}
return {
type: 'DeclarationList',
loc: this.getLocationFromList(children),
children
};
}
function parse$g() {
const start = this.tokenStart;
const value = this.consumeNumber(Dimension);
return {
type: 'Dimension',
loc: this.getLocation(start, this.tokenStart),
value,
unit: this.substring(start + value.length, this.tokenStart)
};
}
// <function-token> <sequence> )
function parse$h(readSequence, recognizer) {
const start = this.tokenStart;
const name = this.consumeFunctionName();
const nameLowerCase = name.toLowerCase();
let children;
children = recognizer.hasOwnProperty(nameLowerCase)
? recognizer[nameLowerCase].call(this, recognizer)
: readSequence.call(this, recognizer);
if (!this.eof) {
this.eat(RightParenthesis);
}
return {
type: 'Function',
loc: this.getLocation(start, this.tokenStart),
name,
children
};
}
function parse$i() {
const start = this.tokenStart;
this.eat(Hash);
return {
type: 'Hash',
loc: this.getLocation(start, this.tokenStart),
value: this.substrToCursor(start + 1)
};
}
function parse$j() {
return {
type: 'Identifier',
loc: this.getLocation(this.tokenStart, this.tokenEnd),
name: this.consume(Ident)
};
}
function parse$k() {
const start = this.tokenStart;
// TODO: check value is an ident
this.eat(Hash);
return {
type: 'IdSelector',
loc: this.getLocation(start, this.tokenStart),
name: this.substrToCursor(start + 1)
};
}
function parse$l() {
const start = this.tokenStart;
let name;
let value = null;
this.eat(LeftParenthesis);
this.skipSC();
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 Ident:
value = this.Identifier();
break;
default:
this.error('Number, dimension, ratio or identifier is expected');
}
this.skipSC();
}
this.eat(RightParenthesis);
return {
type: 'MediaFeature',
loc: this.getLocation(start, this.tokenStart),
name,
value
};
}
function parse$m() {
const children = this.createList();
let child = null;
this.skipSC();
scan:
while (!this.eof) {
switch (this.tokenType) {
case Comment:
case WhiteSpace:
this.next();
continue;
case Ident:
child = this.Identifier();
break;
case LeftParenthesis:
child = this.MediaFeature();
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 parse$n() {
const children = this.createList();
this.skipSC();
while (!this.eof) {
children.push(this.MediaQuery());
if (this.tokenType !== Comma) {
break;
}
this.next();
}
return {
type: 'MediaQueryList',
loc: this.getLocationFromList(children),
children
};
}
const AMPERSAND$4 = 0x0026; // U+0026 AMPERSAND (&)
function parse$o() {
const start = this.tokenStart;
this.eatDelim(AMPERSAND$4);
return {
type: 'NestingSelector',
loc: this.getLocation(start, this.tokenStart)
};
}
function parse$p() {
this.skipSC();
const start = this.tokenStart;
let end = start;
let selector = null;
let nth;
if (this.lookupValue(0, 'odd') || this.lookupValue(0, 'even')) {
nth = this.Identifier();
} else {
nth = this.AnPlusB();
}
end = this.tokenStart;
this.skipSC();
if (this.lookupValue(0, 'of')) {
this.next();
selector = this.SelectorList();
end = this.tokenStart;
}
return {
type: 'Nth',
loc: this.getLocation(start, end),
nth,
selector
};
}
function parse$q() {
return {
type: 'Number',
loc: this.getLocation(this.tokenStart, this.tokenEnd),
value: this.consume(Number$1)
};
}
// '/' | '*' | ',' | ':' | '+' | '-'
function parse$r() {
const start = this.tokenStart;
this.next();
return {
type: 'Operator',
loc: this.getLocation(start, this.tokenStart),
value: this.substrToCursor(start)
};
}
function parse$s(readSequence, recognizer) {
const start = this.tokenStart;
let children = null;
this.eat(LeftParenthesis);
children = readSequence.call(this, recognizer);
if (!this.eof) {
this.eat(RightParenthesis);
}
return {
type: 'Parentheses',
loc: this.getLocation(start, this.tokenStart),
children
};
}
function parse$t() {
return {
type: 'Percentage',
loc: this.getLocation(this.tokenStart, this.tokenEnd),
value: this.consumeNumber(Percentage)
};
}
// : [ <ident> | <function-token> <any-value>? ) ]
function parse$u() {
const start = this.tokenStart;
let children = null;
let name;
let nameLowerCase;
this.eat(Colon);
if (this.tokenType === Function$1) {
name = this.consumeFunctionName();
nameLowerCase = name.toLowerCase();
if (hasOwnProperty.call(this.pseudo, nameLowerCase)) {
this.skipSC();
children = this.pseudo[nameLowerCase].call(this);
this.skipSC();
} else {
children = this.createList();
children.push(
this.Raw(this.tokenIndex, null, false)
);
}
this.eat(RightParenthesis);
} else {
name = this.consume(Ident);
}
return {
type: 'PseudoClassSelector',
loc: this.getLocation(start, this.tokenStart),
name,
children
};
}
// :: [ <ident> | <function-token> <any-value>? ) ]
function parse$v() {
const start = this.tokenStart;
let children = null;
let name;
let nameLowerCase;
this.eat(Colon);
this.eat(Colon);
if (this.tokenType === Function$1) {
name = this.consumeFunctionName();
nameLowerCase = name.toLowerCase();
if (hasOwnProperty.call(this.pseudo, nameLowerCase)) {
this.skipSC();
children = this.pseudo[nameLowerCase].call(this);
this.skipSC();
} else {
children = this.createList();
children.push(
this.Raw(this.tokenIndex, null, false)
);
}
this.eat(RightParenthesis);
} else {
name = this.consume(Ident);
}
return {
type: 'PseudoElementSelector',
loc: this.getLocation(start, this.tokenStart),
name,
children
};
}
const SOLIDUS$5 = 0x002F; // U+002F SOLIDUS (/)
const FULLSTOP$2 = 0x002E; // U+002E FULL STOP (.)
// Terms of <ratio> should be a positive numbers (not zero or negative)
// (see https://drafts.csswg.org/mediaqueries-3/#values)
// However, -o-min-device-pixel-ratio takes fractional values as a ratio's term
// and this is using by various sites. Therefore we relax checking on parse
// to test a term is unsigned number without an exponent part.
// Additional checking may be applied on lexer validation.
function consumeNumber$1() {
this.skipSC();
const value = this.consume(Number$1);
for (let i = 0; i < value.length; i++) {
const code = value.charCodeAt(i);
if (!isDigit(code) && code !== FULLSTOP$2) {
this.error('Unsigned number is expected', this.tokenStart - value.length + i);
}
}
if (Number(value) === 0) {
this.error('Zero number is not allowed', this.tokenStart - value.length);
}
return value;
}
// <positive-integer> S* '/' S* <positive-integer>
function parse$w() {
const start = this.tokenStart;
const left = consumeNumber$1.call(this);
let right;
this.skipSC();
this.eatDelim(SOLIDUS$5);
right = consumeNumber$1.call(this);
return {
type: 'Ratio',
loc: this.getLocation(start, this.tokenStart),
left,
right
};
}
function getOffsetExcludeWS() {
if (this.tokenIndex > 0) {
if (this.lookupType(-1) === WhiteSpace) {
return this.tokenIndex > 1
? this.getTokenStart(this.tokenIndex - 1)
: this.firstCharOffset;
}
}
return this.tokenStart;
}
function parse$x(startToken, consumeUntil, excludeWhiteSpace) {
const startOffset = this.getTokenStart(startToken);
let endOffset;
this.skipUntilBalanced(startToken, consumeUntil || this.consumeUntilBalanceEnd);
if (excludeWhiteSpace && this.tokenStart > startOffset) {
endOffset = getOffsetExcludeWS.call(this);
} else {
endOffset = this.tokenStart;
}
return {
type: 'Raw',
loc: this.getLocation(startOffset, endOffset),
value: this.substring(startOffset, endOffset)
};
}
function consumeRaw$4(startToken) {
return this.Raw(startToken, this.consumeUntilLeftCurlyBracket, true);
}
function consumePrelude() {
const prelude = this.SelectorList();
if (prelude.type !== 'Raw' &&
this.eof === false &&
this.tokenType !== LeftCurlyBracket) {
this.error();
}
return prelude;
}
function parse$y() {
const startToken = this.tokenIndex;
const startOffset = this.tokenStart;
let prelude;
let block;
if (this.parseRulePrelude) {
prelude = this.parseWithFallback(consumePrelude, consumeRaw$4);
} else {
prelude = consumeRaw$4.call(this, startToken);
}
block = this.Block(true);
return {
type: 'Rule',
loc: this.getLocation(startOffset, this.tokenStart),
prelude,
block
};
}
function parse$z() {
const children = this.readSequence(this.scope.Selector);
// nothing were consumed
if (this.getFirstListNode(children) === null) {
this.error('Selector is expected');
}
return {
type: 'Selector',
loc: this.getLocationFromList(children),
children
};
}
function parse$A() {
const children = this.createList();
while (!this.eof) {
children.push(this.Selector());
if (this.tokenType === Comma) {
this.next();
continue;
}
break;
}
return {
type: 'SelectorList',
loc: this.getLocationFromList(children),
children
};
}
const REVERSE_SOLIDUS = 0x005c; // U+005C REVERSE SOLIDUS (\)
const QUOTATION_MARK = 0x0022; // "
const APOSTROPHE = 0x0027; // '
function decode$1(str) {
const len = str.length;
const firstChar = str.charCodeAt(0);
const start = firstChar === QUOTATION_MARK || firstChar === APOSTROPHE ? 1 : 0;
const end = start === 1 && len > 1 && str.charCodeAt(len - 1) === firstChar ? len - 2 : len - 1;
let decoded = '';
for (let i = start; i <= end; i++) {
let code = str.charCodeAt(i);
if (code === REVERSE_SOLIDUS) {
// special case at the ending
if (i === end) {
// if the next input code point is EOF, do nothing
// otherwise include last quote as escaped
if (i !== len - 1) {
decoded = str.substr(i + 1);
}
break;
}
code = str.charCodeAt(++i);
// consume escaped
if (isValidEscape(REVERSE_SOLIDUS, code)) {
const escapeStart = i - 1;
const escapeEnd = consumeEscaped(str, escapeStart);
i = escapeEnd - 1;
decoded += decodeEscaped(str.substring(escapeStart + 1, escapeEnd));
} else {
// \r\n
if (code === 0x000d && str.charCodeAt(i + 1) === 0x000a) {
i++;
}
}
} else {
decoded += str[i];
}
}
return decoded;
}
function parse$B() {
return {
type: 'String',
loc: this.getLocation(this.tokenStart, this.tokenEnd),
value: decode$1(this.consume(String$1))
};
}
const EXCLAMATIONMARK$2 = 0x0021; // U+0021 EXCLAMATION MARK (!)
function consumeRaw$5(startToken) {
return this.Raw(startToken, null, false);
}
function parse$C() {
const start = this.tokenStart;
const children = this.createList();
let child;
while (!this.eof) {
switch (this.tokenType) {
case WhiteSpace:
this.next();
continue;
case Comment:
// ignore comments except exclamation comments (i.e. /*! .. */) on top level
if (this.charCodeAt(this.tokenStart + 2) !== EXCLAMATIONMARK$2) {
this.next();
continue;
}
child = this.Comment();
break;
case CDO: // <!--
child = this.CDO();
break;
case CDC: // -->
child = this.CDC();
break;
// CSS Syntax Module Level 3
// §2.2 Error handling
// At the "top level" of a stylesheet, an <at-keyword-token> starts an at-rule.
case AtKeyword:
child = this.parseWithFallback(this.Atrule, consumeRaw$5);
break;
// Anything else starts a qualified rule ...
default:
child = this.parseWithFallback(this.Rule, consumeRaw$5);
}
children.push(child);
}
return {
type: 'StyleSheet',
loc: this.getLocation(start, this.tokenStart),
children
};
}
const ASTERISK$5 = 0x002A; // U+002A ASTERISK (*)
const VERTICALLINE$2 = 0x007C; // U+007C VERTICAL LINE (|)
function eatIdentifierOrAsterisk() {
if (this.tokenType !== Ident &&
this.isDelim(ASTERISK$5) === false) {
this.error('Identifier or asterisk is expected');
}
this.next();
}
// ident
// ident|ident
// ident|*
// *
// *|ident
// *|*
// |ident
// |*
function parse$D() {
const start = this.tokenStart;
if (this.isDelim(VERTICALLINE$2)) {
this.next();
eatIdentifierOrAsterisk.call(this);
} else {
eatIdentifierOrAsterisk.call(this);
if (this.isDelim(VERTICALLINE$2)) {
this.next();
eatIdentifierOrAsterisk.call(this);
}
}
return {
type: 'TypeSelector',
loc: this.getLocation(start, this.tokenStart),
name: this.substrToCursor(start)
};
}
const PLUSSIGN$5 = 0x002B; // U+002B PLUS SIGN (+)
const HYPHENMINUS$3 = 0x002D; // U+002D HYPHEN-MINUS (-)
const QUESTIONMARK = 0x003F; // U+003F QUESTION MARK (?)
function eatHexSequence(offset, allowDash) {
let len = 0;
for (let pos = this.tokenStart + offset; pos < this.tokenEnd; pos++) {
const code = this.charCodeAt(pos);
if (code === HYPHENMINUS$3 && allowDash && len !== 0) {
eatHexSequence.call(this, offset + len + 1, false);
return -1;
}
if (!isHexDigit$1(code)) {
this.error(
allowDash && len !== 0
? 'Hyphen minus' + (len < 6 ? ' or hex digit' : '') + ' is expected'
: (len < 6 ? 'Hex digit is expected' : 'Unexpected input'),
pos
);
}
if (++len > 6) {
this.error('Too many hex digits', pos);
} }
this.next();
return len;
}
function eatQuestionMarkSequence(max) {
let count = 0;
while (this.isDelim(QUESTIONMARK)) {
if (++count > max) {
this.error('Too many question marks');
}
this.next();
}
}
function startsWith(code) {
if (this.charCodeAt(this.tokenStart) !== code) {
this.error((code === PLUSSIGN$5 ? 'Plus sign' : 'Hyphen minus') + ' is expected');
}
}
// https://drafts.csswg.org/css-syntax/#urange
// Informally, the <urange> production has three forms:
// U+0001
// Defines a range consisting of a single code point, in this case the code point "1".
// U+0001-00ff
// Defines a range of codepoints between the first and the second value, in this case
// the range between "1" and "ff" (255 in decimal) inclusive.
// U+00??
// Defines a range of codepoints where the "?" characters range over all hex digits,
// in this case defining the same as the value U+0000-00ff.
// In each form, a maximum of 6 digits is allowed for each hexadecimal number (if you treat "?" as a hexadecimal digit).
//
// <urange> =
// u '+' <ident-token> '?'* |
// u <dimension-token> '?'* |
// u <number-token> '?'* |
// u <number-token> <dimension-token> |
// u <number-token> <number-token> |
// u '+' '?'+
function scanUnicodeRange() {
let hexLength = 0;
switch (this.tokenType) {
case Number$1:
// u <number-token> '?'*
// u <number-token> <dimension-token>
// u <number-token> <number-token>
hexLength = eatHexSequence.call(this, 1, true);
if (this.isDelim(QUESTIONMARK)) {
eatQuestionMarkSequence.call(this, 6 - hexLength);
break;
}
if (this.tokenType === Dimension ||
this.tokenType === Number$1) {
startsWith.call(this, HYPHENMINUS$3);
eatHexSequence.call(this, 1, false);
break;
}
break;
case Dimension:
// u <dimension-token> '?'*
hexLength = eatHexSequence.call(this, 1, true);
if (hexLength > 0) {
eatQuestionMarkSequence.call(this, 6 - hexLength);
}
break;
default:
// u '+' <ident-token> '?'*
// u '+' '?'+
this.eatDelim(PLUSSIGN$5);
if (this.tokenType === Ident) {
hexLength = eatHexSequence.call(this, 0, true);
if (hexLength > 0) {
eatQuestionMarkSequence.call(this, 6 - hexLength);
}
break;
}
if (this.isDelim(QUESTIONMARK)) {
this.next();
eatQuestionMarkSequence.call(this, 5);
break;
}
this.error('Hex digit or question mark is expected');
}
}
function parse$E() {
const start = this.tokenStart;
// U or u
this.eatIdent('u');
scanUnicodeRange.call(this);
return {
type: 'UnicodeRange',
loc: this.getLocation(start, this.tokenStart),
value: this.substrToCursor(start)
};
}
const REVERSE_SOLIDUS$1 = 0x005c; // U+005C REVERSE SOLIDUS (\)
const RIGHTPARENTHESIS = 0x0029; // U+0029 RIGHT PARENTHESIS ())
function decode$2(str) {
const len = str.length;
let start = 4; // length of "url("
let end = str.charCodeAt(len - 1) === RIGHTPARENTHESIS ? len - 2 : len - 1;
let decoded = '';
while (start < end && isWhiteSpace(str.charCodeAt(start))) {
start++;
}
while (start < end && isWhiteSpace(str.charCodeAt(end))) {
end--;
}
for (let i = start; i <= end; i++) {
let code = str.charCodeAt(i);
if (code === REVERSE_SOLIDUS$1) {
// special case at the ending
if (i === end) {
// if the next input code point is EOF, do nothing
// otherwise include last left parenthesis as escaped
if (i !== len - 1) {
decoded = str.substr(i + 1);
}
break;
}
code = str.charCodeAt(++i);
// consume escaped
if (isValidEscape(REVERSE_SOLIDUS$1, code)) {
const escapeStart = i - 1;
const escapeEnd = consumeEscaped(str, escapeStart);
i = escapeEnd - 1;
decoded += decodeEscaped(str.substring(escapeStart + 1, escapeEnd));
} else {
// \r\n
if (code === 0x000d && str.charCodeAt(i + 1) === 0x000a) {
i++;
}
}
} else {
decoded += str[i];
}
}
return decoded;
}
// <url-token> | <function-token> <string> )
function parse$F() {
const start = this.tokenStart;
let value;
switch (this.tokenType) {
case Url:
value = decode$2(this.consume(Url));
break;
case Function$1:
if (!this.cmpStr(this.tokenStart, this.tokenEnd, 'url(')) {
this.error('Function name must be `url`');
}
this.eat(Function$1);
this.skipSC();
value = decode$1(this.consume(String$1));
this.skipSC();
if (!this.eof) {
this.eat(RightParenthesis);
}
break;
default:
this.error('Url or Function is expected');
}
return {
type: 'Url',
loc: this.getLocation(start, this.tokenStart),
value
};
}
function parse$G() {
const start = this.tokenStart;
const children = this.readSequence(this.scope.Value);
return {
type: 'Value',
loc: this.getLocation(start, this.tokenStart),
children
};
}
const SPACE = Object.freeze({
type: 'WhiteSpace',
loc: null,
value: ' '
});
function parse$H() {
this.eat(WhiteSpace);
return SPACE;
// return {
// type: 'WhiteSpace',
// loc: this.getLocation(this.tokenStart, this.tokenEnd),
// value: this.consume(WHITESPACE)
// };
}
var node = /*#__PURE__*/Object.freeze({
__proto__: null,
AnPlusB: parse$3,
Atrule: parse$4,
AtrulePrelude: parse$5,
AttributeSelector: parse$6,
Block: parse$7,
Brackets: parse$8,
CDC: parse$9,
CDO: parse$a,
ClassSelector: parse$b,
Combinator: parse$c,
Comment: parse$d,
Declaration: parse$e,
DeclarationList: parse$f,
Dimension: parse$g,
Function: parse$h,
Hash: parse$i,
Identifier: parse$j,
IdSelector: parse$k,
MediaFeature: parse$l,
MediaQuery: parse$m,
MediaQueryList: parse$n,
NestingSelector: parse$o,
Nth: parse$p,
Number: parse$q,
Operator: parse$r,
Parentheses: parse$s,
Percentage: parse$t,
PseudoClassSelector: parse$u,
PseudoElementSelector: parse$v,
Ratio: parse$w,
Raw: parse$x,
Rule: parse$y,
Selector: parse$z,
SelectorList: parse$A,
String: parse$B,
StyleSheet: parse$C,
TypeSelector: parse$D,
UnicodeRange: parse$E,
Url: parse$F,
Value: parse$G,
WhiteSpace: parse$H
});
var config = {
parseContext: {
default: 'StyleSheet',
stylesheet: 'StyleSheet',
atrule: 'Atrule',
atrulePrelude(options) {
return this.AtrulePrelude(options.atrule ? String(options.atrule) : null);
},
mediaQueryList: 'MediaQueryList',
mediaQuery: 'MediaQuery',
rule: 'Rule',
selectorList: 'SelectorList',
selector: 'Selector',
block() {
return this.Block(true);
},
declarationList: 'DeclarationList',
declaration: 'Declaration',
value: 'Value'
},
scope,
atrule,
pseudo,
node
};
var parse$I = createParser(config);
// @ts-ignore
const regex_closing_style_tag = /<\/style\s*>/;
const regex_starts_with_closing_style_tag = /^<\/style\s*>/;
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$I(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, {
enter: (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
}
};
}
function is_ref_selector(a, b) {
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
];
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;
}
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);
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
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`?
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: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]/;
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' && !parser.customElement ? 'Slot' : 'Element';
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
};
}
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|\/|>)/;
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 = /^["']/;
function read_attribute(parser, unique_names) {
const start = parser.index;
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));
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 = 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
};
}
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 === 'ref')
return 'Ref';
if (name === 'in' || name === 'out' || name === 'transition')
return 'Transition';
}
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;
}
function read_sequence(parser, done, location) {
let current_chunk = {
start: parser.index,
end: null,
type: 'Text',
raw: '',
data: null
};
const chunks = [];
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
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;
}
}
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 parse_expression_at(`${space_with_newline}(${pattern_string} = 1)`, start - 1).left;
}
catch (error) {
parser.acorn_error(error);
}
}
function trim_start(str) {
return str.replace(regex_starts_with_whitespaces, '');
}
function trim_end(str) {
return str.replace(regex_ends_with_whitespaces, '');
}
function to_string(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;
}
}
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*}/;
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(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(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(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(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
});
}
}
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);
}
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'
]);
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]/;
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, '_$&');
}
function getLocator(source, options) {
if (options === void 0) { options = {}; }
var offsetLine = options.offsetLine || 0;
var offsetColumn = options.offsetColumn || 0;
var originalLines = source.split('\n');
var start = 0;
var lineRanges = originalLines.map(function (line, i) {
var end = start + line.length + 1;
var range = { start: start, end: end, line: i };
start = end;
return range;
});
var i = 0;
function rangeContains(range, index) {
return range.start <= index && index < range.end;
}
function getLocation(range, index) {
return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
}
function locate(search, startIndex) {
if (typeof search === 'string') {
search = source.indexOf(search, startIndex || 0);
}
var range = lineRanges[i];
var d = search >= range.end ? 1 : -1;
while (range) {
if (rangeContains(range, search))
return getLocation(range, search);
i += d;
range = lineRanges[i];
}
}
return locate;
}
function locate(source, search, options) {
if (typeof options === 'number') {
throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
}
return getLocator(source, options)(search, options && options.startIndex);
}
const regex_tabs = /^\t+/;
function tabs_to_spaces(str) {
return str.replace(regex_tabs, match => match.split('\t').join(' '));
}
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 isErrorLine = frame_start + i === line;
const line_num = String(i + frame_start + 1).padStart(digits, ' ');
if (isErrorLine) {
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');
}
class CompileError extends Error {
toString() {
return `${this.message} (${this.start.line}:${this.start.column})\n${this.frame}`;
}
}
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$1 {
constructor(template, options) {
this.index = 0;
this.stack = [];
this.css = [];
this.js = [];
this.meta_tags = {};
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);
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];
}
acorn_error(err) {
this.error({
code: 'parse-error',
message: err.message.replace(regex_position_indicator, '')
}, err.pos);
}
error({ code, message }, index = this.index) {
error(message, {
name: 'ParseError',
code,
source: this.template,
start: index,
filename: this.filename
});
}
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;
}
match(str) {
return this.template.slice(this.index, this.index + str.length) === str;
}
/**
* Match a regex at the current index
* @param 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 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;
}
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();
}
}
function parse$J(template, options = {}) {
const parser = new Parser$1(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]
};
}
function is_head(node) {
return node && node.type === 'MemberExpression' && node.object['name'] === '@_document' && node.property['name'] === 'head';
}
class Block {
constructor(options) {
this.dependencies = new Set();
this.binding_group_initialised = new Set();
this.binding_groups = new Set();
this.event_listeners = [];
this.variables = new Map();
this.has_update_method = false;
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() {
const seen = new Set();
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;
}
}
add_dependencies(dependencies) {
dependencies.forEach(dependency => {
this.dependencies.add(dependency);
});
this.has_update_method = true;
if (this.parent) {
this.parent.add_dependencies(dependencies);
}
}
add_element(id, render_statement, claim_statement, parent_node, no_detach) {
this.add_variable(id);
this.chunks.create.push(b `${id} = ${render_statement};`);
if (this.renderer.options.hydratable) {
this.chunks.claim.push(b `${id} = ${claim_statement || render_statement};`);
}
if (parent_node) {
this.chunks.mount.push(b `@append(${parent_node}, ${id});`);
if (is_head(parent_node) && !no_detach)
this.chunks.destroy.push(b `@detach(${id});`);
}
else {
this.chunks.mount.push(b `@insert(#target, ${id}, #anchor);`);
if (!no_detach)
this.chunks.destroy.push(b `if (detaching) @detach(${id});`);
}
}
add_intro(local) {
this.has_intros = this.has_intro_method = true;
if (!local && this.parent)
this.parent.add_intro();
}
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;
}
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 });
}
alias(name) {
if (!this.aliases.has(name)) {
this.aliases.set(name, this.get_unique_name(name));
}
return this.aliases.get(name);
}
child(options) {
return new Block(Object.assign({}, this, { key: null }, options, { parent: this }));
}
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 `#current = true;`);
this.chunks.mount.push(b `#current = true;`);
}
if (this.chunks.outro.length > 0) {
this.chunks.outro.push(b `#current = false;`);
}
}
if (this.autofocus) {
if (this.autofocus.condition_expression) {
this.chunks.mount.push(b `if (${this.autofocus.condition_expression}) ${this.autofocus.element_var}.focus();`);
}
else {
this.chunks.mount.push(b `${this.autofocus.element_var}.focus();`);
}
}
this.render_binding_groups();
this.render_listeners();
const properties = {};
const noop = x `@noop`;
properties.key = key;
if (this.first) {
properties.first = x `null`;
this.chunks.hydrate.push(b `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 `this.h();`
: this.chunks.hydrate);
properties.create = x `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 `function #claim(#nodes) {
${this.chunks.claim}
${this.renderer.options.hydratable && this.chunks.hydrate.length > 0 && b `this.h();`}
}`;
}
}
if (this.renderer.options.hydratable && this.chunks.hydrate.length > 0) {
properties.hydrate = x `function #hydrate() {
${this.chunks.hydrate}
}`;
}
if (this.chunks.mount.length === 0) {
properties.mount = noop;
}
else if (this.event_listeners.length === 0) {
properties.mount = x `function #mount(#target, #anchor) {
${this.chunks.mount}
}`;
}
else {
properties.mount = x `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 `#new_ctx` : x `#ctx`;
let dirty = { type: 'Identifier', name: '#dirty' };
if (!this.renderer.context_overflow && !this.parent) {
dirty = { type: 'ArrayPattern', elements: [dirty] };
}
properties.update = x `function #update(${ctx}, ${dirty}) {
${this.maintain_context && b `#ctx = ${ctx};`}
${this.chunks.update}
}`;
}
}
if (this.has_animation) {
properties.measure = x `function #measure() {
${this.chunks.measure}
}`;
if (this.chunks.restore_measurements.length) {
properties.restore_measurements = x `function #restore_measurements(#measurement) {
${this.chunks.restore_measurements}
}`;
}
properties.fix = x `function #fix() {
${this.chunks.fix}
}`;
properties.animate = x `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 `function #intro(#local) {
${this.has_outros && b `if (#current) return;`}
${this.chunks.intro}
}`;
}
if (this.chunks.outro.length === 0) {
properties.outro = noop;
}
else {
properties.outro = x `function #outro(#local) {
${this.chunks.outro}
}`;
}
}
if (this.chunks.destroy.length === 0) {
properties.destroy = noop;
}
else {
properties.destroy = x `function #destroy(detaching) {
${this.chunks.destroy}
}`;
}
if (!this.renderer.component.compile_options.dev) {
// allow shorthand names
for (const name in properties) {
const property = properties[name];
if (property)
property.id = null;
}
}
const return_value = x `{
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 `
${this.chunks.declarations}
${Array.from(this.variables.values()).map(({ id, init }) => {
return init
? b `let ${id} = ${init}`
: b `let ${id}`;
})}
${this.chunks.init}
${dev
? b `
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 `
return ${return_value};`}
`;
return body;
}
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');
const args = [x `#ctx`];
if (key)
args.unshift(key);
const fn = b `function ${this.name}(${args}) {
${this.get_contents(key)}
}`;
return this.comment
? b `
// ${this.comment}
${fn}`
: fn;
}
render_listeners(chunk = '') {
if (this.event_listeners.length > 0) {
this.add_variable({ type: 'Identifier', name: '#mounted' });
this.chunks.destroy.push(b `#mounted = false`);
const dispose = {
type: 'Identifier',
name: `#dispose${chunk}`
};
this.add_variable(dispose);
if (this.event_listeners.length === 1) {
this.chunks.mount.push(b `
if (!#mounted) {
${dispose} = ${this.event_listeners[0]};
#mounted = true;
}
`);
this.chunks.destroy.push(b `${dispose}();`);
}
else {
this.chunks.mount.push(b `
if (!#mounted) {
${dispose} = [
${this.event_listeners}
];
#mounted = true;
}
`);
this.chunks.destroy.push(b `@run_all(${dispose});`);
}
}
}
render_binding_groups() {
for (const binding_group of this.binding_groups) {
binding_group.render();
}
}
}
class Wrapper {
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
}
});
this.can_use_innerhtml = !renderer.options.hydratable;
this.is_static_content = !renderer.options.hydratable;
block.wrappers.push(this);
}
cannot_use_innerhtml() {
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();
}
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 `@empty()`, parent_nodes && x `@empty()`, parent_node);
}
return anchor;
}
get_update_mount_node(anchor) {
return ((this.parent && this.parent.is_dom_node())
? this.parent.var
: x `${anchor}.parentNode`);
}
is_dom_node() {
return (this.node.type === 'Element' ||
this.node.type === 'Text' ||
this.node.type === 'MustacheTag');
}
render(_block, _parent_node, _parent_nodes) {
throw Error('Wrapper class is not renderable');
}
}
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;
}
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, ' ');
}
class Node$1 {
constructor(component, parent, _scope, info) {
this.start = info.start;
this.end = info.end;
this.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
}
});
}
cannot_use_innerhtml() {
if (this.can_use_innerhtml !== false) {
this.can_use_innerhtml = false;
if (this.parent)
this.parent.cannot_use_innerhtml();
}
}
find_nearest(selector) {
if (selector.test(this.type))
return this;
if (this.parent)
return this.parent.find_nearest(selector);
}
get_static_attribute_value(name) {
const attribute = this.attributes && this.attributes.find((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 attribute.chunks[0].data;
}
return null;
}
has_ancestor(type) {
return this.parent ?
this.parent.type === type || this.parent.has_ancestor(type) :
false;
}
}
// All compiler warnings should be listed and accessed from here
/**
* @internal
*/
var compiler_warnings = {
custom_element_no_tag: {
code: 'custom-element-no-tag',
message: 'No custom element \'tag\' option was specified. To automatically register a custom element, specify a name with a hyphen in it, e.g. <svelte:options tag="my-thing"/>. To hide this warning, use <svelte:options tag={null}/>'
},
unused_export_let: (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: (names) => ({
code: 'module-script-reactive-declaration',
message: `${names.map(name => `"${name}"`).join(', ')} ${names.length > 1 ? 'are' : 'is'} declared in a module script and will not be reactive`
}),
missing_declaration: (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 'tag' option is used when generating a custom element. Did you forget the 'customElement: true' compile option?"
},
css_unused_selector: (selector) => ({
code: 'css-unused-selector',
message: `Unused CSS selector "${selector}"`
}),
empty_block: {
code: 'empty-block',
message: 'Empty block'
},
reactive_component: (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: (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: (name, suggestion) => ({
code: 'invalid-html-attribute',
message: `'${name}' is not a valid HTML attribute. Did you mean '${suggestion}'?`
}),
a11y_aria_attributes: (name) => ({
code: 'a11y-aria-attributes',
message: `A11y: <${name}> should not have aria-* attributes`
}),
a11y_incorrect_attribute_type: (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: (attribute, suggestion) => ({
code: 'a11y-unknown-aria-attribute',
message: `A11y: Unknown aria attribute 'aria-${attribute}'` + (suggestion ? ` (did you mean '${suggestion}'?)` : '')
}),
a11y_hidden: (name) => ({
code: 'a11y-hidden',
message: `A11y: <${name}> element should not be hidden`
}),
a11y_misplaced_role: (name) => ({
code: 'a11y-misplaced-role',
message: `A11y: <${name}> should not have role attribute`
}),
a11y_unknown_role: (role, suggestion) => ({
code: 'a11y-unknown-role',
message: `A11y: Unknown role '${role}'` + (suggestion ? ` (did you mean '${suggestion}'?)` : '')
}),
a11y_no_abstract_role: (role) => ({
code: 'a11y-no-abstract-role',
message: `A11y: Abstract role '${role}' is forbidden`
}),
a11y_no_redundant_roles: (role) => ({
code: 'a11y-no-redundant-roles',
message: `A11y: Redundant role '${role}'`
}),
a11y_no_interactive_element_to_noninteractive_role: (role, element) => ({
code: 'a11y-no-interactive-element-to-noninteractive-role',
message: `A11y: <${element}> cannot have role '${role}'`
}),
a11y_role_has_required_aria_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(name => `"${name}"`).join(', ')}`
}),
a11y_role_supports_aria_props: (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: (href_attribute, href_value) => ({
code: 'a11y-invalid-attribute',
message: `A11y: '${href_value}' is not a valid ${href_attribute} attribute`
}),
a11y_missing_attribute: (name, article, sequence) => ({
code: 'a11y-missing-attribute',
message: `A11y: <${name}> element should have ${article} ${sequence} attribute`
}),
a11y_img_redundant_alt: {
code: 'a11y-img-redundant-alt',
message: 'A11y: Screenreaders already announce <img> elements as an image.'
},
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: (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: (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: (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: (rest_element_name) => ({
code: 'invalid-rest-eachblock-binding',
message: `...${rest_element_name} operator will create a new object and binding propagation with original object will not work`
})
};
const regex_non_whitespace_characters = /[^ \r\n\f\v\t]/;
class AbstractBlock extends Node$1 {
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.test(child.data))) {
this.component.warn(this, compiler_warnings.empty_block);
}
}
}
function flatten_reference(node) {
const nodes = [];
const parts = [];
while (node.type === 'MemberExpression') {
nodes.unshift(node.property);
if (!node.computed) {
parts.unshift(node.property.name);
}
else {
const computed_property = to_string$1(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 };
}
function to_string$1(node) {
switch (node.type) {
case 'Literal':
return String(node.value);
case 'Identifier':
return node.name;
}
}
function create_scopes(expression) {
return analyze(expression);
}
function get_object(node) {
while (node.type === 'MemberExpression')
node = node.object;
return node;
}
const reserved_keywords = new Set(['$$props', '$$restProps', '$$slots']);
function is_reserved_keyword(name) {
return reserved_keywords.has(name);
}
function is_dynamic(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;
}
function invalidate(renderer, scope, node, names, main_execution_context = false) {
const { component } = renderer;
const [head, ...tail] = 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.is_reactive_static &&
(variable.referenced ||
variable.subscribable ||
variable.is_reactive_dependency ||
variable.export_name ||
variable.name[0] === '$'));
});
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 `@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 `$$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 `${subscribe}(${invalidate})`;
}
return invalidate;
}
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 `${`$$subscribe_${name}`}(${value || name})`;
}
else {
const member = renderer.context_lookup.get(name);
return x `${`$$subscribe_${name}`}($$invalidate(${member.index}, ${value || name}))`;
}
}
if (name[0] === '$' && name[1] !== '$') {
return x `${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 `${value}`;
}
else {
const member = renderer.context_lookup.get(name);
return x `$$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 `$$invalidate(${renderer.context_lookup.get(n).index}, ${n})`)
.reduce((lhs, rhs) => x `${lhs}, ${rhs}`);
}
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 = replacement;
return ancestor;
}
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: (element, binding) => ({
code: 'invalid-binding',
message: `'${binding}' is not a valid binding on <${element}> elements`
}),
invalid_binding_element_with: (elements, binding) => ({
code: 'invalid-binding',
message: `'${binding}' binding can only be used with ${elements}`
}),
invalid_binding_on: (binding, element, post) => ({
code: 'invalid-binding',
message: `'${binding}' is not a valid binding on ${element}` + (post || '')
}),
invalid_binding_foreign: (binding) => ({
code: 'invalid-binding',
message: `'${binding}' is not a valid binding. Foreign elements only support bind:this`
}),
invalid_binding_no_checkbox: (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: (binding) => ({
code: 'invalid-binding',
message: `'${binding}' is not a valid binding`
}),
invalid_binding_window: (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: (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 and innerHTML 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: (modifier1, modifier2) => ({
code: 'invalid-event-modifier',
message: `The '${modifier1}' and '${modifier2}' modifiers cannot be used together`
}),
invalid_event_modifier_legacy: (modifier) => ({
code: 'invalid-event-modifier',
message: `The '${modifier}' modifier cannot be used in legacy mode`
}),
invalid_event_modifier: (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: (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: (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_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: (directive, parent_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: (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: (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_tag_attribute: {
code: 'invalid-tag-attribute',
message: "'tag' must be a string literal"
},
invalid_namespace_property: (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: (name) => ({
code: `invalid-${name}-value`,
message: `${name} attribute must be true or false`
}),
invalid_options_attribute_unknown: {
code: 'invalid-options-attribute',
message: '<svelte:options> unknown attribute'
},
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: (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: (name) => ({
code: 'invalid-const-declaration',
message: `'${name}' has already been declared`
}),
invalid_const_update: (name) => ({
code: 'invalid-const-update',
message: `'${name}' is declared using {@const ...} and is read-only`
}),
cyclical_const_tags: (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_style_directive_modifier: (valid) => ({
code: 'invalid-style-directive-modifier',
message: `Valid modifiers for style directives are: ${valid}`
})
};
const regex_contains_term_function_expression = /FunctionExpression/;
class Expression {
constructor(component, owner, template_scope, info, lazy) {
this.type = 'Expression';
this.references = new Set();
this.dependencies = new Set();
this.contextual_dependencies = new Set();
this.declarations = [];
this.uses_context = false;
// 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, {
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.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(name => dependencies.add(name));
}
}
else {
if (!lazy) {
dependencies.add(name);
}
component.add_reference(node, name);
component.warn_if_undefined(name, nodes[0], template_scope);
}
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(name => {
var _a;
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(name => {
const variable = component.var_lookup.get(name);
if (variable)
variable[deep ? 'mutated' : 'reassigned'] = true;
});
const each_block = template_scope.get_owner(name);
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;
}
const declaration = (_a = scope.find_owner(name)) === null || _a === void 0 ? void 0 : _a.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'
});
}
}
});
}
},
leave(node) {
if (map.has(node)) {
scope = scope.parent;
}
if (node === function_expression) {
function_expression = null;
}
}
});
}
dynamic_dependencies() {
return Array.from(this.dependencies).filter(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(variable);
});
}
// TODO move this into a render-dom wrapper?
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;
let dependencies;
let contextual_dependencies;
const node = walk(this.node, {
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(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();
}
}
},
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 `const ${id} = ${node}`;
const extract_functions = () => {
const deps = Array.from(contextual_dependencies);
const function_expression = node;
const has_args = function_expression.params.length > 0;
function_expression.params = [
...deps.map(name => ({ type: 'Identifier', name })),
...function_expression.params
];
const context_args = deps.map(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(id);
const func_declaration = has_args
? b `function ${id}(...args) {
return ${callee}(${context_args}, ...args);
}`
: b `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, {
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));
}
},
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(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') {
const dep_scopes = new Set(deps.map(name => template_scope.get_owner(name)));
// find the nearest scopes
let node = owner.parent;
while (node && !dep_scopes.has(node)) {
node = node.parent;
}
const func_expression = func_declaration[0];
if (node.type === 'InlineComponent' || node.type === 'SlotTemplate') {
// <Comp 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, {
enter(node) {
if (node.type === 'Identifier' && node.name === '#ctx') {
node.name = 'child_ctx';
}
}
});
// add to get_xxx_context
// child_ctx[x] = function () { ... }
template_scope.get_owner(deps[0]).contexts.push({
key: func_id,
modifier: () => func_expression,
default_modifier: 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(assignee));
const traced = new Set();
names.forEach(name => {
const dependencies = template_scope.dependencies_for_name.get(name);
if (dependencies) {
dependencies.forEach(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;
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(declaration => {
block.chunks.init.push(declaration);
});
}
return (this.manipulated = node);
}
}
function get_function_name(_node, parent) {
if (parent.type === 'EventHandler') {
return `${parent.name}_handler`;
}
if (parent.type === 'Action') {
return `${parent.name}_function`;
}
return 'func';
}
function unpack_destructuring({ contexts, node, modifier = (node) => node, default_modifier = (node) => node, scope, component, context_rest_properties }) {
if (!node)
return;
if (node.type === 'Identifier') {
contexts.push({
key: node,
modifier,
default_modifier
});
}
else if (node.type === 'RestElement') {
contexts.push({
key: node.argument,
modifier,
default_modifier
});
context_rest_properties.set(node.argument.name, node);
}
else if (node.type === 'ArrayPattern') {
node.elements.forEach((element, i) => {
if (element && element.type === 'RestElement') {
unpack_destructuring({
contexts,
node: element,
modifier: (node) => x `${modifier(node)}.slice(${i})`,
default_modifier,
scope,
component,
context_rest_properties
});
context_rest_properties.set(element.argument.name, element);
}
else if (element && element.type === 'AssignmentPattern') {
const n = contexts.length;
mark_referenced(element.right, scope, component);
unpack_destructuring({
contexts,
node: element.left,
modifier: (node) => x `${modifier(node)}[${i}]`,
default_modifier: (node, to_ctx) => x `${node} !== undefined ? ${node} : ${update_reference(contexts, n, element.right, to_ctx)}`,
scope,
component,
context_rest_properties
});
}
else {
unpack_destructuring({
contexts,
node: element,
modifier: (node) => x `${modifier(node)}[${i}]`,
default_modifier,
scope,
component,
context_rest_properties
});
}
});
}
else if (node.type === 'ObjectPattern') {
const used_properties = [];
node.properties.forEach((property) => {
if (property.type === 'RestElement') {
unpack_destructuring({
contexts,
node: property.argument,
modifier: (node) => x `@object_without_properties(${modifier(node)}, [${used_properties}])`,
default_modifier,
scope,
component,
context_rest_properties
});
context_rest_properties.set(property.argument.name, property);
}
else {
const key = property.key;
const value = property.value;
used_properties.push(x `"${key.name}"`);
if (value.type === 'AssignmentPattern') {
const n = contexts.length;
mark_referenced(value.right, scope, component);
unpack_destructuring({
contexts,
node: value.left,
modifier: (node) => x `${modifier(node)}.${key.name}`,
default_modifier: (node, to_ctx) => x `${node} !== undefined ? ${node} : ${update_reference(contexts, n, value.right, to_ctx)}`,
scope,
component,
context_rest_properties
});
}
else {
unpack_destructuring({
contexts,
node: value,
modifier: (node) => x `${modifier(node)}.${key.name}`,
default_modifier,
scope,
component,
context_rest_properties
});
}
}
});
}
}
function update_reference(contexts, n, expression, to_ctx) {
const find_from_context = (node) => {
for (let i = n; i < contexts.length; i++) {
const { key } = contexts[i];
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 = clone(expression);
walk(expression, {
enter(node, parent) {
if (is_reference(node, parent)) {
this.replace(find_from_context(node));
this.skip();
}
}
});
return expression;
}
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);
}
}
}
});
}
const allowed_parents = new Set(['EachBlock', 'CatchBlock', 'ThenBlock', 'InlineComponent', 'SlotTemplate', 'IfBlock', 'ElseBlock']);
class ConstTag extends Node$1 {
constructor(component, parent, scope, info) {
super(component, parent, scope, info);
this.contexts = [];
this.context_rest_properties = new Map();
this.assignees = new Set();
this.dependencies = new Set();
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(({ 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, {
enter(node, parent) {
if (is_reference(node, parent)) {
const identifier = get_object(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(context => {
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);
});
}
}
class PendingBlock extends AbstractBlock {
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();
}
}
}
class CatchBlock extends AbstractBlock {
constructor(component, parent, scope, info) {
super(component, parent, scope, info);
this.scope = scope.child();
if (parent.catch_node) {
parent.catch_contexts.forEach(context => {
this.scope.add(context.key.name, parent.expression.dependencies, this);
});
}
([this.const_tags, this.children] = get_const_tags(info.children, component, this, parent));
if (!info.skip) {
this.warn_if_empty_block();
}
}
}
class AwaitBlock extends Node$1 {
constructor(component, parent, scope, info) {
super(component, parent, scope, info);
this.context_rest_properties = new Map();
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$1 = /FunctionExpression/;
class EventHandler extends Node$1 {
constructor(component, parent, template_scope, info) {
super(component, parent, template_scope, info);
this.uses_context = false;
this.can_make_passive = false;
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$1.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(d => 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`);
}
}
get reassigned() {
if (!this.expression) {
return false;
}
const node = this.expression.node;
if (regex_contains_term_function_expression$1.test(node.type)) {
return false;
}
return this.expression.dynamic_dependencies().length > 0;
}
}
class Action extends Node$1 {
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(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;
}
}
class Body extends Node$1 {
constructor(component, parent, scope, info) {
super(component, parent, scope, info);
this.handlers = [];
this.actions = [];
info.attributes.forEach((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));
}
});
}
}
class Comment$1 extends Node$1 {
constructor(component, parent, scope, info) {
super(component, parent, scope, info);
this.data = info.data;
this.ignores = info.ignores;
}
}
class ElseBlock extends AbstractBlock {
constructor(component, parent, scope, info) {
super(component, parent, scope, info);
this.scope = scope.child();
([this.const_tags, this.children] = get_const_tags(info.children, component, this, this));
this.warn_if_empty_block();
}
}
class EachBlock extends AbstractBlock {
constructor(component, parent, scope, info) {
super(component, parent, scope, info);
this.has_binding = false;
this.has_index_binding = false;
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(context => {
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(info.children, component, this, this));
if (this.has_animation) {
this.children = this.children.filter(child => !isEmptyNode(child) && !isCommentNode(child));
if (this.children.length !== 1) {
const child = this.children.find(child => !!child.animation);
component.error(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;
}
}
function isEmptyNode(node) {
return node.type === 'Text' && node.data.trim() === '';
}
function isCommentNode(node) {
return node.type === 'Comment';
}
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');
}
function add_to_set(a, b) {
// @ts-ignore
b.forEach(item => {
a.add(item);
});
}
class Attribute extends Node$1 {
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(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;
});
}
}
get_dependencies() {
if (this.is_spread)
return this.expression.dynamic_dependencies();
const dependencies = new Set();
this.chunks.forEach(chunk => {
if (chunk.type === 'Expression') {
add_to_set(dependencies, chunk.dynamic_dependencies());
}
});
return Array.from(dependencies);
}
get_value(block) {
if (this.is_true)
return x `true`;
if (this.chunks.length === 0)
return x `""`;
if (this.chunks.length === 1) {
return this.chunks[0].type === 'Text'
? string_literal(this.chunks[0].data)
: this.chunks[0].manipulate(block);
}
let expression = this.chunks
.map(chunk => chunk.type === 'Text' ? string_literal(chunk.data) : chunk.manipulate(block))
.reduce((lhs, rhs) => x `${lhs} + ${rhs}`);
if (this.chunks[0].type !== 'Text') {
expression = x `"" + ${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`
? 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;
}
}
// 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'
]);
class Binding extends Node$1 {
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(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(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(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(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) ||
(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);
}
validate_binding_rest_properties(scope) {
this.expression.references.forEach(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(rest_node, compiler_warnings.invalid_rest_eachblock_binding(name));
}
}
});
}
}
function isElement(node) {
return !!node.is_media_node;
}
class Transition extends Node$1 {
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(this, info.name.split('.')[0]);
this.directive = info.intro && info.outro ? 'transition' : info.intro ? 'in' : 'out';
this.is_local = info.modifiers.includes('local');
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;
}
}
class Animation extends Node$1 {
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(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;
}
block.has_animation = true;
this.expression = info.expression
? new Expression(component, this, scope, info.expression, true)
: null;
}
}
class Class extends Node$1 {
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.
*/
function nodes_to_template_literal(value) {
const literal = {
type: 'TemplateLiteral',
expressions: [],
quasis: []
};
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(node.expression);
quasi = {
type: 'TemplateElement',
value: { raw: '', cooked: null },
tail: false
};
}
});
quasi.tail = true;
literal.quasis.push(quasi);
return literal;
}
const valid_modifiers = new Set(['important']);
class StyleDirective extends Node$1 {
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.has(modifier)) {
component.error(this, compiler_errors.invalid_style_directive_modifier(list$1([...valid_modifiers])));
}
}
// 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: '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$/;
class Text extends Node$1 {
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);
}
keep_space() {
if (this.component.component_options.preserveWhitespace)
return true;
return this.within_pre();
}
within_pre() {
let node = this.parent;
while (node) {
if (node.type === 'Element' && node.name === 'pre') {
return true;
}
node = node.parent;
}
return false;
}
}
// 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#template-syntax-svelte-options';
const html = 'http://www.w3.org/1999/xhtml';
const mathml = 'http://www.w3.org/1998/Math/MathML';
const svg$1 = '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$1,
xlink,
xml,
xmlns
];
const namespaces = { foreign, html, mathml, svg: svg$1, xlink, xml, xmlns };
const applicable = new Set(['Identifier', 'ObjectExpression', 'ArrayExpression', 'Property']);
class Let extends Node$1 {
constructor(component, parent, scope, info) {
super(component, parent, scope, info);
this.names = [];
this.name = { type: 'Identifier', name: info.name };
const { names } = this;
if (info.expression) {
this.value = info.expression;
walk(info.expression, {
enter(node) {
if (!applicable.has(node.type)) {
return component.error(node, compiler_errors.invalid_let);
}
if (node.type === 'Identifier') {
names.push(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 commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function unwrapExports (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
function getCjsExportFromNamespace (n) {
return n && n['default'] || n;
}
var iteratorProxy_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = iteratorProxy;
exports.default = _default;
});
unwrapExports(iteratorProxy_1);
var iterationDecorator_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = iterationDecorator;
var _iteratorProxy = _interopRequireDefault(iteratorProxy_1);
function _interopRequireDefault(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;
}
});
unwrapExports(iterationDecorator_1);
var ariaPropsMap_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _iterationDecorator = _interopRequireDefault(iterationDecorator_1);
function _interopRequireDefault(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 properties = [['aria-activedescendant', {
'type': 'id'
}], ['aria-atomic', {
'type': 'boolean'
}], ['aria-autocomplete', {
'type': 'token',
'values': ['inline', 'list', 'both', 'none']
}], ['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-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;
},
forEach: function forEach(fn) {
var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var _iterator = _createForOfIteratorHelper(properties),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var _step$value = _slicedToArray(_step.value, 2),
key = _step$value[0],
values = _step$value[1];
fn.call(thisArg, values, key, properties);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
},
get: function get(key) {
var item = properties.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.map(function (_ref) {
var _ref2 = _slicedToArray(_ref, 1),
key = _ref2[0];
return key;
});
},
values: function values() {
return properties.map(function (_ref3) {
var _ref4 = _slicedToArray(_ref3, 2),
values = _ref4[1];
return values;
});
}
};
var _default = (0, _iterationDecorator.default)(ariaPropsMap, ariaPropsMap.entries());
exports.default = _default;
});
unwrapExports(ariaPropsMap_1);
var domMap_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _iterationDecorator = _interopRequireDefault(iterationDecorator_1);
function _interopRequireDefault(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 dom = [['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;
},
forEach: function forEach(fn) {
var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var _iterator = _createForOfIteratorHelper(dom),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var _step$value = _slicedToArray(_step.value, 2),
key = _step$value[0],
values = _step$value[1];
fn.call(thisArg, values, key, dom);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
},
get: function get(key) {
var item = dom.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.map(function (_ref) {
var _ref2 = _slicedToArray(_ref, 1),
key = _ref2[0];
return key;
});
},
values: function values() {
return dom.map(function (_ref3) {
var _ref4 = _slicedToArray(_ref3, 2),
values = _ref4[1];
return values;
});
}
};
var _default = (0, _iterationDecorator.default)(domMap, domMap.entries());
exports.default = _default;
});
unwrapExports(domMap_1);
var commandRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var commandRole = {
abstract: true,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['author'],
prohibitedProps: [],
props: {},
relatedConcepts: [{
concept: {
name: 'menuitem'
},
module: 'HTML'
}],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'widget']]
};
var _default = commandRole;
exports.default = _default;
});
unwrapExports(commandRole_1);
var compositeRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = compositeRole;
exports.default = _default;
});
unwrapExports(compositeRole_1);
var inputRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = inputRole;
exports.default = _default;
});
unwrapExports(inputRole_1);
var landmarkRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = landmarkRole;
exports.default = _default;
});
unwrapExports(landmarkRole_1);
var rangeRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = rangeRole;
exports.default = _default;
});
unwrapExports(rangeRole_1);
var roletypeRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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: 'rel'
},
module: 'HTML'
}, {
concept: {
name: 'role'
},
module: 'XHTML'
}, {
concept: {
name: 'type'
},
module: 'Dublin Core'
}],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: []
};
var _default = roletypeRole;
exports.default = _default;
});
unwrapExports(roletypeRole_1);
var sectionRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = sectionRole;
exports.default = _default;
});
unwrapExports(sectionRole_1);
var sectionheadRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = sectionheadRole;
exports.default = _default;
});
unwrapExports(sectionheadRole_1);
var selectRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = selectRole;
exports.default = _default;
});
unwrapExports(selectRole_1);
var structureRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var structureRole = {
abstract: true,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: [],
prohibitedProps: [],
props: {},
relatedConcepts: [],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype']]
};
var _default = structureRole;
exports.default = _default;
});
unwrapExports(structureRole_1);
var widgetRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var widgetRole = {
abstract: true,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: [],
prohibitedProps: [],
props: {},
relatedConcepts: [],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype']]
};
var _default = widgetRole;
exports.default = _default;
});
unwrapExports(widgetRole_1);
var windowRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = windowRole;
exports.default = _default;
});
unwrapExports(windowRole_1);
var ariaAbstractRoles_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _commandRole = _interopRequireDefault(commandRole_1);
var _compositeRole = _interopRequireDefault(compositeRole_1);
var _inputRole = _interopRequireDefault(inputRole_1);
var _landmarkRole = _interopRequireDefault(landmarkRole_1);
var _rangeRole = _interopRequireDefault(rangeRole_1);
var _roletypeRole = _interopRequireDefault(roletypeRole_1);
var _sectionRole = _interopRequireDefault(sectionRole_1);
var _sectionheadRole = _interopRequireDefault(sectionheadRole_1);
var _selectRole = _interopRequireDefault(selectRole_1);
var _structureRole = _interopRequireDefault(structureRole_1);
var _widgetRole = _interopRequireDefault(widgetRole_1);
var _windowRole = _interopRequireDefault(windowRole_1);
function _interopRequireDefault(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 = ariaAbstractRoles;
exports.default = _default;
});
unwrapExports(ariaAbstractRoles_1);
var alertRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = alertRole;
exports.default = _default;
});
unwrapExports(alertRole_1);
var alertdialogRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = alertdialogRole;
exports.default = _default;
});
unwrapExports(alertdialogRole_1);
var applicationRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = applicationRole;
exports.default = _default;
});
unwrapExports(applicationRole_1);
var articleRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = articleRole;
exports.default = _default;
});
unwrapExports(articleRole_1);
var bannerRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var bannerRole = {
abstract: false,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['author'],
prohibitedProps: [],
props: {},
relatedConcepts: [{
concept: {
constraints: ['direct descendant of document'],
name: 'header'
},
module: 'HTML'
}],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default = bannerRole;
exports.default = _default;
});
unwrapExports(bannerRole_1);
var blockquoteRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var blockquoteRole = {
abstract: false,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['author'],
prohibitedProps: [],
props: {},
relatedConcepts: [],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section']]
};
var _default = blockquoteRole;
exports.default = _default;
});
unwrapExports(blockquoteRole_1);
var buttonRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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: [{
constraints: ['set'],
name: 'aria-pressed'
}, {
name: 'type',
value: 'checkbox'
}],
name: 'input'
},
module: 'HTML'
}, {
concept: {
attributes: [{
name: 'aria-expanded',
value: 'false'
}],
name: 'summary'
},
module: 'HTML'
}, {
concept: {
attributes: [{
name: 'aria-expanded',
value: 'true'
}],
constraints: ['direct descendant of details element with the open attribute defined'],
name: 'summary'
},
module: 'HTML'
}, {
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 = buttonRole;
exports.default = _default;
});
unwrapExports(buttonRole_1);
var captionRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var captionRole = {
abstract: false,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['prohibited'],
prohibitedProps: ['aria-label', 'aria-labelledby'],
props: {},
relatedConcepts: [],
requireContextRole: ['figure', 'grid', 'table'],
requiredContextRole: ['figure', 'grid', 'table'],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section']]
};
var _default = captionRole;
exports.default = _default;
});
unwrapExports(captionRole_1);
var cellRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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: ['descendant of table'],
name: 'td'
},
module: 'HTML'
}],
requireContextRole: ['row'],
requiredContextRole: ['row'],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section']]
};
var _default = cellRole;
exports.default = _default;
});
unwrapExports(cellRole_1);
var checkboxRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = checkboxRole;
exports.default = _default;
});
unwrapExports(checkboxRole_1);
var codeRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var codeRole = {
abstract: false,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['prohibited'],
prohibitedProps: ['aria-label', 'aria-labelledby'],
props: {},
relatedConcepts: [],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section']]
};
var _default = codeRole;
exports.default = _default;
});
unwrapExports(codeRole_1);
var columnheaderRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var columnheaderRole = {
abstract: false,
accessibleNameRequired: true,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['author', 'contents'],
prohibitedProps: [],
props: {
'aria-sort': null
},
relatedConcepts: [{
attributes: [{
name: 'scope',
value: 'col'
}],
concept: {
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 = columnheaderRole;
exports.default = _default;
});
unwrapExports(columnheaderRole_1);
var comboboxRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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'
}],
name: 'select'
},
module: 'HTML'
}, {
concept: {
attributes: [{
constraints: ['undefined'],
name: 'multiple'
}, {
name: 'size',
value: 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 = comboboxRole;
exports.default = _default;
});
unwrapExports(comboboxRole_1);
var complementaryRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var complementaryRole = {
abstract: false,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['author'],
prohibitedProps: [],
props: {},
relatedConcepts: [{
concept: {
name: 'aside'
},
module: 'HTML'
}],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default = complementaryRole;
exports.default = _default;
});
unwrapExports(complementaryRole_1);
var contentinfoRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var contentinfoRole = {
abstract: false,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['author'],
prohibitedProps: [],
props: {},
relatedConcepts: [{
concept: {
constraints: ['direct descendant of document'],
name: 'footer'
},
module: 'HTML'
}],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default = contentinfoRole;
exports.default = _default;
});
unwrapExports(contentinfoRole_1);
var definitionRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = definitionRole;
exports.default = _default;
});
unwrapExports(definitionRole_1);
var deletionRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var deletionRole = {
abstract: false,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['prohibited'],
prohibitedProps: ['aria-label', 'aria-labelledby'],
props: {},
relatedConcepts: [],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section']]
};
var _default = deletionRole;
exports.default = _default;
});
unwrapExports(deletionRole_1);
var dialogRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = dialogRole;
exports.default = _default;
});
unwrapExports(dialogRole_1);
var directoryRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = directoryRole;
exports.default = _default;
});
unwrapExports(directoryRole_1);
var documentRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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: 'body'
},
module: 'HTML'
}],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure']]
};
var _default = documentRole;
exports.default = _default;
});
unwrapExports(documentRole_1);
var emphasisRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var emphasisRole = {
abstract: false,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['prohibited'],
prohibitedProps: ['aria-label', 'aria-labelledby'],
props: {},
relatedConcepts: [],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section']]
};
var _default = emphasisRole;
exports.default = _default;
});
unwrapExports(emphasisRole_1);
var feedRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = feedRole;
exports.default = _default;
});
unwrapExports(feedRole_1);
var figureRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = figureRole;
exports.default = _default;
});
unwrapExports(figureRole_1);
var formRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = formRole;
exports.default = _default;
});
unwrapExports(formRole_1);
var genericRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var genericRole = {
abstract: false,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['prohibited'],
prohibitedProps: ['aria-label', 'aria-labelledby'],
props: {},
relatedConcepts: [{
concept: {
name: 'span'
},
module: 'HTML'
}, {
concept: {
name: 'div'
},
module: 'HTML'
}],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure']]
};
var _default = genericRole;
exports.default = _default;
});
unwrapExports(genericRole_1);
var gridRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var gridRole = {
abstract: false,
accessibleNameRequired: true,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['author'],
prohibitedProps: [],
props: {
'aria-multiselectable': null,
'aria-readonly': null
},
relatedConcepts: [{
concept: {
attributes: [{
name: 'role',
value: 'grid'
}],
name: 'table'
},
module: 'HTML'
}],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [['row'], ['row', 'rowgroup']],
requiredProps: {},
superClass: [['roletype', 'widget', 'composite'], ['roletype', 'structure', 'section', 'table']]
};
var _default = gridRole;
exports.default = _default;
});
unwrapExports(gridRole_1);
var gridcellRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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: {
attributes: [{
name: 'role',
value: 'gridcell'
}],
name: 'td'
},
module: 'HTML'
}],
requireContextRole: ['row'],
requiredContextRole: ['row'],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section', 'cell'], ['roletype', 'widget']]
};
var _default = gridcellRole;
exports.default = _default;
});
unwrapExports(gridcellRole_1);
var groupRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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'
}],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section']]
};
var _default = groupRole;
exports.default = _default;
});
unwrapExports(groupRole_1);
var headingRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = headingRole;
exports.default = _default;
});
unwrapExports(headingRole_1);
var imgRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = imgRole;
exports.default = _default;
});
unwrapExports(imgRole_1);
var insertionRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var insertionRole = {
abstract: false,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['prohibited'],
prohibitedProps: ['aria-label', 'aria-labelledby'],
props: {},
relatedConcepts: [],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section']]
};
var _default = insertionRole;
exports.default = _default;
});
unwrapExports(insertionRole_1);
var linkRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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: [{
name: 'href'
}],
name: 'a'
},
module: 'HTML'
}, {
concept: {
attributes: [{
name: 'href'
}],
name: 'area'
},
module: 'HTML'
}, {
concept: {
attributes: [{
name: 'href'
}],
name: 'link'
},
module: 'HTML'
}],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'widget', 'command']]
};
var _default = linkRole;
exports.default = _default;
});
unwrapExports(linkRole_1);
var listRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = listRole;
exports.default = _default;
});
unwrapExports(listRole_1);
var listboxRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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'
}, {
name: 'multiple'
}],
name: 'select'
},
module: 'HTML'
}, {
concept: {
attributes: [{
constraints: ['>1'],
name: 'size'
}],
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 = listboxRole;
exports.default = _default;
});
unwrapExports(listboxRole_1);
var listitemRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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, ul or menu'],
name: 'li'
},
module: 'HTML'
}, {
concept: {
name: 'item'
},
module: 'XForms'
}],
requireContextRole: ['directory', 'list'],
requiredContextRole: ['directory', 'list'],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section']]
};
var _default = listitemRole;
exports.default = _default;
});
unwrapExports(listitemRole_1);
var logRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = logRole;
exports.default = _default;
});
unwrapExports(logRole_1);
var mainRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = mainRole;
exports.default = _default;
});
unwrapExports(mainRole_1);
var marqueeRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = marqueeRole;
exports.default = _default;
});
unwrapExports(marqueeRole_1);
var mathRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = mathRole;
exports.default = _default;
});
unwrapExports(mathRole_1);
var menuRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = menuRole;
exports.default = _default;
});
unwrapExports(menuRole_1);
var menubarRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = menubarRole;
exports.default = _default;
});
unwrapExports(menubarRole_1);
var menuitemRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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: 'menuitem'
},
module: 'HTML'
}, {
concept: {
name: 'option'
},
module: 'ARIA'
}],
requireContextRole: ['group', 'menu', 'menubar'],
requiredContextRole: ['group', 'menu', 'menubar'],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'widget', 'command']]
};
var _default = menuitemRole;
exports.default = _default;
});
unwrapExports(menuitemRole_1);
var menuitemcheckboxRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = menuitemcheckboxRole;
exports.default = _default;
});
unwrapExports(menuitemcheckboxRole_1);
var menuitemradioRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = menuitemradioRole;
exports.default = _default;
});
unwrapExports(menuitemradioRole_1);
var meterRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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: [],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {
'aria-valuenow': null
},
superClass: [['roletype', 'structure', 'range']]
};
var _default = meterRole;
exports.default = _default;
});
unwrapExports(meterRole_1);
var navigationRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = navigationRole;
exports.default = _default;
});
unwrapExports(navigationRole_1);
var noneRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var noneRole = {
abstract: false,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: [],
prohibitedProps: [],
props: {},
relatedConcepts: [],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: []
};
var _default = noneRole;
exports.default = _default;
});
unwrapExports(noneRole_1);
var noteRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = noteRole;
exports.default = _default;
});
unwrapExports(noteRole_1);
var optionRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = optionRole;
exports.default = _default;
});
unwrapExports(optionRole_1);
var paragraphRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var paragraphRole = {
abstract: false,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['prohibited'],
prohibitedProps: ['aria-label', 'aria-labelledby'],
props: {},
relatedConcepts: [],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section']]
};
var _default = paragraphRole;
exports.default = _default;
});
unwrapExports(paragraphRole_1);
var presentationRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var presentationRole = {
abstract: false,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['prohibited'],
prohibitedProps: ['aria-label', 'aria-labelledby'],
props: {},
relatedConcepts: [],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure']]
};
var _default = presentationRole;
exports.default = _default;
});
unwrapExports(presentationRole_1);
var progressbarRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = progressbarRole;
exports.default = _default;
});
unwrapExports(progressbarRole_1);
var radioRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = radioRole;
exports.default = _default;
});
unwrapExports(radioRole_1);
var radiogroupRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = radiogroupRole;
exports.default = _default;
});
unwrapExports(radiogroupRole_1);
var regionRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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'
}
}, {
concept: {
name: 'frame'
},
module: 'HTML'
}],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section', 'landmark']]
};
var _default = regionRole;
exports.default = _default;
});
unwrapExports(regionRole_1);
var rowRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = rowRole;
exports.default = _default;
});
unwrapExports(rowRole_1);
var rowgroupRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = rowgroupRole;
exports.default = _default;
});
unwrapExports(rowgroupRole_1);
var rowheaderRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = rowheaderRole;
exports.default = _default;
});
unwrapExports(rowheaderRole_1);
var scrollbarRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = scrollbarRole;
exports.default = _default;
});
unwrapExports(scrollbarRole_1);
var searchRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = searchRole;
exports.default = _default;
});
unwrapExports(searchRole_1);
var searchboxRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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'
}],
name: 'input'
},
module: 'HTML'
}],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'widget', 'input', 'textbox']]
};
var _default = searchboxRole;
exports.default = _default;
});
unwrapExports(searchboxRole_1);
var separatorRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = separatorRole;
exports.default = _default;
});
unwrapExports(separatorRole_1);
var sliderRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = sliderRole;
exports.default = _default;
});
unwrapExports(sliderRole_1);
var spinbuttonRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = spinbuttonRole;
exports.default = _default;
});
unwrapExports(spinbuttonRole_1);
var statusRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = statusRole;
exports.default = _default;
});
unwrapExports(statusRole_1);
var strongRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var strongRole = {
abstract: false,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['prohibited'],
prohibitedProps: ['aria-label', 'aria-labelledby'],
props: {},
relatedConcepts: [],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section']]
};
var _default = strongRole;
exports.default = _default;
});
unwrapExports(strongRole_1);
var subscriptRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var subscriptRole = {
abstract: false,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['prohibited'],
prohibitedProps: ['aria-label', 'aria-labelledby'],
props: {},
relatedConcepts: [],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section']]
};
var _default = subscriptRole;
exports.default = _default;
});
unwrapExports(subscriptRole_1);
var superscriptRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var superscriptRole = {
abstract: false,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['prohibited'],
prohibitedProps: ['aria-label', 'aria-labelledby'],
props: {},
relatedConcepts: [],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section']]
};
var _default = superscriptRole;
exports.default = _default;
});
unwrapExports(superscriptRole_1);
var switchRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = switchRole;
exports.default = _default;
});
unwrapExports(switchRole_1);
var tabRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = tabRole;
exports.default = _default;
});
unwrapExports(tabRole_1);
var tableRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = tableRole;
exports.default = _default;
});
unwrapExports(tableRole_1);
var tablistRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = tablistRole;
exports.default = _default;
});
unwrapExports(tablistRole_1);
var tabpanelRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = tabpanelRole;
exports.default = _default;
});
unwrapExports(tabpanelRole_1);
var termRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = termRole;
exports.default = _default;
});
unwrapExports(termRole_1);
var textboxRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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'
}],
name: 'input'
},
module: 'HTML'
}, {
concept: {
attributes: [{
constraints: ['undefined'],
name: 'list'
}, {
name: 'type',
value: 'email'
}],
name: 'input'
},
module: 'HTML'
}, {
concept: {
attributes: [{
constraints: ['undefined'],
name: 'list'
}, {
name: 'type',
value: 'tel'
}],
name: 'input'
},
module: 'HTML'
}, {
concept: {
attributes: [{
constraints: ['undefined'],
name: 'list'
}, {
name: 'type',
value: 'text'
}],
name: 'input'
},
module: 'HTML'
}, {
concept: {
attributes: [{
constraints: ['undefined'],
name: 'list'
}, {
name: 'type',
value: 'url'
}],
name: 'input'
},
module: 'HTML'
}, {
concept: {
name: 'input'
},
module: 'XForms'
}, {
concept: {
name: 'textarea'
},
module: 'HTML'
}],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'widget', 'input']]
};
var _default = textboxRole;
exports.default = _default;
});
unwrapExports(textboxRole_1);
var timeRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var timeRole = {
abstract: false,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['author'],
prohibitedProps: [],
props: {},
relatedConcepts: [],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section']]
};
var _default = timeRole;
exports.default = _default;
});
unwrapExports(timeRole_1);
var timerRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = timerRole;
exports.default = _default;
});
unwrapExports(timerRole_1);
var toolbarRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = toolbarRole;
exports.default = _default;
});
unwrapExports(toolbarRole_1);
var tooltipRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = tooltipRole;
exports.default = _default;
});
unwrapExports(tooltipRole_1);
var treeRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = treeRole;
exports.default = _default;
});
unwrapExports(treeRole_1);
var treegridRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = treegridRole;
exports.default = _default;
});
unwrapExports(treegridRole_1);
var treeitemRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = treeitemRole;
exports.default = _default;
});
unwrapExports(treeitemRole_1);
var ariaLiteralRoles_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _alertRole = _interopRequireDefault(alertRole_1);
var _alertdialogRole = _interopRequireDefault(alertdialogRole_1);
var _applicationRole = _interopRequireDefault(applicationRole_1);
var _articleRole = _interopRequireDefault(articleRole_1);
var _bannerRole = _interopRequireDefault(bannerRole_1);
var _blockquoteRole = _interopRequireDefault(blockquoteRole_1);
var _buttonRole = _interopRequireDefault(buttonRole_1);
var _captionRole = _interopRequireDefault(captionRole_1);
var _cellRole = _interopRequireDefault(cellRole_1);
var _checkboxRole = _interopRequireDefault(checkboxRole_1);
var _codeRole = _interopRequireDefault(codeRole_1);
var _columnheaderRole = _interopRequireDefault(columnheaderRole_1);
var _comboboxRole = _interopRequireDefault(comboboxRole_1);
var _complementaryRole = _interopRequireDefault(complementaryRole_1);
var _contentinfoRole = _interopRequireDefault(contentinfoRole_1);
var _definitionRole = _interopRequireDefault(definitionRole_1);
var _deletionRole = _interopRequireDefault(deletionRole_1);
var _dialogRole = _interopRequireDefault(dialogRole_1);
var _directoryRole = _interopRequireDefault(directoryRole_1);
var _documentRole = _interopRequireDefault(documentRole_1);
var _emphasisRole = _interopRequireDefault(emphasisRole_1);
var _feedRole = _interopRequireDefault(feedRole_1);
var _figureRole = _interopRequireDefault(figureRole_1);
var _formRole = _interopRequireDefault(formRole_1);
var _genericRole = _interopRequireDefault(genericRole_1);
var _gridRole = _interopRequireDefault(gridRole_1);
var _gridcellRole = _interopRequireDefault(gridcellRole_1);
var _groupRole = _interopRequireDefault(groupRole_1);
var _headingRole = _interopRequireDefault(headingRole_1);
var _imgRole = _interopRequireDefault(imgRole_1);
var _insertionRole = _interopRequireDefault(insertionRole_1);
var _linkRole = _interopRequireDefault(linkRole_1);
var _listRole = _interopRequireDefault(listRole_1);
var _listboxRole = _interopRequireDefault(listboxRole_1);
var _listitemRole = _interopRequireDefault(listitemRole_1);
var _logRole = _interopRequireDefault(logRole_1);
var _mainRole = _interopRequireDefault(mainRole_1);
var _marqueeRole = _interopRequireDefault(marqueeRole_1);
var _mathRole = _interopRequireDefault(mathRole_1);
var _menuRole = _interopRequireDefault(menuRole_1);
var _menubarRole = _interopRequireDefault(menubarRole_1);
var _menuitemRole = _interopRequireDefault(menuitemRole_1);
var _menuitemcheckboxRole = _interopRequireDefault(menuitemcheckboxRole_1);
var _menuitemradioRole = _interopRequireDefault(menuitemradioRole_1);
var _meterRole = _interopRequireDefault(meterRole_1);
var _navigationRole = _interopRequireDefault(navigationRole_1);
var _noneRole = _interopRequireDefault(noneRole_1);
var _noteRole = _interopRequireDefault(noteRole_1);
var _optionRole = _interopRequireDefault(optionRole_1);
var _paragraphRole = _interopRequireDefault(paragraphRole_1);
var _presentationRole = _interopRequireDefault(presentationRole_1);
var _progressbarRole = _interopRequireDefault(progressbarRole_1);
var _radioRole = _interopRequireDefault(radioRole_1);
var _radiogroupRole = _interopRequireDefault(radiogroupRole_1);
var _regionRole = _interopRequireDefault(regionRole_1);
var _rowRole = _interopRequireDefault(rowRole_1);
var _rowgroupRole = _interopRequireDefault(rowgroupRole_1);
var _rowheaderRole = _interopRequireDefault(rowheaderRole_1);
var _scrollbarRole = _interopRequireDefault(scrollbarRole_1);
var _searchRole = _interopRequireDefault(searchRole_1);
var _searchboxRole = _interopRequireDefault(searchboxRole_1);
var _separatorRole = _interopRequireDefault(separatorRole_1);
var _sliderRole = _interopRequireDefault(sliderRole_1);
var _spinbuttonRole = _interopRequireDefault(spinbuttonRole_1);
var _statusRole = _interopRequireDefault(statusRole_1);
var _strongRole = _interopRequireDefault(strongRole_1);
var _subscriptRole = _interopRequireDefault(subscriptRole_1);
var _superscriptRole = _interopRequireDefault(superscriptRole_1);
var _switchRole = _interopRequireDefault(switchRole_1);
var _tabRole = _interopRequireDefault(tabRole_1);
var _tableRole = _interopRequireDefault(tableRole_1);
var _tablistRole = _interopRequireDefault(tablistRole_1);
var _tabpanelRole = _interopRequireDefault(tabpanelRole_1);
var _termRole = _interopRequireDefault(termRole_1);
var _textboxRole = _interopRequireDefault(textboxRole_1);
var _timeRole = _interopRequireDefault(timeRole_1);
var _timerRole = _interopRequireDefault(timerRole_1);
var _toolbarRole = _interopRequireDefault(toolbarRole_1);
var _tooltipRole = _interopRequireDefault(tooltipRole_1);
var _treeRole = _interopRequireDefault(treeRole_1);
var _treegridRole = _interopRequireDefault(treegridRole_1);
var _treeitemRole = _interopRequireDefault(treeitemRole_1);
function _interopRequireDefault(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], ['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 = ariaLiteralRoles;
exports.default = _default;
});
unwrapExports(ariaLiteralRoles_1);
var docAbstractRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docAbstractRole;
exports.default = _default;
});
unwrapExports(docAbstractRole_1);
var docAcknowledgmentsRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docAcknowledgmentsRole;
exports.default = _default;
});
unwrapExports(docAcknowledgmentsRole_1);
var docAfterwordRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docAfterwordRole;
exports.default = _default;
});
unwrapExports(docAfterwordRole_1);
var docAppendixRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docAppendixRole;
exports.default = _default;
});
unwrapExports(docAppendixRole_1);
var docBacklinkRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var docBacklinkRole = {
abstract: false,
accessibleNameRequired: true,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['author', 'content'],
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 = docBacklinkRole;
exports.default = _default;
});
unwrapExports(docBacklinkRole_1);
var docBiblioentryRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docBiblioentryRole;
exports.default = _default;
});
unwrapExports(docBiblioentryRole_1);
var docBibliographyRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docBibliographyRole;
exports.default = _default;
});
unwrapExports(docBibliographyRole_1);
var docBibliorefRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docBibliorefRole;
exports.default = _default;
});
unwrapExports(docBibliorefRole_1);
var docChapterRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docChapterRole;
exports.default = _default;
});
unwrapExports(docChapterRole_1);
var docColophonRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docColophonRole;
exports.default = _default;
});
unwrapExports(docColophonRole_1);
var docConclusionRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docConclusionRole;
exports.default = _default;
});
unwrapExports(docConclusionRole_1);
var docCoverRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docCoverRole;
exports.default = _default;
});
unwrapExports(docCoverRole_1);
var docCreditRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docCreditRole;
exports.default = _default;
});
unwrapExports(docCreditRole_1);
var docCreditsRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docCreditsRole;
exports.default = _default;
});
unwrapExports(docCreditsRole_1);
var docDedicationRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docDedicationRole;
exports.default = _default;
});
unwrapExports(docDedicationRole_1);
var docEndnoteRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docEndnoteRole;
exports.default = _default;
});
unwrapExports(docEndnoteRole_1);
var docEndnotesRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docEndnotesRole;
exports.default = _default;
});
unwrapExports(docEndnotesRole_1);
var docEpigraphRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docEpigraphRole;
exports.default = _default;
});
unwrapExports(docEpigraphRole_1);
var docEpilogueRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docEpilogueRole;
exports.default = _default;
});
unwrapExports(docEpilogueRole_1);
var docErrataRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docErrataRole;
exports.default = _default;
});
unwrapExports(docErrataRole_1);
var docExampleRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docExampleRole;
exports.default = _default;
});
unwrapExports(docExampleRole_1);
var docFootnoteRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docFootnoteRole;
exports.default = _default;
});
unwrapExports(docFootnoteRole_1);
var docForewordRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docForewordRole;
exports.default = _default;
});
unwrapExports(docForewordRole_1);
var docGlossaryRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docGlossaryRole;
exports.default = _default;
});
unwrapExports(docGlossaryRole_1);
var docGlossrefRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docGlossrefRole;
exports.default = _default;
});
unwrapExports(docGlossrefRole_1);
var docIndexRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docIndexRole;
exports.default = _default;
});
unwrapExports(docIndexRole_1);
var docIntroductionRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docIntroductionRole;
exports.default = _default;
});
unwrapExports(docIntroductionRole_1);
var docNoterefRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docNoterefRole;
exports.default = _default;
});
unwrapExports(docNoterefRole_1);
var docNoticeRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docNoticeRole;
exports.default = _default;
});
unwrapExports(docNoticeRole_1);
var docPagebreakRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docPagebreakRole;
exports.default = _default;
});
unwrapExports(docPagebreakRole_1);
var docPagelistRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docPagelistRole;
exports.default = _default;
});
unwrapExports(docPagelistRole_1);
var docPartRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docPartRole;
exports.default = _default;
});
unwrapExports(docPartRole_1);
var docPrefaceRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docPrefaceRole;
exports.default = _default;
});
unwrapExports(docPrefaceRole_1);
var docPrologueRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docPrologueRole;
exports.default = _default;
});
unwrapExports(docPrologueRole_1);
var docPullquoteRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docPullquoteRole;
exports.default = _default;
});
unwrapExports(docPullquoteRole_1);
var docQnaRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docQnaRole;
exports.default = _default;
});
unwrapExports(docQnaRole_1);
var docSubtitleRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docSubtitleRole;
exports.default = _default;
});
unwrapExports(docSubtitleRole_1);
var docTipRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docTipRole;
exports.default = _default;
});
unwrapExports(docTipRole_1);
var docTocRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = docTocRole;
exports.default = _default;
});
unwrapExports(docTocRole_1);
var ariaDpubRoles_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _docAbstractRole = _interopRequireDefault(docAbstractRole_1);
var _docAcknowledgmentsRole = _interopRequireDefault(docAcknowledgmentsRole_1);
var _docAfterwordRole = _interopRequireDefault(docAfterwordRole_1);
var _docAppendixRole = _interopRequireDefault(docAppendixRole_1);
var _docBacklinkRole = _interopRequireDefault(docBacklinkRole_1);
var _docBiblioentryRole = _interopRequireDefault(docBiblioentryRole_1);
var _docBibliographyRole = _interopRequireDefault(docBibliographyRole_1);
var _docBibliorefRole = _interopRequireDefault(docBibliorefRole_1);
var _docChapterRole = _interopRequireDefault(docChapterRole_1);
var _docColophonRole = _interopRequireDefault(docColophonRole_1);
var _docConclusionRole = _interopRequireDefault(docConclusionRole_1);
var _docCoverRole = _interopRequireDefault(docCoverRole_1);
var _docCreditRole = _interopRequireDefault(docCreditRole_1);
var _docCreditsRole = _interopRequireDefault(docCreditsRole_1);
var _docDedicationRole = _interopRequireDefault(docDedicationRole_1);
var _docEndnoteRole = _interopRequireDefault(docEndnoteRole_1);
var _docEndnotesRole = _interopRequireDefault(docEndnotesRole_1);
var _docEpigraphRole = _interopRequireDefault(docEpigraphRole_1);
var _docEpilogueRole = _interopRequireDefault(docEpilogueRole_1);
var _docErrataRole = _interopRequireDefault(docErrataRole_1);
var _docExampleRole = _interopRequireDefault(docExampleRole_1);
var _docFootnoteRole = _interopRequireDefault(docFootnoteRole_1);
var _docForewordRole = _interopRequireDefault(docForewordRole_1);
var _docGlossaryRole = _interopRequireDefault(docGlossaryRole_1);
var _docGlossrefRole = _interopRequireDefault(docGlossrefRole_1);
var _docIndexRole = _interopRequireDefault(docIndexRole_1);
var _docIntroductionRole = _interopRequireDefault(docIntroductionRole_1);
var _docNoterefRole = _interopRequireDefault(docNoterefRole_1);
var _docNoticeRole = _interopRequireDefault(docNoticeRole_1);
var _docPagebreakRole = _interopRequireDefault(docPagebreakRole_1);
var _docPagelistRole = _interopRequireDefault(docPagelistRole_1);
var _docPartRole = _interopRequireDefault(docPartRole_1);
var _docPrefaceRole = _interopRequireDefault(docPrefaceRole_1);
var _docPrologueRole = _interopRequireDefault(docPrologueRole_1);
var _docPullquoteRole = _interopRequireDefault(docPullquoteRole_1);
var _docQnaRole = _interopRequireDefault(docQnaRole_1);
var _docSubtitleRole = _interopRequireDefault(docSubtitleRole_1);
var _docTipRole = _interopRequireDefault(docTipRole_1);
var _docTocRole = _interopRequireDefault(docTocRole_1);
function _interopRequireDefault(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 = ariaDpubRoles;
exports.default = _default;
});
unwrapExports(ariaDpubRoles_1);
var graphicsDocumentRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = graphicsDocumentRole;
exports.default = _default;
});
unwrapExports(graphicsDocumentRole_1);
var graphicsObjectRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = graphicsObjectRole;
exports.default = _default;
});
unwrapExports(graphicsObjectRole_1);
var graphicsSymbolRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = graphicsSymbolRole;
exports.default = _default;
});
unwrapExports(graphicsSymbolRole_1);
var ariaGraphicsRoles_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _graphicsDocumentRole = _interopRequireDefault(graphicsDocumentRole_1);
var _graphicsObjectRole = _interopRequireDefault(graphicsObjectRole_1);
var _graphicsSymbolRole = _interopRequireDefault(graphicsSymbolRole_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ariaGraphicsRoles = [['graphics-document', _graphicsDocumentRole.default], ['graphics-object', _graphicsObjectRole.default], ['graphics-symbol', _graphicsSymbolRole.default]];
var _default = ariaGraphicsRoles;
exports.default = _default;
});
unwrapExports(ariaGraphicsRoles_1);
var rolesMap_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _ariaAbstractRoles = _interopRequireDefault(ariaAbstractRoles_1);
var _ariaLiteralRoles = _interopRequireDefault(ariaLiteralRoles_1);
var _ariaDpubRoles = _interopRequireDefault(ariaDpubRoles_1);
var _ariaGraphicsRoles = _interopRequireDefault(ariaGraphicsRoles_1);
var _iterationDecorator = _interopRequireDefault(iterationDecorator_1);
function _interopRequireDefault(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(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 _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 _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; }
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; }
var roles = [].concat(_ariaAbstractRoles.default, _ariaLiteralRoles.default, _ariaDpubRoles.default, _ariaGraphicsRoles.default);
roles.forEach(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
roleDefinition = _ref2[1];
// Conglomerate the properties
var _iterator = _createForOfIteratorHelper(roleDefinition.superClass),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var superClassIter = _step.value;
var _iterator2 = _createForOfIteratorHelper(superClassIter),
_step2;
try {
var _loop = function _loop() {
var superClassName = _step2.value;
var superClassRoleTuple = roles.find(function (_ref3) {
var _ref4 = _slicedToArray(_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;
},
forEach: function forEach(fn) {
var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var _iterator3 = _createForOfIteratorHelper(roles),
_step3;
try {
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
var _step3$value = _slicedToArray(_step3.value, 2),
key = _step3$value[0],
values = _step3$value[1];
fn.call(thisArg, values, key, roles);
}
} catch (err) {
_iterator3.e(err);
} finally {
_iterator3.f();
}
},
get: function get(key) {
var item = roles.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.map(function (_ref5) {
var _ref6 = _slicedToArray(_ref5, 1),
key = _ref6[0];
return key;
});
},
values: function values() {
return roles.map(function (_ref7) {
var _ref8 = _slicedToArray(_ref7, 2),
values = _ref8[1];
return values;
});
}
};
var _default = (0, _iterationDecorator.default)(rolesMap, rolesMap.entries());
exports.default = _default;
});
unwrapExports(rolesMap_1);
var toStr = Object.prototype.toString;
var isArguments = function isArguments(value) {
var str = toStr.call(value);
var isArgs = str === '[object Arguments]';
if (!isArgs) {
isArgs = str !== '[object Array]' &&
value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
toStr.call(value.callee) === '[object Function]';
}
return isArgs;
};
var keysShim;
if (!Object.keys) {
// modified from https://github.com/es-shims/es5-shim
var has = Object.prototype.hasOwnProperty;
var toStr$1 = Object.prototype.toString;
var isArgs = isArguments; // eslint-disable-line global-require
var isEnumerable = Object.prototype.propertyIsEnumerable;
var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
var dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
var equalsConstructorPrototype = function (o) {
var ctor = o.constructor;
return ctor && ctor.prototype === o;
};
var excludedKeys = {
$applicationCache: true,
$console: true,
$external: true,
$frame: true,
$frameElement: true,
$frames: true,
$innerHeight: true,
$innerWidth: true,
$onmozfullscreenchange: true,
$onmozfullscreenerror: true,
$outerHeight: true,
$outerWidth: true,
$pageXOffset: true,
$pageYOffset: true,
$parent: true,
$scrollLeft: true,
$scrollTop: true,
$scrollX: true,
$scrollY: true,
$self: true,
$webkitIndexedDB: true,
$webkitStorageInfo: true,
$window: true
};
var hasAutomationEqualityBug = (function () {
/* global window */
if (typeof window === 'undefined') { return false; }
for (var k in window) {
try {
if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
try {
equalsConstructorPrototype(window[k]);
} catch (e) {
return true;
}
}
} catch (e) {
return true;
}
}
return false;
}());
var equalsConstructorPrototypeIfNotBuggy = function (o) {
/* global window */
if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
return equalsConstructorPrototype(o);
}
try {
return equalsConstructorPrototype(o);
} catch (e) {
return false;
}
};
keysShim = function keys(object) {
var isObject = object !== null && typeof object === 'object';
var isFunction = toStr$1.call(object) === '[object Function]';
var isArguments = isArgs(object);
var isString = isObject && toStr$1.call(object) === '[object String]';
var theKeys = [];
if (!isObject && !isFunction && !isArguments) {
throw new TypeError('Object.keys called on a non-object');
}
var skipProto = hasProtoEnumBug && isFunction;
if (isString && object.length > 0 && !has.call(object, 0)) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i));
}
}
if (isArguments && object.length > 0) {
for (var j = 0; j < object.length; ++j) {
theKeys.push(String(j));
}
} else {
for (var name in object) {
if (!(skipProto && name === 'prototype') && has.call(object, name)) {
theKeys.push(String(name));
}
}
}
if (hasDontEnumBug) {
var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
for (var k = 0; k < dontEnums.length; ++k) {
if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
theKeys.push(dontEnums[k]);
}
}
}
return theKeys;
};
}
var implementation = keysShim;
var slice = Array.prototype.slice;
var origKeys = Object.keys;
var keysShim$1 = origKeys ? function keys(o) { return origKeys(o); } : implementation;
var originalKeys = Object.keys;
keysShim$1.shim = function shimObjectKeys() {
if (Object.keys) {
var keysWorksWithArguments = (function () {
// Safari 5.0 bug
var args = Object.keys(arguments);
return args && args.length === arguments.length;
}(1, 2));
if (!keysWorksWithArguments) {
Object.keys = function keys(object) { // eslint-disable-line func-name-matching
if (isArguments(object)) {
return originalKeys(slice.call(object));
}
return originalKeys(object);
};
}
} else {
Object.keys = keysShim$1;
}
return Object.keys || keysShim$1;
};
var objectKeys = keysShim$1;
/* eslint complexity: [2, 18], max-statements: [2, 33] */
var shams = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
var shams$1 = function hasToStringTagShams() {
return shams() && !!Symbol.toStringTag;
};
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbols = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return shams();
};
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var slice$1 = Array.prototype.slice;
var toStr$2 = Object.prototype.toString;
var funcType = '[object Function]';
var implementation$1 = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr$2.call(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slice$1.call(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
args.concat(slice$1.call(arguments))
);
if (Object(result) === result) {
return result;
}
return this;
} else {
return target.apply(
that,
args.concat(slice$1.call(arguments))
);
}
};
var boundLength = Math.max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs.push('$' + i);
}
bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
var functionBind = Function.prototype.bind || implementation$1;
var src = functionBind.call(Function.call, Object.prototype.hasOwnProperty);
var undefined$1;
var $SyntaxError = SyntaxError;
var $Function = Function;
var $TypeError = TypeError;
// eslint-disable-next-line consistent-return
var getEvalledConstructor = function (expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
} catch (e) {}
};
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () {
throw new $TypeError();
};
var ThrowTypeError = $gOPD
? (function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}())
: throwTypeError;
var hasSymbols$1 = hasSymbols();
var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto
var needsEval = {};
var TypedArray = typeof Uint8Array === 'undefined' ? undefined$1 : getProto(Uint8Array);
var INTRINSICS = {
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined$1 : AggregateError,
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined$1 : ArrayBuffer,
'%ArrayIteratorPrototype%': hasSymbols$1 ? getProto([][Symbol.iterator]()) : undefined$1,
'%AsyncFromSyncIteratorPrototype%': undefined$1,
'%AsyncFunction%': needsEval,
'%AsyncGenerator%': needsEval,
'%AsyncGeneratorFunction%': needsEval,
'%AsyncIteratorPrototype%': needsEval,
'%Atomics%': typeof Atomics === 'undefined' ? undefined$1 : Atomics,
'%BigInt%': typeof BigInt === 'undefined' ? undefined$1 : BigInt,
'%Boolean%': Boolean,
'%DataView%': typeof DataView === 'undefined' ? undefined$1 : DataView,
'%Date%': Date,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': Error,
'%eval%': eval, // eslint-disable-line no-eval
'%EvalError%': EvalError,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined$1 : Float32Array,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined$1 : Float64Array,
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined$1 : FinalizationRegistry,
'%Function%': $Function,
'%GeneratorFunction%': needsEval,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined$1 : Int8Array,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined$1 : Int16Array,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined$1 : Int32Array,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols$1 ? getProto(getProto([][Symbol.iterator]())) : undefined$1,
'%JSON%': typeof JSON === 'object' ? JSON : undefined$1,
'%Map%': typeof Map === 'undefined' ? undefined$1 : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols$1 ? undefined$1 : getProto(new Map()[Symbol.iterator]()),
'%Math%': Math,
'%Number%': Number,
'%Object%': Object,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined$1 : Promise,
'%Proxy%': typeof Proxy === 'undefined' ? undefined$1 : Proxy,
'%RangeError%': RangeError,
'%ReferenceError%': ReferenceError,
'%Reflect%': typeof Reflect === 'undefined' ? undefined$1 : Reflect,
'%RegExp%': RegExp,
'%Set%': typeof Set === 'undefined' ? undefined$1 : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols$1 ? undefined$1 : getProto(new Set()[Symbol.iterator]()),
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined$1 : SharedArrayBuffer,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols$1 ? getProto(''[Symbol.iterator]()) : undefined$1,
'%Symbol%': hasSymbols$1 ? Symbol : undefined$1,
'%SyntaxError%': $SyntaxError,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypeError%': $TypeError,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined$1 : Uint8Array,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined$1 : Uint8ClampedArray,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined$1 : Uint16Array,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined$1 : Uint32Array,
'%URIError%': URIError,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined$1 : WeakMap,
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined$1 : WeakRef,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined$1 : WeakSet
};
var doEval = function doEval(name) {
var value;
if (name === '%AsyncFunction%') {
value = getEvalledConstructor('async function () {}');
} else if (name === '%GeneratorFunction%') {
value = getEvalledConstructor('function* () {}');
} else if (name === '%AsyncGeneratorFunction%') {
value = getEvalledConstructor('async function* () {}');
} else if (name === '%AsyncGenerator%') {
var fn = doEval('%AsyncGeneratorFunction%');
if (fn) {
value = fn.prototype;
}
} else if (name === '%AsyncIteratorPrototype%') {
var gen = doEval('%AsyncGenerator%');
if (gen) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name] = value;
return value;
};
var LEGACY_ALIASES = {
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
'%ArrayPrototype%': ['Array', 'prototype'],
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
'%BooleanPrototype%': ['Boolean', 'prototype'],
'%DataViewPrototype%': ['DataView', 'prototype'],
'%DatePrototype%': ['Date', 'prototype'],
'%ErrorPrototype%': ['Error', 'prototype'],
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
'%FunctionPrototype%': ['Function', 'prototype'],
'%Generator%': ['GeneratorFunction', 'prototype'],
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
'%JSONParse%': ['JSON', 'parse'],
'%JSONStringify%': ['JSON', 'stringify'],
'%MapPrototype%': ['Map', 'prototype'],
'%NumberPrototype%': ['Number', 'prototype'],
'%ObjectPrototype%': ['Object', 'prototype'],
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
'%PromisePrototype%': ['Promise', 'prototype'],
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
'%Promise_all%': ['Promise', 'all'],
'%Promise_reject%': ['Promise', 'reject'],
'%Promise_resolve%': ['Promise', 'resolve'],
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
'%RegExpPrototype%': ['RegExp', 'prototype'],
'%SetPrototype%': ['Set', 'prototype'],
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
'%StringPrototype%': ['String', 'prototype'],
'%SymbolPrototype%': ['Symbol', 'prototype'],
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
'%URIErrorPrototype%': ['URIError', 'prototype'],
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
'%WeakSetPrototype%': ['WeakSet', 'prototype']
};
var $concat = functionBind.call(Function.call, Array.prototype.concat);
var $spliceApply = functionBind.call(Function.apply, Array.prototype.splice);
var $replace = functionBind.call(Function.call, String.prototype.replace);
var $strSlice = functionBind.call(Function.call, String.prototype.slice);
var $exec = functionBind.call(Function.call, RegExp.prototype.exec);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
var first = $strSlice(string, 0, 1);
var last = $strSlice(string, -1);
if (first === '%' && last !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
} else if (last === '%' && first !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
}
var result = [];
$replace(string, rePropName, function (match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
var intrinsicName = name;
var alias;
if (src(LEGACY_ALIASES, intrinsicName)) {
alias = LEGACY_ALIASES[intrinsicName];
intrinsicName = '%' + alias[0] + '%';
}
if (src(INTRINSICS, intrinsicName)) {
var value = INTRINSICS[intrinsicName];
if (value === needsEval) {
value = doEval(intrinsicName);
}
if (typeof value === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return {
alias: alias,
name: intrinsicName,
value: value
};
}
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
};
var getIntrinsic = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new $TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new $TypeError('"allowMissing" argument must be a boolean');
}
if ($exec(/^%?[^%]*%?$/, name) === null) {
throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
}
var parts = stringToPath(name);
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
var intrinsicRealName = intrinsic.name;
var value = intrinsic.value;
var skipFurtherCaching = false;
var alias = intrinsic.alias;
if (alias) {
intrinsicBaseName = alias[0];
$spliceApply(parts, $concat([0, 1], alias));
}
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
var part = parts[i];
var first = $strSlice(part, 0, 1);
var last = $strSlice(part, -1);
if (
(
(first === '"' || first === "'" || first === '`')
|| (last === '"' || last === "'" || last === '`')
)
&& first !== last
) {
throw new $SyntaxError('property names with quotes must have matching quotes');
}
if (part === 'constructor' || !isOwn) {
skipFurtherCaching = true;
}
intrinsicBaseName += '.' + part;
intrinsicRealName = '%' + intrinsicBaseName + '%';
if (src(INTRINSICS, intrinsicRealName)) {
value = INTRINSICS[intrinsicRealName];
} else if (value != null) {
if (!(part in value)) {
if (!allowMissing) {
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
}
return void undefined$1;
}
if ($gOPD && (i + 1) >= parts.length) {
var desc = $gOPD(value, part);
isOwn = !!desc;
// By convention, when a data property is converted to an accessor
// property to emulate a data property that does not suffer from
// the override mistake, that accessor's getter is marked with
// an `originalValue` property. Here, when we detect this, we
// uphold the illusion by pretending to see that original data
// property, i.e., returning the value rather than the getter
// itself.
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
value = desc.get;
} else {
value = value[part];
}
} else {
isOwn = src(value, part);
value = value[part];
}
if (isOwn && !skipFurtherCaching) {
INTRINSICS[intrinsicRealName] = value;
}
}
}
return value;
};
var callBind = createCommonjsModule(function (module) {
var $apply = getIntrinsic('%Function.prototype.apply%');
var $call = getIntrinsic('%Function.prototype.call%');
var $reflectApply = getIntrinsic('%Reflect.apply%', true) || functionBind.call($call, $apply);
var $gOPD = getIntrinsic('%Object.getOwnPropertyDescriptor%', true);
var $defineProperty = getIntrinsic('%Object.defineProperty%', true);
var $max = getIntrinsic('%Math.max%');
if ($defineProperty) {
try {
$defineProperty({}, 'a', { value: 1 });
} catch (e) {
// IE 8 has a broken defineProperty
$defineProperty = null;
}
}
module.exports = function callBind(originalFunction) {
var func = $reflectApply(functionBind, $call, arguments);
if ($gOPD && $defineProperty) {
var desc = $gOPD(func, 'length');
if (desc.configurable) {
// original length, plus the receiver, minus any additional arguments (after the receiver)
$defineProperty(
func,
'length',
{ value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) }
);
}
}
return func;
};
var applyBind = function applyBind() {
return $reflectApply(functionBind, $apply, arguments);
};
if ($defineProperty) {
$defineProperty(module.exports, 'apply', { value: applyBind });
} else {
module.exports.apply = applyBind;
}
});
var callBind_1 = callBind.apply;
var $indexOf = callBind(getIntrinsic('String.prototype.indexOf'));
var callBound = function callBoundIntrinsic(name, allowMissing) {
var intrinsic = getIntrinsic(name, !!allowMissing);
if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
return callBind(intrinsic);
}
return intrinsic;
};
var hasToStringTag = shams$1();
var $toString = callBound('Object.prototype.toString');
var isStandardArguments = function isArguments(value) {
if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) {
return false;
}
return $toString(value) === '[object Arguments]';
};
var isLegacyArguments = function isArguments(value) {
if (isStandardArguments(value)) {
return true;
}
return value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
$toString(value) !== '[object Array]' &&
$toString(value.callee) === '[object Function]';
};
var supportsStandardArguments = (function () {
return isStandardArguments(arguments);
}());
isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests
var isArguments$1 = supportsStandardArguments ? isStandardArguments : isLegacyArguments;
var $defineProperty = getIntrinsic('%Object.defineProperty%', true);
var hasPropertyDescriptors = function hasPropertyDescriptors() {
if ($defineProperty) {
try {
$defineProperty({}, 'a', { value: 1 });
return true;
} catch (e) {
// IE 8 has a broken defineProperty
return false;
}
}
return false;
};
hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() {
// node v0.6 has a bug where array lengths can be Set but not Defined
if (!hasPropertyDescriptors()) {
return null;
}
try {
return $defineProperty([], 'length', { value: 1 }).length !== 1;
} catch (e) {
// In Firefox 4-22, defining length on an array throws an exception.
return true;
}
};
var hasPropertyDescriptors_1 = hasPropertyDescriptors;
var hasSymbols$2 = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';
var toStr$3 = Object.prototype.toString;
var concat = Array.prototype.concat;
var origDefineProperty = Object.defineProperty;
var isFunction = function (fn) {
return typeof fn === 'function' && toStr$3.call(fn) === '[object Function]';
};
var hasPropertyDescriptors$1 = hasPropertyDescriptors_1();
var supportsDescriptors = origDefineProperty && hasPropertyDescriptors$1;
var defineProperty = function (object, name, value, predicate) {
if (name in object && (!isFunction(predicate) || !predicate())) {
return;
}
if (supportsDescriptors) {
origDefineProperty(object, name, {
configurable: true,
enumerable: false,
value: value,
writable: true
});
} else {
object[name] = value; // eslint-disable-line no-param-reassign
}
};
var defineProperties = function (object, map) {
var predicates = arguments.length > 2 ? arguments[2] : {};
var props = objectKeys(map);
if (hasSymbols$2) {
props = concat.call(props, Object.getOwnPropertySymbols(map));
}
for (var i = 0; i < props.length; i += 1) {
defineProperty(object, props[i], map[props[i]], predicates[props[i]]);
}
};
defineProperties.supportsDescriptors = !!supportsDescriptors;
var defineProperties_1 = defineProperties;
var numberIsNaN = function (value) {
return value !== value;
};
var implementation$2 = function is(a, b) {
if (a === 0 && b === 0) {
return 1 / a === 1 / b;
}
if (a === b) {
return true;
}
if (numberIsNaN(a) && numberIsNaN(b)) {
return true;
}
return false;
};
var polyfill = function getPolyfill() {
return typeof Object.is === 'function' ? Object.is : implementation$2;
};
var shim = function shimObjectIs() {
var polyfill$1 = polyfill();
defineProperties_1(Object, { is: polyfill$1 }, {
is: function testObjectIs() {
return Object.is !== polyfill$1;
}
});
return polyfill$1;
};
var polyfill$1 = callBind(polyfill(), Object);
defineProperties_1(polyfill$1, {
getPolyfill: polyfill,
implementation: implementation$2,
shim: shim
});
var objectIs = polyfill$1;
var hasToStringTag$1 = shams$1();
var has$1;
var $exec$1;
var isRegexMarker;
var badStringifier;
if (hasToStringTag$1) {
has$1 = callBound('Object.prototype.hasOwnProperty');
$exec$1 = callBound('RegExp.prototype.exec');
isRegexMarker = {};
var throwRegexMarker = function () {
throw isRegexMarker;
};
badStringifier = {
toString: throwRegexMarker,
valueOf: throwRegexMarker
};
if (typeof Symbol.toPrimitive === 'symbol') {
badStringifier[Symbol.toPrimitive] = throwRegexMarker;
}
}
var $toString$1 = callBound('Object.prototype.toString');
var gOPD = Object.getOwnPropertyDescriptor;
var regexClass = '[object RegExp]';
var isRegex = hasToStringTag$1
// eslint-disable-next-line consistent-return
? function isRegex(value) {
if (!value || typeof value !== 'object') {
return false;
}
var descriptor = gOPD(value, 'lastIndex');
var hasLastIndexDataProperty = descriptor && has$1(descriptor, 'value');
if (!hasLastIndexDataProperty) {
return false;
}
try {
$exec$1(value, badStringifier);
} catch (e) {
return e === isRegexMarker;
}
}
: function isRegex(value) {
// In older browsers, typeof regex incorrectly returns 'function'
if (!value || (typeof value !== 'object' && typeof value !== 'function')) {
return false;
}
return $toString$1(value) === regexClass;
};
var functionsHaveNames = function functionsHaveNames() {
return typeof function f() {}.name === 'string';
};
var gOPD$1 = Object.getOwnPropertyDescriptor;
if (gOPD$1) {
try {
gOPD$1([], 'length');
} catch (e) {
// IE 8 has a broken gOPD
gOPD$1 = null;
}
}
functionsHaveNames.functionsHaveConfigurableNames = function functionsHaveConfigurableNames() {
if (!functionsHaveNames() || !gOPD$1) {
return false;
}
var desc = gOPD$1(function () {}, 'name');
return !!desc && !!desc.configurable;
};
var $bind = Function.prototype.bind;
functionsHaveNames.boundFunctionsHaveNames = function boundFunctionsHaveNames() {
return functionsHaveNames() && typeof $bind === 'function' && function f() {}.bind().name !== '';
};
var functionsHaveNames_1 = functionsHaveNames;
var implementation$3 = createCommonjsModule(function (module) {
var functionsHaveConfigurableNames = functionsHaveNames_1.functionsHaveConfigurableNames();
var $Object = Object;
var $TypeError = TypeError;
module.exports = function flags() {
if (this != null && this !== $Object(this)) {
throw new $TypeError('RegExp.prototype.flags getter called on non-object');
}
var result = '';
if (this.hasIndices) {
result += 'd';
}
if (this.global) {
result += 'g';
}
if (this.ignoreCase) {
result += 'i';
}
if (this.multiline) {
result += 'm';
}
if (this.dotAll) {
result += 's';
}
if (this.unicode) {
result += 'u';
}
if (this.sticky) {
result += 'y';
}
return result;
};
if (functionsHaveConfigurableNames && Object.defineProperty) {
Object.defineProperty(module.exports, 'name', { value: 'get flags' });
}
});
var supportsDescriptors$1 = defineProperties_1.supportsDescriptors;
var $gOPD$1 = Object.getOwnPropertyDescriptor;
var polyfill$2 = function getPolyfill() {
if (supportsDescriptors$1 && (/a/mig).flags === 'gim') {
var descriptor = $gOPD$1(RegExp.prototype, 'flags');
if (
descriptor
&& typeof descriptor.get === 'function'
&& typeof RegExp.prototype.dotAll === 'boolean'
&& typeof RegExp.prototype.hasIndices === 'boolean'
) {
/* eslint getter-return: 0 */
var calls = '';
var o = {};
Object.defineProperty(o, 'hasIndices', {
get: function () {
calls += 'd';
}
});
Object.defineProperty(o, 'sticky', {
get: function () {
calls += 'y';
}
});
if (calls === 'dy') {
return descriptor.get;
}
}
}
return implementation$3;
};
var supportsDescriptors$2 = defineProperties_1.supportsDescriptors;
var gOPD$2 = Object.getOwnPropertyDescriptor;
var defineProperty$1 = Object.defineProperty;
var TypeErr = TypeError;
var getProto$1 = Object.getPrototypeOf;
var regex = /a/;
var shim$1 = function shimFlags() {
if (!supportsDescriptors$2 || !getProto$1) {
throw new TypeErr('RegExp.prototype.flags requires a true ES5 environment that supports property descriptors');
}
var polyfill = polyfill$2();
var proto = getProto$1(regex);
var descriptor = gOPD$2(proto, 'flags');
if (!descriptor || descriptor.get !== polyfill) {
defineProperty$1(proto, 'flags', {
configurable: true,
enumerable: false,
get: polyfill
});
}
return polyfill;
};
var flagsBound = callBind(polyfill$2());
defineProperties_1(flagsBound, {
getPolyfill: polyfill$2,
implementation: implementation$3,
shim: shim$1
});
var regexp_prototype_flags = flagsBound;
var toString$1 = {}.toString;
var isarray = Array.isArray || function (arr) {
return toString$1.call(arr) == '[object Array]';
};
var getDay = Date.prototype.getDay;
var tryDateObject = function tryDateGetDayCall(value) {
try {
getDay.call(value);
return true;
} catch (e) {
return false;
}
};
var toStr$4 = Object.prototype.toString;
var dateClass = '[object Date]';
var hasToStringTag$2 = shams$1();
var isDateObject = function isDateObject(value) {
if (typeof value !== 'object' || value === null) {
return false;
}
return hasToStringTag$2 ? tryDateObject(value) : toStr$4.call(value) === dateClass;
};
var strValue = String.prototype.valueOf;
var tryStringObject = function tryStringObject(value) {
try {
strValue.call(value);
return true;
} catch (e) {
return false;
}
};
var toStr$5 = Object.prototype.toString;
var strClass = '[object String]';
var hasToStringTag$3 = shams$1();
var isString = function isString(value) {
if (typeof value === 'string') {
return true;
}
if (typeof value !== 'object') {
return false;
}
return hasToStringTag$3 ? tryStringObject(value) : toStr$5.call(value) === strClass;
};
var numToStr = Number.prototype.toString;
var tryNumberObject = function tryNumberObject(value) {
try {
numToStr.call(value);
return true;
} catch (e) {
return false;
}
};
var toStr$6 = Object.prototype.toString;
var numClass = '[object Number]';
var hasToStringTag$4 = shams$1();
var isNumberObject = function isNumberObject(value) {
if (typeof value === 'number') {
return true;
}
if (typeof value !== 'object') {
return false;
}
return hasToStringTag$4 ? tryNumberObject(value) : toStr$6.call(value) === numClass;
};
var $boolToStr = callBound('Boolean.prototype.toString');
var $toString$2 = callBound('Object.prototype.toString');
var tryBooleanObject = function booleanBrandCheck(value) {
try {
$boolToStr(value);
return true;
} catch (e) {
return false;
}
};
var boolClass = '[object Boolean]';
var hasToStringTag$5 = shams$1();
var isBooleanObject = function isBoolean(value) {
if (typeof value === 'boolean') {
return true;
}
if (value === null || typeof value !== 'object') {
return false;
}
return hasToStringTag$5 && Symbol.toStringTag in value ? tryBooleanObject(value) : $toString$2(value) === boolClass;
};
var isSymbol = createCommonjsModule(function (module) {
var toStr = Object.prototype.toString;
var hasSymbols$1 = hasSymbols();
if (hasSymbols$1) {
var symToStr = Symbol.prototype.toString;
var symStringRegex = /^Symbol\(.*\)$/;
var isSymbolObject = function isRealSymbolObject(value) {
if (typeof value.valueOf() !== 'symbol') {
return false;
}
return symStringRegex.test(symToStr.call(value));
};
module.exports = function isSymbol(value) {
if (typeof value === 'symbol') {
return true;
}
if (toStr.call(value) !== '[object Symbol]') {
return false;
}
try {
return isSymbolObject(value);
} catch (e) {
return false;
}
};
} else {
module.exports = function isSymbol(value) {
// this environment does not support Symbols.
return false ;
};
}
});
var $BigInt = typeof BigInt !== 'undefined' && BigInt;
var hasBigints = function hasNativeBigInts() {
return typeof $BigInt === 'function'
&& typeof BigInt === 'function'
&& typeof $BigInt(42) === 'bigint' // eslint-disable-line no-magic-numbers
&& typeof BigInt(42) === 'bigint'; // eslint-disable-line no-magic-numbers
};
var isBigint = createCommonjsModule(function (module) {
var hasBigInts = hasBigints();
if (hasBigInts) {
var bigIntValueOf = BigInt.prototype.valueOf;
var tryBigInt = function tryBigIntObject(value) {
try {
bigIntValueOf.call(value);
return true;
} catch (e) {
}
return false;
};
module.exports = function isBigInt(value) {
if (
value === null
|| typeof value === 'undefined'
|| typeof value === 'boolean'
|| typeof value === 'string'
|| typeof value === 'number'
|| typeof value === 'symbol'
|| typeof value === 'function'
) {
return false;
}
if (typeof value === 'bigint') {
return true;
}
return tryBigInt(value);
};
} else {
module.exports = function isBigInt(value) {
return false ;
};
}
});
// eslint-disable-next-line consistent-return
var whichBoxedPrimitive = function whichBoxedPrimitive(value) {
// eslint-disable-next-line eqeqeq
if (value == null || (typeof value !== 'object' && typeof value !== 'function')) {
return null;
}
if (isString(value)) {
return 'String';
}
if (isNumberObject(value)) {
return 'Number';
}
if (isBooleanObject(value)) {
return 'Boolean';
}
if (isSymbol(value)) {
return 'Symbol';
}
if (isBigint(value)) {
return 'BigInt';
}
};
var $Map = typeof Map === 'function' && Map.prototype ? Map : null;
var $Set = typeof Set === 'function' && Set.prototype ? Set : null;
var exported;
if (!$Map) {
// eslint-disable-next-line no-unused-vars
exported = function isMap(x) {
// `Map` is not present in this environment.
return false;
};
}
var $mapHas = $Map ? Map.prototype.has : null;
var $setHas = $Set ? Set.prototype.has : null;
if (!exported && !$mapHas) {
// eslint-disable-next-line no-unused-vars
exported = function isMap(x) {
// `Map` does not have a `has` method
return false;
};
}
var isMap = exported || function isMap(x) {
if (!x || typeof x !== 'object') {
return false;
}
try {
$mapHas.call(x);
if ($setHas) {
try {
$setHas.call(x);
} catch (e) {
return true;
}
}
return x instanceof $Map; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
};
var $Map$1 = typeof Map === 'function' && Map.prototype ? Map : null;
var $Set$1 = typeof Set === 'function' && Set.prototype ? Set : null;
var exported$1;
if (!$Set$1) {
// eslint-disable-next-line no-unused-vars
exported$1 = function isSet(x) {
// `Set` is not present in this environment.
return false;
};
}
var $mapHas$1 = $Map$1 ? Map.prototype.has : null;
var $setHas$1 = $Set$1 ? Set.prototype.has : null;
if (!exported$1 && !$setHas$1) {
// eslint-disable-next-line no-unused-vars
exported$1 = function isSet(x) {
// `Set` does not have a `has` method
return false;
};
}
var isSet = exported$1 || function isSet(x) {
if (!x || typeof x !== 'object') {
return false;
}
try {
$setHas$1.call(x);
if ($mapHas$1) {
try {
$mapHas$1.call(x);
} catch (e) {
return true;
}
}
return x instanceof $Set$1; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
};
var $WeakMap = typeof WeakMap === 'function' && WeakMap.prototype ? WeakMap : null;
var $WeakSet = typeof WeakSet === 'function' && WeakSet.prototype ? WeakSet : null;
var exported$2;
if (!$WeakMap) {
// eslint-disable-next-line no-unused-vars
exported$2 = function isWeakMap(x) {
// `WeakMap` is not present in this environment.
return false;
};
}
var $mapHas$2 = $WeakMap ? $WeakMap.prototype.has : null;
var $setHas$2 = $WeakSet ? $WeakSet.prototype.has : null;
if (!exported$2 && !$mapHas$2) {
// eslint-disable-next-line no-unused-vars
exported$2 = function isWeakMap(x) {
// `WeakMap` does not have a `has` method
return false;
};
}
var isWeakmap = exported$2 || function isWeakMap(x) {
if (!x || typeof x !== 'object') {
return false;
}
try {
$mapHas$2.call(x, $mapHas$2);
if ($setHas$2) {
try {
$setHas$2.call(x, $setHas$2);
} catch (e) {
return true;
}
}
return x instanceof $WeakMap; // core-js workaround, pre-v3
} catch (e) {}
return false;
};
var isWeakset = createCommonjsModule(function (module) {
var $WeakSet = getIntrinsic('%WeakSet%', true);
var $setHas = callBound('WeakSet.prototype.has', true);
if ($setHas) {
var $mapHas = callBound('WeakMap.prototype.has', true);
module.exports = function isWeakSet(x) {
if (!x || typeof x !== 'object') {
return false;
}
try {
$setHas(x, $setHas);
if ($mapHas) {
try {
$mapHas(x, $mapHas);
} catch (e) {
return true;
}
}
return x instanceof $WeakSet; // core-js workaround, pre-v3
} catch (e) {}
return false;
};
} else {
// eslint-disable-next-line no-unused-vars
module.exports = function isWeakSet(x) {
// `WeakSet` does not exist, or does not have a `has` method
return false;
};
}
});
var whichCollection = function whichCollection(value) {
if (value && typeof value === 'object') {
if (isMap(value)) {
return 'Map';
}
if (isSet(value)) {
return 'Set';
}
if (isWeakmap(value)) {
return 'WeakMap';
}
if (isWeakset(value)) {
return 'WeakSet';
}
}
return false;
};
// this should only run in node >= 13.7, so it
// does not need any of the intense fallbacks that old node/browsers do
var $iterator = Symbol.iterator;
function getIterator(iterable) {
// alternatively, `iterable[$iterator]?.()`
if (iterable != null && iterable[$iterator] !== undefined) {
return iterable[$iterator]();
}
}
var node$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
'default': getIterator
});
var toStr$7 = Object.prototype.toString;
var fnToStr = Function.prototype.toString;
var isFnRegex = /^\s*(?:function)?\*/;
var hasToStringTag$6 = shams$1();
var getProto$2 = Object.getPrototypeOf;
var getGeneratorFunc = function () { // eslint-disable-line consistent-return
if (!hasToStringTag$6) {
return false;
}
try {
return Function('return function*() {}')();
} catch (e) {
}
};
var GeneratorFunction;
var isGeneratorFunction = function isGeneratorFunction(fn) {
if (typeof fn !== 'function') {
return false;
}
if (isFnRegex.test(fnToStr.call(fn))) {
return true;
}
if (!hasToStringTag$6) {
var str = toStr$7.call(fn);
return str === '[object GeneratorFunction]';
}
if (!getProto$2) {
return false;
}
if (typeof GeneratorFunction === 'undefined') {
var generatorFunc = getGeneratorFunc();
GeneratorFunction = generatorFunc ? getProto$2(generatorFunc) : false;
}
return getProto$2(fn) === GeneratorFunction;
};
var fnToStr$1 = Function.prototype.toString;
var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply;
var badArrayLike;
var isCallableMarker;
if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') {
try {
badArrayLike = Object.defineProperty({}, 'length', {
get: function () {
throw isCallableMarker;
}
});
isCallableMarker = {};
// eslint-disable-next-line no-throw-literal
reflectApply(function () { throw 42; }, null, badArrayLike);
} catch (_) {
if (_ !== isCallableMarker) {
reflectApply = null;
}
}
} else {
reflectApply = null;
}
var constructorRegex = /^\s*class\b/;
var isES6ClassFn = function isES6ClassFunction(value) {
try {
var fnStr = fnToStr$1.call(value);
return constructorRegex.test(fnStr);
} catch (e) {
return false; // not a function
}
};
var tryFunctionObject = function tryFunctionToStr(value) {
try {
if (isES6ClassFn(value)) { return false; }
fnToStr$1.call(value);
return true;
} catch (e) {
return false;
}
};
var toStr$8 = Object.prototype.toString;
var objectClass = '[object Object]';
var fnClass = '[object Function]';
var genClass = '[object GeneratorFunction]';
var ddaClass = '[object HTMLAllCollection]'; // IE 11
var ddaClass2 = '[object HTML document.all class]';
var ddaClass3 = '[object HTMLCollection]'; // IE 9-10
var hasToStringTag$7 = typeof Symbol === 'function' && !!Symbol.toStringTag; // better: use `has-tostringtag`
var isIE68 = !(0 in [,]); // eslint-disable-line no-sparse-arrays, comma-spacing
var isDDA = function isDocumentDotAll() { return false; };
if (typeof document === 'object') {
// Firefox 3 canonicalizes DDA to undefined when it's not accessed directly
var all = document.all;
if (toStr$8.call(all) === toStr$8.call(document.all)) {
isDDA = function isDocumentDotAll(value) {
/* globals document: false */
// in IE 6-8, typeof document.all is "object" and it's truthy
if ((isIE68 || !value) && (typeof value === 'undefined' || typeof value === 'object')) {
try {
var str = toStr$8.call(value);
return (
str === ddaClass
|| str === ddaClass2
|| str === ddaClass3 // opera 12.16
|| str === objectClass // IE 6-8
) && value('') == null; // eslint-disable-line eqeqeq
} catch (e) { /**/ }
}
return false;
};
}
}
var isCallable = reflectApply
? function isCallable(value) {
if (isDDA(value)) { return true; }
if (!value) { return false; }
if (typeof value !== 'function' && typeof value !== 'object') { return false; }
try {
reflectApply(value, null, badArrayLike);
} catch (e) {
if (e !== isCallableMarker) { return false; }
}
return !isES6ClassFn(value) && tryFunctionObject(value);
}
: function isCallable(value) {
if (isDDA(value)) { return true; }
if (!value) { return false; }
if (typeof value !== 'function' && typeof value !== 'object') { return false; }
if (hasToStringTag$7) { return tryFunctionObject(value); }
if (isES6ClassFn(value)) { return false; }
var strClass = toStr$8.call(value);
if (strClass !== fnClass && strClass !== genClass && !(/^\[object HTML/).test(strClass)) { return false; }
return tryFunctionObject(value);
};
var toStr$9 = Object.prototype.toString;
var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
var forEachArray = function forEachArray(array, iterator, receiver) {
for (var i = 0, len = array.length; i < len; i++) {
if (hasOwnProperty$2.call(array, i)) {
if (receiver == null) {
iterator(array[i], i, array);
} else {
iterator.call(receiver, array[i], i, array);
}
}
}
};
var forEachString = function forEachString(string, iterator, receiver) {
for (var i = 0, len = string.length; i < len; i++) {
// no such thing as a sparse string.
if (receiver == null) {
iterator(string.charAt(i), i, string);
} else {
iterator.call(receiver, string.charAt(i), i, string);
}
}
};
var forEachObject = function forEachObject(object, iterator, receiver) {
for (var k in object) {
if (hasOwnProperty$2.call(object, k)) {
if (receiver == null) {
iterator(object[k], k, object);
} else {
iterator.call(receiver, object[k], k, object);
}
}
}
};
var forEach = function forEach(list, iterator, thisArg) {
if (!isCallable(iterator)) {
throw new TypeError('iterator must be a function');
}
var receiver;
if (arguments.length >= 3) {
receiver = thisArg;
}
if (toStr$9.call(list) === '[object Array]') {
forEachArray(list, iterator, receiver);
} else if (typeof list === 'string') {
forEachString(list, iterator, receiver);
} else {
forEachObject(list, iterator, receiver);
}
};
var forEach_1 = forEach;
var possibleNames = [
'BigInt64Array',
'BigUint64Array',
'Float32Array',
'Float64Array',
'Int16Array',
'Int32Array',
'Int8Array',
'Uint16Array',
'Uint32Array',
'Uint8Array',
'Uint8ClampedArray'
];
var g = typeof globalThis === 'undefined' ? commonjsGlobal : globalThis;
var availableTypedArrays = function availableTypedArrays() {
var out = [];
for (var i = 0; i < possibleNames.length; i++) {
if (typeof g[possibleNames[i]] === 'function') {
out[out.length] = possibleNames[i];
}
}
return out;
};
var $gOPD$2 = getIntrinsic('%Object.getOwnPropertyDescriptor%', true);
if ($gOPD$2) {
try {
$gOPD$2([], 'length');
} catch (e) {
// IE 8 has a broken gOPD
$gOPD$2 = null;
}
}
var getOwnPropertyDescriptor = $gOPD$2;
var $toString$3 = callBound('Object.prototype.toString');
var hasToStringTag$8 = shams$1();
var g$1 = typeof globalThis === 'undefined' ? commonjsGlobal : globalThis;
var typedArrays = availableTypedArrays();
var $indexOf$1 = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) {
for (var i = 0; i < array.length; i += 1) {
if (array[i] === value) {
return i;
}
}
return -1;
};
var $slice = callBound('String.prototype.slice');
var toStrTags = {};
var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof');
if (hasToStringTag$8 && getOwnPropertyDescriptor && getPrototypeOf) {
forEach_1(typedArrays, function (typedArray) {
var arr = new g$1[typedArray]();
if (Symbol.toStringTag in arr) {
var proto = getPrototypeOf(arr);
var descriptor = getOwnPropertyDescriptor(proto, Symbol.toStringTag);
if (!descriptor) {
var superProto = getPrototypeOf(proto);
descriptor = getOwnPropertyDescriptor(superProto, Symbol.toStringTag);
}
toStrTags[typedArray] = descriptor.get;
}
});
}
var tryTypedArrays = function tryAllTypedArrays(value) {
var anyTrue = false;
forEach_1(toStrTags, function (getter, typedArray) {
if (!anyTrue) {
try {
anyTrue = getter.call(value) === typedArray;
} catch (e) { /**/ }
}
});
return anyTrue;
};
var isTypedArray = function isTypedArray(value) {
if (!value || typeof value !== 'object') { return false; }
if (!hasToStringTag$8 || !(Symbol.toStringTag in value)) {
var tag = $slice($toString$3(value), 8, -1);
return $indexOf$1(typedArrays, tag) > -1;
}
if (!getOwnPropertyDescriptor) { return false; }
return tryTypedArrays(value);
};
var $toString$4 = callBound('Object.prototype.toString');
var hasToStringTag$9 = shams$1();
var g$2 = typeof globalThis === 'undefined' ? commonjsGlobal : globalThis;
var typedArrays$1 = availableTypedArrays();
var $slice$1 = callBound('String.prototype.slice');
var toStrTags$1 = {};
var getPrototypeOf$1 = Object.getPrototypeOf; // require('getprototypeof');
if (hasToStringTag$9 && getOwnPropertyDescriptor && getPrototypeOf$1) {
forEach_1(typedArrays$1, function (typedArray) {
if (typeof g$2[typedArray] === 'function') {
var arr = new g$2[typedArray]();
if (Symbol.toStringTag in arr) {
var proto = getPrototypeOf$1(arr);
var descriptor = getOwnPropertyDescriptor(proto, Symbol.toStringTag);
if (!descriptor) {
var superProto = getPrototypeOf$1(proto);
descriptor = getOwnPropertyDescriptor(superProto, Symbol.toStringTag);
}
toStrTags$1[typedArray] = descriptor.get;
}
}
});
}
var tryTypedArrays$1 = function tryAllTypedArrays(value) {
var foundName = false;
forEach_1(toStrTags$1, function (getter, typedArray) {
if (!foundName) {
try {
var name = getter.call(value);
if (name === typedArray) {
foundName = name;
}
} catch (e) {}
}
});
return foundName;
};
var whichTypedArray = function whichTypedArray(value) {
if (!isTypedArray(value)) { return false; }
if (!hasToStringTag$9 || !(Symbol.toStringTag in value)) { return $slice$1($toString$4(value), 8, -1); }
return tryTypedArrays$1(value);
};
var types$2 = createCommonjsModule(function (module, exports) {
function uncurryThis(f) {
return f.call.bind(f);
}
var BigIntSupported = typeof BigInt !== 'undefined';
var SymbolSupported = typeof Symbol !== 'undefined';
var ObjectToString = uncurryThis(Object.prototype.toString);
var numberValue = uncurryThis(Number.prototype.valueOf);
var stringValue = uncurryThis(String.prototype.valueOf);
var booleanValue = uncurryThis(Boolean.prototype.valueOf);
if (BigIntSupported) {
var bigIntValue = uncurryThis(BigInt.prototype.valueOf);
}
if (SymbolSupported) {
var symbolValue = uncurryThis(Symbol.prototype.valueOf);
}
function checkBoxedPrimitive(value, prototypeValueOf) {
if (typeof value !== 'object') {
return false;
}
try {
prototypeValueOf(value);
return true;
} catch(e) {
return false;
}
}
exports.isArgumentsObject = isArguments$1;
exports.isGeneratorFunction = isGeneratorFunction;
exports.isTypedArray = isTypedArray;
// Taken from here and modified for better browser support
// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js
function isPromise(input) {
return (
(
typeof Promise !== 'undefined' &&
input instanceof Promise
) ||
(
input !== null &&
typeof input === 'object' &&
typeof input.then === 'function' &&
typeof input.catch === 'function'
)
);
}
exports.isPromise = isPromise;
function isArrayBufferView(value) {
if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {
return ArrayBuffer.isView(value);
}
return (
isTypedArray(value) ||
isDataView(value)
);
}
exports.isArrayBufferView = isArrayBufferView;
function isUint8Array(value) {
return whichTypedArray(value) === 'Uint8Array';
}
exports.isUint8Array = isUint8Array;
function isUint8ClampedArray(value) {
return whichTypedArray(value) === 'Uint8ClampedArray';
}
exports.isUint8ClampedArray = isUint8ClampedArray;
function isUint16Array(value) {
return whichTypedArray(value) === 'Uint16Array';
}
exports.isUint16Array = isUint16Array;
function isUint32Array(value) {
return whichTypedArray(value) === 'Uint32Array';
}
exports.isUint32Array = isUint32Array;
function isInt8Array(value) {
return whichTypedArray(value) === 'Int8Array';
}
exports.isInt8Array = isInt8Array;
function isInt16Array(value) {
return whichTypedArray(value) === 'Int16Array';
}
exports.isInt16Array = isInt16Array;
function isInt32Array(value) {
return whichTypedArray(value) === 'Int32Array';
}
exports.isInt32Array = isInt32Array;
function isFloat32Array(value) {
return whichTypedArray(value) === 'Float32Array';
}
exports.isFloat32Array = isFloat32Array;
function isFloat64Array(value) {
return whichTypedArray(value) === 'Float64Array';
}
exports.isFloat64Array = isFloat64Array;
function isBigInt64Array(value) {
return whichTypedArray(value) === 'BigInt64Array';
}
exports.isBigInt64Array = isBigInt64Array;
function isBigUint64Array(value) {
return whichTypedArray(value) === 'BigUint64Array';
}
exports.isBigUint64Array = isBigUint64Array;
function isMapToString(value) {
return ObjectToString(value) === '[object Map]';
}
isMapToString.working = (
typeof Map !== 'undefined' &&
isMapToString(new Map())
);
function isMap(value) {
if (typeof Map === 'undefined') {
return false;
}
return isMapToString.working
? isMapToString(value)
: value instanceof Map;
}
exports.isMap = isMap;
function isSetToString(value) {
return ObjectToString(value) === '[object Set]';
}
isSetToString.working = (
typeof Set !== 'undefined' &&
isSetToString(new Set())
);
function isSet(value) {
if (typeof Set === 'undefined') {
return false;
}
return isSetToString.working
? isSetToString(value)
: value instanceof Set;
}
exports.isSet = isSet;
function isWeakMapToString(value) {
return ObjectToString(value) === '[object WeakMap]';
}
isWeakMapToString.working = (
typeof WeakMap !== 'undefined' &&
isWeakMapToString(new WeakMap())
);
function isWeakMap(value) {
if (typeof WeakMap === 'undefined') {
return false;
}
return isWeakMapToString.working
? isWeakMapToString(value)
: value instanceof WeakMap;
}
exports.isWeakMap = isWeakMap;
function isWeakSetToString(value) {
return ObjectToString(value) === '[object WeakSet]';
}
isWeakSetToString.working = (
typeof WeakSet !== 'undefined' &&
isWeakSetToString(new WeakSet())
);
function isWeakSet(value) {
return isWeakSetToString(value);
}
exports.isWeakSet = isWeakSet;
function isArrayBufferToString(value) {
return ObjectToString(value) === '[object ArrayBuffer]';
}
isArrayBufferToString.working = (
typeof ArrayBuffer !== 'undefined' &&
isArrayBufferToString(new ArrayBuffer())
);
function isArrayBuffer(value) {
if (typeof ArrayBuffer === 'undefined') {
return false;
}
return isArrayBufferToString.working
? isArrayBufferToString(value)
: value instanceof ArrayBuffer;
}
exports.isArrayBuffer = isArrayBuffer;
function isDataViewToString(value) {
return ObjectToString(value) === '[object DataView]';
}
isDataViewToString.working = (
typeof ArrayBuffer !== 'undefined' &&
typeof DataView !== 'undefined' &&
isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1))
);
function isDataView(value) {
if (typeof DataView === 'undefined') {
return false;
}
return isDataViewToString.working
? isDataViewToString(value)
: value instanceof DataView;
}
exports.isDataView = isDataView;
// Store a copy of SharedArrayBuffer in case it's deleted elsewhere
var SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined;
function isSharedArrayBufferToString(value) {
return ObjectToString(value) === '[object SharedArrayBuffer]';
}
function isSharedArrayBuffer(value) {
if (typeof SharedArrayBufferCopy === 'undefined') {
return false;
}
if (typeof isSharedArrayBufferToString.working === 'undefined') {
isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy());
}
return isSharedArrayBufferToString.working
? isSharedArrayBufferToString(value)
: value instanceof SharedArrayBufferCopy;
}
exports.isSharedArrayBuffer = isSharedArrayBuffer;
function isAsyncFunction(value) {
return ObjectToString(value) === '[object AsyncFunction]';
}
exports.isAsyncFunction = isAsyncFunction;
function isMapIterator(value) {
return ObjectToString(value) === '[object Map Iterator]';
}
exports.isMapIterator = isMapIterator;
function isSetIterator(value) {
return ObjectToString(value) === '[object Set Iterator]';
}
exports.isSetIterator = isSetIterator;
function isGeneratorObject(value) {
return ObjectToString(value) === '[object Generator]';
}
exports.isGeneratorObject = isGeneratorObject;
function isWebAssemblyCompiledModule(value) {
return ObjectToString(value) === '[object WebAssembly.Module]';
}
exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule;
function isNumberObject(value) {
return checkBoxedPrimitive(value, numberValue);
}
exports.isNumberObject = isNumberObject;
function isStringObject(value) {
return checkBoxedPrimitive(value, stringValue);
}
exports.isStringObject = isStringObject;
function isBooleanObject(value) {
return checkBoxedPrimitive(value, booleanValue);
}
exports.isBooleanObject = isBooleanObject;
function isBigIntObject(value) {
return BigIntSupported && checkBoxedPrimitive(value, bigIntValue);
}
exports.isBigIntObject = isBigIntObject;
function isSymbolObject(value) {
return SymbolSupported && checkBoxedPrimitive(value, symbolValue);
}
exports.isSymbolObject = isSymbolObject;
function isBoxedPrimitive(value) {
return (
isNumberObject(value) ||
isStringObject(value) ||
isBooleanObject(value) ||
isBigIntObject(value) ||
isSymbolObject(value)
);
}
exports.isBoxedPrimitive = isBoxedPrimitive;
function isAnyArrayBuffer(value) {
return typeof Uint8Array !== 'undefined' && (
isArrayBuffer(value) ||
isSharedArrayBuffer(value)
);
}
exports.isAnyArrayBuffer = isAnyArrayBuffer;
['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) {
Object.defineProperty(exports, method, {
enumerable: false,
value: function() {
throw new Error(method + ' is not supported in userland');
}
});
});
});
var types_1 = types$2.isArgumentsObject;
var types_2 = types$2.isGeneratorFunction;
var types_3 = types$2.isTypedArray;
var types_4 = types$2.isPromise;
var types_5 = types$2.isArrayBufferView;
var types_6 = types$2.isUint8Array;
var types_7 = types$2.isUint8ClampedArray;
var types_8 = types$2.isUint16Array;
var types_9 = types$2.isUint32Array;
var types_10 = types$2.isInt8Array;
var types_11 = types$2.isInt16Array;
var types_12 = types$2.isInt32Array;
var types_13 = types$2.isFloat32Array;
var types_14 = types$2.isFloat64Array;
var types_15 = types$2.isBigInt64Array;
var types_16 = types$2.isBigUint64Array;
var types_17 = types$2.isMap;
var types_18 = types$2.isSet;
var types_19 = types$2.isWeakMap;
var types_20 = types$2.isWeakSet;
var types_21 = types$2.isArrayBuffer;
var types_22 = types$2.isDataView;
var types_23 = types$2.isSharedArrayBuffer;
var types_24 = types$2.isAsyncFunction;
var types_25 = types$2.isMapIterator;
var types_26 = types$2.isSetIterator;
var types_27 = types$2.isGeneratorObject;
var types_28 = types$2.isWebAssemblyCompiledModule;
var types_29 = types$2.isNumberObject;
var types_30 = types$2.isStringObject;
var types_31 = types$2.isBooleanObject;
var types_32 = types$2.isBigIntObject;
var types_33 = types$2.isSymbolObject;
var types_34 = types$2.isBoxedPrimitive;
var types_35 = types$2.isAnyArrayBuffer;
var isBuffer = function isBuffer(arg) {
return arg instanceof Buffer;
};
var inherits_browser = createCommonjsModule(function (module) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
}
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor;
var TempCtor = function () {};
TempCtor.prototype = superCtor.prototype;
ctor.prototype = new TempCtor();
ctor.prototype.constructor = ctor;
}
};
}
});
var inherits = createCommonjsModule(function (module) {
try {
var util$1 = util;
/* istanbul ignore next */
if (typeof util$1.inherits !== 'function') throw '';
module.exports = util$1.inherits;
} catch (e) {
/* istanbul ignore next */
module.exports = inherits_browser;
}
});
var util = createCommonjsModule(function (module, exports) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||
function getOwnPropertyDescriptors(obj) {
var keys = Object.keys(obj);
var descriptors = {};
for (var i = 0; i < keys.length; i++) {
descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);
}
return descriptors;
};
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
if (typeof process !== 'undefined' && process.noDeprecation === true) {
return fn;
}
// Allow for deprecating things in the process of starting up.
if (typeof process === 'undefined') {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnvRegex = /^$/;
exports.debuglog = function(set) {
set = set.toUpperCase();
if (!debugs[set]) {
if (debugEnvRegex.test(set)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').slice(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.slice(1, -1);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var length = output.reduce(function(prev, cur) {
if (cur.indexOf('\n') >= 0) ;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
exports.types = types$2;
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
exports.types.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
exports.types.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
exports.types.isNativeError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = inherits;
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;
exports.promisify = function promisify(original) {
if (typeof original !== 'function')
throw new TypeError('The "original" argument must be of type Function');
if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {
var fn = original[kCustomPromisifiedSymbol];
if (typeof fn !== 'function') {
throw new TypeError('The "util.promisify.custom" argument must be of type Function');
}
Object.defineProperty(fn, kCustomPromisifiedSymbol, {
value: fn, enumerable: false, writable: false, configurable: true
});
return fn;
}
function fn() {
var promiseResolve, promiseReject;
var promise = new Promise(function (resolve, reject) {
promiseResolve = resolve;
promiseReject = reject;
});
var args = [];
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
args.push(function (err, value) {
if (err) {
promiseReject(err);
} else {
promiseResolve(value);
}
});
try {
original.apply(this, args);
} catch (err) {
promiseReject(err);
}
return promise;
}
Object.setPrototypeOf(fn, Object.getPrototypeOf(original));
if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {
value: fn, enumerable: false, writable: false, configurable: true
});
return Object.defineProperties(
fn,
getOwnPropertyDescriptors(original)
);
};
exports.promisify.custom = kCustomPromisifiedSymbol;
function callbackifyOnRejected(reason, cb) {
// `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).
// Because `null` is a special error value in callbacks which means "no error
// occurred", we error-wrap so the callback consumer can distinguish between
// "the promise rejected with null" or "the promise fulfilled with undefined".
if (!reason) {
var newReason = new Error('Promise was rejected with a falsy value');
newReason.reason = reason;
reason = newReason;
}
return cb(reason);
}
function callbackify(original) {
if (typeof original !== 'function') {
throw new TypeError('The "original" argument must be of type Function');
}
// We DO NOT return the promise as it gives the user a false sense that
// the promise is actually somehow related to the callback's execution
// and that the callback throwing will reject the promise.
function callbackified() {
var args = [];
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
var maybeCb = args.pop();
if (typeof maybeCb !== 'function') {
throw new TypeError('The last argument must be of type Function');
}
var self = this;
var cb = function() {
return maybeCb.apply(self, arguments);
};
// In true node style we process the callback on `nextTick` with all the
// implications (stack, `uncaughtException`, `async_hooks`)
original.apply(this, args)
.then(function(ret) { process.nextTick(cb.bind(null, null, ret)); },
function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)); });
}
Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));
Object.defineProperties(callbackified,
getOwnPropertyDescriptors(original));
return callbackified;
}
exports.callbackify = callbackify;
});
var util_1 = util.format;
var util_2 = util.deprecate;
var util_3 = util.debuglog;
var util_4 = util.inspect;
var util_5 = util.types;
var util_6 = util.isArray;
var util_7 = util.isBoolean;
var util_8 = util.isNull;
var util_9 = util.isNullOrUndefined;
var util_10 = util.isNumber;
var util_11 = util.isString;
var util_12 = util.isSymbol;
var util_13 = util.isUndefined;
var util_14 = util.isRegExp;
var util_15 = util.isObject;
var util_16 = util.isDate;
var util_17 = util.isError;
var util_18 = util.isFunction;
var util_19 = util.isPrimitive;
var util_20 = util.isBuffer;
var util_21 = util.log;
var util_22 = util.inherits;
var util_23 = util._extend;
var util_24 = util.promisify;
var util_25 = util.callbackify;
var util_inspect = util.inspect;
var hasMap = typeof Map === 'function' && Map.prototype;
var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;
var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;
var mapForEach = hasMap && Map.prototype.forEach;
var hasSet = typeof Set === 'function' && Set.prototype;
var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null;
var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null;
var setForEach = hasSet && Set.prototype.forEach;
var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype;
var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null;
var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype;
var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;
var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype;
var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null;
var booleanValueOf = Boolean.prototype.valueOf;
var objectToString = Object.prototype.toString;
var functionToString = Function.prototype.toString;
var $match = String.prototype.match;
var $slice$2 = String.prototype.slice;
var $replace$1 = String.prototype.replace;
var $toUpperCase = String.prototype.toUpperCase;
var $toLowerCase = String.prototype.toLowerCase;
var $test = RegExp.prototype.test;
var $concat$1 = Array.prototype.concat;
var $join = Array.prototype.join;
var $arrSlice = Array.prototype.slice;
var $floor = Math.floor;
var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null;
var gOPS = Object.getOwnPropertySymbols;
var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null;
var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object';
// ie, `has-tostringtag/shams
var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol')
? Symbol.toStringTag
: null;
var isEnumerable$1 = Object.prototype.propertyIsEnumerable;
var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || (
[].__proto__ === Array.prototype // eslint-disable-line no-proto
? function (O) {
return O.__proto__; // eslint-disable-line no-proto
}
: null
);
function addNumericSeparator(num, str) {
if (
num === Infinity
|| num === -Infinity
|| num !== num
|| (num && num > -1000 && num < 1000)
|| $test.call(/e/, str)
) {
return str;
}
var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;
if (typeof num === 'number') {
var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num)
if (int !== num) {
var intStr = String(int);
var dec = $slice$2.call(str, intStr.length + 1);
return $replace$1.call(intStr, sepRegex, '$&_') + '.' + $replace$1.call($replace$1.call(dec, /([0-9]{3})/g, '$&_'), /_$/, '');
}
}
return $replace$1.call(str, sepRegex, '$&_');
}
var inspectCustom = util_inspect.custom;
var inspectSymbol = isSymbol$1(inspectCustom) ? inspectCustom : null;
var objectInspect = function inspect_(obj, options, depth, seen) {
var opts = options || {};
if (has$2(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) {
throw new TypeError('option "quoteStyle" must be "single" or "double"');
}
if (
has$2(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number'
? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity
: opts.maxStringLength !== null
)
) {
throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');
}
var customInspect = has$2(opts, 'customInspect') ? opts.customInspect : true;
if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') {
throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`');
}
if (
has$2(opts, 'indent')
&& opts.indent !== null
&& opts.indent !== '\t'
&& !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)
) {
throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');
}
if (has$2(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') {
throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');
}
var numericSeparator = opts.numericSeparator;
if (typeof obj === 'undefined') {
return 'undefined';
}
if (obj === null) {
return 'null';
}
if (typeof obj === 'boolean') {
return obj ? 'true' : 'false';
}
if (typeof obj === 'string') {
return inspectString(obj, opts);
}
if (typeof obj === 'number') {
if (obj === 0) {
return Infinity / obj > 0 ? '0' : '-0';
}
var str = String(obj);
return numericSeparator ? addNumericSeparator(obj, str) : str;
}
if (typeof obj === 'bigint') {
var bigIntStr = String(obj) + 'n';
return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr;
}
var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth;
if (typeof depth === 'undefined') { depth = 0; }
if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') {
return isArray$1(obj) ? '[Array]' : '[Object]';
}
var indent = getIndent(opts, depth);
if (typeof seen === 'undefined') {
seen = [];
} else if (indexOf$1(seen, obj) >= 0) {
return '[Circular]';
}
function inspect(value, from, noIndent) {
if (from) {
seen = $arrSlice.call(seen);
seen.push(from);
}
if (noIndent) {
var newOpts = {
depth: opts.depth
};
if (has$2(opts, 'quoteStyle')) {
newOpts.quoteStyle = opts.quoteStyle;
}
return inspect_(value, newOpts, depth + 1, seen);
}
return inspect_(value, opts, depth + 1, seen);
}
if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable
var name = nameOf(obj);
var keys = arrObjKeys(obj, inspect);
return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : '');
}
if (isSymbol$1(obj)) {
var symString = hasShammedSymbols ? $replace$1.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj);
return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString;
}
if (isElement$1(obj)) {
var s = '<' + $toLowerCase.call(String(obj.nodeName));
var attrs = obj.attributes || [];
for (var i = 0; i < attrs.length; i++) {
s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts);
}
s += '>';
if (obj.childNodes && obj.childNodes.length) { s += '...'; }
s += '</' + $toLowerCase.call(String(obj.nodeName)) + '>';
return s;
}
if (isArray$1(obj)) {
if (obj.length === 0) { return '[]'; }
var xs = arrObjKeys(obj, inspect);
if (indent && !singleLineValues(xs)) {
return '[' + indentedJoin(xs, indent) + ']';
}
return '[ ' + $join.call(xs, ', ') + ' ]';
}
if (isError(obj)) {
var parts = arrObjKeys(obj, inspect);
if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable$1.call(obj, 'cause')) {
return '{ [' + String(obj) + '] ' + $join.call($concat$1.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }';
}
if (parts.length === 0) { return '[' + String(obj) + ']'; }
return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }';
}
if (typeof obj === 'object' && customInspect) {
if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && util_inspect) {
return util_inspect(obj, { depth: maxDepth - depth });
} else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') {
return obj.inspect();
}
}
if (isMap$1(obj)) {
var mapParts = [];
mapForEach.call(obj, function (value, key) {
mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj));
});
return collectionOf('Map', mapSize.call(obj), mapParts, indent);
}
if (isSet$1(obj)) {
var setParts = [];
setForEach.call(obj, function (value) {
setParts.push(inspect(value, obj));
});
return collectionOf('Set', setSize.call(obj), setParts, indent);
}
if (isWeakMap(obj)) {
return weakCollectionOf('WeakMap');
}
if (isWeakSet(obj)) {
return weakCollectionOf('WeakSet');
}
if (isWeakRef(obj)) {
return weakCollectionOf('WeakRef');
}
if (isNumber(obj)) {
return markBoxed(inspect(Number(obj)));
}
if (isBigInt(obj)) {
return markBoxed(inspect(bigIntValueOf.call(obj)));
}
if (isBoolean(obj)) {
return markBoxed(booleanValueOf.call(obj));
}
if (isString$1(obj)) {
return markBoxed(inspect(String(obj)));
}
if (!isDate(obj) && !isRegExp(obj)) {
var ys = arrObjKeys(obj, inspect);
var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object;
var protoTag = obj instanceof Object ? '' : 'null prototype';
var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice$2.call(toStr$a(obj), 8, -1) : protoTag ? 'Object' : '';
var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : '';
var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat$1.call([], stringTag || [], protoTag || []), ': ') + '] ' : '');
if (ys.length === 0) { return tag + '{}'; }
if (indent) {
return tag + '{' + indentedJoin(ys, indent) + '}';
}
return tag + '{ ' + $join.call(ys, ', ') + ' }';
}
return String(obj);
};
function wrapQuotes(s, defaultStyle, opts) {
var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'";
return quoteChar + s + quoteChar;
}
function quote(s) {
return $replace$1.call(String(s), /"/g, '&quot;');
}
function isArray$1(obj) { return toStr$a(obj) === '[object Array]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isDate(obj) { return toStr$a(obj) === '[object Date]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isRegExp(obj) { return toStr$a(obj) === '[object RegExp]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isError(obj) { return toStr$a(obj) === '[object Error]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isString$1(obj) { return toStr$a(obj) === '[object String]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isNumber(obj) { return toStr$a(obj) === '[object Number]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isBoolean(obj) { return toStr$a(obj) === '[object Boolean]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives
function isSymbol$1(obj) {
if (hasShammedSymbols) {
return obj && typeof obj === 'object' && obj instanceof Symbol;
}
if (typeof obj === 'symbol') {
return true;
}
if (!obj || typeof obj !== 'object' || !symToString) {
return false;
}
try {
symToString.call(obj);
return true;
} catch (e) {}
return false;
}
function isBigInt(obj) {
if (!obj || typeof obj !== 'object' || !bigIntValueOf) {
return false;
}
try {
bigIntValueOf.call(obj);
return true;
} catch (e) {}
return false;
}
var hasOwn$1 = Object.prototype.hasOwnProperty || function (key) { return key in this; };
function has$2(obj, key) {
return hasOwn$1.call(obj, key);
}
function toStr$a(obj) {
return objectToString.call(obj);
}
function nameOf(f) {
if (f.name) { return f.name; }
var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/);
if (m) { return m[1]; }
return null;
}
function indexOf$1(xs, x) {
if (xs.indexOf) { return xs.indexOf(x); }
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) { return i; }
}
return -1;
}
function isMap$1(x) {
if (!mapSize || !x || typeof x !== 'object') {
return false;
}
try {
mapSize.call(x);
try {
setSize.call(x);
} catch (s) {
return true;
}
return x instanceof Map; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isWeakMap(x) {
if (!weakMapHas || !x || typeof x !== 'object') {
return false;
}
try {
weakMapHas.call(x, weakMapHas);
try {
weakSetHas.call(x, weakSetHas);
} catch (s) {
return true;
}
return x instanceof WeakMap; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isWeakRef(x) {
if (!weakRefDeref || !x || typeof x !== 'object') {
return false;
}
try {
weakRefDeref.call(x);
return true;
} catch (e) {}
return false;
}
function isSet$1(x) {
if (!setSize || !x || typeof x !== 'object') {
return false;
}
try {
setSize.call(x);
try {
mapSize.call(x);
} catch (m) {
return true;
}
return x instanceof Set; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isWeakSet(x) {
if (!weakSetHas || !x || typeof x !== 'object') {
return false;
}
try {
weakSetHas.call(x, weakSetHas);
try {
weakMapHas.call(x, weakMapHas);
} catch (s) {
return true;
}
return x instanceof WeakSet; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isElement$1(x) {
if (!x || typeof x !== 'object') { return false; }
if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) {
return true;
}
return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function';
}
function inspectString(str, opts) {
if (str.length > opts.maxStringLength) {
var remaining = str.length - opts.maxStringLength;
var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : '');
return inspectString($slice$2.call(str, 0, opts.maxStringLength), opts) + trailer;
}
// eslint-disable-next-line no-control-regex
var s = $replace$1.call($replace$1.call(str, /(['\\])/g, '\\$1'), /[\x00-\x1f]/g, lowbyte);
return wrapQuotes(s, 'single', opts);
}
function lowbyte(c) {
var n = c.charCodeAt(0);
var x = {
8: 'b',
9: 't',
10: 'n',
12: 'f',
13: 'r'
}[n];
if (x) { return '\\' + x; }
return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16));
}
function markBoxed(str) {
return 'Object(' + str + ')';
}
function weakCollectionOf(type) {
return type + ' { ? }';
}
function collectionOf(type, size, entries, indent) {
var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', ');
return type + ' (' + size + ') {' + joinedEntries + '}';
}
function singleLineValues(xs) {
for (var i = 0; i < xs.length; i++) {
if (indexOf$1(xs[i], '\n') >= 0) {
return false;
}
}
return true;
}
function getIndent(opts, depth) {
var baseIndent;
if (opts.indent === '\t') {
baseIndent = '\t';
} else if (typeof opts.indent === 'number' && opts.indent > 0) {
baseIndent = $join.call(Array(opts.indent + 1), ' ');
} else {
return null;
}
return {
base: baseIndent,
prev: $join.call(Array(depth + 1), baseIndent)
};
}
function indentedJoin(xs, indent) {
if (xs.length === 0) { return ''; }
var lineJoiner = '\n' + indent.prev + indent.base;
return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev;
}
function arrObjKeys(obj, inspect) {
var isArr = isArray$1(obj);
var xs = [];
if (isArr) {
xs.length = obj.length;
for (var i = 0; i < obj.length; i++) {
xs[i] = has$2(obj, i) ? inspect(obj[i], obj) : '';
}
}
var syms = typeof gOPS === 'function' ? gOPS(obj) : [];
var symMap;
if (hasShammedSymbols) {
symMap = {};
for (var k = 0; k < syms.length; k++) {
symMap['$' + syms[k]] = syms[k];
}
}
for (var key in obj) { // eslint-disable-line no-restricted-syntax
if (!has$2(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue
if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue
if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) {
// this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section
continue; // eslint-disable-line no-restricted-syntax, no-continue
} else if ($test.call(/[^\w$]/, key)) {
xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj));
} else {
xs.push(key + ': ' + inspect(obj[key], obj));
}
}
if (typeof gOPS === 'function') {
for (var j = 0; j < syms.length; j++) {
if (isEnumerable$1.call(obj, syms[j])) {
xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj));
}
}
}
return xs;
}
var $TypeError$1 = getIntrinsic('%TypeError%');
var $WeakMap$1 = getIntrinsic('%WeakMap%', true);
var $Map$2 = getIntrinsic('%Map%', true);
var $weakMapGet = callBound('WeakMap.prototype.get', true);
var $weakMapSet = callBound('WeakMap.prototype.set', true);
var $weakMapHas = callBound('WeakMap.prototype.has', true);
var $mapGet = callBound('Map.prototype.get', true);
var $mapSet = callBound('Map.prototype.set', true);
var $mapHas$3 = callBound('Map.prototype.has', true);
/*
* This function traverses the list returning the node corresponding to the
* given key.
*
* That node is also moved to the head of the list, so that if it's accessed
* again we don't need to traverse the whole list. By doing so, all the recently
* used nodes can be accessed relatively quickly.
*/
var listGetNode = function (list, key) { // eslint-disable-line consistent-return
for (var prev = list, curr; (curr = prev.next) !== null; prev = curr) {
if (curr.key === key) {
prev.next = curr.next;
curr.next = list.next;
list.next = curr; // eslint-disable-line no-param-reassign
return curr;
}
}
};
var listGet = function (objects, key) {
var node = listGetNode(objects, key);
return node && node.value;
};
var listSet = function (objects, key, value) {
var node = listGetNode(objects, key);
if (node) {
node.value = value;
} else {
// Prepend the new node to the beginning of the list
objects.next = { // eslint-disable-line no-param-reassign
key: key,
next: objects.next,
value: value
};
}
};
var listHas = function (objects, key) {
return !!listGetNode(objects, key);
};
var sideChannel = function getSideChannel() {
var $wm;
var $m;
var $o;
var channel = {
assert: function (key) {
if (!channel.has(key)) {
throw new $TypeError$1('Side channel does not contain ' + objectInspect(key));
}
},
get: function (key) { // eslint-disable-line consistent-return
if ($WeakMap$1 && key && (typeof key === 'object' || typeof key === 'function')) {
if ($wm) {
return $weakMapGet($wm, key);
}
} else if ($Map$2) {
if ($m) {
return $mapGet($m, key);
}
} else {
if ($o) { // eslint-disable-line no-lonely-if
return listGet($o, key);
}
}
},
has: function (key) {
if ($WeakMap$1 && key && (typeof key === 'object' || typeof key === 'function')) {
if ($wm) {
return $weakMapHas($wm, key);
}
} else if ($Map$2) {
if ($m) {
return $mapHas$3($m, key);
}
} else {
if ($o) { // eslint-disable-line no-lonely-if
return listHas($o, key);
}
}
return false;
},
set: function (key, value) {
if ($WeakMap$1 && key && (typeof key === 'object' || typeof key === 'function')) {
if (!$wm) {
$wm = new $WeakMap$1();
}
$weakMapSet($wm, key, value);
} else if ($Map$2) {
if (!$m) {
$m = new $Map$2();
}
$mapSet($m, key, value);
} else {
if (!$o) {
/*
* Initialize the linked list as an empty node, so that we don't have
* to special-case handling of the first node: we can always refer to
* it as (previous node).next, instead of something like (list).head
*/
$o = { key: {}, next: null };
}
listSet($o, key, value);
}
}
};
return channel;
};
// modified from https://github.com/es-shims/es6-shim
var hasSymbols$3 = shams();
var toObject = Object;
var $push = callBound('Array.prototype.push');
var $propIsEnumerable = callBound('Object.prototype.propertyIsEnumerable');
var originalGetSymbols = hasSymbols$3 ? Object.getOwnPropertySymbols : null;
// eslint-disable-next-line no-unused-vars
var implementation$4 = function assign(target, source1) {
if (target == null) { throw new TypeError('target must be an object'); }
var to = toObject(target); // step 1
if (arguments.length === 1) {
return to; // step 2
}
for (var s = 1; s < arguments.length; ++s) {
var from = toObject(arguments[s]); // step 3.a.i
// step 3.a.ii:
var keys = objectKeys(from);
var getSymbols = hasSymbols$3 && (Object.getOwnPropertySymbols || originalGetSymbols);
if (getSymbols) {
var syms = getSymbols(from);
for (var j = 0; j < syms.length; ++j) {
var key = syms[j];
if ($propIsEnumerable(from, key)) {
$push(keys, key);
}
}
}
// step 3.a.iii:
for (var i = 0; i < keys.length; ++i) {
var nextKey = keys[i];
if ($propIsEnumerable(from, nextKey)) { // step 3.a.iii.2
var propValue = from[nextKey]; // step 3.a.iii.2.a
to[nextKey] = propValue; // step 3.a.iii.2.b
}
}
}
return to; // step 4
};
var lacksProperEnumerationOrder = function () {
if (!Object.assign) {
return false;
}
/*
* v8, specifically in node 4.x, has a bug with incorrect property enumeration order
* note: this does not detect the bug unless there's 20 characters
*/
var str = 'abcdefghijklmnopqrst';
var letters = str.split('');
var map = {};
for (var i = 0; i < letters.length; ++i) {
map[letters[i]] = letters[i];
}
var obj = Object.assign({}, map);
var actual = '';
for (var k in obj) {
actual += k;
}
return str !== actual;
};
var assignHasPendingExceptions = function () {
if (!Object.assign || !Object.preventExtensions) {
return false;
}
/*
* Firefox 37 still has "pending exception" logic in its Object.assign implementation,
* which is 72% slower than our shim, and Firefox 40's native implementation.
*/
var thrower = Object.preventExtensions({ 1: 2 });
try {
Object.assign(thrower, 'xy');
} catch (e) {
return thrower[1] === 'y';
}
return false;
};
var polyfill$3 = function getPolyfill() {
if (!Object.assign) {
return implementation$4;
}
if (lacksProperEnumerationOrder()) {
return implementation$4;
}
if (assignHasPendingExceptions()) {
return implementation$4;
}
return Object.assign;
};
var shim$2 = function shimAssign() {
var polyfill = polyfill$3();
defineProperties_1(
Object,
{ assign: polyfill },
{ assign: function () { return Object.assign !== polyfill; } }
);
return polyfill;
};
var polyfill$4 = callBind.apply(polyfill$3());
// eslint-disable-next-line no-unused-vars
var bound = function assign(target, source1) {
return polyfill$4(Object, arguments);
};
defineProperties_1(bound, {
getPolyfill: polyfill$3,
implementation: implementation$4,
shim: shim$2
});
var object_assign = bound;
var getIterator$1 = getCjsExportFromNamespace(node$1);
var $getTime = callBound('Date.prototype.getTime');
var gPO$1 = Object.getPrototypeOf;
var $objToString = callBound('Object.prototype.toString');
var $Set$2 = getIntrinsic('%Set%', true);
var $mapHas$4 = callBound('Map.prototype.has', true);
var $mapGet$1 = callBound('Map.prototype.get', true);
var $mapSize = callBound('Map.prototype.size', true);
var $setAdd = callBound('Set.prototype.add', true);
var $setDelete = callBound('Set.prototype.delete', true);
var $setHas$3 = callBound('Set.prototype.has', true);
var $setSize = callBound('Set.prototype.size', true);
// taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L401-L414
function setHasEqualElement(set, val1, opts, channel) {
var i = getIterator$1(set);
var result;
while ((result = i.next()) && !result.done) {
if (internalDeepEqual(val1, result.value, opts, channel)) { // eslint-disable-line no-use-before-define
// Remove the matching element to make sure we do not check that again.
$setDelete(set, result.value);
return true;
}
}
return false;
}
// taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L416-L439
function findLooseMatchingPrimitives(prim) {
if (typeof prim === 'undefined') {
return null;
}
if (typeof prim === 'object') { // Only pass in null as object!
return void 0;
}
if (typeof prim === 'symbol') {
return false;
}
if (typeof prim === 'string' || typeof prim === 'number') {
// Loose equal entries exist only if the string is possible to convert to a regular number and not NaN.
return +prim === +prim; // eslint-disable-line no-implicit-coercion
}
return true;
}
// taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L449-L460
function mapMightHaveLoosePrim(a, b, prim, item, opts, channel) {
var altValue = findLooseMatchingPrimitives(prim);
if (altValue != null) {
return altValue;
}
var curB = $mapGet$1(b, altValue);
var looseOpts = object_assign({}, opts, { strict: false });
if (
(typeof curB === 'undefined' && !$mapHas$4(b, altValue))
// eslint-disable-next-line no-use-before-define
|| !internalDeepEqual(item, curB, looseOpts, channel)
) {
return false;
}
// eslint-disable-next-line no-use-before-define
return !$mapHas$4(a, altValue) && internalDeepEqual(item, curB, looseOpts, channel);
}
// taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L441-L447
function setMightHaveLoosePrim(a, b, prim) {
var altValue = findLooseMatchingPrimitives(prim);
if (altValue != null) {
return altValue;
}
return $setHas$3(b, altValue) && !$setHas$3(a, altValue);
}
// taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L518-L533
function mapHasEqualEntry(set, map, key1, item1, opts, channel) {
var i = getIterator$1(set);
var result;
var key2;
while ((result = i.next()) && !result.done) {
key2 = result.value;
if (
// eslint-disable-next-line no-use-before-define
internalDeepEqual(key1, key2, opts, channel)
// eslint-disable-next-line no-use-before-define
&& internalDeepEqual(item1, $mapGet$1(map, key2), opts, channel)
) {
$setDelete(set, key2);
return true;
}
}
return false;
}
function internalDeepEqual(actual, expected, options, channel) {
var opts = options || {};
// 7.1. All identical values are equivalent, as determined by ===.
if (opts.strict ? objectIs(actual, expected) : actual === expected) {
return true;
}
var actualBoxed = whichBoxedPrimitive(actual);
var expectedBoxed = whichBoxedPrimitive(expected);
if (actualBoxed !== expectedBoxed) {
return false;
}
// 7.3. Other pairs that do not both pass typeof value == 'object', equivalence is determined by ==.
if (!actual || !expected || (typeof actual !== 'object' && typeof expected !== 'object')) {
return opts.strict ? objectIs(actual, expected) : actual == expected; // eslint-disable-line eqeqeq
}
/*
* 7.4. For all other Object pairs, including Array objects, equivalence is
* determined by having the same number of owned properties (as verified
* with Object.prototype.hasOwnProperty.call), the same set of keys
* (although not necessarily the same order), equivalent values for every
* corresponding key, and an identical 'prototype' property. Note: this
* accounts for both named and indexed properties on Arrays.
*/
// see https://github.com/nodejs/node/commit/d3aafd02efd3a403d646a3044adcf14e63a88d32 for memos/channel inspiration
var hasActual = channel.has(actual);
var hasExpected = channel.has(expected);
var sentinel;
if (hasActual && hasExpected) {
if (channel.get(actual) === channel.get(expected)) {
return true;
}
} else {
sentinel = {};
}
if (!hasActual) { channel.set(actual, sentinel); }
if (!hasExpected) { channel.set(expected, sentinel); }
// eslint-disable-next-line no-use-before-define
return objEquiv(actual, expected, opts, channel);
}
function isBuffer$1(x) {
if (!x || typeof x !== 'object' || typeof x.length !== 'number') {
return false;
}
if (typeof x.copy !== 'function' || typeof x.slice !== 'function') {
return false;
}
if (x.length > 0 && typeof x[0] !== 'number') {
return false;
}
return !!(x.constructor && x.constructor.isBuffer && x.constructor.isBuffer(x));
}
function setEquiv(a, b, opts, channel) {
if ($setSize(a) !== $setSize(b)) {
return false;
}
var iA = getIterator$1(a);
var iB = getIterator$1(b);
var resultA;
var resultB;
var set;
while ((resultA = iA.next()) && !resultA.done) {
if (resultA.value && typeof resultA.value === 'object') {
if (!set) { set = new $Set$2(); }
$setAdd(set, resultA.value);
} else if (!$setHas$3(b, resultA.value)) {
if (opts.strict) { return false; }
if (!setMightHaveLoosePrim(a, b, resultA.value)) {
return false;
}
if (!set) { set = new $Set$2(); }
$setAdd(set, resultA.value);
}
}
if (set) {
while ((resultB = iB.next()) && !resultB.done) {
// We have to check if a primitive value is already matching and only if it's not, go hunting for it.
if (resultB.value && typeof resultB.value === 'object') {
if (!setHasEqualElement(set, resultB.value, opts.strict, channel)) {
return false;
}
} else if (
!opts.strict
&& !$setHas$3(a, resultB.value)
&& !setHasEqualElement(set, resultB.value, opts.strict, channel)
) {
return false;
}
}
return $setSize(set) === 0;
}
return true;
}
function mapEquiv(a, b, opts, channel) {
if ($mapSize(a) !== $mapSize(b)) {
return false;
}
var iA = getIterator$1(a);
var iB = getIterator$1(b);
var resultA;
var resultB;
var set;
var key;
var item1;
var item2;
while ((resultA = iA.next()) && !resultA.done) {
key = resultA.value[0];
item1 = resultA.value[1];
if (key && typeof key === 'object') {
if (!set) { set = new $Set$2(); }
$setAdd(set, key);
} else {
item2 = $mapGet$1(b, key);
if ((typeof item2 === 'undefined' && !$mapHas$4(b, key)) || !internalDeepEqual(item1, item2, opts, channel)) {
if (opts.strict) {
return false;
}
if (!mapMightHaveLoosePrim(a, b, key, item1, opts, channel)) {
return false;
}
if (!set) { set = new $Set$2(); }
$setAdd(set, key);
}
}
}
if (set) {
while ((resultB = iB.next()) && !resultB.done) {
key = resultB.value[0];
item2 = resultB.value[1];
if (key && typeof key === 'object') {
if (!mapHasEqualEntry(set, a, key, item2, opts, channel)) {
return false;
}
} else if (
!opts.strict
&& (!a.has(key) || !internalDeepEqual($mapGet$1(a, key), item2, opts, channel))
&& !mapHasEqualEntry(set, a, key, item2, object_assign({}, opts, { strict: false }), channel)
) {
return false;
}
}
return $setSize(set) === 0;
}
return true;
}
function objEquiv(a, b, opts, channel) {
/* eslint max-statements: [2, 100], max-lines-per-function: [2, 120], max-depth: [2, 5] */
var i, key;
if (typeof a !== typeof b) { return false; }
if (a == null || b == null) { return false; }
if ($objToString(a) !== $objToString(b)) { return false; }
if (isArguments$1(a) !== isArguments$1(b)) { return false; }
var aIsArray = isarray(a);
var bIsArray = isarray(b);
if (aIsArray !== bIsArray) { return false; }
// TODO: replace when a cross-realm brand check is available
var aIsError = a instanceof Error;
var bIsError = b instanceof Error;
if (aIsError !== bIsError) { return false; }
if (aIsError || bIsError) {
if (a.name !== b.name || a.message !== b.message) { return false; }
}
var aIsRegex = isRegex(a);
var bIsRegex = isRegex(b);
if (aIsRegex !== bIsRegex) { return false; }
if ((aIsRegex || bIsRegex) && (a.source !== b.source || regexp_prototype_flags(a) !== regexp_prototype_flags(b))) {
return false;
}
var aIsDate = isDateObject(a);
var bIsDate = isDateObject(b);
if (aIsDate !== bIsDate) { return false; }
if (aIsDate || bIsDate) { // && would work too, because both are true or both false here
if ($getTime(a) !== $getTime(b)) { return false; }
}
if (opts.strict && gPO$1 && gPO$1(a) !== gPO$1(b)) { return false; }
if (whichTypedArray(a) !== whichTypedArray(b)) {
return false;
}
var aIsBuffer = isBuffer$1(a);
var bIsBuffer = isBuffer$1(b);
if (aIsBuffer !== bIsBuffer) { return false; }
if (aIsBuffer || bIsBuffer) { // && would work too, because both are true or both false here
if (a.length !== b.length) { return false; }
for (i = 0; i < a.length; i++) {
if (a[i] !== b[i]) { return false; }
}
return true;
}
if (typeof a !== typeof b) { return false; }
var ka = objectKeys(a);
var kb = objectKeys(b);
// having the same number of owned properties (keys incorporates hasOwnProperty)
if (ka.length !== kb.length) { return false; }
// the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
// ~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i]) { return false; } // eslint-disable-line eqeqeq
}
// equivalent values for every corresponding key, and ~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!internalDeepEqual(a[key], b[key], opts, channel)) { return false; }
}
var aCollection = whichCollection(a);
var bCollection = whichCollection(b);
if (aCollection !== bCollection) {
return false;
}
if (aCollection === 'Set' || bCollection === 'Set') { // aCollection === bCollection
return setEquiv(a, b, opts, channel);
}
if (aCollection === 'Map') { // aCollection === bCollection
return mapEquiv(a, b, opts, channel);
}
return true;
}
var deepEqual = function deepEqual(a, b, opts) {
return internalDeepEqual(a, b, opts, sideChannel());
};
var elementRoleMap_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _deepEqual = _interopRequireDefault(deepEqual);
var _iterationDecorator = _interopRequireDefault(iterationDecorator_1);
var _rolesMap = _interopRequireDefault(rolesMap_1);
function _interopRequireDefault(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 elementRoles = [];
var keys = _rolesMap.default.keys();
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var role = _rolesMap.default.get(key);
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) {
(function () {
var conceptStr = JSON.stringify(concept);
var elementRoleRelation = elementRoles.find(function (relation) {
return JSON.stringify(relation[0]) === conceptStr;
});
var roles = void 0;
if (elementRoleRelation) {
roles = elementRoleRelation[1];
} else {
roles = [];
}
var isUnique = true;
for (var _i = 0; _i < roles.length; _i++) {
if (roles[_i] === key) {
isUnique = false;
break;
}
}
if (isUnique) {
roles.push(key);
}
elementRoles.push([concept, roles]);
})();
}
}
}
}
}
var elementRoleMap = {
entries: function entries() {
return elementRoles;
},
forEach: function forEach(fn) {
var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var _iterator = _createForOfIteratorHelper(elementRoles),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var _step$value = _slicedToArray(_step.value, 2),
_key = _step$value[0],
values = _step$value[1];
fn.call(thisArg, values, _key, elementRoles);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
},
get: function get(key) {
var item = elementRoles.find(function (tuple) {
return (0, _deepEqual.default)(key, tuple[0]);
});
return item && item[1];
},
has: function has(key) {
return !!elementRoleMap.get(key);
},
keys: function keys() {
return elementRoles.map(function (_ref) {
var _ref2 = _slicedToArray(_ref, 1),
key = _ref2[0];
return key;
});
},
values: function values() {
return elementRoles.map(function (_ref3) {
var _ref4 = _slicedToArray(_ref3, 2),
values = _ref4[1];
return values;
});
}
};
var _default = (0, _iterationDecorator.default)(elementRoleMap, elementRoleMap.entries());
exports.default = _default;
});
unwrapExports(elementRoleMap_1);
var roleElementMap_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _iterationDecorator = _interopRequireDefault(iterationDecorator_1);
var _rolesMap = _interopRequireDefault(rolesMap_1);
function _interopRequireDefault(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 roleElement = [];
var keys = _rolesMap.default.keys();
var _loop = function _loop(i) {
var key = keys[i];
var role = _rolesMap.default.get(key);
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) {
var roleElementRelation = roleElement.find(function (item) {
return item[0] === key;
});
var relationConcepts = void 0;
if (roleElementRelation) {
relationConcepts = roleElementRelation[1];
} else {
relationConcepts = [];
}
relationConcepts.push(concept);
roleElement.push([key, relationConcepts]);
}
}
}
}
};
for (var i = 0; i < keys.length; i++) {
_loop(i);
}
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(roleElement),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var _step$value = _slicedToArray(_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(_ref, 1),
key = _ref2[0];
return key;
});
},
values: function values() {
return roleElement.map(function (_ref3) {
var _ref4 = _slicedToArray(_ref3, 2),
values = _ref4[1];
return values;
});
}
};
var _default = (0, _iterationDecorator.default)(roleElementMap, roleElementMap.entries());
exports.default = _default;
});
unwrapExports(roleElementMap_1);
var lib = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.roles = exports.roleElements = exports.elementRoles = exports.dom = exports.aria = void 0;
var _ariaPropsMap = _interopRequireDefault(ariaPropsMap_1);
var _domMap = _interopRequireDefault(domMap_1);
var _rolesMap = _interopRequireDefault(rolesMap_1);
var _elementRoleMap = _interopRequireDefault(elementRoleMap_1);
var _roleElementMap = _interopRequireDefault(roleElementMap_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var aria = _ariaPropsMap.default;
exports.aria = aria;
var dom = _domMap.default;
exports.dom = dom;
var roles = _rolesMap.default;
exports.roles = roles;
var elementRoles = _elementRoleMap.default;
exports.elementRoles = elementRoles;
var roleElements = _roleElementMap.default;
exports.roleElements = roleElements;
});
unwrapExports(lib);
var lib_1 = lib.roles;
var lib_2 = lib.roleElements;
var lib_3 = lib.elementRoles;
var lib_4 = lib.dom;
var lib_5 = lib.aria;
var iteratorProxy_1$1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
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 = iteratorProxy;
exports.default = _default;
});
unwrapExports(iteratorProxy_1$1);
var iterationDecorator_1$1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = iterationDecorator;
var _iteratorProxy = _interopRequireDefault(iteratorProxy_1$1);
function _interopRequireDefault(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;
}
});
unwrapExports(iterationDecorator_1$1);
var AbbrRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var AbbrRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'abbr'
}
}],
type: 'structure'
};
var _default = AbbrRole;
exports.default = _default;
});
unwrapExports(AbbrRole_1);
var AlertDialogRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var AlertDialogRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'alertdialog'
}
}],
type: 'window'
};
var _default = AlertDialogRole;
exports.default = _default;
});
unwrapExports(AlertDialogRole_1);
var AlertRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var AlertRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'alert'
}
}],
type: 'structure'
};
var _default = AlertRole;
exports.default = _default;
});
unwrapExports(AlertRole_1);
var AnnotationRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var AnnotationRole = {
relatedConcepts: [],
type: 'structure'
};
var _default = AnnotationRole;
exports.default = _default;
});
unwrapExports(AnnotationRole_1);
var ApplicationRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var ApplicationRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'application'
}
}],
type: 'window'
};
var _default = ApplicationRole;
exports.default = _default;
});
unwrapExports(ApplicationRole_1);
var ArticleRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var ArticleRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'article'
}
}, {
module: 'HTML',
concept: {
name: 'article'
}
}],
type: 'structure'
};
var _default = ArticleRole;
exports.default = _default;
});
unwrapExports(ArticleRole_1);
var AudioRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var AudioRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'audio'
}
}],
type: 'widget'
};
var _default = AudioRole;
exports.default = _default;
});
unwrapExports(AudioRole_1);
var BannerRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var BannerRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'banner'
}
}],
type: 'structure'
};
var _default = BannerRole;
exports.default = _default;
});
unwrapExports(BannerRole_1);
var BlockquoteRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var BlockquoteRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'blockquote'
}
}],
type: 'structure'
};
var _default = BlockquoteRole;
exports.default = _default;
});
unwrapExports(BlockquoteRole_1);
var BusyIndicatorRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var BusyIndicatorRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
attributes: [{
name: 'aria-busy',
value: 'true'
}]
}
}],
type: 'widget'
};
var _default = BusyIndicatorRole;
exports.default = _default;
});
unwrapExports(BusyIndicatorRole_1);
var ButtonRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var ButtonRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'button'
}
}, {
module: 'HTML',
concept: {
name: 'button'
}
}],
type: 'widget'
};
var _default = ButtonRole;
exports.default = _default;
});
unwrapExports(ButtonRole_1);
var CanvasRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var CanvasRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'canvas'
}
}],
type: 'widget'
};
var _default = CanvasRole;
exports.default = _default;
});
unwrapExports(CanvasRole_1);
var CaptionRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var CaptionRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'caption'
}
}],
type: 'structure'
};
var _default = CaptionRole;
exports.default = _default;
});
unwrapExports(CaptionRole_1);
var CellRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = CellRole;
exports.default = _default;
});
unwrapExports(CellRole_1);
var CheckBoxRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = CheckBoxRole;
exports.default = _default;
});
unwrapExports(CheckBoxRole_1);
var ColorWellRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var ColorWellRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'input',
attributes: [{
name: 'type',
value: 'color'
}]
}
}],
type: 'widget'
};
var _default = ColorWellRole;
exports.default = _default;
});
unwrapExports(ColorWellRole_1);
var ColumnHeaderRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var ColumnHeaderRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'columnheader'
}
}, {
module: 'HTML',
concept: {
name: 'th'
}
}],
type: 'widget'
};
var _default = ColumnHeaderRole;
exports.default = _default;
});
unwrapExports(ColumnHeaderRole_1);
var ColumnRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var ColumnRole = {
relatedConcepts: [],
type: 'structure'
};
var _default = ColumnRole;
exports.default = _default;
});
unwrapExports(ColumnRole_1);
var ComboBoxRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var ComboBoxRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'combobox'
}
}, {
module: 'HTML',
concept: {
name: 'select'
}
}],
type: 'widget'
};
var _default = ComboBoxRole;
exports.default = _default;
});
unwrapExports(ComboBoxRole_1);
var ComplementaryRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var ComplementaryRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'complementary'
}
}],
type: 'structure'
};
var _default = ComplementaryRole;
exports.default = _default;
});
unwrapExports(ComplementaryRole_1);
var ContentInfoRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var ContentInfoRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'structureinfo'
}
}],
type: 'structure'
};
var _default = ContentInfoRole;
exports.default = _default;
});
unwrapExports(ContentInfoRole_1);
var DateRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var DateRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'input',
attributes: [{
name: 'type',
value: 'date'
}]
}
}],
type: 'widget'
};
var _default = DateRole;
exports.default = _default;
});
unwrapExports(DateRole_1);
var DateTimeRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var DateTimeRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'input',
attributes: [{
name: 'type',
value: 'datetime'
}]
}
}],
type: 'widget'
};
var _default = DateTimeRole;
exports.default = _default;
});
unwrapExports(DateTimeRole_1);
var DefinitionRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var DefinitionRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'dfn'
}
}],
type: 'structure'
};
var _default = DefinitionRole;
exports.default = _default;
});
unwrapExports(DefinitionRole_1);
var DescriptionListDetailRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var DescriptionListDetailRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'dd'
}
}],
type: 'structure'
};
var _default = DescriptionListDetailRole;
exports.default = _default;
});
unwrapExports(DescriptionListDetailRole_1);
var DescriptionListRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var DescriptionListRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'dl'
}
}],
type: 'structure'
};
var _default = DescriptionListRole;
exports.default = _default;
});
unwrapExports(DescriptionListRole_1);
var DescriptionListTermRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var DescriptionListTermRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'dt'
}
}],
type: 'structure'
};
var _default = DescriptionListTermRole;
exports.default = _default;
});
unwrapExports(DescriptionListTermRole_1);
var DetailsRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var DetailsRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'details'
}
}],
type: 'structure'
};
var _default = DetailsRole;
exports.default = _default;
});
unwrapExports(DetailsRole_1);
var DialogRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var DialogRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'dialog'
}
}, {
module: 'HTML',
concept: {
name: 'dialog'
}
}],
type: 'window'
};
var _default = DialogRole;
exports.default = _default;
});
unwrapExports(DialogRole_1);
var DirectoryRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var DirectoryRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'directory'
}
}, {
module: 'HTML',
concept: {
name: 'dir'
}
}],
type: 'structure'
};
var _default = DirectoryRole;
exports.default = _default;
});
unwrapExports(DirectoryRole_1);
var DisclosureTriangleRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var DisclosureTriangleRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'summary'
}
}],
type: 'widget'
};
var _default = DisclosureTriangleRole;
exports.default = _default;
});
unwrapExports(DisclosureTriangleRole_1);
var DivRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var DivRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'div'
}
}],
type: 'generic'
};
var _default = DivRole;
exports.default = _default;
});
unwrapExports(DivRole_1);
var DocumentRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var DocumentRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'document'
}
}],
type: 'structure'
};
var _default = DocumentRole;
exports.default = _default;
});
unwrapExports(DocumentRole_1);
var EmbeddedObjectRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var EmbeddedObjectRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'embed'
}
}],
type: 'widget'
};
var _default = EmbeddedObjectRole;
exports.default = _default;
});
unwrapExports(EmbeddedObjectRole_1);
var FeedRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var FeedRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'feed'
}
}],
type: 'structure'
};
var _default = FeedRole;
exports.default = _default;
});
unwrapExports(FeedRole_1);
var FigcaptionRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var FigcaptionRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'figcaption'
}
}],
type: 'structure'
};
var _default = FigcaptionRole;
exports.default = _default;
});
unwrapExports(FigcaptionRole_1);
var FigureRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var FigureRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'figure'
}
}, {
module: 'HTML',
concept: {
name: 'figure'
}
}],
type: 'structure'
};
var _default = FigureRole;
exports.default = _default;
});
unwrapExports(FigureRole_1);
var FooterRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var FooterRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'footer'
}
}],
type: 'structure'
};
var _default = FooterRole;
exports.default = _default;
});
unwrapExports(FooterRole_1);
var FormRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var FormRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'form'
}
}, {
module: 'HTML',
concept: {
name: 'form'
}
}],
type: 'structure'
};
var _default = FormRole;
exports.default = _default;
});
unwrapExports(FormRole_1);
var GridRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var GridRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'grid'
}
}],
type: 'widget'
};
var _default = GridRole;
exports.default = _default;
});
unwrapExports(GridRole_1);
var GroupRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var GroupRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'group'
}
}],
type: 'structure'
};
var _default = GroupRole;
exports.default = _default;
});
unwrapExports(GroupRole_1);
var HeadingRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = HeadingRole;
exports.default = _default;
});
unwrapExports(HeadingRole_1);
var IframePresentationalRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var IframePresentationalRole = {
relatedConcepts: [],
type: 'window'
};
var _default = IframePresentationalRole;
exports.default = _default;
});
unwrapExports(IframePresentationalRole_1);
var IframeRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var IframeRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'iframe'
}
}],
type: 'window'
};
var _default = IframeRole;
exports.default = _default;
});
unwrapExports(IframeRole_1);
var IgnoredRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var IgnoredRole = {
relatedConcepts: [],
type: 'structure'
};
var _default = IgnoredRole;
exports.default = _default;
});
unwrapExports(IgnoredRole_1);
var ImageMapLinkRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var ImageMapLinkRole = {
relatedConcepts: [],
type: 'widget'
};
var _default = ImageMapLinkRole;
exports.default = _default;
});
unwrapExports(ImageMapLinkRole_1);
var ImageMapRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var ImageMapRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'img',
attributes: [{
name: 'usemap'
}]
}
}],
type: 'structure'
};
var _default = ImageMapRole;
exports.default = _default;
});
unwrapExports(ImageMapRole_1);
var ImageRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var ImageRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'img'
}
}, {
module: 'HTML',
concept: {
name: 'img'
}
}],
type: 'structure'
};
var _default = ImageRole;
exports.default = _default;
});
unwrapExports(ImageRole_1);
var InlineTextBoxRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var InlineTextBoxRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'input'
}
}],
type: 'widget'
};
var _default = InlineTextBoxRole;
exports.default = _default;
});
unwrapExports(InlineTextBoxRole_1);
var InputTimeRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var InputTimeRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'input',
attributes: [{
name: 'type',
value: 'time'
}]
}
}],
type: 'widget'
};
var _default = InputTimeRole;
exports.default = _default;
});
unwrapExports(InputTimeRole_1);
var LabelRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var LabelRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'label'
}
}],
type: 'structure'
};
var _default = LabelRole;
exports.default = _default;
});
unwrapExports(LabelRole_1);
var LegendRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var LegendRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'legend'
}
}],
type: 'structure'
};
var _default = LegendRole;
exports.default = _default;
});
unwrapExports(LegendRole_1);
var LineBreakRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var LineBreakRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'br'
}
}],
type: 'structure'
};
var _default = LineBreakRole;
exports.default = _default;
});
unwrapExports(LineBreakRole_1);
var LinkRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var LinkRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'link'
}
}, {
module: 'HTML',
concept: {
name: 'a',
attributes: [{
name: 'href'
}]
}
}],
type: 'widget'
};
var _default = LinkRole;
exports.default = _default;
});
unwrapExports(LinkRole_1);
var ListBoxOptionRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var ListBoxOptionRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'option'
}
}, {
module: 'HTML',
concept: {
name: 'option'
}
}],
type: 'widget'
};
var _default = ListBoxOptionRole;
exports.default = _default;
});
unwrapExports(ListBoxOptionRole_1);
var ListBoxRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = ListBoxRole;
exports.default = _default;
});
unwrapExports(ListBoxRole_1);
var ListItemRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var ListItemRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'listitem'
}
}, {
module: 'HTML',
concept: {
name: 'li'
}
}],
type: 'structure'
};
var _default = ListItemRole;
exports.default = _default;
});
unwrapExports(ListItemRole_1);
var ListMarkerRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var ListMarkerRole = {
relatedConcepts: [],
type: 'structure'
};
var _default = ListMarkerRole;
exports.default = _default;
});
unwrapExports(ListMarkerRole_1);
var ListRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = ListRole;
exports.default = _default;
});
unwrapExports(ListRole_1);
var LogRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var LogRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'log'
}
}],
type: 'structure'
};
var _default = LogRole;
exports.default = _default;
});
unwrapExports(LogRole_1);
var MainRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var MainRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'main'
}
}, {
module: 'HTML',
concept: {
name: 'main'
}
}],
type: 'structure'
};
var _default = MainRole;
exports.default = _default;
});
unwrapExports(MainRole_1);
var MarkRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var MarkRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'mark'
}
}],
type: 'structure'
};
var _default = MarkRole;
exports.default = _default;
});
unwrapExports(MarkRole_1);
var MarqueeRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var MarqueeRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'marquee'
}
}, {
module: 'HTML',
concept: {
name: 'marquee'
}
}],
type: 'structure'
};
var _default = MarqueeRole;
exports.default = _default;
});
unwrapExports(MarqueeRole_1);
var MathRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var MathRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'math'
}
}],
type: 'structure'
};
var _default = MathRole;
exports.default = _default;
});
unwrapExports(MathRole_1);
var MenuBarRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var MenuBarRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'menubar'
}
}],
type: 'structure'
};
var _default = MenuBarRole;
exports.default = _default;
});
unwrapExports(MenuBarRole_1);
var MenuButtonRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var MenuButtonRole = {
relatedConcepts: [],
type: 'widget'
};
var _default = MenuButtonRole;
exports.default = _default;
});
unwrapExports(MenuButtonRole_1);
var MenuItemRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var MenuItemRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'menuitem'
}
}, {
module: 'HTML',
concept: {
name: 'menuitem'
}
}],
type: 'widget'
};
var _default = MenuItemRole;
exports.default = _default;
});
unwrapExports(MenuItemRole_1);
var MenuItemCheckBoxRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var MenuItemCheckBoxRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'menuitemcheckbox'
}
}],
type: 'widget'
};
var _default = MenuItemCheckBoxRole;
exports.default = _default;
});
unwrapExports(MenuItemCheckBoxRole_1);
var MenuItemRadioRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var MenuItemRadioRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'menuitemradio'
}
}],
type: 'widget'
};
var _default = MenuItemRadioRole;
exports.default = _default;
});
unwrapExports(MenuItemRadioRole_1);
var MenuListOptionRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var MenuListOptionRole = {
relatedConcepts: [],
type: 'widget'
};
var _default = MenuListOptionRole;
exports.default = _default;
});
unwrapExports(MenuListOptionRole_1);
var MenuListPopupRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var MenuListPopupRole = {
relatedConcepts: [],
type: 'widget'
};
var _default = MenuListPopupRole;
exports.default = _default;
});
unwrapExports(MenuListPopupRole_1);
var MenuRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var MenuRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'menu'
}
}, {
module: 'HTML',
concept: {
name: 'menu'
}
}],
type: 'structure'
};
var _default = MenuRole;
exports.default = _default;
});
unwrapExports(MenuRole_1);
var MeterRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var MeterRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'meter'
}
}],
type: 'structure'
};
var _default = MeterRole;
exports.default = _default;
});
unwrapExports(MeterRole_1);
var NavigationRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var NavigationRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'navigation'
}
}, {
module: 'HTML',
concept: {
name: 'nav'
}
}],
type: 'structure'
};
var _default = NavigationRole;
exports.default = _default;
});
unwrapExports(NavigationRole_1);
var NoneRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var NoneRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'none'
}
}],
type: 'structure'
};
var _default = NoneRole;
exports.default = _default;
});
unwrapExports(NoneRole_1);
var NoteRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var NoteRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'note'
}
}],
type: 'structure'
};
var _default = NoteRole;
exports.default = _default;
});
unwrapExports(NoteRole_1);
var OutlineRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var OutlineRole = {
relatedConcepts: [],
type: 'structure'
};
var _default = OutlineRole;
exports.default = _default;
});
unwrapExports(OutlineRole_1);
var ParagraphRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var ParagraphRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'p'
}
}],
type: 'structure'
};
var _default = ParagraphRole;
exports.default = _default;
});
unwrapExports(ParagraphRole_1);
var PopUpButtonRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var PopUpButtonRole = {
relatedConcepts: [],
type: 'widget'
};
var _default = PopUpButtonRole;
exports.default = _default;
});
unwrapExports(PopUpButtonRole_1);
var PreRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var PreRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'pre'
}
}],
type: 'structure'
};
var _default = PreRole;
exports.default = _default;
});
unwrapExports(PreRole_1);
var PresentationalRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var PresentationalRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'presentation'
}
}],
type: 'structure'
};
var _default = PresentationalRole;
exports.default = _default;
});
unwrapExports(PresentationalRole_1);
var ProgressIndicatorRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var ProgressIndicatorRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'progressbar'
}
}, {
module: 'HTML',
concept: {
name: 'progress'
}
}],
type: 'structure'
};
var _default = ProgressIndicatorRole;
exports.default = _default;
});
unwrapExports(ProgressIndicatorRole_1);
var RadioButtonRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = RadioButtonRole;
exports.default = _default;
});
unwrapExports(RadioButtonRole_1);
var RadioGroupRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var RadioGroupRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'radiogroup'
}
}],
type: 'structure'
};
var _default = RadioGroupRole;
exports.default = _default;
});
unwrapExports(RadioGroupRole_1);
var RegionRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var RegionRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'region'
}
}],
type: 'structure'
};
var _default = RegionRole;
exports.default = _default;
});
unwrapExports(RegionRole_1);
var RootWebAreaRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var RootWebAreaRole = {
relatedConcepts: [],
type: 'structure'
};
var _default = RootWebAreaRole;
exports.default = _default;
});
unwrapExports(RootWebAreaRole_1);
var RowHeaderRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = RowHeaderRole;
exports.default = _default;
});
unwrapExports(RowHeaderRole_1);
var RowRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var RowRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'row'
}
}, {
module: 'HTML',
concept: {
name: 'tr'
}
}],
type: 'structure'
};
var _default = RowRole;
exports.default = _default;
});
unwrapExports(RowRole_1);
var RubyRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var RubyRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'ruby'
}
}],
type: 'structure'
};
var _default = RubyRole;
exports.default = _default;
});
unwrapExports(RubyRole_1);
var RulerRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var RulerRole = {
relatedConcepts: [],
type: 'structure'
};
var _default = RulerRole;
exports.default = _default;
});
unwrapExports(RulerRole_1);
var ScrollAreaRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var ScrollAreaRole = {
relatedConcepts: [],
type: 'structure'
};
var _default = ScrollAreaRole;
exports.default = _default;
});
unwrapExports(ScrollAreaRole_1);
var ScrollBarRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var ScrollBarRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'scrollbar'
}
}],
type: 'widget'
};
var _default = ScrollBarRole;
exports.default = _default;
});
unwrapExports(ScrollBarRole_1);
var SeamlessWebAreaRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var SeamlessWebAreaRole = {
relatedConcepts: [],
type: 'structure'
};
var _default = SeamlessWebAreaRole;
exports.default = _default;
});
unwrapExports(SeamlessWebAreaRole_1);
var SearchRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var SearchRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'search'
}
}],
type: 'structure'
};
var _default = SearchRole;
exports.default = _default;
});
unwrapExports(SearchRole_1);
var SearchBoxRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = SearchBoxRole;
exports.default = _default;
});
unwrapExports(SearchBoxRole_1);
var SliderRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = SliderRole;
exports.default = _default;
});
unwrapExports(SliderRole_1);
var SliderThumbRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var SliderThumbRole = {
relatedConcepts: [],
type: 'structure'
};
var _default = SliderThumbRole;
exports.default = _default;
});
unwrapExports(SliderThumbRole_1);
var SpinButtonRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = SpinButtonRole;
exports.default = _default;
});
unwrapExports(SpinButtonRole_1);
var SpinButtonPartRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var SpinButtonPartRole = {
relatedConcepts: [],
type: 'structure'
};
var _default = SpinButtonPartRole;
exports.default = _default;
});
unwrapExports(SpinButtonPartRole_1);
var SplitterRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var SplitterRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'separator'
}
}],
type: 'widget'
};
var _default = SplitterRole;
exports.default = _default;
});
unwrapExports(SplitterRole_1);
var StaticTextRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var StaticTextRole = {
relatedConcepts: [],
type: 'structure'
};
var _default = StaticTextRole;
exports.default = _default;
});
unwrapExports(StaticTextRole_1);
var StatusRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var StatusRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'status'
}
}],
type: 'structure'
};
var _default = StatusRole;
exports.default = _default;
});
unwrapExports(StatusRole_1);
var SVGRootRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var SVGRootRole = {
relatedConcepts: [],
type: 'structure'
};
var _default = SVGRootRole;
exports.default = _default;
});
unwrapExports(SVGRootRole_1);
var SwitchRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = SwitchRole;
exports.default = _default;
});
unwrapExports(SwitchRole_1);
var TabGroupRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var TabGroupRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'tablist'
}
}],
type: 'structure'
};
var _default = TabGroupRole;
exports.default = _default;
});
unwrapExports(TabGroupRole_1);
var TabRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var TabRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'tab'
}
}],
type: 'widget'
};
var _default = TabRole;
exports.default = _default;
});
unwrapExports(TabRole_1);
var TableHeaderContainerRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var TableHeaderContainerRole = {
relatedConcepts: [],
type: 'structure'
};
var _default = TableHeaderContainerRole;
exports.default = _default;
});
unwrapExports(TableHeaderContainerRole_1);
var TableRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var TableRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'table'
}
}, {
module: 'HTML',
concept: {
name: 'table'
}
}],
type: 'structure'
};
var _default = TableRole;
exports.default = _default;
});
unwrapExports(TableRole_1);
var TabListRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var TabListRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'tablist'
}
}],
type: 'structure'
};
var _default = TabListRole;
exports.default = _default;
});
unwrapExports(TabListRole_1);
var TabPanelRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var TabPanelRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'tabpanel'
}
}],
type: 'structure'
};
var _default = TabPanelRole;
exports.default = _default;
});
unwrapExports(TabPanelRole_1);
var TermRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var TermRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'term'
}
}],
type: 'structure'
};
var _default = TermRole;
exports.default = _default;
});
unwrapExports(TermRole_1);
var TextFieldRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.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 = TextFieldRole;
exports.default = _default;
});
unwrapExports(TextFieldRole_1);
var TimeRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var TimeRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'time'
}
}],
type: 'structure'
};
var _default = TimeRole;
exports.default = _default;
});
unwrapExports(TimeRole_1);
var TimerRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var TimerRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'timer'
}
}],
type: 'structure'
};
var _default = TimerRole;
exports.default = _default;
});
unwrapExports(TimerRole_1);
var ToggleButtonRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var ToggleButtonRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
attributes: [{
name: 'aria-pressed'
}]
}
}],
type: 'widget'
};
var _default = ToggleButtonRole;
exports.default = _default;
});
unwrapExports(ToggleButtonRole_1);
var ToolbarRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var ToolbarRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'toolbar'
}
}],
type: 'structure'
};
var _default = ToolbarRole;
exports.default = _default;
});
unwrapExports(ToolbarRole_1);
var TreeRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var TreeRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'tree'
}
}],
type: 'widget'
};
var _default = TreeRole;
exports.default = _default;
});
unwrapExports(TreeRole_1);
var TreeGridRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var TreeGridRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'treegrid'
}
}],
type: 'widget'
};
var _default = TreeGridRole;
exports.default = _default;
});
unwrapExports(TreeGridRole_1);
var TreeItemRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var TreeItemRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'treeitem'
}
}],
type: 'widget'
};
var _default = TreeItemRole;
exports.default = _default;
});
unwrapExports(TreeItemRole_1);
var UserInterfaceTooltipRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var UserInterfaceTooltipRole = {
relatedConcepts: [{
module: 'ARIA',
concept: {
name: 'tooltip'
}
}],
type: 'structure'
};
var _default = UserInterfaceTooltipRole;
exports.default = _default;
});
unwrapExports(UserInterfaceTooltipRole_1);
var VideoRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var VideoRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'video'
}
}],
type: 'widget'
};
var _default = VideoRole;
exports.default = _default;
});
unwrapExports(VideoRole_1);
var WebAreaRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var WebAreaRole = {
relatedConcepts: [],
type: 'structure'
};
var _default = WebAreaRole;
exports.default = _default;
});
unwrapExports(WebAreaRole_1);
var WindowRole_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var WindowRole = {
relatedConcepts: [],
type: 'window'
};
var _default = WindowRole;
exports.default = _default;
});
unwrapExports(WindowRole_1);
var AXObjectsMap_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _iterationDecorator = _interopRequireDefault(iterationDecorator_1$1);
var _AbbrRole = _interopRequireDefault(AbbrRole_1);
var _AlertDialogRole = _interopRequireDefault(AlertDialogRole_1);
var _AlertRole = _interopRequireDefault(AlertRole_1);
var _AnnotationRole = _interopRequireDefault(AnnotationRole_1);
var _ApplicationRole = _interopRequireDefault(ApplicationRole_1);
var _ArticleRole = _interopRequireDefault(ArticleRole_1);
var _AudioRole = _interopRequireDefault(AudioRole_1);
var _BannerRole = _interopRequireDefault(BannerRole_1);
var _BlockquoteRole = _interopRequireDefault(BlockquoteRole_1);
var _BusyIndicatorRole = _interopRequireDefault(BusyIndicatorRole_1);
var _ButtonRole = _interopRequireDefault(ButtonRole_1);
var _CanvasRole = _interopRequireDefault(CanvasRole_1);
var _CaptionRole = _interopRequireDefault(CaptionRole_1);
var _CellRole = _interopRequireDefault(CellRole_1);
var _CheckBoxRole = _interopRequireDefault(CheckBoxRole_1);
var _ColorWellRole = _interopRequireDefault(ColorWellRole_1);
var _ColumnHeaderRole = _interopRequireDefault(ColumnHeaderRole_1);
var _ColumnRole = _interopRequireDefault(ColumnRole_1);
var _ComboBoxRole = _interopRequireDefault(ComboBoxRole_1);
var _ComplementaryRole = _interopRequireDefault(ComplementaryRole_1);
var _ContentInfoRole = _interopRequireDefault(ContentInfoRole_1);
var _DateRole = _interopRequireDefault(DateRole_1);
var _DateTimeRole = _interopRequireDefault(DateTimeRole_1);
var _DefinitionRole = _interopRequireDefault(DefinitionRole_1);
var _DescriptionListDetailRole = _interopRequireDefault(DescriptionListDetailRole_1);
var _DescriptionListRole = _interopRequireDefault(DescriptionListRole_1);
var _DescriptionListTermRole = _interopRequireDefault(DescriptionListTermRole_1);
var _DetailsRole = _interopRequireDefault(DetailsRole_1);
var _DialogRole = _interopRequireDefault(DialogRole_1);
var _DirectoryRole = _interopRequireDefault(DirectoryRole_1);
var _DisclosureTriangleRole = _interopRequireDefault(DisclosureTriangleRole_1);
var _DivRole = _interopRequireDefault(DivRole_1);
var _DocumentRole = _interopRequireDefault(DocumentRole_1);
var _EmbeddedObjectRole = _interopRequireDefault(EmbeddedObjectRole_1);
var _FeedRole = _interopRequireDefault(FeedRole_1);
var _FigcaptionRole = _interopRequireDefault(FigcaptionRole_1);
var _FigureRole = _interopRequireDefault(FigureRole_1);
var _FooterRole = _interopRequireDefault(FooterRole_1);
var _FormRole = _interopRequireDefault(FormRole_1);
var _GridRole = _interopRequireDefault(GridRole_1);
var _GroupRole = _interopRequireDefault(GroupRole_1);
var _HeadingRole = _interopRequireDefault(HeadingRole_1);
var _IframePresentationalRole = _interopRequireDefault(IframePresentationalRole_1);
var _IframeRole = _interopRequireDefault(IframeRole_1);
var _IgnoredRole = _interopRequireDefault(IgnoredRole_1);
var _ImageMapLinkRole = _interopRequireDefault(ImageMapLinkRole_1);
var _ImageMapRole = _interopRequireDefault(ImageMapRole_1);
var _ImageRole = _interopRequireDefault(ImageRole_1);
var _InlineTextBoxRole = _interopRequireDefault(InlineTextBoxRole_1);
var _InputTimeRole = _interopRequireDefault(InputTimeRole_1);
var _LabelRole = _interopRequireDefault(LabelRole_1);
var _LegendRole = _interopRequireDefault(LegendRole_1);
var _LineBreakRole = _interopRequireDefault(LineBreakRole_1);
var _LinkRole = _interopRequireDefault(LinkRole_1);
var _ListBoxOptionRole = _interopRequireDefault(ListBoxOptionRole_1);
var _ListBoxRole = _interopRequireDefault(ListBoxRole_1);
var _ListItemRole = _interopRequireDefault(ListItemRole_1);
var _ListMarkerRole = _interopRequireDefault(ListMarkerRole_1);
var _ListRole = _interopRequireDefault(ListRole_1);
var _LogRole = _interopRequireDefault(LogRole_1);
var _MainRole = _interopRequireDefault(MainRole_1);
var _MarkRole = _interopRequireDefault(MarkRole_1);
var _MarqueeRole = _interopRequireDefault(MarqueeRole_1);
var _MathRole = _interopRequireDefault(MathRole_1);
var _MenuBarRole = _interopRequireDefault(MenuBarRole_1);
var _MenuButtonRole = _interopRequireDefault(MenuButtonRole_1);
var _MenuItemRole = _interopRequireDefault(MenuItemRole_1);
var _MenuItemCheckBoxRole = _interopRequireDefault(MenuItemCheckBoxRole_1);
var _MenuItemRadioRole = _interopRequireDefault(MenuItemRadioRole_1);
var _MenuListOptionRole = _interopRequireDefault(MenuListOptionRole_1);
var _MenuListPopupRole = _interopRequireDefault(MenuListPopupRole_1);
var _MenuRole = _interopRequireDefault(MenuRole_1);
var _MeterRole = _interopRequireDefault(MeterRole_1);
var _NavigationRole = _interopRequireDefault(NavigationRole_1);
var _NoneRole = _interopRequireDefault(NoneRole_1);
var _NoteRole = _interopRequireDefault(NoteRole_1);
var _OutlineRole = _interopRequireDefault(OutlineRole_1);
var _ParagraphRole = _interopRequireDefault(ParagraphRole_1);
var _PopUpButtonRole = _interopRequireDefault(PopUpButtonRole_1);
var _PreRole = _interopRequireDefault(PreRole_1);
var _PresentationalRole = _interopRequireDefault(PresentationalRole_1);
var _ProgressIndicatorRole = _interopRequireDefault(ProgressIndicatorRole_1);
var _RadioButtonRole = _interopRequireDefault(RadioButtonRole_1);
var _RadioGroupRole = _interopRequireDefault(RadioGroupRole_1);
var _RegionRole = _interopRequireDefault(RegionRole_1);
var _RootWebAreaRole = _interopRequireDefault(RootWebAreaRole_1);
var _RowHeaderRole = _interopRequireDefault(RowHeaderRole_1);
var _RowRole = _interopRequireDefault(RowRole_1);
var _RubyRole = _interopRequireDefault(RubyRole_1);
var _RulerRole = _interopRequireDefault(RulerRole_1);
var _ScrollAreaRole = _interopRequireDefault(ScrollAreaRole_1);
var _ScrollBarRole = _interopRequireDefault(ScrollBarRole_1);
var _SeamlessWebAreaRole = _interopRequireDefault(SeamlessWebAreaRole_1);
var _SearchRole = _interopRequireDefault(SearchRole_1);
var _SearchBoxRole = _interopRequireDefault(SearchBoxRole_1);
var _SliderRole = _interopRequireDefault(SliderRole_1);
var _SliderThumbRole = _interopRequireDefault(SliderThumbRole_1);
var _SpinButtonRole = _interopRequireDefault(SpinButtonRole_1);
var _SpinButtonPartRole = _interopRequireDefault(SpinButtonPartRole_1);
var _SplitterRole = _interopRequireDefault(SplitterRole_1);
var _StaticTextRole = _interopRequireDefault(StaticTextRole_1);
var _StatusRole = _interopRequireDefault(StatusRole_1);
var _SVGRootRole = _interopRequireDefault(SVGRootRole_1);
var _SwitchRole = _interopRequireDefault(SwitchRole_1);
var _TabGroupRole = _interopRequireDefault(TabGroupRole_1);
var _TabRole = _interopRequireDefault(TabRole_1);
var _TableHeaderContainerRole = _interopRequireDefault(TableHeaderContainerRole_1);
var _TableRole = _interopRequireDefault(TableRole_1);
var _TabListRole = _interopRequireDefault(TabListRole_1);
var _TabPanelRole = _interopRequireDefault(TabPanelRole_1);
var _TermRole = _interopRequireDefault(TermRole_1);
var _TextFieldRole = _interopRequireDefault(TextFieldRole_1);
var _TimeRole = _interopRequireDefault(TimeRole_1);
var _TimerRole = _interopRequireDefault(TimerRole_1);
var _ToggleButtonRole = _interopRequireDefault(ToggleButtonRole_1);
var _ToolbarRole = _interopRequireDefault(ToolbarRole_1);
var _TreeRole = _interopRequireDefault(TreeRole_1);
var _TreeGridRole = _interopRequireDefault(TreeGridRole_1);
var _TreeItemRole = _interopRequireDefault(TreeItemRole_1);
var _UserInterfaceTooltipRole = _interopRequireDefault(UserInterfaceTooltipRole_1);
var _VideoRole = _interopRequireDefault(VideoRole_1);
var _WebAreaRole = _interopRequireDefault(WebAreaRole_1);
var _WindowRole = _interopRequireDefault(WindowRole_1);
function _interopRequireDefault(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 AXObjects = [['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], ['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;
},
forEach: function forEach(fn) {
var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var _iterator = _createForOfIteratorHelper(AXObjects),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var _step$value = _slicedToArray(_step.value, 2),
key = _step$value[0],
values = _step$value[1];
fn.call(thisArg, values, key, AXObjects);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
},
get: function get(key) {
var item = AXObjects.find(function (tuple) {
return tuple[0] === key ? true : false;
});
return item && item[1];
},
has: function has(key) {
return !!this.get(key);
},
keys: function keys() {
return AXObjects.map(function (_ref) {
var _ref2 = _slicedToArray(_ref, 1),
key = _ref2[0];
return key;
});
},
values: function values() {
return AXObjects.map(function (_ref3) {
var _ref4 = _slicedToArray(_ref3, 2),
values = _ref4[1];
return values;
});
}
};
var _default = (0, _iterationDecorator.default)(AXObjectsMap, AXObjectsMap.entries());
exports.default = _default;
});
unwrapExports(AXObjectsMap_1);
var AXObjectElementMap_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _iterationDecorator = _interopRequireDefault(iterationDecorator_1$1);
var _AXObjectsMap = _interopRequireDefault(AXObjectsMap_1);
function _interopRequireDefault(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 AXObjectElements = [];
var _iterator = _createForOfIteratorHelper(_AXObjectsMap.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) {
var index = AXObjectElements.findIndex(function (_ref5) {
var _ref6 = _slicedToArray(_ref5, 1),
key = _ref6[0];
return key === name;
});
if (index === -1) {
AXObjectElements.push([name, []]);
index = AXObjectElements.length - 1;
}
AXObjectElements[index][1].push(concept);
}
}
});
}
};
for (_iterator.s(); !(_step = _iterator.n()).done;) {
_loop();
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
var AXObjectElementMap = {
entries: function entries() {
return AXObjectElements;
},
forEach: function forEach(fn) {
var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var _iterator2 = _createForOfIteratorHelper(AXObjectElements),
_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, AXObjectElements);
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
},
get: function get(key) {
var item = AXObjectElements.find(function (tuple) {
return tuple[0] === key ? true : false;
});
return item && item[1];
},
has: function has(key) {
return !!this.get(key);
},
keys: function keys() {
return AXObjectElements.map(function (_ref) {
var _ref2 = _slicedToArray(_ref, 1),
key = _ref2[0];
return key;
});
},
values: function values() {
return AXObjectElements.map(function (_ref3) {
var _ref4 = _slicedToArray(_ref3, 2),
values = _ref4[1];
return values;
});
}
};
var _default = (0, _iterationDecorator.default)(AXObjectElementMap, AXObjectElementMap.entries());
exports.default = _default;
});
unwrapExports(AXObjectElementMap_1);
var AXObjectRoleMap_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _iterationDecorator = _interopRequireDefault(iterationDecorator_1$1);
var _AXObjectsMap = _interopRequireDefault(AXObjectsMap_1);
function _interopRequireDefault(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 AXObjectRoleElements = [];
var _iterator = _createForOfIteratorHelper(_AXObjectsMap.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 === 'ARIA') {
var concept = relation.concept;
if (concept) {
var index = AXObjectRoleElements.findIndex(function (_ref5) {
var _ref6 = _slicedToArray(_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.s(); !(_step = _iterator.n()).done;) {
_loop();
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.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(AXObjectRoleElements),
_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, 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 !!this.get(key);
},
keys: function keys() {
return AXObjectRoleElements.map(function (_ref) {
var _ref2 = _slicedToArray(_ref, 1),
key = _ref2[0];
return key;
});
},
values: function values() {
return AXObjectRoleElements.map(function (_ref3) {
var _ref4 = _slicedToArray(_ref3, 2),
values = _ref4[1];
return values;
});
}
};
var _default = (0, _iterationDecorator.default)(AXObjectRoleMap, AXObjectRoleMap.entries());
exports.default = _default;
});
unwrapExports(AXObjectRoleMap_1);
var elementAXObjectMap_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _AXObjectsMap = _interopRequireDefault(AXObjectsMap_1);
var _deepEqual = _interopRequireDefault(deepEqual);
var _iterationDecorator = _interopRequireDefault(iterationDecorator_1$1);
function _interopRequireDefault(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 = [];
var _iterator = _createForOfIteratorHelper(_AXObjectsMap.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.length; index++) {
var key = elementAXObjects[index][0];
if (JSON.stringify(key) === conceptStr) {
axObjects = elementAXObjects[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.length) {
elementAXObjects.splice(index, 1, [concept, axObjects]);
} else {
elementAXObjects.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;
},
forEach: function forEach(fn) {
var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var _iterator2 = _createForOfIteratorHelper(elementAXObjects),
_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);
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
},
get: function get(key) {
var item = elementAXObjects.find(function (tuple) {
return (0, _deepEqual.default)(key, tuple[0]) ? true : false;
});
return item && item[1];
},
has: function has(key) {
return !!this.get(key);
},
keys: function keys() {
return elementAXObjects.map(function (_ref) {
var _ref2 = _slicedToArray(_ref, 1),
key = _ref2[0];
return key;
});
},
values: function values() {
return elementAXObjects.map(function (_ref3) {
var _ref4 = _slicedToArray(_ref3, 2),
values = _ref4[1];
return values;
});
}
};
var _default = (0, _iterationDecorator.default)(elementAXObjectMap, elementAXObjectMap.entries());
exports.default = _default;
});
unwrapExports(elementAXObjectMap_1);
var lib$1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.elementAXObjects = exports.AXObjects = exports.AXObjectRoles = exports.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;
exports.AXObjectElements = AXObjectElements;
var AXObjectRoles = _AXObjectRoleMap.default;
exports.AXObjectRoles = AXObjectRoles;
var AXObjects = _AXObjectsMap.default;
exports.AXObjects = AXObjects;
var elementAXObjects = _elementAXObjectMap.default;
exports.elementAXObjects = elementAXObjects;
});
unwrapExports(lib$1);
var lib_1$1 = lib$1.elementAXObjects;
var lib_2$1 = lib$1.AXObjects;
var lib_3$1 = lib$1.AXObjectRoles;
var lib_4$1 = lib$1.AXObjectElements;
const non_abstract_roles = [...lib_1.keys()].filter((name) => !lib_1.get(name).abstract);
const non_interactive_roles = new Set(non_abstract_roles
.filter((name) => {
const role = lib_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.
!['toolbar', 'tabpanel'].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)));
function is_non_interactive_roles(role) {
return non_interactive_roles.has(role);
}
function is_interactive_roles(role) {
return interactive_roles.has(role);
}
const presentation_roles = new Set(['presentation', 'none']);
function is_presentation_role(role) {
return presentation_roles.has(role);
}
function is_hidden_from_screen_reader(tag_name, attribute_map) {
var _a;
if (tag_name === 'input') {
const type = (_a = attribute_map.get('type')) === null || _a === void 0 ? void 0 : _a.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';
}
const non_interactive_element_role_schemas = [];
lib_3.entries().forEach(([schema, roles]) => {
if ([...roles].every((role) => non_interactive_roles.has(role))) {
non_interactive_element_role_schemas.push(schema);
}
});
const interactive_element_role_schemas = [];
lib_3.entries().forEach(([schema, roles]) => {
if ([...roles].every((role) => interactive_roles.has(role))) {
interactive_element_role_schemas.push(schema);
}
});
const interactive_ax_objects = new Set([...lib_2$1.keys()].filter((name) => lib_2$1.get(name).type === 'widget'));
const interactive_element_ax_object_schemas = [];
lib_1$1.entries().forEach(([schema, ax_object]) => {
if ([...ax_object].every((role) => interactive_ax_objects.has(role))) {
interactive_element_ax_object_schemas.push(schema);
}
});
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;
});
}
function is_interactive_element(tag_name, attribute_map) {
if (interactive_element_role_schemas.some((schema) => match_schema(schema, tag_name, attribute_map))) {
return true;
}
if (non_interactive_element_role_schemas.some((schema) => match_schema(schema, tag_name, attribute_map))) {
return false;
}
if (interactive_element_ax_object_schemas.some((schema) => match_schema(schema, tag_name, attribute_map))) {
return true;
}
return false;
}
function is_semantic_role_element(role, tag_name, attribute_map) {
for (const [schema, ax_object] of lib_1$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 = lib_3$1.get(name);
if (roles) {
for (const { name } of roles) {
if (name === role) {
return true;
}
}
}
}
}
}
return false;
}
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 = lib_1.keys();
const aria_role_set = new Set(aria_roles);
const aria_role_abstract_set = new Set(lib_1.keys().filter(role => lib_1.get(role).abstract));
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_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'],
['form', 'form'],
['h1', 'heading'],
['h2', 'heading'],
['h3', 'heading'],
['h4', 'heading'],
['h5', 'heading'],
['h6', 'heading'],
['hr', 'separator'],
['img', 'img'],
['li', 'listitem'],
['link', 'link'],
['menu', 'list'],
['meter', 'progressbar'],
['nav', 'navigation'],
['ol', 'list'],
['option', 'option'],
['optgroup', 'group'],
['output', 'status'],
['progress', 'progressbar'],
['section', 'region'],
['summary', 'button'],
['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']
]);
const combobox_if_list = new Set(['email', 'search', 'tel', 'text', 'url']);
function input_implicit_role(attribute_map) {
const type_attribute = attribute_map.get('type');
if (!type_attribute || !type_attribute.is_static)
return;
const type = 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);
}
function menuitem_implicit_role(attribute_map) {
const type_attribute = attribute_map.get('type');
if (!type_attribute || !type_attribute.is_static)
return;
const type = type_attribute.get_static_value();
return menuitem_type_to_implicit_role.get(type);
}
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$1 = 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'];
function is_parent(parent, elements) {
let check = false;
while (parent) {
const parent_name = parent.name;
if (elements.includes(parent_name)) {
check = true;
break;
}
if (parent.type === 'Element') {
break;
}
parent = parent.parent;
}
return check;
}
function get_namespace(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;
}
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((id) => typeof id === 'string');
case 'tokenlist': // if list of tokens, split each
return typeof value === 'string'
&& value.split(regex_any_repeated_whitespaces).every((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-.])|[\^$@%&#?!|()[\]{}^*+~;]/;
class Element extends Node$1 {
constructor(component, parent, scope, info) {
super(component, parent, scope, info);
this.attributes = [];
this.actions = [];
this.bindings = [];
this.classes = [];
this.styles = [];
this.handlers = [];
this.lets = [];
this.intro = null;
this.outro = null;
this.animation = null;
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, string_literal(info.tag));
this.name = info.tag;
}
}
else {
this.tag_expr = new Expression(component, this, scope, string_literal(this.name));
}
this.namespace = get_namespace(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(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(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(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((a, b) => order.indexOf(a.type) - order.indexOf(b.type));
info.attributes.forEach(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(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);
}
get is_dynamic_element() {
return this.name === 'svelte:element';
}
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(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() {
var _a;
const { component, attributes, handlers } = this;
const attribute_map = new Map();
const handlers_map = new Map();
attributes.forEach(attribute => (attribute_map.set(attribute.name, attribute)));
handlers.forEach(handler => (handlers_map.set(handler.name, handler)));
attributes.forEach(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 && lib_5.has(name)) {
const schema = lib_5.get(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((current_role) => {
if (current_role && aria_role_abstract_set.has(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
const has_redundant_role = current_role === get_implicit_role(this.name, attribute_map);
if (this.name === current_role || has_redundant_role) {
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 = lib_1.get(current_role);
if (role) {
const required_role_props = Object.keys(role.requiredProps);
const has_missing_props = required_role_props.some(prop => !attributes.find(a => a.name === prop));
if (has_missing_props) {
component.warn(attribute, compiler_warnings.a11y_role_has_required_aria_props(current_role, required_role_props));
}
}
}
// 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-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 === null || role === void 0 ? void 0 : role.is_static) && !is_presentation_role(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(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);
}
}
}
// no-noninteractive-tabindex
if (!this.is_dynamic_element && !is_interactive_element(this.name, attribute_map) && !is_interactive_roles((_a = attribute_map.get('role')) === null || _a === void 0 ? void 0 : _a.get_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
const role = attribute_map.get('role');
const role_value = (role ? role.get_static_value() : get_implicit_role(this.name, attribute_map));
if (typeof role_value === 'string' && lib_1.has(role_value)) {
const { props } = lib_1.get(role_value);
const invalid_aria_props = new Set(lib_5.keys().filter(attribute => !(attribute in props)));
const is_implicit = role_value && role === undefined;
attributes
.filter(prop => prop.type !== 'Spread')
.forEach(prop => {
if (invalid_aria_props.has(prop.name)) {
component.warn(prop, compiler_warnings.a11y_role_supports_aria_props(prop.name, role_value, is_implicit, this.name));
}
});
}
}
validate_special_cases() {
const { component, attributes, handlers } = this;
const attribute_map = new Map();
const handlers_map = new Map();
attributes.forEach(attribute => (attribute_map.set(attribute.name, attribute)));
handlers.forEach(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(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(name => attribute_map.has(name));
if (!has_attribute) {
should_have_attribute(this, required_attributes, 'input type="image"');
}
}
}
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') {
const has_input_child = (children) => {
if (children.some(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((i) => i.name === 'track');
if (track) {
has_caption = track.attributes.find(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 (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(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(child => 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(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((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(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((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 (name === 'textContent' ||
name === 'innerHTML') {
const contenteditable = this.attributes.find((attribute) => attribute.name === 'contenteditable');
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') {
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((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(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(modifier => {
if (!valid_modifiers$1.has(modifier)) {
return component.error(handler, compiler_errors.invalid_event_modifier(list$1(Array.from(valid_modifiers$1))));
}
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(attr => attr.is_spread)) {
this.needs_manual_style_scoping = true;
return;
}
const { id } = this.component.stylesheet;
const class_attribute = this.attributes.find(a => a.name === 'class');
if (class_attribute && !class_attribute.is_true) {
if (class_attribute.chunks.length === 1 && class_attribute.chunks[0].type === 'Text') {
class_attribute.chunks[0].data += ` ${id}`;
}
else {
class_attribute.chunks.push(new Text(this.component, this, this.scope, {
type: 'Text',
data: ` ${id}`,
synthetic: true
}));
}
}
else {
this.attributes.push(new Attribute(this.component, this, this.scope, {
type: 'Attribute',
name: 'class',
value: [{ type: 'Text', data: id, synthetic: true }]
}));
}
}
get slot_template_name() {
return this.attributes.find(attribute => attribute.name === 'slot').get_static_value();
}
optimise() {
attributes_to_compact_whitespace.forEach(attribute_name => {
const attribute = this.attributes.find(a => a.name === attribute_name);
if (attribute && !attribute.is_true) {
attribute.chunks.forEach((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;
}
});
}
});
}
}
const regex_starts_with_vowel = /^[aeiou]/;
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 = /-/;
function within_custom_element(parent) {
while (parent) {
if (parent.type === 'InlineComponent')
return false;
if (parent.type === 'Element' && regex_minus_sign.test(parent.name))
return true;
parent = parent.parent;
}
return false;
}
// https://github.com/darkskyapp/string-hash/blob/master/index.js
const regex_return_characters = /\r/g;
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);
}
class Head extends Node$1 {
constructor(component, parent, scope, info) {
super(component, parent, scope, info);
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(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))}`;
}
}
}
class IfBlock extends AbstractBlock {
constructor(component, parent, scope, info) {
super(component, parent, scope, info);
this.scope = scope.child();
this.expression = new Expression(component, this, this.scope, info.expression);
([this.const_tags, this.children] = get_const_tags(info.children, component, this, this));
this.else = info.else
? new ElseBlock(component, this, scope, info.else)
: null;
this.warn_if_empty_block();
}
}
class InlineComponent extends Node$1 {
constructor(component, parent, scope, info) {
super(component, parent, scope, info);
this.attributes = [];
this.bindings = [];
this.handlers = [];
this.lets = [];
this.css_custom_properties = [];
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(this, name);
}
this.name = info.name;
this.namespace = get_namespace$1(parent, component.namespace);
this.expression = this.name === 'svelte:component'
? new Expression(component, this, scope, info.expression)
: null;
info.attributes.forEach(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':
this.lets.push(new Let(component, this, scope, node));
break;
case 'Transition':
return component.error(node, compiler_errors.invalid_transition);
case 'StyleDirective':
return component.error(node, compiler_errors.invalid_component_style_directive);
default:
throw new Error(`Not implemented: ${node.type}`);
}
/* eslint-enable no-fallthrough */
});
if (this.lets.length > 0) {
this.scope = scope.child();
this.lets.forEach(l => {
const dependencies = new Set([l.name.name]);
l.names.forEach(name => {
this.scope.add(name, dependencies, this);
});
});
}
else {
this.scope = scope;
}
this.handlers.forEach(handler => {
handler.modifiers.forEach(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(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(node => not_whitespace_text(node))) {
children.push({
start: info.start,
end: info.end,
type: 'SlotTemplate',
name: 'svelte:fragment',
attributes: [],
children: info.children
});
}
this.children = map_children(component, this, this.scope, children);
}
get slot_template_name() {
return this.attributes.find(attribute => attribute.name === 'slot').get_static_value();
}
}
function not_whitespace_text(node) {
return !(node.type === 'Text' && regex_only_whitespaces.test(node.data));
}
function get_namespace$1(parent, explicit_namespace) {
const parent_element = parent.find_nearest(/^Element/);
if (!parent_element) {
return explicit_namespace;
}
return parent_element.namespace;
}
class KeyBlock extends AbstractBlock {
constructor(component, parent, scope, info) {
super(component, parent, scope, info);
this.expression = new Expression(component, this, scope, info.expression);
this.children = map_children(component, this, scope, info.children);
this.warn_if_empty_block();
}
}
class Tag extends Node$1 {
constructor(component, parent, scope, info) {
super(component, parent, scope, info);
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)));
}
}
class MustacheTag extends Tag {
}
class Options extends Node$1 {
}
class RawMustacheTag extends Tag {
}
class DebugTag extends Node$1 {
constructor(component, parent, scope, info) {
super(component, parent, scope, info);
this.expressions = info.identifiers.map((node) => {
return new Expression(component, parent, scope, node);
});
}
}
class Slot extends Element {
constructor(component, parent, scope, info) {
super(component, parent, scope, info);
this.values = new Map();
info.attributes.forEach(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';
if (this.slot_name === 'default') {
// if this is the default slot, add our dependencies to any
// other slots (which inherit our slot values) that were
// previously encountered
component.slots.forEach((slot) => {
this.values.forEach((attribute, name) => {
if (!slot.values.has(name)) {
slot.values.set(name, attribute);
}
});
});
}
else if (component.slots.has('default')) {
// otherwise, go the other way — inherit values from
// a previously encountered default slot
const default_slot = component.slots.get('default');
default_slot.values.forEach((attribute, name) => {
if (!this.values.has(name)) {
this.values.set(name, attribute);
}
});
}
component.slots.set(this.slot_name, this);
}
}
class SlotTemplate extends Node$1 {
constructor(component, parent, scope, info) {
super(component, parent, scope, info);
this.lets = [];
this.slot_template_name = 'default';
this.validate_slot_template_placement();
scope = scope.child();
info.attributes.forEach((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((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 = 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(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);
}
}
}
class Title extends Node$1 {
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(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',
'online'
];
class Window extends Node$1 {
constructor(component, parent, scope, info) {
super(component, parent, scope, info);
this.handlers = [];
this.bindings = [];
this.actions = [];
info.attributes.forEach(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$1(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));
}
});
}
}
/**
* 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).
* @param array
* @param items
*/
function push_array$1(array, items) {
for (let i = 0; i < items.length; i++) {
array.push(items[i]);
}
}
function get_constructor(type) {
switch (type) {
case 'AwaitBlock': return AwaitBlock;
case 'Body': return Body;
case 'Comment': return Comment$1;
case 'ConstTag': return ConstTag;
case 'EachBlock': return EachBlock;
case 'Element': return Element;
case 'Head': return Head;
case 'IfBlock': return IfBlock;
case 'InlineComponent': return InlineComponent;
case 'KeyBlock': return KeyBlock;
case 'MustacheTag': return MustacheTag;
case 'Options': return Options;
case 'RawMustacheTag': return RawMustacheTag;
case 'DebugTag': return DebugTag;
case 'Slot': return Slot;
case 'SlotTemplate': return SlotTemplate;
case 'Text': return Text;
case 'Title': return Title;
case 'Window': return Window;
default: throw new Error(`Not implemented: ${type}`);
}
}
function map_children(component, parent, scope, children) {
let last = null;
let ignores = [];
return children.map(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$1(ignores, node.ignores);
}
if (last)
last.next = node;
node.prev = last;
last = node;
return node;
});
}
function check_graph_for_cycles(edges) {
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];
}
function get_const_tags(children, component, node, parent) {
const const_tags = [];
const others = [];
for (const child of children) {
if (child.type === 'ConstTag') {
const_tags.push(child);
}
else {
others.push(child);
}
}
const consts_nodes = const_tags.map(tag => new ConstTag(component, node, node.scope, tag));
const sorted_consts_nodes = sort_consts_nodes(consts_nodes, component);
sorted_consts_nodes.forEach(node => node.parse_expression());
const children_nodes = map_children(component, parent, node.scope, others);
return [sorted_consts_nodes, children_nodes];
}
function sort_consts_nodes(consts_nodes, component) {
const sorted_consts_nodes = [];
const unsorted_consts_nodes = consts_nodes.map(node => {
return {
assignees: node.assignees,
dependencies: node.dependencies,
node
};
});
const lookup = new Map();
unsorted_consts_nodes.forEach(node => {
node.assignees.forEach(name => {
if (!lookup.has(name)) {
lookup.set(name, []);
}
lookup.get(name).push(node);
});
});
const cycle = check_graph_for_cycles(unsorted_consts_nodes.reduce((acc, node) => {
node.assignees.forEach(v => {
node.dependencies.forEach(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));
}
const add_node = (node) => {
if (sorted_consts_nodes.includes(node))
return;
node.dependencies.forEach(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(node => node.node);
}
class ThenBlock extends AbstractBlock {
constructor(component, parent, scope, info) {
super(component, parent, scope, info);
this.scope = scope.child();
if (parent.then_node) {
parent.then_contexts.forEach(context => {
this.scope.add(context.key.name, parent.expression.dependencies, this);
});
}
([this.const_tags, this.children] = get_const_tags(info.children, component, this, parent));
if (!info.skip) {
this.warn_if_empty_block();
}
}
}
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 `const ${name} = ${const_tag.expression.manipulate(block, ctx)}`);
const_tag.contexts.forEach(context => {
const_tags_props.push(b `${ctx}[${block.renderer.context_lookup.get(context.key.name).index}] = ${context.default_modifier(context.modifier({ type: 'Identifier', name }), name => block.renderer.context_lookup.has(name) ? x `${ctx}[${block.renderer.context_lookup.get(name).index}]` : { type: 'Identifier', name })};`);
});
});
return const_tags_props;
}
function add_const_tags_context(renderer, const_tags) {
const_tags.forEach(const_tag => {
const_tag.contexts.forEach(context => {
renderer.add_to_context(context.key.name, true);
});
});
}
class AwaitBlockBranch extends Wrapper {
constructor(status, renderer, block, parent, node, strip_whitespace, next_sibling) {
super(renderer, block, parent, node);
this.var = null;
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;
}
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 => {
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);
}
}
has_consts(node) {
return node instanceof ThenBlock || node instanceof CatchBlock;
}
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 => b `#ctx[${this.block.renderer.context_lookup.get(prop.key.name).index}] = ${prop.default_modifier(prop.modifier(x `#ctx[${this.value_index}]`), name => this.renderer.reference(name))};`) : 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 `
function ${get_context}(#ctx) {
${props}
${const_tags_props}
}
`);
this.block.chunks.declarations.push(b `${get_context}(#ctx)`);
if (this.block.has_update_method) {
this.block.chunks.update.unshift(b `${get_context}(#ctx)`);
}
}
}
class AwaitBlockWrapper extends Wrapper {
constructor(renderer, block, parent, node, strip_whitespace, next_sibling) {
super(renderer, block, parent, node);
this.var = { type: 'Identifier', name: 'await_block' };
this.cannot_use_innerhtml();
this.not_static_content();
block.add_dependencies(this.node.expression.dependencies);
let is_dynamic = false;
let has_intros = false;
let has_outros = false;
['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();
}
}
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;
const info_props = x `{
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 `[,,,]`}
}`;
block.chunks.init.push(b `
let ${info} = ${info_props};
`);
block.chunks.init.push(b `
@handle_promise(${promise} = ${snippet}, ${info});
`);
block.chunks.create.push(b `
${info}.block.c();
`);
if (parent_nodes && this.renderer.options.hydratable) {
block.chunks.claim.push(b `
${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 `
${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 `@transition_in(${info}.block);`);
}
const dependencies = this.node.expression.dynamic_dependencies();
const update_await_block_branch = b `@update_await_block_branch(${info}, #ctx, #dirty)`;
if (dependencies.length > 0) {
const condition = x `
${block.renderer.dirty(dependencies)} &&
${promise} !== (${promise} = ${snippet}) &&
@handle_promise(${promise}, ${info})`;
block.chunks.update.push(b `${info}.ctx = #ctx;`);
if (this.pending.block.has_update_method) {
block.chunks.update.push(b `
if (${condition}) {
} else {
${update_await_block_branch}
}
`);
}
else {
block.chunks.update.push(b `
${condition}
`);
}
}
else {
if (this.pending.block.has_update_method) {
block.chunks.update.push(b `
${update_await_block_branch}
`);
}
}
if (this.pending.block.has_outro_method) {
block.chunks.outro.push(b `
for (let #i = 0; #i < 3; #i += 1) {
const block = ${info}.blocks[#i];
@transition_out(block);
}
`);
}
block.chunks.destroy.push(b `
${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, x `#nodes`);
});
}
}
const TRUE = x `true`;
const FALSE = x `false`;
class EventHandlerWrapper {
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 `
function ${node.handler_name.name}(event) {
@bubble.call(this, $$self, event);
}
`);
}
}
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 `function () { if (@is_function(${snippet})) ${snippet}.apply(this, arguments); }`;
}
return snippet;
}
render(block, target) {
let snippet = this.get_snippet(block);
if (this.node.modifiers.has('preventDefault'))
snippet = x `@prevent_default(${snippet})`;
if (this.node.modifiers.has('stopPropagation'))
snippet = x `@stop_propagation(${snippet})`;
if (this.node.modifiers.has('stopImmediatePropagation'))
snippet = x `@stop_immediate_propagation(${snippet})`;
if (this.node.modifiers.has('self'))
snippet = x `@self(${snippet})`;
if (this.node.modifiers.has('trusted'))
snippet = x `@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 `{ ${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 `@listen(${target}, "${this.node.name}", ${snippet}, ${args})`);
}
}
function add_event_handlers(block, target, handlers) {
handlers.forEach(handler => add_event_handler(block, target, handler));
}
function add_event_handler(block, target, handler) {
handler.render(block, target);
}
function add_actions(block, target, actions) {
actions.forEach(action => add_action(block, target, action));
}
const regex_invalid_variable_identifier_characters = /[^a-zA-Z0-9_$]/g;
function add_action(block, target, action) {
const { expression, template_scope } = action;
let snippet;
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, '_')}_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 `${lhs}.${rhs}`, fn);
block.event_listeners.push(x `@action_destroyer(${id} = ${member_expression}(${target}, ${snippet}))`);
}
else {
block.event_listeners.push(x `@action_destroyer(${id} = ${fn}.call(null, ${target}, ${snippet}))`);
}
if (dependencies && dependencies.length > 0) {
let condition = x `${id} && @is_function(${id}.update)`;
if (dependencies.length > 0) {
condition = x `${condition} && ${block.renderer.dirty(dependencies)}`;
}
block.chunks.update.push(b `if (${condition}) ${id}.update.call(null, ${snippet});`);
}
}
class BodyWrapper extends Wrapper {
constructor(renderer, block, parent, node) {
super(renderer, block, parent, node);
this.handlers = this.node.handlers.map(handler => new EventHandlerWrapper(handler, this));
}
render(block, _parent_node, _parent_nodes) {
add_event_handlers(block, x `@_document.body`, this.handlers);
add_actions(block, x `@_document.body`, this.node.actions);
}
}
class DebugTagWrapper extends Wrapper {
constructor(renderer, block, parent, node, _strip_whitespace, _next_sibling) {
super(renderer, block, parent, node);
}
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 };
const debug = {
type: 'DebuggerStatement',
loc
};
if (this.node.expressions.length === 0) {
// Debug all
block.chunks.create.push(debug);
block.chunks.update.push(debug);
}
else {
const log = {
type: 'Identifier',
name: 'log',
loc
};
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(e.node.name);
return !(variable && variable.hoistable);
})
.map(e => e.node.name);
const logged_identifiers = this.node.expressions.map(e => p `${e.node.name}`);
const debug_statements = b `
${contextual_identifiers.map(name => b `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 `
if (${condition}) {
${debug_statements}
}
`);
}
block.chunks.create.push(b `{
${debug_statements}
}`);
}
}
}
class ElseBlockWrapper extends Wrapper {
constructor(renderer, block, parent, node, strip_whitespace, next_sibling) {
super(renderer, block, parent, node);
this.var = null;
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;
}
}
class EachBlockWrapper extends Wrapper {
constructor(renderer, block, parent, node, strip_whitespace, next_sibling) {
super(renderer, block, parent, node);
this.updates = [];
this.var = { type: 'Identifier', name: 'each' };
this.cannot_use_innerhtml();
this.not_static_content();
const { dependencies } = node.expression;
block.add_dependencies(dependencies);
this.node.contexts.forEach(context => {
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: 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 `${each_block_value}.${length}` : fixed_length,
view_length: fixed_length === null ? x `${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 => {
this.block.bindings.set(prop.key.name, {
object: this.vars.each_block_value,
property: this.index_name,
modifier: prop.modifier,
snippet: prop.modifier(x `${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();
}
}
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 = this.node.expression.manipulate(block);
block.chunks.init.push(b `let ${this.vars.each_block_value} = ${snippet};`);
if (this.renderer.options.dev) {
block.chunks.init.push(b `@validate_each_argument(${this.vars.each_block_value});`);
}
const initial_anchor_node = { type: 'Identifier', name: parent_node ? 'null' : '#anchor' };
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' };
const update_mount_node = this.get_update_mount_node(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 `
for (let #i = 0; #i < ${this.vars.data_length}; #i += 1) {
@transition_in(${this.vars.iterations}[#i]);
}
`);
}
if (needs_anchor) {
block.add_element(update_anchor_node, x `@empty()`, parent_nodes && x `@empty()`, parent_node);
}
if (this.else) {
let else_ctx = x `#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 `
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 `${get_ctx_name}(#ctx)`;
}
const each_block_else = component.get_unique_name(`${this.var.name}_else`);
block.chunks.init.push(b `let ${each_block_else} = null;`);
// TODO neaten this up... will end up with an empty line in the block
block.chunks.init.push(b `
if (!${this.vars.data_length}) {
${each_block_else} = ${this.else.block.name}(${else_ctx});
}
`);
block.chunks.create.push(b `
if (${each_block_else}) {
${each_block_else}.c();
}
`);
if (this.renderer.options.hydratable) {
block.chunks.claim.push(b `
if (${each_block_else}) {
${each_block_else}.l(${parent_nodes});
}
`);
}
block.chunks.mount.push(b `
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 `
@group_outros();
@transition_out(${each_block_else}, 1, 1, () => {
${each_block_else} = null;
});
@check_outros();`
: b `
${each_block_else}.d(1);
${each_block_else} = null;`;
if (this.else.block.has_update_method) {
this.updates.push(b `
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 `@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 `
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 `@transition_in(${each_block_else}, 1);`}
${each_block_else}.m(${update_mount_node}, ${update_anchor_node});
}
`);
}
block.chunks.destroy.push(b `
if (${each_block_else}) ${each_block_else}.d(${parent_node ? '' : 'detaching'});
`);
}
if (this.updates.length) {
block.chunks.update.push(b `
if (${block.renderer.dirty(Array.from(all_dependencies))}) {
${this.updates}
}
`);
}
this.fragment.render(this.block, null, x `#nodes`);
if (this.else) {
this.else.fragment.render(this.else.block, null, x `#nodes`);
}
this.context_props = this.node.contexts.map(prop => b `child_ctx[${renderer.context_lookup.get(prop.key.name).index}] = ${prop.default_modifier(prop.modifier(x `list[i]`), name => renderer.context_lookup.has(name) ? x `child_ctx[${renderer.context_lookup.get(name).index}]` : { type: 'Identifier', name })};`);
if (this.node.has_binding)
this.context_props.push(b `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 `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 `
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;
}
`);
}
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 `[]`);
block.add_variable(lookup, x `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 `@empty()`, parent_nodes && x `@empty()`, null);
}
block.chunks.init.push(b `
const ${get_key} = #ctx => ${this.node.key.manipulate(block)};
${this.renderer.options.dev && b `@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 `
for (let #i = 0; #i < ${view_length}; #i += 1) {
${iterations}[#i].c();
}
`);
if (parent_nodes && this.renderer.options.hydratable) {
block.chunks.claim.push(b `
for (let #i = 0; #i < ${view_length}; #i += 1) {
${iterations}[#i].l(${parent_nodes});
}
`);
}
block.chunks.mount.push(b `
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 `
${this.vars.each_block_value} = ${snippet};
${this.renderer.options.dev && b `@validate_each_argument(${this.vars.each_block_value});`}
${this.block.has_outros && b `@group_outros();`}
${this.node.has_animation && b `for (let #i = 0; #i < ${view_length}; #i += 1) ${iterations}[#i].r();`}
${this.renderer.options.dev && b `@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 `for (let #i = 0; #i < ${view_length}; #i += 1) ${iterations}[#i].a();`}
${this.block.has_outros && b `@check_outros();`}
`);
}
if (this.block.has_outros) {
block.chunks.outro.push(b `
for (let #i = 0; #i < ${view_length}; #i += 1) {
@transition_out(${iterations}[#i]);
}
`);
}
block.chunks.destroy.push(b `
for (let #i = 0; #i < ${view_length}; #i += 1) {
${iterations}[#i].d(${parent_node ? null : 'detaching'});
}
`);
}
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 `
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 `
for (let #i = 0; #i < ${view_length}; #i += 1) {
${iterations}[#i].c();
}
`);
if (parent_nodes && this.renderer.options.hydratable) {
block.chunks.claim.push(b `
for (let #i = 0; #i < ${view_length}; #i += 1) {
${iterations}[#i].l(${parent_nodes});
}
`);
}
block.chunks.mount.push(b `
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 `
if (${iterations}[#i]) {
${iterations}[#i].p(child_ctx, #dirty);
${has_transitions && b `@transition_in(${this.vars.iterations}[#i], 1);`}
} else {
${iterations}[#i] = ${create_each_block}(child_ctx);
${iterations}[#i].c();
${has_transitions && b `@transition_in(${this.vars.iterations}[#i], 1);`}
${iterations}[#i].m(${update_mount_node}, ${update_anchor_node});
}
`
: has_transitions
? b `
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 `
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';
let remove_old_blocks;
if (this.block.has_outros) {
const out = block.get_unique_name('out');
block.chunks.init.push(b `
const ${out} = i => @transition_out(${iterations}[i], 1, 1, () => {
${iterations}[i] = null;
});
`);
remove_old_blocks = b `
@group_outros();
for (#i = ${data_length}; #i < ${view_length}; #i += 1) {
${out}(#i);
}
@check_outros();
`;
}
else {
remove_old_blocks = b `
for (${this.block.has_update_method ? null : x `#i = ${data_length}`}; #i < ${this.block.has_update_method ? view_length : '#old_length'}; #i += 1) {
${iterations}[#i].d(1);
}
${!fixed_length && b `${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 `
${!this.block.has_update_method && b `const #old_length = ${this.vars.each_block_value}.length;`}
${this.vars.each_block_value} = ${snippet};
${this.renderer.options.dev && b `@validate_each_argument(${this.vars.each_block_value});`}
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 `
${iterations} = ${iterations}.filter(@_Boolean);
for (let #i = 0; #i < ${view_length}; #i += 1) {
@transition_out(${iterations}[#i]);
}
`);
}
block.chunks.destroy.push(b `@destroy_each(${iterations}, detaching);`);
}
}
const regex_non_whitespace_characters$1 = /[\S\u00A0]/;
class TextWrapper extends Wrapper {
constructor(renderer, block, parent, node, data) {
super(renderer, block, parent, node);
this.skip = this.node.should_skip();
this.data = data;
this.var = (this.skip ? null : x `t`);
}
use_space() {
if (this.renderer.component.component_options.preserveWhitespace)
return false;
if (regex_non_whitespace_characters$1.test(this.data))
return false;
return !this.node.within_pre();
}
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 `@space()` : x `@text(${string_literal})`, parent_nodes && (use_space ? x `@claim_space(${parent_nodes})` : x `@claim_text(${parent_nodes}, ${string_literal})`), 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);
});
function fix_attribute_casing(name) {
name = name.toLowerCase();
return svg_attribute_lookup.get(name) || name;
}
function handle_select_value_binding(attr, dependencies) {
const { parent } = attr;
if (parent.node.name === 'select') {
parent.select_binding_dependencies = dependencies;
dependencies.forEach((prop) => {
parent.renderer.component.indirect_dependencies.set(prop, new Set());
});
}
}
const _boolean_attributes = [
'allowfullscreen',
'allowpaymentrequest',
'async',
'autofocus',
'autoplay',
'checked',
'controls',
'default',
'defer',
'disabled',
'formnovalidate',
'hidden',
'inert',
'ismap',
'itemscope',
'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
*/
const boolean_attributes = new Set([..._boolean_attributes]);
const non_textlike_input_types = new Set([
'button',
'checkbox',
'color',
'date',
'datetime-local',
'file',
'hidden',
'image',
'radio',
'range',
'reset',
'submit'
]);
class BaseAttributeWrapper {
constructor(parent, block, node) {
this.node = node;
this.parent = parent;
if (node.dependencies.size > 0) {
parent.cannot_use_innerhtml();
parent.not_static_content();
block.add_dependencies(node.dependencies);
}
}
render(_block) { }
}
const regex_minus_sign$1 = /-/;
const regex_invalid_variable_identifier_characters$1 = /[^a-zA-Z_$]/g;
class AttributeWrapper extends BaseAttributeWrapper {
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.should_cache = should_cache(this);
}
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$1.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);
let updater;
const init = this.get_init(block, value);
if (is_legacy_input_type) {
block.chunks.hydrate.push(b `@set_input_type(${element.var}, ${init});`);
updater = b `@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 `@select_options(${element.var}, ${value});`;
}
else {
updater = b `@select_option(${element.var}, ${value});`;
}
block.chunks.mount.push(b `
${updater}
`);
}
else if (this.is_src) {
block.chunks.hydrate.push(b `if (!@src_url_equal(${element.var}.src, ${init})) ${method}(${element.var}, "${name}", ${this.last});`);
updater = b `${method}(${element.var}, "${name}", ${should_cache ? this.last : value});`;
}
else if (property_name) {
block.chunks.hydrate.push(b `${element.var}.${property_name} = ${init};`);
updater = block.renderer.options.dev
? b `@prop_dev(${element.var}, "${property_name}", ${should_cache ? this.last : value});`
: b `${element.var}.${property_name} = ${should_cache ? this.last : value};`;
}
else {
block.chunks.hydrate.push(b `${method}(${element.var}, "${name}", ${init});`);
updater = b `${method}(${element.var}, "${name}", ${should_cache ? this.last : value});`;
}
if (is_indirectly_bound_value) {
const update_value = b `${element.var}.value = ${element.var}.__value;`;
block.chunks.hydrate.push(update_value);
updater = b `
${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 `false`);
updater = b `
${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 `
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
};
}
}
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$1, '_')}_value`);
if (this.should_cache)
block.add_variable(this.last);
return this.should_cache ? x `${this.last} = ${value}` : value;
}
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 `${condition} && (!@src_url_equal(${element.var}.src, (${last} = ${value})))`
: x `${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 `${condition} && ${element.var}.${property_name} !== ${should_cache ? last : value}`;
}
}
if (block.has_outros) {
condition = x `!#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;
}
get_value(block) {
if (this.node.is_true) {
if (this.metadata && boolean_attributes.has(this.metadata.property_name.toLowerCase())) {
return x `true`;
}
return x `""`;
}
if (this.node.chunks.length === 0)
return x `""`;
// 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(this.node.chunks[0].data)
: 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 `${lhs} + ${rhs}`);
// '{foo} {bar}' — treat as string concatenation
if (this.node.chunks[0].type !== 'Text') {
value = x `"" + ${value}`;
}
return value;
}
get_class_name_text(block) {
const scoped_css = this.node.chunks.some((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 `@null_to_empty(${rendered[0]})`;
}
return rendered.reduce((lhs, rhs) => x `${lhs} + ${rhs}`);
}
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('')}"`;
}
}
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'] },
itemscope: {},
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;
});
function should_cache(attribute) {
return attribute.is_src || attribute.node.should_cache();
}
const regex_contains_checked_or_group = /checked|group/;
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))));
}
class StyleAttributeWrapper extends AttributeWrapper {
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$1(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 `${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 `!#current || ${condition}`;
}
const update = b `
if (${condition}) {
@set_style(${this.parent.var}, "${prop.key}", ${value}, ${prop.important ? 1 : null});
}`;
block.chunks.update.push(update);
}
}
else {
value = string_literal(prop.value[0].data);
}
block.chunks.hydrate.push(b `@set_style(${this.parent.var}, "${prop.key}", ${value}, ${prop.important ? 1 : null});`);
});
}
}
const regex_style_prop_key = /^\s*([\w-]+):\s*/;
function optimize_style(value) {
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] = {
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]/;
function get_style_value(chunks) {
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: '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({
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
};
}
function is_dynamic$1(value) {
return value.length > 1 || value[0].type !== 'Text';
}
class SpreadAttributeWrapper extends BaseAttributeWrapper {
}
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) {
each_block.has_binding = true;
}
});
if (binding.name === 'group') {
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 {
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();
}
render(block, lock) {
if (this.is_readonly)
return;
const { parent } = this;
const update_conditions = this.needs_lock ? [x `!${lock}`] : [];
const mount_conditions = [];
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 `${parent.var}.${this.node.name} !== ${this.snippet}`);
}
else if (type === 'number') {
update_conditions.push(x `@to_number(${parent.var}.${this.node.name}) !== ${this.snippet}`);
}
}
// model to view
let update_dom = get_dom_updater(parent, this);
let mount_dom = update_dom;
// special cases
switch (this.node.name) {
case 'group':
{
block.renderer.add_to_context('$$binding_groups');
this.binding_group.elements.push(this.parent.var);
if (this.parent.has_dynamic_value) {
update_or_condition = this.parent.dynamic_value_condition;
}
break;
}
case 'textContent':
update_conditions.push(x `${this.snippet} !== ${parent.var}.textContent`);
mount_conditions.push(x `${this.snippet} !== void 0`);
break;
case 'innerHTML':
update_conditions.push(x `${this.snippet} !== ${parent.var}.innerHTML`);
mount_conditions.push(x `${this.snippet} !== void 0`);
break;
case 'currentTime':
update_conditions.push(x `!@_isNaN(${this.snippet})`);
mount_dom = null;
break;
case 'playbackRate':
case 'volume':
update_conditions.push(x `!@_isNaN(${this.snippet})`);
mount_conditions.push(x `!@_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 `true`);
update_conditions.push(x `${last} !== (${last} = ${this.snippet})`);
update_dom = b `${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 `${lhs} && ${rhs}`);
if (update_or_condition)
condition = x `${update_or_condition} || (${condition})`;
block.chunks.update.push(b `
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 `${lhs} && ${rhs}`);
block.chunks.mount.push(b `
if (${condition}) {
${mount_dom}
}
`);
}
else {
block.chunks.mount.push(mount_dom);
}
}
}
}
function get_dom_updater(element, binding) {
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 `@select_options(${element.var}, ${binding.snippet})` :
b `@select_option(${element.var}, ${binding.snippet})`;
}
if (binding.node.name === 'group') {
const type = node.get_static_attribute_value('type');
const condition = type === 'checkbox'
? x `~(${binding.snippet} || []).indexOf(${element.var}.__value)`
: x `${element.var}.__value === ${binding.snippet}`;
return b `${element.var}.checked = ${condition};`;
}
if (binding.node.name === 'value') {
return b `@set_input_value(${element.var}, ${binding.snippet});`;
}
return b `${element.var}.${binding.node.name} = ${binding.snippet};`;
}
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;
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;
}
const elements = [];
contexts.forEach(context => {
renderer.add_to_context(context, true);
});
renderer.binding_groups.set(keypath, {
binding_group: () => {
let obj = x `$$binding_groups[${index}]`;
if (contexts.length > 0) {
contexts.forEach(secondary_index => {
obj = x `${obj}[${secondary_index}]`;
});
}
return obj;
},
contexts,
list_dependencies,
keypath,
elements,
render() {
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 `${local_name} = @init_binding_group_dynamic(${binding_group}[${index}], ${indexes})`);
block.chunks.update.push(b `if (${block.renderer.dirty(Array.from(list_dependencies))}) ${local_name}.u(${indexes})`);
}
else {
block.chunks.init.push(b `${local_name} = @init_binding_group(${binding_group}[${index}])`);
}
block.chunks.hydrate.push(b `${local_name}.p(${elements})`);
block.chunks.destroy.push(b `${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;
}
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);
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 `${store}.set(${`$${store}`});`;
}
}
else {
const object = get_object(lhs);
if (object.name[0] === '$') {
const store = object.name.slice(1);
set_store = b `${store}.set(${object.name});`;
}
}
const value = get_value_from_dom(renderer, binding.parent, binding, contextual_dependencies);
const mutation = b `
${lhs} = ${value};
${set_store}
`;
return {
uses_context: binding.node.is_contextual || binding.node.expression.uses_context,
mutation,
contextual_dependencies,
lhs
};
}
function get_value_from_dom(_renderer, element, binding, contextual_dependencies) {
const { node } = element;
const { name } = binding.node;
if (name === 'this') {
return x `$$value`;
}
// <select bind:value='selected>
if (node.name === 'select') {
return node.get_static_attribute_value('multiple') === true ?
x `@select_multiple_value(this)` :
x `@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 `@get_binding_group_value(${binding_group()}, this.__value, this.checked)`;
}
return x `this.__value`;
}
// <input type='range|number' bind:value>
if (type === 'range' || type === 'number') {
return x `@to_number(this.${name})`;
}
if ((name === 'buffered' || name === 'seekable' || name === 'played')) {
return x `@time_ranges_to_array(this.${name})`;
}
// everything else
return x `this.${name}`;
}
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 === b.name;
case 'MemberExpression':
return (compare_node(a.object, b.object) &&
compare_node(a.property, b.property) &&
a.computed === b.computed);
case 'Literal':
return a.value === b.value;
}
}
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 `
${mutation}
${Array.from(dependencies)
.filter(dep => dep[0] !== '$')
.filter(dep => !contextual_dependencies.has(dep))
.map(dep => b `${block.renderer.invalidate(dep)};`)}
`;
if (contextual_dependencies.size) {
const params = Array.from(contextual_dependencies).map(name => ({
type: 'Identifier',
name
}));
component.partly_hoisted.push(b `
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 `
const ${assign} = () => ${callee}(${variable}, ${args});
const ${unassign} = () => ${callee}(null, ${args});
`);
const condition = Array.from(args)
.map(name => x `${name} !== ${block.renderer.reference(alias_map.get(name.name) || name.name)}`)
.reduce((lhs, rhs) => x `${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 `
if (${condition}) {
${unassign}();
${args.map(a => b `${a} = ${block.renderer.reference(alias_map.get(a.name) || a.name)}`)};
${assign}();
}`);
block.chunks.destroy.push(b `${unassign}();`);
return b `${assign}();`;
}
component.partly_hoisted.push(b `
function ${fn}($$value) {
@binding_callbacks[$$value ? 'unshift' : 'push'](() => {
${body}
});
}
`);
block.chunks.destroy.push(b `${callee}(null);`);
return b `${callee}(${variable});`;
}
class Tag$1 extends Wrapper {
constructor(renderer, block, parent, node) {
super(renderer, block, parent, node);
this.cannot_use_innerhtml();
if (!this.is_dependencies_static()) {
this.not_static_content();
}
block.add_dependencies(node.expression.dependencies);
}
is_dependencies_static() {
return this.node.expression.contextual_dependencies.size === 0 && this.node.expression.dynamic_dependencies().length === 0;
}
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 `${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 `!#current || ${condition}`;
}
const update_cached_value = x `${value} !== (${value} = ${snippet})`;
if (this.node.should_cache) {
condition = x `${condition} && ${update_cached_value}`;
}
block.chunks.update.push(b `if (${condition}) ${update(content)}`);
}
return { init: content };
}
}
class MustacheTagWrapper extends Tag$1 {
constructor(renderer, block, parent, node) {
super(renderer, block, parent, node);
this.var = { type: 'Identifier', name: 't' };
}
render(block, parent_node, parent_nodes) {
const { init } = this.rename_this_method(block, value => x `@set_data(${this.var}, ${value})`);
block.add_element(this.var, x `@text(${init})`, parent_nodes && x `@claim_text(${parent_nodes}, ${init})`, parent_node);
}
}
class RawMustacheTagWrapper extends Tag$1 {
constructor(renderer, block, parent, node) {
super(renderer, block, parent, node);
this.var = { type: 'Identifier', name: 'raw' };
this.cannot_use_innerhtml();
this.not_static_content();
}
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) {
const insert = (content) => b `${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 `${html_tag}.p(${content})`);
const update_anchor = needs_anchor ? html_anchor : this.next ? this.next.var : 'null';
const parent_element = this.node.find_nearest(/^Element/);
const is_svg = parent_element && parent_element.namespace === namespaces.svg;
block.chunks.create.push(b `${html_tag} = new @HtmlTag(${is_svg ? 'true' : 'false'});`);
if (this.renderer.options.hydratable) {
block.chunks.claim.push(b `${html_tag} = @claim_html_tag(${_parent_nodes}, ${is_svg ? 'true' : 'false'});`);
}
block.chunks.hydrate.push(b `${html_tag}.a = ${update_anchor};`);
block.chunks.mount.push(b `${html_tag}.m(${init}, ${parent_node || '#target'}, ${parent_node ? null : '#anchor'});`);
if (needs_anchor) {
block.add_element(html_anchor, x `@empty()`, x `@empty()`, parent_node);
}
if (!parent_node || in_head) {
block.chunks.destroy.push(b `if (detaching) ${html_tag}.d();`);
}
}
}
}
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(node.get_static_attribute_value('type'))
},
{
event_names: ['input'],
filter: (node, name) => (name === 'textContent' || name === 'innerHTML') &&
node.attributes.some(attribute => attribute.name === 'contenteditable')
},
{
event_names: ['change'],
filter: (node, _name) => node.name === 'select' ||
node.name === 'input' &&
regex_contains_radio_or_checkbox_or_file.test(node.get_static_attribute_value('type'))
},
{
event_names: ['change', 'input'],
filter: (node, _name) => node.name === 'input' && node.get_static_attribute_value('type') === 'range'
},
{
event_names: ['elementresize'],
filter: (_node, name) => regex_dimensions.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$2 = /[^a-zA-Z0-9_$]/g;
const regex_minus_signs = /-/g;
class ElementWrapper extends Wrapper {
constructor(renderer, block, parent, node, strip_whitespace, next_sibling) {
super(renderer, block, parent, node);
this.child_dynamic_element_block = null;
this.child_dynamic_element = null;
this.var = {
type: 'Identifier',
name: node.name.replace(regex_invalid_variable_identifier_characters$2, '_')
};
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);
// 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;
}
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 || node.outro) {
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);
}
});
if (this.parent) {
if (node.actions.length > 0 ||
node.animation ||
node.bindings.length > 0 ||
node.classes.length > 0 ||
node.intro || node.outro ||
node.handlers.length > 0 ||
node.styles.length > 0 ||
this.node.name === 'option' ||
node.tag_expr.dynamic_dependencies().length ||
node.is_dynamic_element ||
renderer.options.dev) {
this.parent.cannot_use_innerhtml(); // need to use add_location
this.parent.not_static_content();
}
}
this.fragment = new FragmentWrapper(renderer, block, node.children, this, strip_whitespace, next_sibling);
}
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);
}
}
render_dynamic_element(block, parent_node, parent_nodes) {
this.child_dynamic_element.render(this.child_dynamic_element_block, null, x `#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 `
${this.renderer.options.dev && b `@validate_dynamic_element(${tag});`}
${this.renderer.options.dev && this.node.children.length > 0 && b `@validate_void_dynamic_element(${tag});`}
let ${this.var} = ${tag} && ${this.child_dynamic_element_block.name}(#ctx);
`);
block.chunks.create.push(b `
if (${this.var}) ${this.var}.c();
`);
if (this.renderer.options.hydratable) {
block.chunks.claim.push(b `
if (${this.var}) ${this.var}.l(${parent_nodes});
`);
}
block.chunks.mount.push(b `
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 `@not_equal` : x `@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 `false`);
}
block.chunks.update.push(b `
if (${tag}) {
if (!${previous_tag}) {
${this.var} = ${this.child_dynamic_element_block.name}(#ctx);
${previous_tag} = ${tag};
${this.var}.c();
${has_transitions && b `@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 `@validate_dynamic_element(${tag});`}
${this.renderer.options.dev && this.node.children.length > 0 && b `@validate_void_dynamic_element(${tag});`}
${this.var} = ${this.child_dynamic_element_block.name}(#ctx);
${previous_tag} = ${tag};
${this.var}.c();
${has_transitions && b `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 `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 `
${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 `
${this.var}.d(1);
${this.var} = null;
${previous_tag} = ${tag};
`}
}
`);
}
else {
block.chunks.update.push(b `
if (${tag}) {
${this.var}.p(#ctx, #dirty);
}
`);
}
if (this.child_dynamic_element_block.has_intros) {
block.chunks.intro.push(b `@transition_in(${this.var});`);
}
if (this.child_dynamic_element_block.has_outros) {
block.chunks.outro.push(b `@transition_out(${this.var});`);
}
block.chunks.destroy.push(b `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 `${measurements} = ${this.var}.r()`);
block.chunks.fix.push(b `${this.var}.f();`);
block.chunks.animate.push(b `
${this.var}.s(${measurements});
${this.var}.a()
`);
}
}
is_dom_node() {
return super.is_dom_node() && !this.child_dynamic_element;
}
render_element(block, parent_node, parent_nodes) {
const { renderer } = this;
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 `@children(${this.node.name === 'template' ? x `${node}.content` : node})`;
block.add_variable(node);
const render_statement = this.get_render_statement(block);
block.chunks.create.push(b `${node} = ${render_statement};`);
if (renderer.options.hydratable) {
if (parent_nodes) {
block.chunks.claim.push(b `
${node} = ${this.get_claim_statement(block, parent_nodes)};
`);
if (!this.void && this.node.children.length > 0) {
block.chunks.claim.push(b `
var ${nodes} = ${children};
`);
}
}
else {
block.chunks.claim.push(b `${node} = ${render_statement};`);
}
}
if (parent_node) {
const append = b `@append(${parent_node}, ${node});`;
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 `@detach(${node});`);
}
}
else {
const insert = b `@insert(#target, ${node}, #anchor);`;
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 `if (detaching) @detach(${node});`);
}
// insert static children with textContent or innerHTML
// skip textcontent for <template>. append nodes to TemplateElement.content instead
const can_use_textcontent = this.can_use_textcontent();
const is_template = this.node.name === 'template';
const is_template_with_text_content = is_template && can_use_textcontent;
if (!is_template_with_text_content && !this.node.namespace && (this.can_use_innerhtml || can_use_textcontent) && this.fragment.nodes.length > 0) {
if (this.fragment.nodes.length === 1 && this.fragment.nodes[0].node.type === 'Text') {
block.chunks.create.push(b `${node}.textContent = ${string_literal(this.fragment.nodes[0].data)};`);
}
else {
const state = {
quasi: {
type: 'TemplateElement',
value: { raw: '' }
}
};
const literal = {
type: 'TemplateLiteral',
expressions: [],
quasis: []
};
const can_use_raw_text = !this.can_use_innerhtml && can_use_textcontent;
to_html(this.fragment.nodes, block, literal, state, can_use_raw_text);
literal.quasis.push(state.quasi);
block.chunks.create.push(b `${node}.${this.can_use_innerhtml ? 'innerHTML' : 'textContent'} = ${literal};`);
}
}
else {
this.fragment.nodes.forEach((child) => {
child.render(block, is_template ? x `${node}.content` : node, nodes);
});
}
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 && this.renderer.options.hydratable && !this.void) {
block.chunks.claim.push(b `${this.node.children.length > 0 ? nodes : children}.forEach(@detach);`);
}
if (renderer.options.dev) {
const loc = renderer.locate(this.node.start);
block.chunks.hydrate.push(b `@add_location(${this.var}, ${renderer.file_var}, ${loc.line - 1}, ${loc.column}, ${this.node.start});`);
}
block.renderer.dirty(this.node.tag_expr.dynamic_dependencies());
}
can_use_textcontent() {
return this.is_static_content && this.fragment.nodes.every(node => node.node.type === 'Text' || node.node.type === 'MustacheTag');
}
get_render_statement(block) {
const { name, namespace, tag_expr } = this.node;
const reference = tag_expr.manipulate(block);
if (namespace === namespaces.svg) {
return x `@svg_element(${reference})`;
}
if (namespace) {
return x `@_document.createElementNS("${namespace}", "${name}")`;
}
const is = this.attributes.find(attr => attr.node.name === 'is');
if (is) {
return x `@element_is("${name}", ${is.render_chunks(block).reduce((lhs, rhs) => x `${lhs} + ${rhs}`)})`;
}
return x `@element(${reference})`;
}
get_claim_statement(block, nodes) {
const attributes = this.attributes
.filter((attr) => !(attr instanceof SpreadAttributeWrapper) && !attr.property_name)
.map((attr) => p `${attr.name}: true`);
let reference;
if (this.node.tag_expr.node.type === 'Literal') {
if (this.node.namespace) {
reference = `"${this.node.tag_expr.node.value}"`;
}
else {
reference = `"${(this.node.tag_expr.node.value || '').toUpperCase()}"`;
}
}
else if (this.node.namespace) {
reference = x `${this.node.tag_expr.manipulate(block)}`;
}
else {
reference = x `(${this.node.tag_expr.manipulate(block)} || 'null').toUpperCase()`;
}
if (this.node.namespace === namespaces.svg) {
return x `@claim_svg_element(${nodes}, ${reference}, { ${attributes} })`;
}
else {
return x `@claim_element(${nodes}, ${reference}, { ${attributes} })`;
}
}
add_directives_in_order(block) {
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');
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;
}
}
[
...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);
}
});
}
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 `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);
const dependencies = new Set();
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
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 `
function ${handler}() {
@_cancelAnimationFrame(${animation_frame});
if (!${this.var}.paused) {
${animation_frame} = @raf(${handler});
${needs_lock && b `${lock} = true;`}
}
${callee}.call(${this.var}, ${args});
}
`);
}
else {
block.chunks.init.push(b `
function ${handler}() {
${needs_lock && b `${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 `
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 `${this.renderer.invalidate(dep)};`)}
}
`);
binding_group.events.forEach(name => {
if (name === 'elementresize') {
// special case
const resize_listener = block.get_unique_name(`${this.var.name}_resize_listener`);
block.add_variable(resize_listener);
block.chunks.mount.push(b `${resize_listener} = @add_resize_listener(${this.var}, ${callee}.bind(${this.var}));`);
block.chunks.destroy.push(b `${resize_listener}();`);
}
else {
block.event_listeners.push(x `@listen(${this.var}, "${name}", ${callee})`);
}
});
const some_initial_state_is_undefined = binding_group.bindings
.map(binding => x `${binding.snippet} === void 0`)
.reduce((lhs, rhs) => x `${lhs} || ${rhs}`);
const should_initialise = (this.node.name === 'select' ||
binding_group.bindings.find(binding => {
return (binding.node.name === 'indeterminate' ||
binding.node.name === 'textContent' ||
binding.node.name === 'innerHTML' ||
binding.is_readonly_media_attribute());
}));
if (should_initialise) {
const callback = has_local_function ? handler : x `() => ${callee}.call(${this.var})`;
block.chunks.hydrate.push(b `if (${some_initial_state_is_undefined}) @add_render_callback(${callback});`);
}
if (binding_group.events[0] === 'elementresize') {
block.chunks.hydrate.push(b `@add_render_callback(() => ${callee}.call(${this.var}));`);
}
if (lock) {
block.chunks.update.push(b `${lock} = false;`);
}
}
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);
}
add_attributes(block) {
// Get all the class dependencies first
this.attributes.forEach((attribute) => {
if (attribute.node.name === 'class') {
const dependencies = attribute.node.get_dependencies();
push_array$1(this.class_dependencies, dependencies);
}
});
if (this.node.attributes.some(attr => attr.is_spread)) {
this.add_spread_attributes(block);
return;
}
this.attributes.forEach((attribute) => {
attribute.render(block);
});
}
add_spread_attributes(block) {
const levels = block.get_unique_name(`${this.var.name}_levels`);
const data = block.get_unique_name(`${this.var.name}_data`);
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 `${condition} && ${snippet}` : snippet);
}
else {
const name = attr.property_name || attr.name;
initial_props.push(x `{ ${name}: ${attr.get_init(block, attr.get_value(block))} }`);
const snippet = x `{ ${name}: ${attr.should_cache ? attr.last : attr.get_value(block)} }`;
updates.push(condition ? x `${attr.get_dom_update_conditions(block, condition)} && ${snippet}` : snippet);
}
});
block.chunks.init.push(b `
let ${levels} = [${initial_props}];
let ${data} = {};
for (let #i = 0; #i < ${levels}.length; #i += 1) {
${data} = @assign(${data}, ${levels}[#i]);
}
`);
const fn = this.node.namespace === namespaces.svg
? x `@set_svg_attributes`
: this.node.is_dynamic_element
? x `@set_dynamic_element_data(${this.node.tag_expr.manipulate(block)})`
: x `@set_attributes`;
block.chunks.hydrate.push(b `${fn}(${this.var}, ${data});`);
if (this.has_dynamic_attribute) {
block.chunks.update.push(b `
${fn}(${this.var}, ${data} = @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 `
'value' in ${data} && (${data}.multiple ? @select_options : @select_option)(${this.var}, ${data}.value);
`);
block.chunks.update.push(b `
if (${block.renderer.dirty(Array.from(dependencies))} && 'value' in ${data}) (${data}.multiple ? @select_options : @select_option)(${this.var}, ${data}.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 `
if ('value' in ${data}) {
${this.var}.value = ${data}.value;
}
`);
block.chunks.update.push(b `
if ('value' in ${data}) {
${this.var}.value = ${data}.value;
}
`);
}
}
if (['button', 'input', 'keygen', 'select', 'textarea'].includes(this.node.name)) {
block.chunks.mount.push(b `
if (${this.var}.autofocus) ${this.var}.focus();
`);
}
}
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 `@set_svg_attributes`
: this.node.is_dynamic_element
? x `@set_dynamic_element_data(${this.node.tag_expr.manipulate(block)})`
: x `@set_attributes`;
block.chunks.hydrate.push(b `${fn}(${this.var}, {${static_attributes}});`);
}
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 `{}`;
block.add_variable(name);
const fn = this.renderer.reference(intro.name);
const intro_block = b `
@add_render_callback(() => {
if (!${name}) ${name} = @create_bidirectional_transition(${this.var}, ${fn}, ${snippet}, true);
${name}.run(1);
});
`;
const outro_block = b `
if (!${name}) ${name} = @create_bidirectional_transition(${this.var}, ${fn}, ${snippet}, false);
${name}.run(0);
`;
if (intro.is_local) {
block.chunks.intro.push(b `
if (#local) {
${intro_block}
}
`);
block.chunks.outro.push(b `
if (#local) {
${outro_block}
}
`);
}
else {
block.chunks.intro.push(intro_block);
block.chunks.outro.push(outro_block);
}
block.chunks.destroy.push(b `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 `{}`;
const fn = this.renderer.reference(intro.name);
let intro_block;
if (outro) {
intro_block = b `
@add_render_callback(() => {
if (${outro_name}) ${outro_name}.end(1);
${intro_name} = @create_in_transition(${this.var}, ${fn}, ${snippet});
${intro_name}.start();
});
`;
block.chunks.outro.push(b `if (${intro_name}) ${intro_name}.invalidate();`);
}
else {
intro_block = b `
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 `
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 `{}`;
const fn = this.renderer.reference(outro.name);
if (!intro) {
block.chunks.intro.push(b `
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 `
${outro_name} = @create_out_transition(${this.var}, ${fn}, ${snippet});
`;
if (outro.is_local) {
outro_block = b `
if (#local) {
${outro_block}
}
`;
}
block.chunks.outro.push(outro_block);
block.chunks.destroy.push(b `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;
}
}
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 `@noop`);
block.chunks.measure.push(b `
${rect} = ${this.var}.getBoundingClientRect();
`);
if (block.type === CHILD_DYNAMIC_ELEMENT_BLOCK) {
block.chunks.measure.push(b `return ${rect}`);
block.chunks.restore_measurements.push(b `${rect} = #measurement;`);
}
block.chunks.fix.push(b `
@fix_position(${this.var});
${stop_animation}();
${outro && b `@add_transform(${this.var}, ${rect});`}
`);
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 `${params_var} = ${params};`);
params = params_var;
}
}
else {
params = x `{}`;
}
const name = this.renderer.reference(this.node.animation.name);
block.chunks.animate.push(b `
${stop_animation}();
${stop_animation} = @create_animation(${this.var}, ${rect}, ${name}, ${params});
`);
}
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 `@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 `!#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(variable);
});
if (any_dynamic_dependencies) {
block.chunks.update.push(b `
if (${condition}) {
${updater}
}
`);
}
}
});
}
add_styles(block) {
const has_spread = this.node.attributes.some(attr => attr.is_spread);
this.node.styles.forEach((style_directive) => {
const { name, expression, should_cache, important } = 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 `@set_style(${this.var}, "${name}", ${should_cache ? cached_snippet : snippet}, ${important ? 1 : null})`;
block.chunks.hydrate.push(updater);
const dependencies = expression.dynamic_dependencies();
if (has_spread) {
block.chunks.update.push(updater);
}
else if (dependencies.length > 0) {
if (should_cache) {
block.chunks.update.push(b `
if (${block.renderer.dirty(dependencies)} && (${cached_snippet} !== (${cached_snippet} = ${snippet}))) {
${updater}
}
`);
}
else {
block.chunks.update.push(b `
if (${block.renderer.dirty(dependencies)}) {
${updater}
}
`);
}
}
});
}
add_manual_style_scoping(block) {
if (this.node.needs_manual_style_scoping) {
const updater = b `@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;
function to_html(wrappers, block, literal, state, can_use_raw_text) {
wrappers.forEach(wrapper => {
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())
state.quasi.value.raw += ' ';
const parent = 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;
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(wrapper.fragment.nodes, block, literal, state);
state.quasi.value.raw += `</${nodeName}>`;
}
else {
state.quasi.value.raw += '/>';
}
}
});
}
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: '' }
};
}
});
}
class HeadWrapper extends Wrapper {
constructor(renderer, block, parent, node, strip_whitespace, next_sibling) {
super(renderer, block, parent, node);
this.can_use_innerhtml = false;
this.fragment = new FragmentWrapper(renderer, block, node.children, this, strip_whitespace, next_sibling);
}
render(block, _parent_node, _parent_nodes) {
let nodes;
if (this.renderer.options.hydratable && this.fragment.nodes.length) {
nodes = block.get_unique_name('head_nodes');
block.chunks.claim.push(b `const ${nodes} = @head_selector('${this.node.id}', @_document.head);`);
}
this.fragment.render(block, x `@_document.head`, nodes);
if (nodes && this.renderer.options.hydratable) {
block.chunks.claim.push(b `${nodes}.forEach(@detach);`);
}
}
}
function is_else_if(node) {
return (node && node.children.length === 1 && node.children[0].type === 'IfBlock');
}
class IfBlockBranch extends Wrapper {
constructor(renderer, block, parent, node, strip_whitespace, next_sibling) {
super(renderer, block, parent, node);
this.var = null;
const { expression } = 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 = 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: 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');
}
}
}
class IfBlockWrapper extends Wrapper {
constructor(renderer, block, parent, node, strip_whitespace, next_sibling) {
super(renderer, block, parent, node);
this.needs_update = false;
this.var = { type: 'Identifier', name: 'if_block' };
this.cannot_use_innerhtml();
this.not_static_content();
this.branches = [];
const blocks = [];
let is_dynamic = false;
let has_intros = false;
let has_outros = false;
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(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$1(renderer.blocks, blocks);
}
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 `
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 };
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 `@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 `@transition_out(${name});`);
}
}
if (if_exists_condition) {
block.chunks.create.push(b `if (${if_exists_condition}) ${name}.c();`);
}
else {
block.chunks.create.push(b `${name}.c();`);
}
if (parent_nodes && this.renderer.options.hydratable) {
if (if_exists_condition) {
block.chunks.claim.push(b `if (${if_exists_condition}) ${name}.l(${parent_nodes});`);
}
else {
block.chunks.claim.push(b `${name}.l(${parent_nodes});`);
}
}
if (has_intros || has_outros) {
block.chunks.intro.push(b `@transition_in(${name});`);
}
if (needs_anchor) {
block.add_element(anchor, x `@empty()`, parent_nodes && x `@empty()`, parent_node);
}
this.branches.forEach(branch => {
branch.fragment.render(branch.block, null, x `#nodes`);
});
}
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 `${select_block_ctx}(#ctx, ${current_block_type})` : x `#ctx`;
const get_block = has_else
? x `${current_block_type}(${if_ctx})`
: x `${current_block_type} && ${current_block_type}(${if_ctx})`;
if (this.needs_update) {
block.chunks.init.push(b `
function ${select_block_type}(#ctx, #dirty) {
${this.branches.map(({ dependencies, condition, snippet }) => {
return b `${snippet && dependencies.length > 0 ? b `if (${block.renderer.dirty(dependencies)}) ${condition} = null;` : null}`;
})}
${this.branches.map(({ condition, snippet, block }) => condition
? b `
${snippet && b `if (${condition} == null) ${condition} = !!${snippet}`}
if (${condition}) return ${block.name};`
: b `return ${block.name};`)}
}
`);
}
else {
block.chunks.init.push(b `
function ${select_block_type}(#ctx, #dirty) {
${this.branches.map(({ condition, snippet, block }) => condition
? b `if (${snippet || condition}) return ${block.name};`
: b `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 `
function ${select_block_ctx}(#ctx, #type) {
${this.branches.map(({ condition, get_ctx_name, block }) => {
return condition
? b `if (#type === ${block.name}) return ${get_ctx_name}(#ctx);`
: b `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 `
function ${select_block_ctx}(#ctx, #type) {
${this.branches.map(({ get_ctx_name, block }) => {
return get_ctx_name
? b `if (#type === ${block.name}) return ${get_ctx_name}(#ctx);`
: null;
}).filter(Boolean)}
return #ctx;
}
`);
}
}
block.chunks.init.push(b `
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 `if (${if_exists_condition}) ${name}.m(${initial_mount_node}, ${anchor_node});`);
}
else {
block.chunks.mount.push(b `${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 `
${if_exists_condition ? b `if (${if_exists_condition}) ${name}.d(1)` : b `${name}.d(1)`};
${name} = ${get_block};
if (${name}) {
${name}.c();
${has_transitions && b `@transition_in(${name}, 1);`}
${name}.m(${update_mount_node}, ${anchor});
}
`;
if (dynamic) {
block.chunks.update.push(b `
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 `
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 `if (${if_exists_condition}) ${name}.p(${if_ctx}, #dirty);`);
}
else {
block.chunks.update.push(b `${name}.p(${if_ctx}, #dirty);`);
}
}
if (if_exists_condition) {
block.chunks.destroy.push(b `
if (${if_exists_condition}) {
${name}.d(${detaching});
}
`);
}
else {
block.chunks.destroy.push(b `
${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?)
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 `${select_block_ctx}(#ctx, ${current_block_type_index})` : x `#ctx`;
const if_current_block_type_index = has_else
? (nodes) => nodes
: (nodes) => b `if (~${current_block_type_index}) { ${nodes} }`;
block.add_variable(current_block_type_index);
block.add_variable(name);
block.chunks.init.push(b `
const ${if_block_creators} = [
${this.branches.map(branch => branch.block.name)}
];
const ${if_blocks} = [];
${this.needs_update
? b `
function ${select_block_type}(#ctx, #dirty) {
${this.branches.map(({ dependencies, condition, snippet }) => {
return b `${snippet && dependencies.length > 0 ? b `if (${block.renderer.dirty(dependencies)}) ${condition} = null;` : null}`;
})}
${this.branches.map(({ condition, snippet }, i) => condition
? b `
${snippet && b `if (${condition} == null) ${condition} = !!${snippet}`}
if (${condition}) return ${i};`
: b `return ${i};`)}
${!has_else && b `return -1;`}
}
`
: b `
function ${select_block_type}(#ctx, #dirty) {
${this.branches.map(({ condition, snippet }, i) => condition
? b `if (${snippet || condition}) return ${i};`
: b `return ${i};`)}
${!has_else && b `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 `
function ${select_block_ctx}(#ctx, #index) {
${this.branches.map(({ condition, get_ctx_name }, i) => {
return condition
? b `if (#index === ${i}) return ${get_ctx_name}(#ctx);`
: b `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 `
function ${select_block_ctx}(#ctx, #index) {
${this.branches.map(({ get_ctx_name }, i) => {
return get_ctx_name
? b `if (#index === ${i}) return ${get_ctx_name}(#ctx);`
: null;
}).filter(Boolean)}
return #ctx;
}
`);
}
}
if (has_else) {
block.chunks.init.push(b `
${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 `
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 `${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 `
@group_outros();
@transition_out(${if_blocks}[${previous_block_index}], 1, 1, () => {
${if_blocks}[${previous_block_index}] = null;
});
@check_outros();
`;
const create_new_block = b `
${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 `${name}.p(${if_ctx}, #dirty);`}
}
${has_transitions && b `@transition_in(${name}, 1);`}
${name}.m(${update_mount_node}, ${anchor});
`;
const change_block = has_else
? b `
${destroy_old_block}
${create_new_block}
`
: b `
if (${name}) {
${destroy_old_block}
}
if (~${current_block_type_index}) {
${create_new_block}
} else {
${name} = null;
}
`;
block.chunks.update.push(b `
let ${previous_block_index} = ${current_block_type_index};
${current_block_type_index} = ${select_block_type}(#ctx, #dirty);
`);
if (dynamic) {
block.chunks.update.push(b `
if (${current_block_type_index} === ${previous_block_index}) {
${if_current_block_type_index(b `${if_blocks}[${current_block_type_index}].p(${if_ctx}, #dirty);`)}
} else {
${change_block}
}
`);
}
else {
block.chunks.update.push(b `
if (${current_block_type_index} !== ${previous_block_index}) {
${change_block}
}
`);
}
}
else if (dynamic) {
if (if_exists_condition) {
block.chunks.update.push(b `if (${if_exists_condition}) ${name}.p(${if_ctx}, #dirty);`);
}
else {
block.chunks.update.push(b `${name}.p(${if_ctx}, #dirty);`);
}
}
block.chunks.destroy.push(if_current_block_type_index(b `${if_blocks}[${current_block_type_index}].d(${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 `${branch.get_ctx_name}(#ctx)` : x `#ctx`;
if (branch.snippet)
block.add_variable(branch.condition, branch.snippet);
block.chunks.init.push(b `
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 `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 `
if (${name}) {
${dynamic && b `${name}.p(${if_ctx}, #dirty);`}
${has_transitions &&
b `if (${block.renderer.dirty(branch.dependencies)}) {
@transition_in(${name}, 1);
}`}
} else {
${name} = ${branch.block.name}(${if_ctx});
${name}.c();
${has_transitions && b `@transition_in(${name}, 1);`}
${name}.m(${update_mount_node}, ${anchor});
}
`;
if (branch.snippet) {
block.chunks.update.push(b `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 `
if (${branch.condition}) {
${enter}
} else if (${name}) {
@group_outros();
@transition_out(${name}, 1, 1, () => {
${name} = null;
});
@check_outros();
}
`);
}
else {
block.chunks.update.push(b `
if (${branch.condition}) {
${enter}
} else if (${name}) {
${name}.d(1);
${name} = null;
}
`);
}
}
else if (dynamic) {
block.chunks.update.push(b `
if (${branch.condition}) ${name}.p(${if_ctx}, #dirty);
`);
}
if (if_exists_condition) {
block.chunks.destroy.push(b `
if (${if_exists_condition}) ${name}.d(${detaching});
`);
}
else {
block.chunks.destroy.push(b `
${name}.d(${detaching});
`);
}
}
}
class KeyBlockWrapper extends Wrapper {
constructor(renderer, block, parent, node, strip_whitespace, next_sibling) {
super(renderer, block, parent, node);
this.var = { type: 'Identifier', name: 'key_block' };
this.cannot_use_innerhtml();
this.not_static_content();
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);
}
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);
}
}
render_static_key(_block, parent_node, parent_nodes) {
this.fragment.render(this.block, parent_node, parent_nodes);
}
render_dynamic_key(block, parent_node, parent_nodes) {
this.fragment.render(this.block, null, x `#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 `@not_equal` : x `@safe_not_equal`;
const condition = x `${this.renderer.dirty(this.dependencies)} && ${not_equal}(${previous_key}, ${previous_key} = ${snippet})`;
block.chunks.init.push(b `
let ${this.var} = ${this.block.name}(#ctx);
`);
block.chunks.create.push(b `${this.var}.c();`);
if (this.renderer.options.hydratable) {
block.chunks.claim.push(b `${this.var}.l(${parent_nodes});`);
}
block.chunks.mount.push(b `${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 `
${has_transitions
? b `
@group_outros();
@transition_out(${this.var}, 1, 1, @noop);
@check_outros();
`
: b `${this.var}.d(1);`}
${this.var} = ${this.block.name}(#ctx);
${this.var}.c();
${has_transitions && b `@transition_in(${this.var}, 1)`}
${this.var}.m(${this.get_update_mount_node(anchor)}, ${anchor});
`;
if (dynamic) {
block.chunks.update.push(b `
if (${condition}) {
${body}
} else {
${this.var}.p(#ctx, #dirty);
}
`);
}
else {
block.chunks.update.push(b `
if (${condition}) {
${body}
}
`);
}
if (has_transitions) {
block.chunks.intro.push(b `@transition_in(${this.var})`);
block.chunks.outro.push(b `@transition_out(${this.var})`);
}
block.chunks.destroy.push(b `${this.var}.d(detaching)`);
}
}
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 => {
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
};
const names = new Set();
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 = 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 `${name} ? ${1 << n} : 0`)
.reduce((lhs, rhs) => x `${lhs} | ${rhs}`)
: x `0`;
}
return {
type: 'ArrayExpression',
elements
};
}
return Array.from(names)
.map(name => {
const lookup_name = names_lookup.has(name) ? names_lookup.get(name) : name;
const i = context_lookup.get(name).index.value;
return x `${lookup_name} ? ${1 << i} : 0`;
})
.reduce((lhs, rhs) => x `${lhs} | ${rhs}`);
}
};
return {
block,
scope,
get_context: x `${context_input} => ${context}`,
get_changes: x `${changes_input} => ${changes}`
};
}
class SlotTemplateWrapper extends Wrapper {
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);
const seen = new Set(lets.map(l => l.name.name));
this.parent.node.lets.forEach(l => {
if (!seen.has(l.name.name))
lets.push(l);
});
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, x `#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 `
function ${get_context}(#ctx) {
${add_const_tags(this.block, this.node.const_tags, '#ctx')}
}
`);
this.block.chunks.declarations.push(b `${get_context}(#ctx)`);
if (this.block.has_update_method) {
this.block.chunks.update.unshift(b `${get_context}(#ctx)`);
}
}
}
function string_to_member_expression(name) {
const parts = name.split('.');
let node = {
type: 'Identifier',
name: parts[0]
};
for (let i = 1; i < parts.length; i++) {
node = {
type: 'MemberExpression',
object: node,
property: { type: 'Identifier', name: parts[i] }
};
}
return node;
}
const regex_invalid_variable_identifier_characters$3 = /[^a-zA-Z_$]/g;
class InlineComponentWrapper extends Wrapper {
constructor(renderer, block, parent, node, strip_whitespace, next_sibling) {
super(renderer, block, parent, node);
this.slots = new Map();
this.children = [];
this.cannot_use_innerhtml();
this.not_static_content();
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: '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.node.lets.forEach(l => {
extract_names(l.value || l.name).forEach(name => {
renderer.add_to_context(name, true);
});
});
this.children = this.node.children.map(child => new SlotTemplateWrapper(renderer, block, this, child, strip_whitespace, next_sibling));
}
block.add_outro();
}
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();
}
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 = x `{}`;
const statements = [];
const updates = [];
this.children.forEach((child) => {
this.renderer.add_to_context('$$scope', true);
child.render(block, null, x `#nodes`);
});
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 `{ ${initial_props} }`
: x `{
${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(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 `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 = [];
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;
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 `@get_spread_object(${value})`;
}
change_object = value_object;
}
else {
const obj = x `{ ${name}: ${attr.get_value(block)} }`;
initial_props.push(obj);
change_object = obj;
}
changes.push(unchanged
? x `${levels}[${i}]`
: condition
? x `${condition} && ${change_object}`
: change_object);
});
block.chunks.init.push(b `
const ${levels} = [
${initial_props}
];
`);
statements.push(b `
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 `
const ${name_changes} = ${condition} ? @get_spread_update(${levels}, [
${changes}
]) : {}
`);
}
else {
updates.push(b `
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 `
if (${condition}) ${name_changes}.${attribute.name} = ${attribute.get_value(block)};
`);
}
});
}
}
if (fragment_dependencies.size > 0) {
updates.push(b `
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 `
if (${snippet} !== void 0) {
${props}.${binding.name} = ${snippet};
}`);
updates.push(b `
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);
}
const params = [x `#value`];
const args = [x `#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 `
function ${id}(#value) {
${callee}(${args});
}
`);
let invalidate_binding = b `
${lhs} = #value;
${renderer.invalidate(dependencies[0])};
`;
if (binding.expression.node.type === 'MemberExpression') {
invalidate_binding = b `
if ($$self.$$.not_equal(${lhs}, #value)) {
${invalidate_binding}
}
`;
}
const body = b `
function ${id}(${params}) {
${invalidate_binding}
}
`;
component.partly_hoisted.push(body);
return b `@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 `@once(${snippet})`;
return b `${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 `
var ${switch_value} = ${snippet};
function ${switch_props}(#ctx) {
${(this.node.attributes.length > 0 || this.node.bindings.length > 0) && b `
${props && b `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 `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 `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 `if (${name}) @claim_component(${name}.$$.fragment, ${claim_nodes});`);
}
if (updates.length) {
block.chunks.update.push(b `
${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 `@insert(${tmp_anchor}.parentNode, ${css_custom_properties_wrapper}, ${tmp_anchor});`
: b `@insert(${parent_node}, ${css_custom_properties_wrapper}, ${tmp_anchor});`);
let update_condition = x `${switch_value} !== (${switch_value} = ${snippet})`;
if (dependencies.length > 0) {
update_condition = x `${block.renderer.dirty(dependencies)} && ${update_condition}`;
}
block.chunks.update.push(b `
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 `@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 `${name}.$set(${name_changes});`}
}
`);
block.chunks.intro.push(b `
if (${name}) @transition_in(${name}.$$.fragment, #local);
`);
block.chunks.outro.push(b `if (${name}) @transition_out(${name}.$$.fragment, #local);`);
block.chunks.destroy.push(b `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 `
${(this.node.attributes.length > 0 || this.node.bindings.length > 0) && b `
${props && b `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 `@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 `@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 `@claim_component(${name}.$$.fragment, ${claim_nodes});`);
}
block.chunks.intro.push(b `
@transition_in(${name}.$$.fragment, #local);
`);
if (updates.length) {
block.chunks.update.push(b `
${updates}
${name}.$set(${name_changes});
`);
}
block.chunks.destroy.push(b `
@destroy_component(${name}, ${parent_node ? null : 'detaching'});
`);
block.chunks.outro.push(b `@transition_out(${name}.$$.fragment, #local);`);
}
}
create_css_custom_properties_wrapper_mount_chunk(block, parent_node, css_custom_properties_wrapper) {
if (parent_node) {
block.chunks.mount.push(b `@append(${parent_node}, ${css_custom_properties_wrapper})`);
if (is_head(parent_node)) {
block.chunks.destroy.push(b `@detach(${css_custom_properties_wrapper});`);
}
}
else {
block.chunks.mount.push(b `@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 `if (detaching && ${this.var}) @detach(${css_custom_properties_wrapper});`);
}
}
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 `@claim_svg_element` : x `@claim_element`;
block.chunks.claim.push(b `
${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;
}
set_css_custom_properties(block, css_custom_properties_wrapper, css_custom_properties_wrapper_element, is_svg_namespace) {
const element = is_svg_namespace ? x `@svg_element` : x `@element`;
block.chunks.create.push(b `${css_custom_properties_wrapper} = ${element}("${css_custom_properties_wrapper_element}");`);
if (!is_svg_namespace)
block.chunks.hydrate.push(b `@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$3, '_')}_last`);
if (should_cache)
block.add_variable(last);
const value = attr.get_value(block);
const init = should_cache ? x `${last} = ${value}` : value;
block.chunks.hydrate.push(b `@set_style(${css_custom_properties_wrapper}, "${attr.name}", ${init});`);
if (dependencies.length > 0) {
let condition = block.renderer.dirty(dependencies);
if (should_cache)
condition = x `${condition} && (${last} !== (${last} = ${value}))`;
block.chunks.update.push(b `
if (${condition}) {
@set_style(${css_custom_properties_wrapper}, "${attr.name}", ${should_cache ? last : value});
}
`);
}
});
}
}
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}`;
})
};
}
function get_value(block, attribute) {
if (attribute.is_true)
return x `true`;
if (attribute.chunks.length === 0)
return x `""`;
let value = attribute.chunks
.map(chunk => chunk.type === 'Text' ? string_literal(chunk.data) : (block ? chunk.manipulate(block) : chunk.node))
.reduce((lhs, rhs) => x `${lhs} + ${rhs}`);
if (attribute.chunks.length > 1 && attribute.chunks[0].type !== 'Text') {
value = x `"" + ${value}`;
}
return value;
}
function get_spread_value(block, attribute) {
return block ? attribute.expression.manipulate(block) : attribute.expression.node;
}
class SlotWrapper extends Wrapper {
constructor(renderer, block, parent, node, strip_whitespace, next_sibling) {
super(renderer, block, parent, node);
this.fallback = null;
this.var = { type: 'Identifier', name: 'slot' };
this.dependencies = new Set(['$$scope']);
this.cannot_use_innerhtml();
this.not_static_content();
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();
}
render(block, parent_node, parent_nodes) {
const { renderer } = this;
const { slot_name } = this.node;
if (this.slot_block) {
block = this.slot_block;
}
let get_slot_changes_fn;
let get_slot_spread_changes_fn;
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 = x `{}`;
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 `
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 `
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, x `#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 `
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 `const ${slot_or_fallback} = ${slot} || ${this.fallback.name}(#ctx);` : null}
`);
block.chunks.create.push(b `if (${slot_or_fallback}) ${slot_or_fallback}.c();`);
if (renderer.options.hydratable) {
block.chunks.claim.push(b `if (${slot_or_fallback}) ${slot_or_fallback}.l(${parent_nodes});`);
}
block.chunks.mount.push(b `
if (${slot_or_fallback}) {
${slot_or_fallback}.m(${parent_node || '#target'}, ${parent_node ? 'null' : '#anchor'});
}
`);
block.chunks.intro.push(b `@transition_in(${slot_or_fallback}, #local);`);
block.chunks.outro.push(b `@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 `!#current || ${condition}`;
}
// conditions to treat everything as dirty
const all_dirty_conditions = [
get_slot_spread_changes_fn ? x `${get_slot_spread_changes_fn}(#dirty)` : null,
block.has_outros ? x `!#current` : null
].filter(Boolean);
const all_dirty_condition = all_dirty_conditions.length ? all_dirty_conditions.reduce((condition1, condition2) => x `${condition1} || ${condition2}`) : null;
let slot_update;
if (all_dirty_condition) {
const dirty = x `${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 `
if (${slot}.p && ${condition}) {
@update_slot_base(${slot}, ${slot_definition}, #ctx, ${renderer.reference('$$scope')}, ${dirty}, ${get_slot_context_fn});
}
`;
}
else {
slot_update = b `
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 `#dirty`;
if (block.has_outros) {
fallback_condition = x `!#current || ${fallback_condition}`;
fallback_dirty = x `!#current ? ${renderer.get_initial_dirty()} : ${fallback_dirty}`;
}
const fallback_update = has_fallback && fallback_dynamic_dependencies.length > 0 && b `
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 `
if (${slot}) {
${slot_update}
} else {
${fallback_update}
}
`);
}
else {
block.chunks.update.push(b `
if (${slot}) {
${slot_update}
}
`);
}
block.chunks.destroy.push(b `if (${slot_or_fallback}) ${slot_or_fallback}.d(detaching);`);
}
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(variable);
}
}
class TitleWrapper extends Wrapper {
constructor(renderer, block, parent, node, _strip_whitespace, _next_sibling) {
super(renderer, block, parent, node);
}
render(block, _parent_node, _parent_nodes) {
const is_dynamic = !!this.node.children.find(node => node.type !== 'Text');
if (is_dynamic) {
let value;
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);
chunk.expression.dependencies.forEach(d => {
all_dependencies.add(d);
});
return chunk.expression.manipulate(block);
})
.reduce((lhs, rhs) => x `${lhs} + ${rhs}`);
if (this.node.children[0].type !== 'Text') {
value = x `"" + ${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 `${last} = ${value}` : value;
block.chunks.init.push(b `@_document.title = ${init};`);
const updater = b `@_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 `!#current || ${condition}`;
}
if (this.node.should_cache) {
condition = x `${condition} && (${last} !== (${last} = ${value}))`;
}
block.chunks.update.push(b `
if (${condition}) {
${updater}
}`);
}
}
else {
const value = this.node.children.length > 0
? string_literal(this.node.children[0].data)
: x `""`;
block.chunks.hydrate.push(b `@_document.title = ${value};`);
}
}
}
const associated_events = {
innerWidth: 'resize',
innerHeight: 'resize',
outerWidth: 'resize',
outerHeight: 'resize',
scrollX: 'scroll',
scrollY: 'scroll'
};
const properties = {
scrollX: 'pageXOffset',
scrollY: 'pageYOffset'
};
const readonly = new Set([
'innerWidth',
'innerHeight',
'outerWidth',
'outerHeight',
'online'
]);
class WindowWrapper extends Wrapper {
constructor(renderer, block, parent, node) {
super(renderer, block, parent, node);
this.handlers = this.node.handlers.map(handler => new EventHandlerWrapper(handler, this));
}
render(block, _parent_node, _parent_nodes) {
const { renderer } = this;
const { component } = renderer;
const events = {};
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 = 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 `false`);
block.add_variable(clear_scrolling, x `() => { ${scrolling} = false }`);
block.add_variable(scrolling_timeout);
const condition = bindings.scrollX && bindings.scrollY
? x `"${bindings.scrollX}" in this._state || "${bindings.scrollY}" in this._state`
: x `"${bindings.scrollX || bindings.scrollY}" in this._state`;
const scrollX = bindings.scrollX && x `this._state.${bindings.scrollX}`;
const scrollY = bindings.scrollY && x `this._state.${bindings.scrollY}`;
renderer.meta_bindings.push(b `
if (${condition}) {
@_scrollTo(${scrollX || '@_window.pageXOffset'}, ${scrollY || '@_window.pageYOffset'});
}
${scrollX && `${scrollX} = @_window.pageXOffset;`}
${scrollY && `${scrollY} = @_window.pageYOffset;`}
`);
block.event_listeners.push(x `
@listen(@_window, "${event}", () => {
${scrolling} = true;
@_clearTimeout(${scrolling_timeout});
${scrolling_timeout} = @_setTimeout(${clear_scrolling}, 100);
${fn}();
})
`);
}
else {
props.forEach(prop => {
renderer.meta_bindings.push(b `this._state.${prop.name} = @_window.${prop.value};`);
});
block.event_listeners.push(x `
@listen(@_window, "${event}", ${fn})
`);
}
component.partly_hoisted.push(b `
function ${id}() {
${props.map(prop => renderer.invalidate(prop.name, x `${prop.name} = @_window.${prop.value}`))}
}
`);
block.chunks.init.push(b `
@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 `@_window.pageXOffset`;
const scrollY = bindings.scrollY ? renderer.reference(bindings.scrollY) : x `@_window.pageYOffset`;
block.chunks.update.push(b `
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 `
function ${id}() {
${renderer.invalidate(name, x `${name} = @_navigator.onLine`)}
}
`);
block.chunks.init.push(b `
@add_render_callback(${reference});
`);
block.event_listeners.push(x `@listen(@_window, "online", ${reference})`, x `@listen(@_window, "offline", ${reference})`);
component.has_reactive_assignments = true;
}
}
}
function link(next, prev) {
prev.next = next;
if (next)
next.prev = prev;
}
const wrappers = {
AwaitBlock: AwaitBlockWrapper,
Body: BodyWrapper,
Comment: null,
DebugTag: DebugTagWrapper,
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
};
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.node.find_nearest(/EachBlock/) === child.find_nearest(/EachBlock/)) || next_sibling.node.prev.type === 'EachBlock';
}
class FragmentWrapper {
constructor(renderer, block, nodes, parent, strip_whitespace, next_sibling) {
this.nodes = [];
let last_child;
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(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') {
last_child.data = data + 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)
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 = 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);
}
}
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);
}
}
}
class Renderer {
constructor(component, options) {
this.context = [];
this.initial_context = [];
this.context_lookup = new Map();
this.blocks = [];
this.readonly = new Set();
this.meta_bindings = []; // initial values for e.g. window.innerWidth, if there's a <svelte:window> meta tag
this.binding_groups = new Map();
this.component = component;
this.options = options;
this.locate = component.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({
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) {
block.assign_variable_names();
}
});
this.block.assign_variable_names();
this.fragment.render(this.block, null, x `#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) || (a.index.value - 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);
}
add_to_context(name, contextual = false) {
if (!this.context_lookup.has(name)) {
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;
}
invalidate(name, value, main_execution_context = false) {
return renderer_invalidate(this, name, value, main_execution_context);
}
dirty(names, is_reactive_declaration = false) {
const renderer = this;
const dirty = (is_reactive_declaration
? x `$$self.$$.dirty`
: x `#dirty`);
const get_bitmask = () => {
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 = 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 {
// 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 x `${dirty} & /*${names.join(', ')}*/ 0`;
}
if (renderer.context_overflow) {
return bitmask
.map((b, i) => ({ b, i }))
.filter(({ b }) => b)
.map(({ b, i }) => x `${dirty}[${i}] & /*${b.names.join(', ')}*/ ${b.n}`)
.reduce((lhs, rhs) => x `${lhs} | ${rhs}`);
}
return x `${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
get_initial_dirty() {
const _this = this;
// TODO: context-overflow make it less gross
const val = x `-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
};
}
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 = x `/*${member.name}*/ ${ctx}[${member.index}]`;
if (nodes[0].loc)
replacement.object.loc = nodes[0].loc;
nodes[0] = replacement;
return nodes.reduce((lhs, rhs) => x `${lhs}.${rhs}`);
}
return node;
}
remove_block(block) {
this.blocks.splice(this.blocks.indexOf(block), 1);
}
}
var charToInteger = {};
var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
for (var i$1 = 0; i$1 < chars$1.length; i$1++) {
charToInteger[chars$1.charCodeAt(i$1)] = i$1;
}
function decode$3(mappings) {
var decoded = [];
var line = [];
var segment = [
0,
0,
0,
0,
0,
];
var j = 0;
for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) {
var c = mappings.charCodeAt(i);
if (c === 44) { // ","
segmentify(line, segment, j);
j = 0;
}
else if (c === 59) { // ";"
segmentify(line, segment, j);
j = 0;
decoded.push(line);
line = [];
segment[0] = 0;
}
else {
var integer = charToInteger[c];
if (integer === undefined) {
throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
}
var hasContinuationBit = integer & 32;
integer &= 31;
value += integer << shift;
if (hasContinuationBit) {
shift += 5;
}
else {
var shouldNegate = value & 1;
value >>>= 1;
if (shouldNegate) {
value = value === 0 ? -0x80000000 : -value;
}
segment[j] += value;
j++;
value = shift = 0; // reset
}
}
}
segmentify(line, segment, j);
decoded.push(line);
return decoded;
}
function segmentify(line, segment, j) {
// This looks ugly, but we're creating specialized arrays with a specific
// length. This is much faster than creating a new array (which v8 expands to
// a capacity of 17 after pushing the first item), or slicing out a subarray
// (which is slow). Length 4 is assumed to be the most frequent, followed by
// length 5 (since not everything will have an associated name), followed by
// length 1 (it's probably rare for a source substring to not have an
// associated segment data).
if (j === 4)
line.push([segment[0], segment[1], segment[2], segment[3]]);
else if (j === 5)
line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);
else if (j === 1)
line.push([segment[0]]);
}
function encode$1(decoded) {
var sourceFileIndex = 0; // second field
var sourceCodeLine = 0; // third field
var sourceCodeColumn = 0; // fourth field
var nameIndex = 0; // fifth field
var mappings = '';
for (var i = 0; i < decoded.length; i++) {
var line = decoded[i];
if (i > 0)
mappings += ';';
if (line.length === 0)
continue;
var generatedCodeColumn = 0; // first field
var lineMappings = [];
for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
var segment = line_1[_i];
var segmentMappings = encodeInteger$1(segment[0] - generatedCodeColumn);
generatedCodeColumn = segment[0];
if (segment.length > 1) {
segmentMappings +=
encodeInteger$1(segment[1] - sourceFileIndex) +
encodeInteger$1(segment[2] - sourceCodeLine) +
encodeInteger$1(segment[3] - sourceCodeColumn);
sourceFileIndex = segment[1];
sourceCodeLine = segment[2];
sourceCodeColumn = segment[3];
}
if (segment.length === 5) {
segmentMappings += encodeInteger$1(segment[4] - nameIndex);
nameIndex = segment[4];
}
lineMappings.push(segmentMappings);
}
mappings += lineMappings.join(',');
}
return mappings;
}
function encodeInteger$1(num) {
var result = '';
num = num < 0 ? (-num << 1) | 1 : num << 1;
do {
var clamped = num & 31;
num >>>= 5;
if (num > 0) {
clamped |= 32;
}
result += chars$1[clamped];
} while (num > 0);
return result;
}
/**
* Copyright 2019 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Creates a brand new (prototype-less) object with the enumerable-own
* properties of `target`. Any enumerable-own properties from `source` which
* are not present on `target` will be copied as well.
*/
function defaults(target, source) {
return Object.assign(Object.create(null), source, target);
}
/**
* Copyright 2019 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Decodes an input sourcemap into a `DecodedSourceMap` sourcemap object.
*
* Valid input maps include a `DecodedSourceMap`, a `RawSourceMap`, or JSON
* representations of either type.
*/
function decodeSourceMap(map) {
if (typeof map === 'string') {
map = JSON.parse(map);
}
let { mappings } = map;
if (typeof mappings === 'string') {
mappings = decode$3(mappings);
}
else {
// Clone the Line so that we can sort it. We don't want to mutate an array
// that we don't own directly.
mappings = mappings.map(cloneSegmentLine);
}
// Sort each Line's segments. There's no guarantee that segments are sorted for us,
// and even Chrome's implementation sorts:
// https://cs.chromium.org/chromium/src/third_party/devtools-frontend/src/front_end/sdk/SourceMap.js?l=507-508&rcl=109232bcf479c8f4ef8ead3cf56c49eb25f8c2f0
mappings.forEach(sortSegments);
return defaults({ mappings }, map);
}
function cloneSegmentLine(segments) {
return segments.slice();
}
function sortSegments(segments) {
segments.sort(segmentComparator);
}
function segmentComparator(a, b) {
return a[0] - b[0];
}
/**
* Copyright 2019 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A "leaf" node in the sourcemap tree, representing an original, unmodified
* source file. Recursive segment tracing ends at the `OriginalSource`.
*/
class OriginalSource {
constructor(filename, content) {
this.filename = filename;
this.content = content;
}
/**
* Tracing a `SourceMapSegment` ends when we get to an `OriginalSource`,
* meaning this line/column location originated from this source file.
*/
traceSegment(line, column, name) {
return { column, line, name, source: this };
}
}
/* istanbul ignore next */
const Url$1 = (typeof URL !== 'undefined' ? URL : require('url').URL);
// Matches "..", which must be preceeded by "/" or the start of the string, and
// must be followed by a "/". We do not eat the following "/", so that the next
// iteration can match on it.
const parentRegex = /(^|\/)\.\.(?=\/|$)/g;
function isAbsoluteUrl(url) {
try {
return !!new Url$1(url);
}
catch (e) {
return false;
}
}
/**
* Creates a directory name that is guaranteed to not be in `str`.
*/
function uniqInStr(str) {
let uniq = String(Math.random()).slice(2);
while (str.indexOf(uniq) > -1) {
/* istanbul ignore next */
uniq += uniq;
}
return uniq;
}
/**
* Removes the filename from the path (everything trailing the last "/"). This
* is only safe to call on a path, never call with an absolute or protocol
* relative URL.
*/
function stripPathFilename(path) {
path = normalizePath(path);
const index = path.lastIndexOf('/');
return path.slice(0, index + 1);
}
/**
* Normalizes a protocol-relative URL, but keeps it protocol relative by
* stripping out the protocl before returning it.
*/
function normalizeProtocolRelative(input, absoluteBase) {
const { href, protocol } = new Url$1(input, absoluteBase);
return href.slice(protocol.length);
}
/**
* Normalizes a simple path (one that has no ".."s, or is absolute so ".."s can
* be normalized absolutely).
*/
function normalizeSimplePath(input) {
const { href } = new Url$1(input, 'https://foo.com/');
return href.slice('https://foo.com/'.length);
}
/**
* Normalizes a path, ensuring that excess ".."s are preserved for relative
* paths in the output.
*
* If the input is absolute, this will return an absolutey normalized path, but
* it will not have a leading "/".
*
* If the input has a leading "..", the output will have a leading "..".
*
* If the input has a leading ".", the output will not have a leading "."
* unless there are too many ".."s, in which case there will be a leading "..".
*/
function normalizePath(input) {
// If there are no ".."s, we can treat this as if it were an absolute path.
// The return won't be an absolute path, so it's easy.
if (!parentRegex.test(input))
return normalizeSimplePath(input);
// We already found one "..". Let's see how many there are.
let total = 1;
while (parentRegex.test(input))
total++;
// If there are ".."s, we need to prefix the the path with the same number of
// unique directories. This is to ensure that we "remember" how many parent
// directories we are accessing. Eg, "../../.." must keep 3, and "foo/../.."
// must keep 1.
const uniqDirectory = `z${uniqInStr(input)}/`;
// uniqDirectory is just a "z", followed by numbers, followed by a "/". So
// generating a runtime regex from it is safe. We'll use this search regex to
// strip out our uniq directory names and insert any needed ".."s.
const search = new RegExp(`^(?:${uniqDirectory})*`);
// Now we can resolve the total path. If there are excess ".."s, they will
// eliminate one or more of the unique directories we prefix with.
const relative = normalizeSimplePath(uniqDirectory.repeat(total) + input);
// We can now count the number of unique directories that were eliminated. If
// there were 3, and 1 was eliminated, we know we only need to add 1 "..". If
// 2 were eliminated, we need to insert 2 ".."s. If all 3 were eliminated,
// then we need 3, etc. This replace is guranteed to match (it may match 0 or
// more times), and we can count the total match to see how many were eliminated.
return relative.replace(search, (all) => {
const leftover = all.length / uniqDirectory.length;
return '../'.repeat(total - leftover);
});
}
/**
* Attempts to resolve `input` URL relative to `base`.
*/
function resolve(input, base) {
if (!base)
base = '';
// Absolute URLs are very easy to resolve right.
if (isAbsoluteUrl(input))
return new Url$1(input).href;
if (base) {
// Absolute URLs are easy...
if (isAbsoluteUrl(base))
return new Url$1(input, base).href;
// If base is protocol relative, we'll resolve with it but keep the result
// protocol relative.
if (base.startsWith('//'))
return normalizeProtocolRelative(input, `https:${base}`);
}
// Normalize input, but keep it protocol relative. We know base doesn't supply
// a protocol, because that would have been handled above.
if (input.startsWith('//'))
return normalizeProtocolRelative(input, 'https://foo.com/');
// We now know that base (if there is one) and input are paths. We've handled
// both absolute and protocol-relative variations above.
// Absolute paths don't need any special handling, because they cannot have
// extra "." or ".."s. That'll all be stripped away. Input takes priority here,
// because if input is an absolute path, base path won't affect it in any way.
if (input.startsWith('/'))
return '/' + normalizeSimplePath(input);
// Since input and base are paths, we need to join them to do any further
// processing. Paths are joined at the directory level, so we need to remove
// the base's filename before joining. We also know that input does not have a
// leading slash, and that the stripped base will have a trailing slash if
// there are any directories (or it'll be empty).
const joined = stripPathFilename(base) + input;
// If base is an absolute path, then input will be relative to it.
if (base.startsWith('/'))
return '/' + normalizeSimplePath(joined);
// We now know both base (if there is one) and input are relative paths.
const relative = normalizePath(joined);
// 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.
if ((base || input).startsWith('.') && !relative.startsWith('.')) {
return './' + relative;
}
return relative;
}
/**
* Copyright 2019 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function resolve$1(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(input, base);
}
/**
* Copyright 2019 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A binary search implementation that returns the index if a match is found,
* or the negated index of where the `needle` should be inserted.
*
* The `comparator` callback receives both the `item` under comparison and the
* needle we are searching for. It must return `0` if the `item` is a match,
* any negative number if `item` is too small (and we must search after it), or
* any positive number if the `item` is too large (and we must search before
* it).
*
* If no match is found, a negated index of where to insert the `needle` is
* returned. This negated index is guaranteed to be less than 0. To insert an
* item, negate it (again) and splice:
*
* ```js
* const array = [1, 3];
* const needle = 2;
* const index = binarySearch(array, needle, (item, needle) => item - needle);
*
* assert.equal(index, -2);
* assert.equal(~index, 1);
* array.splice(~index, 0, needle);
* assert.deepEqual(array, [1, 2, 3]);
* ```
*/
function binarySearch(haystack, needle, comparator) {
let low = 0;
let high = haystack.length - 1;
while (low <= high) {
const mid = low + ((high - low) >> 1);
const cmp = comparator(haystack[mid], needle);
if (cmp === 0) {
return mid;
}
if (cmp < 0) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
return ~low;
}
/**
* Copyright 2019 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* FastStringArray 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 `sourcesContent[i]` is the source content
* associated with `source[i]`, and there are never duplicates.
*/
class FastStringArray {
constructor() {
this.indexes = Object.create(null);
this.array = [];
}
/**
* Puts `key` into the backing array, if it is not already present. Returns
* the index of the `key` in the backing array.
*/
put(key) {
const { array, indexes } = this;
// The key may or may not be present. If it is present, it's a number.
let index = indexes[key];
// If it's not yet present, we need to insert it and track the index in the
// indexes.
if (index === undefined) {
index = indexes[key] = array.length;
array.push(key);
}
return index;
}
}
/**
* Copyright 2019 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* SourceMapTree represents a single sourcemap, with the ability to trace
* mappings into its child nodes (which may themselves be SourceMapTrees).
*/
class SourceMapTree {
constructor(map, sources) {
this.map = map;
this.sources = sources;
}
/**
* traceMappings is only called on the root level SourceMapTree, and begins
* the process of resolving each mapping in terms of the original source
* files.
*/
traceMappings() {
const mappings = [];
const names = new FastStringArray();
const sources = new FastStringArray();
const sourcesContent = [];
const { mappings: rootMappings, names: rootNames } = this.map;
for (let i = 0; i < rootMappings.length; i++) {
const segments = rootMappings[i];
const tracedSegments = [];
for (let j = 0; j < segments.length; j++) {
const segment = segments[j];
// 1-length segments only move the current generated column, there's no
// source information to gather from it.
if (segment.length === 1)
continue;
const source = this.sources[segment[1]];
const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : '');
if (!traced)
continue;
// So we traced a segment down into its original source file. Now push a
// new segment pointing to this location.
const { column, line, name } = traced;
const { content, filename } = traced.source;
// Store the source location, and ensure we keep sourcesContent up to
// date with the sources array.
const sourceIndex = sources.put(filename);
sourcesContent[sourceIndex] = content;
// This looks like unnecessary duplication, but it noticeably increases
// performance. If we were to push the nameIndex onto length-4 array, v8
// would internally allocate 22 slots! That's 68 wasted bytes! Array
// literals have the same capacity as their length, saving memory.
if (name) {
tracedSegments.push([segment[0], sourceIndex, line, column, names.put(name)]);
}
else {
tracedSegments.push([segment[0], sourceIndex, line, column]);
}
}
mappings.push(tracedSegments);
}
// TODO: Make all sources relative to the sourceRoot.
return defaults({
mappings,
names: names.array,
sources: sources.array,
sourcesContent,
}, this.map);
}
/**
* traceSegment is only called on children SourceMapTrees. It recurses down
* into its own child SourceMapTrees, until we find the original source map.
*/
traceSegment(line, column, name) {
const { mappings, names } = this.map;
// It's common for parent sourcemaps to have pointers to lines that have no
// mapping (like a "//# sourceMappingURL=") at the end of the child file.
if (line >= mappings.length)
return null;
const segments = mappings[line];
if (segments.length === 0)
return null;
let index = binarySearch(segments, column, segmentComparator$1);
if (index === -1)
return null; // we come before any mapped segment
// If we can't find a segment that lines up to this column, we use the
// segment before.
if (index < 0) {
index = ~index - 1;
}
const segment = segments[index];
// 1-length segments only move the current generated column, there's no
// source information to gather from it.
if (segment.length === 1)
return null;
const source = this.sources[segment[1]];
// So now we can recurse down, until we hit the original source file.
return source.traceSegment(segment[2], segment[3],
// A child map's recorded name for this segment takes precedence over the
// parent's mapped name. Imagine a mangler changing the name over, etc.
segment.length === 5 ? names[segment[4]] : name);
}
}
function segmentComparator$1(segment, column) {
return segment[0] - column;
}
/**
* Copyright 2019 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Removes the filename from a path.
*/
function stripFilename(path) {
if (!path)
return '';
const index = path.lastIndexOf('/');
return path.slice(0, index + 1);
}
/**
* Copyright 2019 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
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, relativeRoot) {
const maps = asArray(input).map(decodeSourceMap);
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?');
}
}
const { sourceRoot, sources, sourcesContent } = map;
const children = sources.map((sourceFile, i) => {
// Each source file is loaded relative to the sourcemap's own sourceRoot,
// which is itself relative to the sourcemap's parent.
const uri = resolve$1(sourceFile || '', resolve$1(sourceRoot || '', stripFilename(relativeRoot)));
// Use the provided loader callback to retrieve the file's sourcemap.
// TODO: We should eventually support async loading of sourcemap files.
const sourceMap = loader(uri);
// If there is no sourcemap, then it is an unmodified source file.
if (!sourceMap) {
// The source file's actual contents must be included in the sourcemap
// (done when generating the sourcemap) for it to be included as a
// sourceContent in the output sourcemap.
const sourceContent = sourcesContent ? sourcesContent[i] : null;
return new OriginalSource(uri, sourceContent);
}
// Else, it's a real sourcemap, and we need to recurse into it to load its
// source files.
return buildSourceMapTree(decodeSourceMap(sourceMap), loader, uri);
});
let tree = new SourceMapTree(map, children);
for (let i = maps.length - 1; i >= 0; i--) {
tree = new SourceMapTree(maps[i], [tree]);
}
return tree;
}
/**
* Copyright 2019 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A SourceMap v3 compatible sourcemap, which only includes fields that were
* provided to it.
*/
class SourceMap {
constructor(map, excludeContent) {
this.version = 3; // SourceMap spec says this should be first.
if ('file' in map)
this.file = map.file;
this.mappings = encode$1(map.mappings);
this.names = map.names;
// TODO: We first need to make all source URIs relative to the sourceRoot
// before we can support a sourceRoot.
// if ('sourceRoot' in map) this.sourceRoot = map.sourceRoot;
this.sources = map.sources;
if (!excludeContent && 'sourcesContent' in map)
this.sourcesContent = map.sourcesContent;
}
toString() {
return JSON.stringify(this);
}
}
/**
* Copyright 2019 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* 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` content to exclude any self-containing source file
* content from the output sourcemap.
*/
function remapping(input, loader, excludeContent) {
const graph = buildSourceMapTree(input, loader);
return new SourceMap(graph.traceMappings(), !!excludeContent);
}
function last_line_length(s) {
return s.length - s.lastIndexOf('\n') - 1;
}
// mutate map in-place
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;
}
}
}
}
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 {
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
*/
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$1(m1.mappings[m1.mappings.length - 1], m2.mappings.shift());
// append other lines
push_array$1(m1.mappings, m2.mappings);
return this;
}
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 from_source({ source, file_basename, get_location }) {
let offset = get_location(0);
if (!offset)
offset = { line: 0, column: 0 };
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);
}
}
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
function loader(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;
}
// browser vs node.js
const b64enc = typeof btoa == 'function' ? btoa : b => Buffer.from(b).toString('base64');
const b64dec = typeof atob == 'function' ? atob : a => Buffer.from(a, 'base64').toString();
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,' + b64enc(this.toString());
}
}
});
return result_map;
}
const regex_data_uri = /data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(\S*)/;
// parse attached sourcemap in processed.code
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*\\*/$');
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 = b64dec(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
});
}
function check_enable_sourcemap(enable_sourcemap, namespace) {
return typeof enable_sourcemap === 'boolean'
? enable_sourcemap
: enable_sourcemap[namespace];
}
function dom(component, options) {
const { name } = component;
const renderer = new Renderer(component, options);
const { block } = renderer;
block.has_outro_method = true;
// prevent fragment being created twice (#1063)
if (options.customElement)
block.chunks.create.push(b `this.c = @noop;`);
const body = [];
if (renderer.file_var) {
const file = component.file ? x `"${component.file}"` : x `undefined`;
body.push(b `const ${renderer.file_var} = ${file};`);
}
const css = component.stylesheet.render(options.filename, !options.customElement);
const css_sourcemap_enabled = check_enable_sourcemap(options.enableSourcemap, 'css');
if (css_sourcemap_enabled) {
css.map = apply_preprocessor_sourcemap(options.filename, css.map, 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 = (!options.customElement &&
!!styles &&
options.css === 'injected');
if (should_add_css) {
body.push(b `
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$1(body, blocks.map(block => {
// TODO this is a horrible mess — renderer.blocks
// contains a mixture of Blocks and Nodes
if (block.render)
return block.render();
return block;
}));
if (options.dev && !options.hydratable) {
block.chunks.claim.push(b `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');
let compute_slots;
if (uses_slots) {
compute_slots = b `
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 `@compute_rest_props($$props, ${omit_props_names.name})`;
const rest = uses_rest ? b `
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 `
${$$props} => {
${uses_props && renderer.invalidate('$$props', x `$$props = @assign(@assign({}, $$props), @exclude_internal_props($$new_props))`)}
${uses_rest && !uses_props && x `$$props = @assign(@assign({}, $$props), @exclude_internal_props($$new_props))`}
${uses_rest && renderer.invalidate('$$restProps', x `$$restProps = ${compute_rest}`)}
${writable_props.map(prop => b `if ('${prop.export_name}' in ${$$props}) ${renderer.invalidate(prop.name, x `${prop.name} = ${$$props}.${prop.export_name}`)};`)}
${component.slots.size > 0 &&
b `if ('$$scope' in ${$$props}) ${renderer.invalidate('$$scope', x `$$scope = ${$$props}.$$scope`)};`}
}
`
: null;
const accessors = [];
const not_equal = component.component_options.immutable ? x `@not_equal` : x `@safe_not_equal`;
let missing_props_check;
let inject_state;
let capture_state;
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 `function() {
return ${prop.hoistable ? prop.name : x `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 `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 `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 `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 `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 = Object.assign(Object.assign({}, exports_from), { type: 'ImportDeclaration', specifiers: [], source: exports_from.source });
component.imports.push(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(Object.assign(Object.assign({}, specifier), { type: 'ImportSpecifier', imported: specifier.local, local: name }));
accessors.push({
type: 'MethodDefinition',
kind: 'get',
key: { type: 'Identifier', name: specifier.exported.name },
value: x `function() {
return ${name}
}`
});
}
else if (component.compile_options.dev) {
accessors.push({
type: 'MethodDefinition',
kind: 'get',
key: { type: 'Identifier', name: specifier.exported.name },
value: x `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 `
$$self.$$.on_mount.push(function () {
${expected.map(prop => b `
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 `() => ({ ${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 `
${$$props} => {
${uses_props && renderer.invalidate('$$props', x `$$props = @assign(@assign({}, $$props), $$new_props)`)}
${injectable_vars.map(v => b `if ('${v.name}' in $$props) ${renderer.invalidate(v.name, x `${v.name} = ${$$props}.${v.name}`)};`)}
}
`;
props_inject = b `
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;
let execution_context = null;
walk(component.ast.instance.content, {
enter(node) {
if (map.has(node)) {
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(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 `${`$$subscribe_${name}`}()`
: b `@component_subscribe($$self, ${name}, #value => $$invalidate(${i}, ${value} = #value))`;
if (component.compile_options.dev) {
return b `@validate_store(${name}, '${name}'); ${insert}`;
}
return insert;
});
}
const args = [x `$$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 `$$props`, x `$$invalidate`);
}
else if (component.compile_options.dev) {
// $$props arg is still needed for unknown prop check
args.push(x `$$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 `
function create_fragment(#ctx) {
${block.get_contents()}
}
`);
}
body.push(b `
${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 `
${component.compile_options.dev && b `@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) && !variable.is_reactive_static;
})
.map(({ name }) => b `$$self.$$.on_destroy.push(() => ${`$$unsubscribe_${name.slice(1)}`}());`);
if (has_definition) {
const reactive_declarations = [];
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 = b `if (${condition}) { ${statement} }`[0];
if (condition || uses_rest_or_props) {
reactive_declarations.push(statement);
}
else {
fixed_reactive_declarations.push(statement);
for (const assignee of d.assignees) {
const variable = component.var_lookup.get(assignee);
if (variable && variable.subscribable) {
fixed_reactive_declarations.push(b `
${component.compile_options.dev && b `@validate_store(${assignee}, '${assignee}');`}
@component_subscribe($$self, ${assignee}, $$value => $$invalidate(${renderer.context_lookup.get('$' + assignee).index}, ${'$' + assignee} = $$value));
`);
}
}
}
});
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) && !store.is_reactive_static) {
const unsubscribe = `$$unsubscribe_${name}`;
const subscribe = `$$subscribe_${name}`;
const i = renderer.context_lookup.get($name).index;
return b `let ${$name}, ${unsubscribe} = @noop, ${subscribe} = () => (${unsubscribe}(), ${unsubscribe} = @subscribe(${name}, $$value => $$invalidate(${i}, ${$name} = $$value)), ${name})`;
}
return b `let ${$name};`;
});
let unknown_props_check;
if (component.compile_options.dev && !(uses_props || uses_rest)) {
unknown_props_check = b `
const writable_props = [${writable_props.map(prop => x `'${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: 'Identifier',
name: member.name
}))
};
body.push(b `
function ${definition}(${args}) {
${injected.map(name => b `let ${name};`)}
${rest}
${reactive_store_declarations}
${reactive_store_subscriptions}
${resubscribable_reactive_store_unsubscribers}
${component.slots.size || component.compile_options.dev || uses_slots ? b `let { $$slots: #slots = {}, $$scope } = $$props;` : null}
${component.compile_options.dev && b `@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 `const $$binding_groups = [${[...renderer.binding_groups.keys()].map(_ => x `[]`)}];`}
${component.partly_hoisted}
${set && b `$$self.$$set = ${set};`}
${capture_state && b `$$self.$capture_state = ${capture_state};`}
${inject_state && b `$$self.$inject_state = ${inject_state};`}
${ /* before reactive declarations */props_inject}
${reactive_declarations.length > 0 && b `
$$self.$$.update = () => {
${reactive_declarations}
};
`}
${fixed_reactive_declarations}
${uses_props && b `$$props = @exclude_internal_props($$props);`}
return ${return_value};
}
`);
}
const prop_indexes = x `{
${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 `[]`;
for (let i = 0; i < renderer.context.length; i += 31) {
dirty.elements.push(x `-1`);
}
}
if (options.customElement) {
let init_props = x `@attribute_to_object(this.attributes)`;
if (uses_slots) {
init_props = x `{ ...${init_props}, $$slots: @get_custom_elements_slots(this) }`;
}
const declaration = b `
class ${name} extends @SvelteElement {
constructor(options) {
super();
${css.code && b `
const style = document.createElement('style');
style.textContent = \`${css.code.replace(regex_backslashes, '\\\\')}${css_sourcemap_enabled && options.dev ? `\n/*# sourceMappingURL=${css.map.toUrl()} */` : ''}\`
this.shadowRoot.appendChild(style)`}
@init(this, { target: this.shadowRoot, props: ${init_props}, customElement: true }, ${definition}, ${has_create_fragment ? 'create_fragment' : 'null'}, ${not_equal}, ${prop_indexes}, null, ${dirty});
if (options) {
if (options.target) {
@insert(options.target, this, options.anchor);
}
${(props.length > 0 || uses_props || uses_rest) && b `
if (options.props) {
this.$set(options.props);
@flush();
}`}
}
}
}
`[0];
if (props.length > 0) {
declaration.body.body.push({
type: 'MethodDefinition',
kind: 'get',
static: true,
computed: false,
key: { type: 'Identifier', name: 'observedAttributes' },
value: x `function() {
return [${props.map(prop => x `"${prop.export_name}"`)}];
}`
});
}
push_array$1(declaration.body.body, accessors);
body.push(declaration);
if (component.tag != null) {
body.push(b `
@_customElements.define("${component.tag}", ${name});
`);
}
}
else {
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 `null`);
}
if (dirty) {
optional_parameters.push(dirty);
}
const declaration = b `
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 `@dispatch_dev("SvelteRegisterComponent", { component: this, tagName: "${name.name}", options, id: create_fragment.name });`}
}
}
`[0];
push_array$1(declaration.body.body, accessors);
body.push(declaration);
}
return { js: flatten(body), css };
}
function get_const_tags$1(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
};
})
};
}
function AwaitBlock$1 (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 `
function(__value) {
if (@is_promise(__value)) {
__value.then(null, @noop);
return ${pending};
}
return (function(${node.then_node ? node.then_node : ''}) { ${get_const_tags$1(node.then.const_tags)}; return ${then}; }(__value));
}(${node.expression.node})
`);
}
function Comment$2 (node, renderer, options) {
if (options.preserveComments) {
renderer.add_string(`<!--${node.data}-->`);
}
}
function DebugTag$1 (node, renderer, options) {
if (!options.dev)
return;
const filename = options.filename || null;
const { line, column } = options.locate(node.start + 1);
const obj = x `{
${node.expressions.map(e => p `${e.node.name}`)}
}`;
renderer.add_expression(x `@debug(${filename ? x `"${filename}"` : x `null`}, ${line - 1}, ${column}, ${obj})`);
}
function EachBlock$1 (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 `@each(${node.expression.node}, (${args}) => { ${get_const_tags$1(node.const_tags)}; return ${result} })`;
if (node.else) {
renderer.push();
renderer.render(node.else.children, options);
let alternate = renderer.pop();
if (node.else.const_tags.length > 0)
alternate = x `(() => { ${get_const_tags$1(node.else.const_tags)}; return ${alternate} })()`;
renderer.add_expression(x `${node.expression.node}.length ? ${consequent} : ${alternate}`);
}
else {
renderer.add_expression(consequent);
}
}
function get_class_attribute_value(attribute) {
// handle special case — `class={possiblyUndefined}` with scoped CSS
if (attribute.chunks.length === 2 && attribute.chunks[1].synthetic) {
const value = attribute.chunks[0].node;
return x `@escape(@null_to_empty(${value}), true) + "${attribute.chunks[1].data}"`;
}
return get_attribute_value(attribute);
}
function get_attribute_value(attribute) {
if (attribute.chunks.length === 0)
return x `""`;
return attribute.chunks
.map((chunk) => {
return chunk.type === 'Text'
? string_literal(chunk.data.replace(regex_double_quotes, '&quot;'))
: x `@escape(${chunk.node}, true)`;
})
.reduce((lhs, rhs) => x `${lhs} + ${rhs}`);
}
function get_attribute_expression(attribute) {
if (attribute.chunks.length === 1 && attribute.chunks[0].type === 'Expression') {
return 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
function remove_whitespace_children(children, next) {
const nodes = [];
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$1(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;
}
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;
}
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.find_nearest(/EachBlock/) ===
child.find_nearest(/EachBlock/) || next_sibling.prev.type === 'EachBlock');
}
function Element$1 (node, renderer, options) {
const children = remove_whitespace_children(node.children, node.next);
// awkward special case
let node_contents;
const contenteditable = (node.name !== 'textarea' &&
node.name !== 'input' &&
node.attributes.some((attribute) => attribute.name === 'contenteditable'));
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 `#ctx.${name}`; // TODO is this right?
return x `${snippet} ? "${name}" : ""`;
});
if (node.needs_manual_style_scoping) {
class_expression_list.push(x `"${node.component.stylesheet.id}"`);
}
const class_expression = class_expression_list.length > 0 &&
class_expression_list.reduce((lhs, rhs) => x `${lhs} + ' ' + ${rhs}`);
const style_expression_list = node.styles.map(style_directive => {
let { name, important, expression: { node: expression } } = style_directive;
if (important) {
expression = x `${expression} + ' !important'`;
}
return p `"${name}": ${expression}`;
});
const style_expression = style_expression_list.length > 0 &&
x `{ ${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 `@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 `{ ${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 `{ ${attr_name}: ${attribute.chunks[0].node} || null }`);
}
else if (attribute.chunks.length === 1 && attribute.chunks[0].type !== 'Text') {
const snippet = attribute.chunks[0].node;
args.push(x `{ ${attr_name}: @escape_attribute_value(${snippet}) }`);
}
else {
args.push(x `{ ${attr_name}: ${get_attribute_value(attribute)} }`);
}
}
});
renderer.add_expression(x `@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 `${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 `[${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 `@add_styles(@merge_ssr_styles(${get_attribute_value(attribute)}, ${style_expression}))`);
}
else if (attribute.chunks.length === 1 && attribute.chunks[0].type !== 'Text') {
const snippet = attribute.chunks[0].node;
renderer.add_expression(x `@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 `@add_classes((${class_expression}).trim())`);
}
if (add_style_attribute) {
renderer.add_expression(x `@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 `~${bound}.indexOf(${value})` : x `${value} === ${bound}`;
renderer.add_expression(x `${condition} ? @add_attribute("checked", true, 1) : ""`);
}
}
else if (contenteditable && (name === 'textContent' || name === 'innerHTML')) {
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 `${snippet} || ""`;
}
else if (binding.name === 'value' && node.name === 'select') ;
else {
const snippet = expression.node;
renderer.add_expression(x `@add_attribute("${name}", ${snippet}, ${boolean_attributes.has(name) ? 1 : 0})`);
}
});
renderer.add_string('>');
if (node_contents !== undefined) {
if (contenteditable) {
renderer.push();
renderer.render(children, options);
const result = renderer.pop();
renderer.add_expression(x `($$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 `@is_void(#tag) ? '' : ${children}`);
}
add_close_tag();
}
if (node.is_dynamic_element) {
let content = renderer.pop();
if (options.dev && node.children.length > 0)
content = x `(() => { @validate_void_dynamic_element(#tag); return ${content}; })()`;
renderer.add_expression(x `((#tag) => {
${options.dev && x `@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(node.tag_expr.node.value)) {
renderer.add_string('</');
add_tag_name();
renderer.add_string('>');
}
return;
}
renderer.add_expression(x `@is_void(#tag) ? '' : \`</\${#tag}>\``);
}
function add_tag_name() {
if (node.tag_expr.node.type === 'Literal') {
renderer.add_string(node.tag_expr.node.value);
}
else {
renderer.add_expression(node.tag_expr.node);
}
}
}
function Head$1 (node, renderer, options) {
const head_options = Object.assign(Object.assign({}, options), { head_id: node.id });
renderer.push();
renderer.render(node.children, head_options);
const result = renderer.pop();
let expression = result;
if (options.hydratable) {
const start_comment = `HEAD_${node.id}_START`;
const end_comment = `HEAD_${node.id}_END`;
expression = x `'<!-- ${start_comment} -->' + ${expression} + '<!-- ${end_comment} -->'`;
}
renderer.add_expression(x `$$result.head += ${expression}, ""`);
}
function HtmlTag (node, renderer, options) {
if (options.hydratable)
renderer.add_string('<!-- HTML_TAG_START -->');
renderer.add_expression(node.expression.node);
if (options.hydratable)
renderer.add_string('<!-- HTML_TAG_END -->');
}
function IfBlock$1 (node, renderer, options) {
const condition = node.expression.node;
renderer.push();
renderer.render(node.children, options);
let consequent = renderer.pop();
if (node.const_tags.length > 0)
consequent = x `(() => { ${get_const_tags$1(node.const_tags)}; return ${consequent} })()`;
renderer.push();
if (node.else)
renderer.render(node.else.children, options);
let alternate = renderer.pop();
if (node.else && node.else.const_tags.length > 0)
alternate = x `(() => { ${get_const_tags$1(node.else.const_tags)}; return ${alternate} })()`;
renderer.add_expression(x `${condition} ? ${consequent} : ${alternate}`);
}
function get_prop_value(attribute) {
if (attribute.is_true)
return x `true`;
if (attribute.chunks.length === 0)
return x `''`;
return attribute.chunks
.map(chunk => {
if (chunk.type === 'Text')
return string_literal(chunk.data);
return chunk.node;
})
.reduce((lhs, rhs) => x `${lhs} + ${rhs}`);
}
function InlineComponent$1 (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 `@_Object.assign({}, ${node.attributes
.map(attribute => {
if (attribute.is_spread) {
return attribute.expression.node;
}
else {
return x `{ ${attribute.name}: ${get_prop_value(attribute)} }`;
}
})
.concat(binding_props.map(p => x `{ ${p} }`))})`;
}
else {
props = x `{
${node.attributes.map(attribute => p `${attribute.name}: ${get_prop_value(attribute)}`)},
${binding_props}
}`;
}
const bindings = x `{
${binding_fns}
}`;
const expression = (node.name === 'svelte:self'
? renderer.name
: node.name === 'svelte:component'
? x `(${node.expression.node}) || @missing_component`
: node.name.split('.').reduce(((lhs, rhs) => x `${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 `{
${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 `@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>');
}
}
}
function KeyBlock$1 (node, renderer, options) {
renderer.render(node.children, options);
}
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
};
})
};
}
function Slot$1 (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 `
#slots.${node.slot_name}
? #slots.${node.slot_name}(${slot_data})
: ${result}
`);
if (slot && nearest_inline_component) {
const lets = node.lets;
const seen = new Set(lets.map(l => l.name.name));
nearest_inline_component.lets.forEach(l => {
if (!seen.has(l.name.name))
lets.push(l);
});
options.slot_scopes.set(slot, {
input: get_slot_scope(node.lets),
output: renderer.pop()
});
}
}
function SlotTemplate$1 (node, renderer, options) {
const parent_inline_component = node.parent;
const children = remove_whitespace_children(node instanceof SlotTemplate ? node.children : [node], node.next);
renderer.push();
renderer.render(children, options);
const lets = node.lets;
const seen = new Set(lets.map(l => l.name.name));
parent_inline_component.lets.forEach(l => {
if (!seen.has(l.name.name))
lets.push(l);
});
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$1(node.const_tags)
});
}
}
function is_empty_template_literal(template_literal) {
return (template_literal.expressions.length === 0 &&
template_literal.quasis.length === 1 &&
template_literal.quasis[0].value.raw === '');
}
function Tag$2 (node, renderer, _options) {
const snippet = node.expression.node;
renderer.add_expression(node.parent &&
node.parent.type === 'Element' &&
node.parent.name === 'style'
? snippet
: x `@escape(${snippet})`);
}
function Text$1 (node, renderer, _options) {
let text = node.data;
if (!node.parent ||
node.parent.type !== 'Element' ||
(node.parent.name !== 'script' && node.parent.name !== 'style')) {
// unless this Text node is inside a <script> or <style> element, escape &,<,>
text = escape_html(text);
}
renderer.add_string(text);
}
function Title$1 (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 `$$result.title = ${result}, ""`);
}
/**
* Collapse string literals together
*/
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() { }
const handlers$1 = {
AwaitBlock: AwaitBlock$1,
Body: noop,
Comment: Comment$2,
DebugTag: DebugTag$1,
EachBlock: EachBlock$1,
Element: Element$1,
Head: Head$1,
IfBlock: IfBlock$1,
InlineComponent: InlineComponent$1,
KeyBlock: KeyBlock$1,
MustacheTag: Tag$2,
Options: noop,
RawMustacheTag: HtmlTag,
Slot: Slot$1,
SlotTemplate: SlotTemplate$1,
Text: Text$1,
Title: Title$1,
Window: noop
};
class Renderer$1 {
constructor({ name }) {
this.has_bindings = false;
this.stack = [];
this.targets = [];
this.name = name;
this.push();
}
add_string(str) {
this.current.value += escape_template(str);
}
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;
}
render(nodes, options) {
nodes.forEach(node => {
const handler = handlers$1[node.type];
if (!handler) {
throw new Error(`No handler for '${node.type}' nodes`);
}
handler(node, this, options);
});
}
}
function ssr(component, options) {
const renderer = new Renderer$1({
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, true);
const uses_rest = component.var_lookup.has('$$restProps');
const props = component.vars.filter(variable => !variable.module && variable.export_name);
const rest = uses_rest ? b `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 `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 `
${component.compile_options.dev && b `@validate_store(${store_name}, '${store_name}');`}
${`$$unsubscribe_${store_name}`} = @subscribe(${store_name}, #value => ${name} = #value)
`;
});
const reactive_store_unsubscriptions = reactive_stores.map(({ name }) => b `${`$$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 `let ${name}, ${unsubscribe} = @noop, ${subscribe} = () => (${unsubscribe}(), ${unsubscribe} = @subscribe(${store_name}, $$value => ${name} = $$value), ${store_name})`;
}
return b `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(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({ component }, scope, node, to_invalidate, true));
}
}
}
});
}
component.rewrite_props(({ name, reassigned }) => {
const value = `$${name}`;
let insert = reassigned
? b `${`$$subscribe_${name}`}()`
: b `${`$$unsubscribe_${name}`} = @subscribe(${name}, #value => $${value} = #value)`;
if (component.compile_options.dev) {
insert = b `@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 `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 = d.node.body;
let statement = b `${body}`;
if (!d.declaration) { // TODO do not add label if it's not referenced
statement = b `$: { ${statement} }`;
}
return statement;
});
const main = renderer.has_bindings
? b `
let $$settled;
let $$rendered;
do {
$$settled = true;
${reactive_declarations}
$$rendered = ${literal};
} while (!$$settled);
${reactive_store_unsubscriptions}
return $$rendered;
`
: b `
${reactive_declarations}
${reactive_store_unsubscriptions}
return ${literal};`;
const blocks = [
...injected.map(name => b `let ${name};`),
rest,
slots,
...reactive_store_declarations,
...reactive_store_subscriptions,
instance_javascript,
...parent_bindings,
css.code && b `$$result.css.add(#css);`,
main
].filter(Boolean);
const css_sourcemap_enabled = check_enable_sourcemap(options.enableSourcemap, 'css');
const js = b `
${css.code ? b `
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 };
}
function trim(nodes) {
let start = 0;
for (; start < nodes.length; start += 1) {
const node = 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 = 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.mjs`.
Generated At: 2022-09-03T15:22:37.415Z
---------------------------------------------------------------------- */
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'
]);
const wrappers$1 = { esm, cjs };
function create_module(program, format, name, banner, sveltePath = 'svelte', helpers, globals, imports, module_exports, exports_from) {
const internal_path = `${sveltePath}/internal`;
helpers.sort((a, b) => (a.name < b.name) ? -1 : 1);
globals.sort((a, b) => (a.name < b.name) ? -1 : 1);
const formatter = wrappers$1[format];
if (!formatter) {
throw new Error(`options.format is invalid (must be ${list$1(Object.keys(wrappers$1))})`);
}
return formatter(program, name, banner, sveltePath, internal_path, helpers, globals, imports, module_exports, exports_from);
}
function edit_source(source, sveltePath) {
return source === 'svelte' || source.startsWith('svelte/')
? source.replace('svelte', sveltePath)
: source;
}
function get_internal_globals(globals, helpers) {
return globals.length > 0 && {
type: 'VariableDeclaration',
kind: 'const',
declarations: [{
type: 'VariableDeclarator',
id: {
type: 'ObjectPattern',
properties: globals.map(g => ({
type: 'Property',
method: false,
shorthand: false,
computed: false,
key: { type: 'Identifier', name: g.name },
value: g.alias,
kind: 'init'
}))
},
init: helpers.find(({ name }) => name === 'globals').alias
}]
};
}
function esm(program, name, banner, sveltePath, internal_path, helpers, globals, imports, module_exports, exports_from) {
const import_declaration = {
type: 'ImportDeclaration',
specifiers: helpers.map(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
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(x => ({
type: 'Specifier',
local: { type: 'Identifier', name: x.name },
exported: { type: 'Identifier', name: x.as }
}))
};
program.body = b `
/* ${banner} */
${import_declaration}
${internal_globals}
${imports}
${exports_from}
${program.body}
export default ${name};
${exports}
`;
}
function cjs(program, name, banner, sveltePath, internal_path, helpers, globals, imports, module_exports, exports_from) {
const internal_requires = {
type: 'VariableDeclaration',
kind: 'const',
declarations: [{
type: 'VariableDeclarator',
id: {
type: 'ObjectPattern',
properties: helpers.map(h => ({
type: 'Property',
method: false,
shorthand: false,
computed: false,
key: { type: 'Identifier', name: h.name },
value: h.alias,
kind: 'init'
}))
},
init: x `require("${internal_path}")`
}]
};
const internal_globals = get_internal_globals(globals, helpers);
const user_requires = imports.map(node => {
const init = x `require("${edit_source(node.source.value, sveltePath)}")`;
if (node.specifiers.length === 0) {
return b `${init};`;
}
return {
type: 'VariableDeclaration',
kind: 'const',
declarations: [{
type: 'VariableDeclarator',
id: node.specifiers[0].type === 'ImportNamespaceSpecifier'
? { type: 'Identifier', name: node.specifiers[0].local.name }
: {
type: 'ObjectPattern',
properties: node.specifiers.map(s => ({
type: 'Property',
method: false,
shorthand: false,
computed: false,
key: s.type === 'ImportSpecifier' ? s.imported : { type: 'Identifier', name: 'default' },
value: s.local,
kind: 'init'
}))
},
init
}]
};
});
const exports = module_exports.map(x => b `exports.${{ type: 'Identifier', name: x.as }} = ${{ type: 'Identifier', name: x.name }};`);
const user_exports_from = exports_from.map(node => {
const init = x `require("${edit_source(node.source.value, sveltePath)}")`;
return node.specifiers.map(specifier => {
return b `exports.${specifier.exported} = ${init}.${specifier.local};`;
});
});
program.body = b `
/* ${banner} */
"use strict";
${internal_requires}
${internal_globals}
${user_requires}
${user_exports_from}
${program.body}
exports.default = ${name};
${exports}
`;
}
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$2 = /*#__PURE__*/ getBtoa();
class SourceMap$1 {
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$2(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$2 = Object.prototype.toString;
function isObject(thing) {
return toString$2.call(thing) === '[object Object]';
}
function getLocator$1(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$1(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$1(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$1(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 = {};
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);
}
}
var BlockAppliesToNode;
(function (BlockAppliesToNode) {
BlockAppliesToNode[BlockAppliesToNode["NotPossible"] = 0] = "NotPossible";
BlockAppliesToNode[BlockAppliesToNode["Possible"] = 1] = "Possible";
BlockAppliesToNode[BlockAppliesToNode["UnknownSelectorType"] = 2] = "UnknownSelectorType";
})(BlockAppliesToNode || (BlockAppliesToNode = {}));
var NodeExist;
(function (NodeExist) {
NodeExist[NodeExist["Probably"] = 1] = "Probably";
NodeExist[NodeExist["Definitely"] = 2] = "Definitely";
})(NodeExist || (NodeExist = {}));
const whitelist_attribute_selector = new Map([
['details', new Set(['open'])],
['dialog', new Set(['open'])]
]);
const regex_is_single_css_selector = /[^\\],(?!([^([]+[^\\]|[^([\\])[)\]])/;
class Selector {
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;
}
apply(node) {
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;
}
}
minify(code) {
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;
});
}
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;
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);
}
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);
});
}
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);
}
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);
}
}
}
}
}
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)));
}
}
}
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;
}
}
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;
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;
}
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");
}
}
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;
}
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;
}
function get_element_parent(node) {
let parent = node;
while ((parent = parent.parent) && parent.type !== 'Element')
;
return parent;
}
function get_possible_element_siblings(node, adjacent_only) {
const result = new Map();
let prev = node;
while (prev = prev.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) {
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;
}
function get_possible_last_child(block, adjacent_only) {
const result = new Map();
if (block.type === 'EachBlock') {
const each_result = loop_child(block.children, adjacent_only);
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') {
const if_result = loop_child(block.children, adjacent_only);
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') {
const pending_result = block.pending ? loop_child(block.pending.children, adjacent_only) : new Map();
const then_result = block.then ? loop_child(block.then.children, adjacent_only) : new Map();
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;
}
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;
}
function add_to_map(from, to) {
from.forEach((exist, element) => {
to.set(element, higher_existence(exist, to.get(element)));
});
}
function higher_existence(exist1, exist2) {
if (exist1 === undefined || exist2 === undefined)
return exist1 || exist2;
return exist1 > exist2 ? exist1 : exist2;
}
function mark_as_probably(result) {
for (const key of result.keys()) {
result.set(key, NodeExist.Probably);
}
}
function loop_child(children, adjacent_only) {
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$1 {
constructor(combinator) {
this.combinator = combinator;
this.host = false;
this.root = false;
this.selectors = [];
this.start = null;
this.end = null;
this.should_encapsulate = false;
}
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'));
}
}
function group_selectors(selector) {
let block = new Block$1(null);
const blocks = [block];
selector.children.forEach((child) => {
if (child.type === 'WhiteSpace' || child.type === 'Combinator') {
block = new Block$1(child);
blocks.push(block);
}
else {
block.add(child);
}
});
return blocks;
}
const regex_css_browser_prefix = /^-((webkit)|(moz)|(o)|(ms))-/;
function remove_css_prefix(name) {
return name.replace(regex_css_browser_prefix, '');
}
const is_keyframes_node = (node) => remove_css_prefix(node.name) === 'keyframes';
const at_rule_has_declaration = ({ block }) => block &&
block.children &&
block.children.find((node) => node.type === 'Declaration');
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 {
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));
}
apply(node) {
this.selectors.forEach(selector => selector.apply(node)); // TODO move the logic in here?
}
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);
}
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);
}
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));
}
validate(component) {
this.selectors.forEach(selector => {
selector.validate(component);
});
}
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 {
constructor(node) {
this.node = node;
}
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));
}
}
});
}
}
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 {
constructor(node) {
this.node = node;
this.children = [];
this.declarations = [];
}
apply(node) {
if (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((rule) => {
rule.selectors.forEach(selector => {
selector.used = true;
});
});
}
}
is_used(_dev) {
return true; // TODO
}
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);
}
}
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((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);
});
}
validate(component) {
this.children.forEach(child => {
child.validate(component);
});
}
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()));
}
}
const get_default_css_hash = ({ css, hash }) => {
return `svelte-${hash(css)}`;
};
class Stylesheet {
constructor({ source, ast, component_name, filename, dev, get_css_hash = get_default_css_hash }) {
this.children = [];
this.keyframes = new Map();
this.nodes_with_css_class = new Set();
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;
const stack = [];
let depth = 0;
let current_atrule = null;
walk(ast.css, {
enter: (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$1(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: (node) => {
if (node.type === 'Atrule') {
stack.pop();
current_atrule = stack[stack.length - 1];
}
depth -= 1;
}
});
}
else {
this.has_styles = false;
}
}
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();
});
}
render(file, should_transform_selectors) {
if (!this.has_styles) {
return { code: null, map: null };
}
const code = new MagicString(this.source);
walk(this.ast.css, {
enter: (node) => {
code.addSourcemapLocation(node.start);
code.addSourcemapLocation(node.end);
}
});
if (should_transform_selectors) {
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
})
};
}
validate(component) {
this.children.forEach(child => {
child.validate(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();
}
}
const test = typeof process !== 'undefined' && process.env.TEST;
class TemplateScope {
constructor(parent) {
this.owners = new Map();
this.parent = parent;
this.names = new Set(parent ? parent.names : []);
this.dependencies_for_name = new Map(parent ? parent.dependencies_for_name : []);
}
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;
}
is_top_level(name) {
return !this.parent || !this.names.has(name) && this.parent.is_top_level(name);
}
get_owner(name) {
return this.owners.get(name) || (this.parent && this.parent.get_owner(name));
}
is_let(name) {
const owner = this.get_owner(name);
return owner && (owner.type === 'Element' || owner.type === 'InlineComponent' || owner.type === 'SlotTemplate');
}
is_await(name) {
const owner = this.get_owner(name);
return owner && (owner.type === 'ThenBlock' || owner.type === 'CatchBlock');
}
is_const(name) {
const owner = this.get_owner(name);
return owner && owner.type === 'ConstTag';
}
}
class Fragment extends Node$1 {
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", "SvelteComponent", "SvelteComponentDev", "SvelteComponentTyped", "SvelteElement", "action_destroyer", "add_attribute", "add_classes", "add_flush_callback", "add_location", "add_render_callback", "add_resize_listener", "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_component", "claim_element", "claim_html_tag", "claim_space", "claim_svg_element", "claim_text", "clear_loops", "component_subscribe", "compute_rest_props", "compute_slots", "construct_svelte_component", "construct_svelte_component_dev", "createEventDispatcher", "create_animation", "create_bidirectional_transition", "create_component", "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", "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", "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", "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_dev", "set_dynamic_element_data", "set_input_type", "set_input_value", "set_now", "set_raf", "set_store_value", "set_style", "set_svg_attributes", "space", "spread", "src_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_argument", "validate_each_keys", "validate_slots", "validate_store", "validate_void_dynamic_element", "xlink_attr"]);
function is_used_as_reference(node, parent) {
if (!is_reference(node, 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;
}
}
const regex_leading_directory_separator = /^[/\\]/;
const regex_starts_with_term_export = /^Export/;
const regex_contains_term_function = /Function/;
class Component {
constructor(ast, source, name, compile_options, stats, warnings) {
this.ignore_stack = [];
this.vars = [];
this.var_lookup = new Map();
this.imports = [];
this.exports_from = [];
this.instance_exports_from = [];
this.hoistable_nodes = new Set();
this.node_for_declaration = new Map();
this.partly_hoisted = [];
this.fully_hoisted = [];
this.reactive_declarations = [];
this.reactive_declaration_nodes = new Set();
this.has_reactive_assignments = false;
this.injected_reactive_declaration_vars = new Set();
this.helpers = new Map();
this.globals = new Map();
this.indirect_dependencies = new Map();
this.elements = [];
this.aliases = new Map();
this.used_names = new Set();
this.globally_used_names = new Set();
this.slots = new Map();
this.slot_outlets = new Set();
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);
this.locate = getLocator(this.source, { offsetLine: 1 });
// 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) {
if (this.component_options.tag === undefined &&
compile_options.tag === undefined) {
const svelteOptions = ast.html.children.find(child => child.name === 'svelte:options') || { start: 0, end: 0 };
this.warn(svelteOptions, compiler_warnings.custom_element_no_tag);
}
this.tag = this.component_options.tag || compile_options.tag;
}
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(element => this.stylesheet.apply(element));
if (!compile_options.customElement)
this.stylesheet.reify();
this.stylesheet.warn_on_unused_selectors(this);
}
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(node, compiler_errors.illegal_variable_declaration);
}
}
this.var_lookup.set(variable.name, variable);
}
}
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);
}
}
alias(name) {
if (!this.aliases.has(name)) {
this.aliases.set(name, this.get_unique_name(name));
}
return this.aliases.get(name);
}
apply_stylesheet(element) {
this.elements.push(element);
}
global(name) {
const alias = this.alias(name);
this.globals.set(name, alias);
return alias;
}
generate(result) {
let js = null;
let css = null;
if (result) {
const { compile_options, name } = this;
const { format = 'esm' } = compile_options;
const banner = `${this.file ? `${this.file} ` : ''}generated by Svelte v${'3.56.0'}`;
const program = { type: 'Program', body: result.js };
walk(program, {
enter: (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
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, ([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, ([name, alias]) => ({
name,
alias
}));
create_module(program, format, name, banner, compile_options.sveltePath, imported_helpers, referenced_globals, this.imports, this.vars
.filter(variable => variable.module && variable.export_name)
.map(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, compile_options.sourcemap);
}
}
return {
js,
css,
ast: this.original_ast,
warnings: this.warnings,
vars: this.get_vars_report(),
stats: this.stats.render()
};
}
get_unique_name(name, scope) {
if (test)
name = `${name}$`;
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();
function add(name) {
local_used_names.add(name);
}
reserved.forEach(add);
internal_exports.forEach(add);
this.var_lookup.forEach((_value, key) => add(key));
return (name) => {
if (test)
name = `${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
};
};
}
get_vars_report() {
const { compile_options, vars } = this;
const vars_report = compile_options.varsReport === false
? []
: compile_options.varsReport === 'full'
? vars
: vars.filter(v => !v.global && !v.internal);
return vars_report.map(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
}));
}
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
});
}
}
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}`
});
}
extract_imports(node) {
this.imports.push(node);
}
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;
}
_extract_exports(node, module_script) {
if (node.type === 'ExportDefaultDeclaration') {
return this.error(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(declarator => {
extract_names(declarator.id).forEach(name => {
const variable = this.var_lookup.get(name);
variable.export_name = name;
if (!module_script && variable.writable && !(variable.referenced || variable.referenced_from_script || variable.subscribable)) {
this.warn(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(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(specifier, compiler_warnings.unused_export_let(this.name.name, specifier.exported.name));
}
}
});
return null;
}
}
}
extract_javascript(script) {
if (!script)
return null;
return script.content.body.filter(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, {
enter(node) {
if (node.type === 'LabeledStatement' && node.label.name === '$') {
component.warn(node, compiler_warnings.module_script_reactive_declaration);
}
}
});
const { scope, globals } = create_scopes(script.content);
this.module_scope = scope;
scope.declarations.forEach((node, name) => {
if (name[0] === '$') {
return this.error(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((node, name) => {
if (name[0] === '$') {
return this.error(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(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(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((node, name) => {
if (name[0] === '$') {
return this.error(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(key => key[0] !== '$'),
...global_keys.filter(key => key[0] === '$')
];
sorted_globals.forEach(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(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();
}
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 = [];
const remove = (parent, prop, index) => {
to_remove.unshift([parent, prop, index]);
};
let scope_updated = false;
const current_function_stack = [];
let current_function = null;
walk(content, {
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;
let names = [];
if (node.type === 'AssignmentExpression') {
if (node.left.type === 'ArrayPattern') {
walk(node.left, {
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(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 && declaration.kind === 'const' && !deep) {
component.error(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);
},
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, {
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(assignee);
const deep = assignee.type === 'MemberExpression';
names.forEach(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;
}
}
},
leave(node) {
if (map.has(node)) {
scope = scope.parent;
}
}
});
}
warn_on_undefined_store_value_references(node, parent, prop, scope) {
if (node.type === 'LabeledStatement' &&
node.label.name === '$' &&
parent.type !== 'Program') {
this.warn(node, compiler_warnings.non_top_level_reactive_declaration);
}
if (is_reference(node, 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(node, compiler_errors.contextual_store);
}
}
}
}
}
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 `const ${guard} = @loop_guard(${timeout})`;
const inside = b `${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;
}
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, {
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 = [];
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') {
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;
}
function rename_identifiers(param) {
switch (param.type) {
case 'ObjectPattern': {
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(prop.value);
}
};
param.properties.forEach(handle_prop);
break;
}
case 'ArrayPattern': {
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':
param.argument = get_new_name(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(b `
${node.declarations.length ? node : null}
${props.length > 0 && b `let { ${props} } = $$props;`}
${inserts}
`);
return this.skip();
}
}
},
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(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 } = 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(variable => variable.name === name && variable.module)) {
return false;
}
return true;
});
if (all_hoistable) {
node.declarations.forEach(d => {
const variable = this.var_lookup.get(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();
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, {
enter(node, parent) {
if (!hoistable)
return this.skip();
if (map.has(node)) {
scope = map.get(node);
}
if (is_reference(node, 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();
}
},
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;
const unsorted_reactive_declarations = [];
this.ast.instance.content.body.forEach(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 map = this.instance_scope_map;
walk(node.body, {
enter(node, parent) {
if (map.has(node)) {
scope = map.get(node);
}
if (node.type === 'AssignmentExpression') {
const left = get_object(node.left);
extract_identifiers(left).forEach(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(node, 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);
}
}
if (should_add_as_dependency &&
(!owner || owner === component.instance_scope) &&
(name[0] === '$' || variable)) {
dependencies.add(name);
}
}
this.skip();
}
},
leave(node) {
if (map.has(node)) {
scope = scope.parent;
}
}
});
if (module_dependencies.size > 0 && dependencies.size === 0) {
component.warn(node.body, compiler_warnings.module_script_variable_reactive_declaration(Array.from(module_dependencies)));
}
const { expression } = node.body;
const declaration = expression && expression.left;
const is_dependency_static = Array.from(dependencies).every(dependency => dependency !== '$$props' && dependency !== '$$restProps' && !is_dynamic(this.var_lookup.get(dependency)));
if (is_dependency_static) {
assignees.forEach(assignee => {
const variable = component.var_lookup.get(assignee);
if (variable) {
variable.is_reactive_static = true;
}
});
}
unsorted_reactive_declarations.push({
assignees,
dependencies,
node,
declaration
});
}
if (ignores.length)
this.pop_ignores();
});
const lookup = new Map();
unsorted_reactive_declarations.forEach(declaration => {
declaration.assignees.forEach(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((acc, declaration) => {
declaration.assignees.forEach(v => {
declaration.dependencies.forEach(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));
}
const add_declaration = declaration => {
if (this.reactive_declarations.includes(declaration))
return;
declaration.dependencies.forEach(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);
}
warn_if_undefined(name, node, template_scope) {
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;
this.warn(node, compiler_warnings.missing_declaration(name, !!this.ast.instance));
}
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-]+$/;
function process_component_options(component, nodes) {
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(node => node.name === 'svelte:options');
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(attribute => {
if (attribute.type === 'Attribute') {
const { name } = attribute;
switch (name) {
case 'tag': {
const tag = get_value(attribute, compiler_errors.invalid_tag_attribute);
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.tag = tag;
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);
}
}
else {
return component.error(attribute, compiler_errors.invalid_options_attribute);
}
});
}
return component_options;
}
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('/');
}
function get_basename(filename) {
return filename.split(/[/\\]/).pop();
}
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);
}
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 = /^_?(.+?)_?$/;
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 = [
'format',
'name',
'filename',
'sourcemap',
'enableSourcemap',
'generate',
'errorMode',
'varsReport',
'outputFilename',
'cssOutputFilename',
'sveltePath',
'dev',
'accessors',
'immutable',
'hydratable',
'legacy',
'customElement',
'namespace',
'tag',
'css',
'loopGuardTimeout',
'preserveComments',
'preserveWhitespace',
'cssHash'
];
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]/;
function validate_options(options, warnings) {
const { name, filename, loopGuardTimeout, dev, namespace, css } = options;
Object.keys(options).forEach(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 (valid_css_values.indexOf(css) === -1) {
throw new Error(`options.css must be true, false, 'injected', 'external', or 'none' (got '${css}')`);
}
if (css === true || css === false) {
options.css = css === true ? 'injected' : 'external';
// possibly show this warning once we decided how Svelte 4 looks like
// const message = `options.css as a boolean is deprecated. Use '${options.css}' instead of ${css}.`;
// warnings.push({
// code: 'options-css-boolean-deprecated',
// message,
// filename,
// toString: () => message
// });
// }
}
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}'`);
}
}
}
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$J(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.
*/
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;
}
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(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;
}
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
};
}
function calculate_replacements(re, get_replacement, source) {
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);
}
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);
}
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 = /[/\\]/;
function get_file_basename(filename) {
return filename.split(regex_filepath_separator).pop();
}
/**
* Represents intermediate states of the preprocessing.
*/
class PreprocessResult {
constructor(source, filename) {
this.source = source;
this.filename = 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
this.sourcemap_list = [];
this.dependencies = [];
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);
}
update_source({ string: source, map, dependencies }) {
if (source != null) {
this.source = source;
this.get_location = getLocator(source);
}
if (map) {
this.sourcemap_list.unshift(map);
}
if (dependencies) {
this.dependencies.push(...dependencies);
}
}
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: map,
toString: () => this.source
};
}
}
/**
* Convert preprocessor output for the tag content into MappedCode
*/
function processed_content_to_code(processed, location, file_basename) {
// Convert the preprocessed code and its sourcemap to a MappedCode
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`.
*/
function processed_tag_to_code(processed, tag_name, attributes, source) {
const { file_basename, get_location } = source;
const build_mapped_code = (code, offset) => MappedCode.from_source(slice_source(code, offset, source));
const tag_open = `<${tag_name}${attributes || ''}>`;
const tag_close = `</${tag_name}>`;
const tag_open_code = build_mapped_code(tag_open, 0);
const tag_close_code = build_mapped_code(tag_close, tag_open.length + source.source.length);
parse_attached_sourcemap(processed, tag_name);
const content_code = processed_content_to_code(processed, get_location(tag_open.length), file_basename);
return tag_open_code.concat(content_code).concat(tag_close_code);
}
const regex_quoted_value = /^['"](.*)['"]$/;
function parse_tag_attributes(str) {
// note: won't work with attribute values containing spaces.
return str
.split(regex_whitespaces)
.filter(Boolean)
.reduce((attrs, attr) => {
var _a;
const i = attr.indexOf('=');
const [key, value] = i > 0 ? [attr.slice(0, i), attr.slice(i + 1)] : [attr];
const [, unquoted] = (value && value.match(regex_quoted_value)) || [];
return Object.assign(Object.assign({}, attrs), { [key]: (_a = unquoted !== null && unquoted !== void 0 ? unquoted : value) !== null && _a !== void 0 ? _a : true });
}, {});
}
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.
*/
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;
const dependencies = [];
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, slice_source(content, tag_offset, source));
}
const { string, map } = await replace_in_code(tag_regex, process_single_tag, source);
return { string, map, dependencies };
}
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 {};
}
}
async function preprocess(source, preprocessor, options) {
const filename = (options && options.filename) || preprocessor.filename; // legacy
const preprocessors = preprocessor ? (Array.isArray(preprocessor) ? preprocessor : [preprocessor]) : [];
const markup = preprocessors.map(p => p.markup).filter(Boolean);
const script = preprocessors.map(p => p.script).filter(Boolean);
const style = preprocessors.map(p => p.style).filter(Boolean);
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 process of markup) {
result.update_source(await process_markup(process, result));
}
for (const process of script) {
result.update_source(await process_tag('script', process, result));
}
for (const preprocess of style) {
result.update_source(await process_tag('style', preprocess, result));
}
return result.to_processed();
}
const VERSION = '3.56.0';
// additional exports added through generate-type-definitions.js
exports.VERSION = VERSION;
exports.compile = compile;
exports.parse = parse$J;
exports.preprocess = preprocess;
exports.walk = walk;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=compiler.js.map