Path: blob/main/src/resources/formats/html/ojs/quarto-ojs-runtime.js
12923 views
// quarto-ojs-runtime v0.0.18 Copyright 2024 undefined1var EOL = {},2EOF = {},3QUOTE = 34,4NEWLINE = 10,5RETURN = 13;67function objectConverter(columns) {8return new Function("d", "return {" + columns.map(function(name, i) {9return JSON.stringify(name) + ": d[" + i + "] || \"\"";10}).join(",") + "}");11}1213function customConverter(columns, f) {14var object = objectConverter(columns);15return function(row, i) {16return f(object(row), i, columns);17};18}1920// Compute unique columns in order of discovery.21function inferColumns(rows) {22var columnSet = Object.create(null),23columns = [];2425rows.forEach(function(row) {26for (var column in row) {27if (!(column in columnSet)) {28columns.push(columnSet[column] = column);29}30}31});3233return columns;34}3536function pad$1(value, width) {37var s = value + "", length = s.length;38return length < width ? new Array(width - length + 1).join(0) + s : s;39}4041function formatYear$1(year) {42return year < 0 ? "-" + pad$1(-year, 6)43: year > 9999 ? "+" + pad$1(year, 6)44: pad$1(year, 4);45}4647function formatDate$2(date) {48var hours = date.getUTCHours(),49minutes = date.getUTCMinutes(),50seconds = date.getUTCSeconds(),51milliseconds = date.getUTCMilliseconds();52return isNaN(date) ? "Invalid Date"53: formatYear$1(date.getUTCFullYear()) + "-" + pad$1(date.getUTCMonth() + 1, 2) + "-" + pad$1(date.getUTCDate(), 2)54+ (milliseconds ? "T" + pad$1(hours, 2) + ":" + pad$1(minutes, 2) + ":" + pad$1(seconds, 2) + "." + pad$1(milliseconds, 3) + "Z"55: seconds ? "T" + pad$1(hours, 2) + ":" + pad$1(minutes, 2) + ":" + pad$1(seconds, 2) + "Z"56: minutes || hours ? "T" + pad$1(hours, 2) + ":" + pad$1(minutes, 2) + "Z"57: "");58}5960function dsv$1(delimiter) {61var reFormat = new RegExp("[\"" + delimiter + "\n\r]"),62DELIMITER = delimiter.charCodeAt(0);6364function parse(text, f) {65var convert, columns, rows = parseRows(text, function(row, i) {66if (convert) return convert(row, i - 1);67columns = row, convert = f ? customConverter(row, f) : objectConverter(row);68});69rows.columns = columns || [];70return rows;71}7273function parseRows(text, f) {74var rows = [], // output rows75N = text.length,76I = 0, // current character index77n = 0, // current line number78t, // current token79eof = N <= 0, // current token followed by EOF?80eol = false; // current token followed by EOL?8182// Strip the trailing newline.83if (text.charCodeAt(N - 1) === NEWLINE) --N;84if (text.charCodeAt(N - 1) === RETURN) --N;8586function token() {87if (eof) return EOF;88if (eol) return eol = false, EOL;8990// Unescape quotes.91var i, j = I, c;92if (text.charCodeAt(j) === QUOTE) {93while (I++ < N && text.charCodeAt(I) !== QUOTE || text.charCodeAt(++I) === QUOTE);94if ((i = I) >= N) eof = true;95else if ((c = text.charCodeAt(I++)) === NEWLINE) eol = true;96else if (c === RETURN) { eol = true; if (text.charCodeAt(I) === NEWLINE) ++I; }97return text.slice(j + 1, i - 1).replace(/""/g, "\"");98}99100// Find next delimiter or newline.101while (I < N) {102if ((c = text.charCodeAt(i = I++)) === NEWLINE) eol = true;103else if (c === RETURN) { eol = true; if (text.charCodeAt(I) === NEWLINE) ++I; }104else if (c !== DELIMITER) continue;105return text.slice(j, i);106}107108// Return last token before EOF.109return eof = true, text.slice(j, N);110}111112while ((t = token()) !== EOF) {113var row = [];114while (t !== EOL && t !== EOF) row.push(t), t = token();115if (f && (row = f(row, n++)) == null) continue;116rows.push(row);117}118119return rows;120}121122function preformatBody(rows, columns) {123return rows.map(function(row) {124return columns.map(function(column) {125return formatValue(row[column]);126}).join(delimiter);127});128}129130function format(rows, columns) {131if (columns == null) columns = inferColumns(rows);132return [columns.map(formatValue).join(delimiter)].concat(preformatBody(rows, columns)).join("\n");133}134135function formatBody(rows, columns) {136if (columns == null) columns = inferColumns(rows);137return preformatBody(rows, columns).join("\n");138}139140function formatRows(rows) {141return rows.map(formatRow).join("\n");142}143144function formatRow(row) {145return row.map(formatValue).join(delimiter);146}147148function formatValue(value) {149return value == null ? ""150: value instanceof Date ? formatDate$2(value)151: reFormat.test(value += "") ? "\"" + value.replace(/"/g, "\"\"") + "\""152: value;153}154155return {156parse: parse,157parseRows: parseRows,158format: format,159formatBody: formatBody,160formatRows: formatRows,161formatRow: formatRow,162formatValue: formatValue163};164}165166var csv = dsv$1(",");167168var csvParse = csv.parse;169var csvParseRows = csv.parseRows;170171var tsv = dsv$1("\t");172173var tsvParse = tsv.parse;174var tsvParseRows = tsv.parseRows;175176function autoType(object) {177for (var key in object) {178var value = object[key].trim(), number, m;179if (!value) value = null;180else if (value === "true") value = true;181else if (value === "false") value = false;182else if (value === "NaN") value = NaN;183else if (!isNaN(number = +value)) value = number;184else if (m = value.match(/^([-+]\d{2})?\d{4}(-\d{2}(-\d{2})?)?(T\d{2}:\d{2}(:\d{2}(\.\d{3})?)?(Z|[-+]\d{2}:\d{2})?)?$/)) {185if (fixtz && !!m[4] && !m[7]) value = value.replace(/-/g, "/").replace(/T/, " ");186value = new Date(value);187}188else continue;189object[key] = value;190}191return object;192}193194// https://github.com/d3/d3-dsv/issues/45195const fixtz = new Date("2019-01-01T00:00").getHours() || new Date("2019-07-01T00:00").getHours();196197function dependency(name, version, main) {198return {199resolve(path = main) {200return `${name}@${version}/${path}`;201}202};203}204205const d3 = dependency("d3", "7.8.5", "dist/d3.min.js");206const inputs = dependency("@observablehq/inputs", "0.10.6", "dist/inputs.min.js");207const plot = dependency("@observablehq/plot", "0.6.11", "dist/plot.umd.min.js");208const graphviz = dependency("@observablehq/graphviz", "0.2.1", "dist/graphviz.min.js");209const highlight = dependency("@observablehq/highlight.js", "2.0.0", "highlight.min.js");210const katex = dependency("@observablehq/katex", "0.11.1", "dist/katex.min.js");211const lodash = dependency("lodash", "4.17.21", "lodash.min.js");212const htl = dependency("htl", "0.3.1", "dist/htl.min.js");213const jszip = dependency("jszip", "3.10.1", "dist/jszip.min.js");214const marked = dependency("marked", "0.3.12", "marked.min.js");215const sql = dependency("sql.js", "1.8.0", "dist/sql-wasm.js");216const vega = dependency("vega", "5.22.1", "build/vega.min.js");217const vegalite = dependency("vega-lite", "5.6.0", "build/vega-lite.min.js");218const vegaliteApi = dependency("vega-lite-api", "5.0.0", "build/vega-lite-api.min.js");219const arrow4 = dependency("apache-arrow", "4.0.1", "Arrow.es2015.min.js");220const arrow9 = dependency("apache-arrow", "9.0.0", "+esm");221const arrow11 = dependency("apache-arrow", "11.0.0", "+esm");222const arquero = dependency("arquero", "4.8.8", "dist/arquero.min.js");223const topojson = dependency("topojson-client", "3.1.0", "dist/topojson-client.min.js");224const exceljs = dependency("exceljs", "4.3.0", "dist/exceljs.min.js");225const mermaid$1 = dependency("mermaid", "9.2.2", "dist/mermaid.min.js");226const leaflet$1 = dependency("leaflet", "1.9.3", "dist/leaflet.js");227const duckdb = dependency("@duckdb/duckdb-wasm", "1.24.0", "+esm");228229const metas = new Map;230const queue$1 = [];231const map$2 = queue$1.map;232const some = queue$1.some;233const hasOwnProperty$2 = queue$1.hasOwnProperty;234const identifierRe = /^((?:@[^/@]+\/)?[^/@]+)(?:@([^/]+))?(?:\/(.*))?$/;235const versionRe = /^\d+\.\d+\.\d+(-[\w-.+]+)?$/;236const extensionRe = /(?:\.[^/]*|\/)$/;237238class RequireError extends Error {239constructor(message) {240super(message);241}242}243244RequireError.prototype.name = RequireError.name;245246function parseIdentifier(identifier) {247const match = identifierRe.exec(identifier);248return match && {249name: match[1],250version: match[2],251path: match[3]252};253}254255function resolveFrom(origin = "https://cdn.jsdelivr.net/npm/", mains = ["unpkg", "jsdelivr", "browser", "main"]) {256if (!/\/$/.test(origin)) throw new Error("origin lacks trailing slash");257258function main(meta) {259for (const key of mains) {260let value = meta[key];261if (typeof value === "string") {262if (value.startsWith("./")) value = value.slice(2);263return extensionRe.test(value) ? value : `${value}.js`;264}265}266}267268function resolveMeta(target) {269const url = `${origin}${target.name}${target.version ? `@${target.version}` : ""}/package.json`;270let meta = metas.get(url);271if (!meta) metas.set(url, meta = fetch(url).then(response => {272if (!response.ok) throw new RequireError("unable to load package.json");273if (response.redirected && !metas.has(response.url)) metas.set(response.url, meta);274return response.json();275}));276return meta;277}278279return async function resolve(name, base) {280if (name.startsWith(origin)) name = name.substring(origin.length);281if (/^(\w+:)|\/\//i.test(name)) return name;282if (/^[.]{0,2}\//i.test(name)) return new URL(name, base == null ? location : base).href;283if (!name.length || /^[\s._]/.test(name) || /\s$/.test(name)) throw new RequireError("illegal name");284const target = parseIdentifier(name);285if (!target) return `${origin}${name}`;286if (!target.version && base != null && base.startsWith(origin)) {287const meta = await resolveMeta(parseIdentifier(base.substring(origin.length)));288target.version = meta.dependencies && meta.dependencies[target.name] || meta.peerDependencies && meta.peerDependencies[target.name];289}290if (target.path && !extensionRe.test(target.path)) target.path += ".js";291if (target.path && target.version && versionRe.test(target.version)) return `${origin}${target.name}@${target.version}/${target.path}`;292const meta = await resolveMeta(target);293return `${origin}${meta.name}@${meta.version}/${target.path || main(meta) || "index.js"}`;294};295}296297var require = requireFrom(resolveFrom());298let requestsInFlight = 0;299let prevDefine = undefined;300301function requireFrom(resolver) {302const cache = new Map;303const requireBase = requireRelative(null);304305function requireAbsolute(url) {306if (typeof url !== "string") return url;307let module = cache.get(url);308if (!module) cache.set(url, module = new Promise((resolve, reject) => {309const script = document.createElement("script");310script.onload = () => {311try { resolve(queue$1.pop()(requireRelative(url))); }312catch (error) { reject(new RequireError("invalid module")); }313script.remove();314requestsInFlight--;315if (requestsInFlight === 0) {316window.define = prevDefine;317}318};319script.onerror = () => {320reject(new RequireError("unable to load module"));321script.remove();322requestsInFlight--;323if (requestsInFlight === 0) {324window.define = prevDefine;325}326};327script.async = true;328script.src = url;329if (requestsInFlight === 0) {330prevDefine = window.define;331window.define = define;332}333requestsInFlight++;334335document.head.appendChild(script);336}));337return module;338}339340function requireRelative(base) {341return name => Promise.resolve(resolver(name, base)).then(requireAbsolute);342}343344function requireAlias(aliases) {345return requireFrom((name, base) => {346if (name in aliases) {347name = aliases[name], base = null;348if (typeof name !== "string") return name;349}350return resolver(name, base);351});352}353354function require(name) {355return arguments.length > 1356? Promise.all(map$2.call(arguments, requireBase)).then(merge$1)357: requireBase(name);358}359360require.alias = requireAlias;361require.resolve = resolver;362363return require;364}365366function merge$1(modules) {367const o = {};368for (const m of modules) {369for (const k in m) {370if (hasOwnProperty$2.call(m, k)) {371if (m[k] == null) Object.defineProperty(o, k, {get: getter(m, k)});372else o[k] = m[k];373}374}375}376return o;377}378379function getter(object, name) {380return () => object[name];381}382383function isbuiltin(name) {384name = name + "";385return name === "exports" || name === "module";386}387388function define(name, dependencies, factory) {389const n = arguments.length;390if (n < 2) factory = name, dependencies = [];391else if (n < 3) factory = dependencies, dependencies = typeof name === "string" ? [] : name;392queue$1.push(some.call(dependencies, isbuiltin) ? require => {393const exports = {};394const module = {exports};395return Promise.all(map$2.call(dependencies, name => {396name = name + "";397return name === "exports" ? exports : name === "module" ? module : require(name);398})).then(dependencies => {399factory.apply(null, dependencies);400return module.exports;401});402} : require => {403return Promise.all(map$2.call(dependencies, require)).then(dependencies => {404return typeof factory === "function" ? factory.apply(null, dependencies) : factory;405});406});407}408409define.amd = {};410411// TODO Allow this to be overridden using the Library’s resolver.412const cdn = "https://cdn.observableusercontent.com/npm/";413414let requireDefault = require;415416function setDefaultRequire(require) {417requireDefault = require;418}419420function requirer(resolver) {421return resolver == null ? requireDefault : requireFrom(resolver);422}423424function fromEntries(obj) {425const result = {};426for (const [key, value] of obj) {427result[key] = value;428}429return result;430}431432async function SQLite(require) {433const [init, dist] = await Promise.all([require(sql.resolve()), require.resolve(sql.resolve("dist/"))]);434return init({locateFile: file => `${dist}${file}`});435}436437class SQLiteDatabaseClient {438constructor(db) {439Object.defineProperties(this, {440_db: {value: db}441});442}443static async open(source) {444const [SQL, buffer] = await Promise.all([SQLite(requireDefault), Promise.resolve(source).then(load$1)]);445return new SQLiteDatabaseClient(new SQL.Database(buffer));446}447async query(query, params) {448return await exec(this._db, query, params);449}450async queryRow(query, params) {451return (await this.query(query, params))[0] || null;452}453async explain(query, params) {454const rows = await this.query(`EXPLAIN QUERY PLAN ${query}`, params);455return element$1("pre", {className: "observablehq--inspect"}, [456text$2(rows.map(row => row.detail).join("\n"))457]);458}459async describeTables({schema} = {}) {460return this.query(`SELECT NULLIF(schema, 'main') AS schema, name FROM pragma_table_list() WHERE type = 'table'${schema == null ? "" : ` AND schema = ?`} AND name NOT LIKE 'sqlite_%' ORDER BY schema, name`, schema == null ? [] : [schema]);461}462async describeColumns({schema, table} = {}) {463if (table == null) throw new Error(`missing table`);464const rows = await this.query(`SELECT name, type, "notnull" FROM pragma_table_info(?${schema == null ? "" : `, ?`}) ORDER BY cid`, schema == null ? [table] : [table, schema]);465if (!rows.length) throw new Error(`table not found: ${table}`);466return rows.map(({name, type, notnull}) => ({name, type: sqliteType(type), databaseType: type, nullable: !notnull}));467}468async describe(object) {469const rows = await (object === undefined470? this.query(`SELECT name FROM sqlite_master WHERE type = 'table'`)471: this.query(`SELECT * FROM pragma_table_info(?)`, [object]));472if (!rows.length) throw new Error("Not found");473const {columns} = rows;474return element$1("table", {value: rows}, [475element$1("thead", [element$1("tr", columns.map(c => element$1("th", [text$2(c)])))]),476element$1("tbody", rows.map(r => element$1("tr", columns.map(c => element$1("td", [text$2(r[c])])))))477]);478}479async sql() {480return this.query(...this.queryTag.apply(this, arguments));481}482queryTag(strings, ...params) {483return [strings.join("?"), params];484}485}486487Object.defineProperty(SQLiteDatabaseClient.prototype, "dialect", {488value: "sqlite"489});490491// https://www.sqlite.org/datatype3.html492function sqliteType(type) {493switch (type) {494case "NULL":495return "null";496case "INT":497case "INTEGER":498case "TINYINT":499case "SMALLINT":500case "MEDIUMINT":501case "BIGINT":502case "UNSIGNED BIG INT":503case "INT2":504case "INT8":505return "integer";506case "TEXT":507case "CLOB":508return "string";509case "REAL":510case "DOUBLE":511case "DOUBLE PRECISION":512case "FLOAT":513case "NUMERIC":514return "number";515case "BLOB":516return "buffer";517case "DATE":518case "DATETIME":519return "string"; // TODO convert strings to Date instances in sql.js520default:521return /^(?:(?:(?:VARYING|NATIVE) )?CHARACTER|(?:N|VAR|NVAR)CHAR)\(/.test(type) ? "string"522: /^(?:DECIMAL|NUMERIC)\(/.test(type) ? "number"523: "other";524}525}526527function load$1(source) {528return typeof source === "string" ? fetch(source).then(load$1)529: source instanceof Response || source instanceof Blob ? source.arrayBuffer().then(load$1)530: source instanceof ArrayBuffer ? new Uint8Array(source)531: source;532}533534async function exec(db, query, params) {535const [result] = await db.exec(query, params);536if (!result) return [];537const {columns, values} = result;538const rows = values.map(row => fromEntries(row.map((value, i) => [columns[i], value])));539rows.columns = columns;540return rows;541}542543function element$1(name, props, children) {544if (arguments.length === 2) children = props, props = undefined;545const element = document.createElement(name);546if (props !== undefined) for (const p in props) element[p] = props[p];547if (children !== undefined) for (const c of children) element.appendChild(c);548return element;549}550551function text$2(value) {552return document.createTextNode(value);553}554555function ascending(a, b) {556return a == null || b == null ? NaN : a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;557}558559function descending(a, b) {560return a == null || b == null ? NaN561: b < a ? -1562: b > a ? 1563: b >= a ? 0564: NaN;565}566567function bisector(f) {568let compare1, compare2, delta;569570// If an accessor is specified, promote it to a comparator. In this case we571// can test whether the search value is (self-) comparable. We can’t do this572// for a comparator (except for specific, known comparators) because we can’t573// tell if the comparator is symmetric, and an asymmetric comparator can’t be574// used to test whether a single value is comparable.575if (f.length !== 2) {576compare1 = ascending;577compare2 = (d, x) => ascending(f(d), x);578delta = (d, x) => f(d) - x;579} else {580compare1 = f === ascending || f === descending ? f : zero;581compare2 = f;582delta = f;583}584585function left(a, x, lo = 0, hi = a.length) {586if (lo < hi) {587if (compare1(x, x) !== 0) return hi;588do {589const mid = (lo + hi) >>> 1;590if (compare2(a[mid], x) < 0) lo = mid + 1;591else hi = mid;592} while (lo < hi);593}594return lo;595}596597function right(a, x, lo = 0, hi = a.length) {598if (lo < hi) {599if (compare1(x, x) !== 0) return hi;600do {601const mid = (lo + hi) >>> 1;602if (compare2(a[mid], x) <= 0) lo = mid + 1;603else hi = mid;604} while (lo < hi);605}606return lo;607}608609function center(a, x, lo = 0, hi = a.length) {610const i = left(a, x, lo, hi - 1);611return i > lo && delta(a[i - 1], x) > -delta(a[i], x) ? i - 1 : i;612}613614return {left, center, right};615}616617function zero() {618return 0;619}620621function number(x) {622return x === null ? NaN : +x;623}624625bisector(ascending);626bisector(number).center;627628function greatest(values, compare = ascending) {629let max;630let defined = false;631if (compare.length === 1) {632let maxValue;633for (const element of values) {634const value = compare(element);635if (defined636? ascending(value, maxValue) > 0637: ascending(value, value) === 0) {638max = element;639maxValue = value;640defined = true;641}642}643} else {644for (const value of values) {645if (defined646? compare(value, max) > 0647: compare(value, value) === 0) {648max = value;649defined = true;650}651}652}653return max;654}655656function reverse(values) {657if (typeof values[Symbol.iterator] !== "function") throw new TypeError("values is not iterable");658return Array.from(values).reverse();659}660661function isArqueroTable(value) {662// Arquero tables have a `toArrowBuffer` function663return value && typeof value.toArrowBuffer === "function";664}665666// Returns true if the vaue is an Apache Arrow table. This uses a “duck” test667// (instead of strict instanceof) because we want it to work with a range of668// Apache Arrow versions at least 7.0.0 or above.669// https://arrow.apache.org/docs/7.0/js/classes/Arrow_dom.Table.html670function isArrowTable(value) {671return (672value &&673typeof value.getChild === "function" &&674typeof value.toArray === "function" &&675value.schema &&676Array.isArray(value.schema.fields)677);678}679680function getArrowTableSchema(table) {681return table.schema.fields.map(getArrowFieldSchema);682}683684function getArrowFieldSchema(field) {685return {686name: field.name,687type: getArrowType(field.type),688nullable: field.nullable,689databaseType: String(field.type)690};691}692693// https://github.com/apache/arrow/blob/89f9a0948961f6e94f1ef5e4f310b707d22a3c11/js/src/enum.ts#L140-L141694function getArrowType(type) {695switch (type.typeId) {696case 2: // Int697return "integer";698case 3: // Float699case 7: // Decimal700return "number";701case 4: // Binary702case 15: // FixedSizeBinary703return "buffer";704case 5: // Utf8705return "string";706case 6: // Bool707return "boolean";708case 8: // Date709case 9: // Time710case 10: // Timestamp711return "date";712case 12: // List713case 16: // FixedSizeList714return "array";715case 13: // Struct716case 14: // Union717return "object";718case 11: // Interval719case 17: // Map720default:721return "other";722}723}724725async function loadArrow() {726return await import(`${cdn}${arrow11.resolve()}`);727}728729// Adapted from https://observablehq.com/@cmudig/duckdb-client730// Copyright 2021 CMU Data Interaction Group731//732// Redistribution and use in source and binary forms, with or without733// modification, are permitted provided that the following conditions are met:734//735// 1. Redistributions of source code must retain the above copyright notice,736// this list of conditions and the following disclaimer.737//738// 2. Redistributions in binary form must reproduce the above copyright notice,739// this list of conditions and the following disclaimer in the documentation740// and/or other materials provided with the distribution.741//742// 3. Neither the name of the copyright holder nor the names of its contributors743// may be used to endorse or promote products derived from this software744// without specific prior written permission.745//746// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"747// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE748// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE749// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE750// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR751// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF752// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS753// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN754// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)755// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE756// POSSIBILITY OF SUCH DAMAGE.757758let promise;759760class DuckDBClient {761constructor(db) {762Object.defineProperties(this, {763_db: {value: db}764});765}766767async queryStream(query, params) {768const connection = await this._db.connect();769let reader, batch;770try {771if (params?.length > 0) {772const statement = await connection.prepare(query);773reader = await statement.send(...params);774} else {775reader = await connection.send(query);776}777batch = await reader.next();778if (batch.done) throw new Error("missing first batch");779} catch (error) {780await connection.close();781throw error;782}783return {784schema: getArrowTableSchema(batch.value),785async *readRows() {786try {787while (!batch.done) {788yield batch.value.toArray();789batch = await reader.next();790}791} finally {792await connection.close();793}794}795};796}797798async query(query, params) {799const result = await this.queryStream(query, params);800const results = [];801for await (const rows of result.readRows()) {802for (const row of rows) {803results.push(row);804}805}806results.schema = result.schema;807return results;808}809810async queryRow(query, params) {811const result = await this.queryStream(query, params);812const reader = result.readRows();813try {814const {done, value} = await reader.next();815return done || !value.length ? null : value[0];816} finally {817await reader.return();818}819}820821async sql(strings, ...args) {822return await this.query(strings.join("?"), args);823}824825queryTag(strings, ...params) {826return [strings.join("?"), params];827}828829escape(name) {830return `"${name}"`;831}832833async describeTables() {834const tables = await this.query(`SHOW TABLES`);835return tables.map(({name}) => ({name}));836}837838async describeColumns({table} = {}) {839const columns = await this.query(`DESCRIBE ${this.escape(table)}`);840return columns.map(({column_name, column_type, null: nullable}) => ({841name: column_name,842type: getDuckDBType(column_type),843nullable: nullable !== "NO",844databaseType: column_type845}));846}847848static async of(sources = {}, config = {}) {849const db = await createDuckDB();850if (config.query?.castTimestampToDate === undefined) {851config = {...config, query: {...config.query, castTimestampToDate: true}};852}853if (config.query?.castBigIntToDouble === undefined) {854config = {...config, query: {...config.query, castBigIntToDouble: true}};855}856await db.open(config);857await Promise.all(858Object.entries(sources).map(async ([name, source]) => {859if (source instanceof FileAttachment) { // bare file860await insertFile(db, name, source);861} else if (isArrowTable(source)) { // bare arrow table862await insertArrowTable(db, name, source);863} else if (Array.isArray(source)) { // bare array of objects864await insertArray(db, name, source);865} else if (isArqueroTable(source)) {866await insertArqueroTable(db, name, source);867} else if ("data" in source) { // data + options868const {data, ...options} = source;869if (isArrowTable(data)) {870await insertArrowTable(db, name, data, options);871} else {872await insertArray(db, name, data, options);873}874} else if ("file" in source) { // file + options875const {file, ...options} = source;876await insertFile(db, name, file, options);877} else {878throw new Error(`invalid source: ${source}`);879}880})881);882return new DuckDBClient(db);883}884}885886Object.defineProperty(DuckDBClient.prototype, "dialect", {887value: "duckdb"888});889890async function insertFile(database, name, file, options) {891const url = await file.url();892if (url.startsWith("blob:")) {893const buffer = await file.arrayBuffer();894await database.registerFileBuffer(file.name, new Uint8Array(buffer));895} else {896await database.registerFileURL(file.name, url, 4); // duckdb.DuckDBDataProtocol.HTTP897}898const connection = await database.connect();899try {900switch (file.mimeType) {901case "text/csv":902case "text/tab-separated-values": {903return await connection.insertCSVFromPath(file.name, {904name,905schema: "main",906...options907}).catch(async (error) => {908// If initial attempt to insert CSV resulted in a conversion909// error, try again, this time treating all columns as strings.910if (error.toString().includes("Could not convert")) {911return await insertUntypedCSV(connection, file, name);912}913throw error;914});915}916case "application/json":917return await connection.insertJSONFromPath(file.name, {918name,919schema: "main",920...options921});922default:923if (/\.arrow$/i.test(file.name)) {924const buffer = new Uint8Array(await file.arrayBuffer());925return await connection.insertArrowFromIPCStream(buffer, {926name,927schema: "main",928...options929});930}931if (/\.parquet$/i.test(file.name)) {932return await connection.query(933`CREATE VIEW '${name}' AS SELECT * FROM parquet_scan('${file.name}')`934);935}936throw new Error(`unknown file type: ${file.mimeType}`);937}938} finally {939await connection.close();940}941}942943async function insertUntypedCSV(connection, file, name) {944const statement = await connection.prepare(945`CREATE TABLE '${name}' AS SELECT * FROM read_csv_auto(?, ALL_VARCHAR=TRUE)`946);947return await statement.send(file.name);948}949950async function insertArrowTable(database, name, table, options) {951const connection = await database.connect();952try {953await connection.insertArrowTable(table, {954name,955schema: "main",956...options957});958} finally {959await connection.close();960}961}962963async function insertArqueroTable(database, name, source) {964// TODO When we have stdlib versioning and can upgrade Arquero to version 5,965// we can then call source.toArrow() directly, with insertArrowTable()966const arrow = await loadArrow();967const table = arrow.tableFromIPC(source.toArrowBuffer());968return await insertArrowTable(database, name, table);969}970971async function insertArray(database, name, array, options) {972const arrow = await loadArrow();973const table = arrow.tableFromJSON(array);974return await insertArrowTable(database, name, table, options);975}976977async function loadDuckDB() {978const module = await import(`${cdn}${duckdb.resolve()}`);979const bundle = await module.selectBundle({980mvp: {981mainModule: `${cdn}${duckdb.resolve("dist/duckdb-mvp.wasm")}`,982mainWorker: `${cdn}${duckdb.resolve("dist/duckdb-browser-mvp.worker.js")}`983},984eh: {985mainModule: `${cdn}${duckdb.resolve("dist/duckdb-eh.wasm")}`,986mainWorker: `${cdn}${duckdb.resolve("dist/duckdb-browser-eh.worker.js")}`987}988});989const logger = new module.ConsoleLogger();990return {module, bundle, logger};991}992993async function createDuckDB() {994if (promise === undefined) promise = loadDuckDB();995const {module, bundle, logger} = await promise;996const worker = await module.createWorker(bundle.mainWorker);997const db = new module.AsyncDuckDB(logger, worker);998await db.instantiate(bundle.mainModule);999return db;1000}10011002// https://duckdb.org/docs/sql/data_types/overview1003function getDuckDBType(type) {1004switch (type) {1005case "BIGINT":1006case "HUGEINT":1007case "UBIGINT":1008return "bigint";1009case "DOUBLE":1010case "REAL":1011case "FLOAT":1012return "number";1013case "INTEGER":1014case "SMALLINT":1015case "TINYINT":1016case "USMALLINT":1017case "UINTEGER":1018case "UTINYINT":1019return "integer";1020case "BOOLEAN":1021return "boolean";1022case "DATE":1023case "TIMESTAMP":1024case "TIMESTAMP WITH TIME ZONE":1025return "date";1026case "VARCHAR":1027case "UUID":1028return "string";1029// case "BLOB":1030// case "INTERVAL":1031// case "TIME":1032default:1033if (/^DECIMAL\(/.test(type)) return "integer";1034return "other";1035}1036}10371038const nChecks = 20; // number of values to check in each array10391040// We support two levels of DatabaseClient. The simplest DatabaseClient1041// implements only the client.sql tagged template literal. More advanced1042// DatabaseClients implement client.query and client.queryStream, which support1043// streaming and abort, and the client.queryTag tagged template literal is used1044// to translate the contents of a SQL cell or Table cell into the appropriate1045// arguments for calling client.query or client.queryStream. For table cells, we1046// additionally require client.describeColumns. The client.describeTables method1047// is optional.1048function isDatabaseClient(value, mode) {1049return (1050value &&1051(typeof value.sql === "function" ||1052(typeof value.queryTag === "function" &&1053(typeof value.query === "function" ||1054typeof value.queryStream === "function"))) &&1055(mode !== "table" || typeof value.describeColumns === "function") &&1056value !== __query // don’t match our internal helper1057);1058}10591060// Returns true if the value is a typed array (for a single-column table), or if1061// it’s an array. In the latter case, the elements of the array must be1062// consistently typed: either plain objects or primitives or dates.1063function isDataArray(value) {1064return (1065(Array.isArray(value) &&1066(isQueryResultSetSchema(value.schema) ||1067isQueryResultSetColumns(value.columns) ||1068arrayContainsObjects(value) ||1069arrayContainsPrimitives(value) ||1070arrayContainsDates(value))) ||1071isTypedArray(value)1072);1073}10741075// Given an array, checks that the given value is an array that does not contain1076// any primitive values (at least for the first few values that we check), and1077// that the first object contains enumerable keys (see computeSchema for how we1078// infer the columns). We assume that the contents of the table are homogenous,1079// but we don’t currently enforce this.1080// https://observablehq.com/@observablehq/database-client-specification#§11081function arrayContainsObjects(value) {1082const n = Math.min(nChecks, value.length);1083for (let i = 0; i < n; ++i) {1084const v = value[i];1085if (v === null || typeof v !== "object") return false;1086}1087return n > 0 && objectHasEnumerableKeys(value[0]);1088}10891090// Using a for-in loop here means that we can abort after finding at least one1091// enumerable key (whereas Object.keys would require materializing the array of1092// all keys, which would be considerably slower if the value has many keys!).1093// This function assumes that value is an object; see arrayContainsObjects.1094function objectHasEnumerableKeys(value) {1095for (const _ in value) return true;1096return false;1097}10981099function isQueryResultSetSchema(schemas) {1100return (1101Array.isArray(schemas) &&1102schemas.every(isColumnSchema)1103);1104}11051106function isQueryResultSetColumns(columns) {1107return (Array.isArray(columns) && columns.every((name) => typeof name === "string"));1108}11091110function isColumnSchema(schema) {1111return schema && typeof schema.name === "string" && typeof schema.type === "string";1112}11131114// Returns true if the value represents an array of primitives (i.e., a1115// single-column table). This should only be passed values for which1116// isDataArray returns true.1117function arrayIsPrimitive(value) {1118return (1119isTypedArray(value) ||1120arrayContainsPrimitives(value) ||1121arrayContainsDates(value)1122);1123}11241125// Given an array, checks that the first n elements are primitives (number,1126// string, boolean, bigint) of a consistent type.1127function arrayContainsPrimitives(value) {1128const n = Math.min(nChecks, value.length);1129if (!(n > 0)) return false;1130let type;1131let hasPrimitive = false; // ensure we encounter 1+ primitives1132for (let i = 0; i < n; ++i) {1133const v = value[i];1134if (v == null) continue; // ignore null and undefined1135const t = typeof v;1136if (type === undefined) {1137switch (t) {1138case "number":1139case "boolean":1140case "string":1141case "bigint":1142type = t;1143break;1144default:1145return false;1146}1147} else if (t !== type) {1148return false;1149}1150hasPrimitive = true;1151}1152return hasPrimitive;1153}11541155// Given an array, checks that the first n elements are dates.1156function arrayContainsDates(value) {1157const n = Math.min(nChecks, value.length);1158if (!(n > 0)) return false;1159let hasDate = false; // ensure we encounter 1+ dates1160for (let i = 0; i < n; ++i) {1161const v = value[i];1162if (v == null) continue; // ignore null and undefined1163if (!(v instanceof Date)) return false;1164hasDate = true;1165}1166return hasDate;1167}11681169function isTypedArray(value) {1170return (1171value instanceof Int8Array ||1172value instanceof Int16Array ||1173value instanceof Int32Array ||1174value instanceof Uint8Array ||1175value instanceof Uint8ClampedArray ||1176value instanceof Uint16Array ||1177value instanceof Uint32Array ||1178value instanceof Float32Array ||1179value instanceof Float64Array1180);1181}11821183// __query is used by table cells; __query.sql is used by SQL cells.1184const __query = Object.assign(1185async (source, operations, invalidation, name) => {1186source = await loadTableDataSource(await source, name);1187if (isDatabaseClient(source)) return evaluateQuery(source, makeQueryTemplate(operations, source), invalidation);1188if (isDataArray(source)) return __table(source, operations);1189if (!source) throw new Error("missing data source");1190throw new Error("invalid data source");1191},1192{1193sql(source, invalidation, name) {1194return async function () {1195return evaluateQuery(await loadSqlDataSource(await source, name), arguments, invalidation);1196};1197}1198}1199);12001201// We use a weak map to cache loaded data sources by key so that we don’t have1202// to e.g. create separate SQLiteDatabaseClients every time we’re querying the1203// same SQLite file attachment. Since this is a weak map, unused references will1204// be garbage collected when they are no longer desired. Note: the name should1205// be consistent, as it is not part of the cache key!1206function sourceCache(loadSource) {1207const cache = new WeakMap();1208return (source, name) => {1209if (!source || typeof source !== "object") throw new Error("invalid data source");1210let promise = cache.get(source);1211if (!promise || (isDataArray(source) && source.length !== promise._numRows)) {1212// Warning: do not await here! We need to populate the cache synchronously.1213promise = loadSource(source, name);1214promise._numRows = source.length; // This will be undefined for DatabaseClients1215cache.set(source, promise);1216}1217return promise;1218};1219}12201221const loadTableDataSource = sourceCache(async (source, name) => {1222if (source instanceof FileAttachment) {1223switch (source.mimeType) {1224case "text/csv": return source.csv();1225case "text/tab-separated-values": return source.tsv();1226case "application/json": return source.json();1227case "application/x-sqlite3": return source.sqlite();1228}1229if (/\.(arrow|parquet)$/i.test(source.name)) return loadDuckDBClient(source, name);1230throw new Error(`unsupported file type: ${source.mimeType}`);1231}1232if (isArrowTable(source) || isArqueroTable(source)) return loadDuckDBClient(source, name);1233if (isDataArray(source) && arrayIsPrimitive(source))1234return Array.from(source, (value) => ({value}));1235return source;1236});12371238const loadSqlDataSource = sourceCache(async (source, name) => {1239if (source instanceof FileAttachment) {1240switch (source.mimeType) {1241case "text/csv":1242case "text/tab-separated-values":1243case "application/json": return loadDuckDBClient(source, name);1244case "application/x-sqlite3": return source.sqlite();1245}1246if (/\.(arrow|parquet)$/i.test(source.name)) return loadDuckDBClient(source, name);1247throw new Error(`unsupported file type: ${source.mimeType}`);1248}1249if (isDataArray(source)) return loadDuckDBClient(await asArrowTable(source, name), name);1250if (isArrowTable(source) || isArqueroTable(source)) return loadDuckDBClient(source, name);1251return source;1252});12531254async function asArrowTable(array, name) {1255const arrow = await loadArrow();1256return arrayIsPrimitive(array)1257? arrow.tableFromArrays({[name]: array})1258: arrow.tableFromJSON(array);1259}12601261function loadDuckDBClient(1262source,1263name = source instanceof FileAttachment1264? getFileSourceName(source)1265: "__table"1266) {1267return DuckDBClient.of({[name]: source});1268}12691270function getFileSourceName(file) {1271return file.name1272.replace(/@\d+(?=\.|$)/, "") // strip Observable file version number1273.replace(/\.\w+$/, ""); // strip file extension1274}12751276async function evaluateQuery(source, args, invalidation) {1277if (!source) throw new Error("missing data source");12781279// If this DatabaseClient supports abort and streaming, use that.1280if (typeof source.queryTag === "function") {1281const abortController = new AbortController();1282const options = {signal: abortController.signal};1283invalidation.then(() => abortController.abort("invalidated"));1284if (typeof source.queryStream === "function") {1285return accumulateQuery(1286source.queryStream(...source.queryTag.apply(source, args), options)1287);1288}1289if (typeof source.query === "function") {1290return source.query(...source.queryTag.apply(source, args), options);1291}1292}12931294// Otherwise, fallback to the basic sql tagged template literal.1295if (typeof source.sql === "function") {1296return source.sql.apply(source, args);1297}12981299// TODO: test if source is a file attachment, and support CSV etc.1300throw new Error("source does not implement query, queryStream, or sql");1301}13021303// Generator function that yields accumulated query results client.queryStream1304async function* accumulateQuery(queryRequest) {1305let then = performance.now();1306const queryResponse = await queryRequest;1307const values = [];1308values.done = false;1309values.error = null;1310values.schema = queryResponse.schema;1311try {1312for await (const rows of queryResponse.readRows()) {1313if (performance.now() - then > 150 && values.length > 0) {1314yield values;1315then = performance.now();1316}1317for (const value of rows) {1318values.push(value);1319}1320}1321values.done = true;1322yield values;1323} catch (error) {1324values.error = error;1325yield values;1326}1327}13281329/**1330* Returns a SQL query in the form [[parts], ...params] where parts is an array1331* of sub-strings and params are the parameter values to be inserted between each1332* sub-string.1333*/1334function makeQueryTemplate(operations, source) {1335const escaper =1336typeof source.escape === "function" ? source.escape : (i) => i;1337const {select, from, filter, sort, slice} = operations;1338if (!from.table)1339throw new Error("missing from table");1340if (select.columns && select.columns.length === 0)1341throw new Error("at least one column must be selected");1342const names = new Map(operations.names?.map(({column, name}) => [column, name]));1343const columns = select.columns ? select.columns.map((column) => {1344const override = names.get(column);1345return override ? `${escaper(column)} AS ${escaper(override)}` : escaper(column);1346}).join(", ") : "*";1347const args = [1348[`SELECT ${columns} FROM ${formatTable(from.table, escaper)}`]1349];1350for (let i = 0; i < filter.length; ++i) {1351appendSql(i ? `\nAND ` : `\nWHERE `, args);1352appendWhereEntry(filter[i], args, escaper);1353}1354for (let i = 0; i < sort.length; ++i) {1355appendSql(i ? `, ` : `\nORDER BY `, args);1356appendOrderBy(sort[i], args, escaper);1357}1358if (source.dialect === "mssql" || source.dialect === "oracle") {1359if (slice.to !== null || slice.from !== null) {1360if (!sort.length) {1361if (!select.columns)1362throw new Error(1363"at least one column must be explicitly specified. Received '*'."1364);1365appendSql(`\nORDER BY `, args);1366appendOrderBy(1367{column: select.columns[0], direction: "ASC"},1368args,1369escaper1370);1371}1372appendSql(`\nOFFSET ${slice.from || 0} ROWS`, args);1373appendSql(1374`\nFETCH NEXT ${1375slice.to !== null ? slice.to - (slice.from || 0) : 1e91376} ROWS ONLY`,1377args1378);1379}1380} else {1381if (slice.to !== null || slice.from !== null) {1382appendSql(1383`\nLIMIT ${slice.to !== null ? slice.to - (slice.from || 0) : 1e9}`,1384args1385);1386}1387if (slice.from !== null) {1388appendSql(` OFFSET ${slice.from}`, args);1389}1390}1391return args;1392}13931394function formatTable(table, escaper) {1395if (typeof table === "object") { // i.e., not a bare string specifier1396let from = "";1397if (table.database != null) from += escaper(table.database) + ".";1398if (table.schema != null) from += escaper(table.schema) + ".";1399from += escaper(table.table);1400return from;1401} else {1402return escaper(table);1403}1404}14051406function appendSql(sql, args) {1407const strings = args[0];1408strings[strings.length - 1] += sql;1409}14101411function appendOrderBy({column, direction}, args, escaper) {1412appendSql(`${escaper(column)} ${direction.toUpperCase()}`, args);1413}14141415function appendWhereEntry({type, operands}, args, escaper) {1416if (operands.length < 1) throw new Error("Invalid operand length");14171418// Unary operations1419// We treat `v` and `nv` as `NULL` and `NOT NULL` unary operations in SQL,1420// since the database already validates column types.1421if (operands.length === 1 || type === "v" || type === "nv") {1422appendOperand(operands[0], args, escaper);1423switch (type) {1424case "n":1425case "nv":1426appendSql(` IS NULL`, args);1427return;1428case "nn":1429case "v":1430appendSql(` IS NOT NULL`, args);1431return;1432default:1433throw new Error("Invalid filter operation");1434}1435}14361437// Binary operations1438if (operands.length === 2) {1439if (["in", "nin"].includes(type)) ; else if (["c", "nc"].includes(type)) {1440// TODO: Case (in)sensitive?1441appendOperand(operands[0], args, escaper);1442switch (type) {1443case "c":1444appendSql(` LIKE `, args);1445break;1446case "nc":1447appendSql(` NOT LIKE `, args);1448break;1449}1450appendOperand(likeOperand(operands[1]), args, escaper);1451return;1452} else {1453appendOperand(operands[0], args, escaper);1454switch (type) {1455case "eq":1456appendSql(` = `, args);1457break;1458case "ne":1459appendSql(` <> `, args);1460break;1461case "gt":1462appendSql(` > `, args);1463break;1464case "lt":1465appendSql(` < `, args);1466break;1467case "gte":1468appendSql(` >= `, args);1469break;1470case "lte":1471appendSql(` <= `, args);1472break;1473default:1474throw new Error("Invalid filter operation");1475}1476appendOperand(operands[1], args, escaper);1477return;1478}1479}14801481// List operations1482appendOperand(operands[0], args, escaper);1483switch (type) {1484case "in":1485appendSql(` IN (`, args);1486break;1487case "nin":1488appendSql(` NOT IN (`, args);1489break;1490default:1491throw new Error("Invalid filter operation");1492}1493appendListOperands(operands.slice(1), args);1494appendSql(")", args);1495}14961497function appendOperand(o, args, escaper) {1498if (o.type === "column") {1499appendSql(escaper(o.value), args);1500} else {1501args.push(o.value);1502args[0].push("");1503}1504}15051506// TODO: Support column operands here?1507function appendListOperands(ops, args) {1508let first = true;1509for (const op of ops) {1510if (first) first = false;1511else appendSql(",", args);1512args.push(op.value);1513args[0].push("");1514}1515}15161517function likeOperand(operand) {1518return {...operand, value: `%${operand.value}%`};1519}15201521// Comparator function that moves null values (undefined, null, NaN) to the1522// end of the array.1523function defined(a, b) {1524return (a == null || !(a >= a)) - (b == null || !(b >= b));1525}15261527// Comparator function that sorts values in ascending order, with null values at1528// the end.1529function ascendingDefined(a, b) {1530return defined(a, b) || (a < b ? -1 : a > b ? 1 : 0);1531}15321533// Comparator function that sorts values in descending order, with null values1534// at the end.1535function descendingDefined(a, b) {1536return defined(a, b) || (a > b ? -1 : a < b ? 1 : 0);1537}15381539// Functions for checking type validity1540const isValidNumber = (value) => typeof value === "number" && !Number.isNaN(value);1541const isValidInteger = (value) => Number.isInteger(value) && !Number.isNaN(value);1542const isValidString = (value) => typeof value === "string";1543const isValidBoolean = (value) => typeof value === "boolean";1544const isValidBigint = (value) => typeof value === "bigint";1545const isValidDate = (value) => value instanceof Date && !isNaN(value);1546const isValidBuffer = (value) => value instanceof ArrayBuffer;1547const isValidArray = (value) => Array.isArray(value);1548const isValidObject = (value) => typeof value === "object" && value !== null;1549const isValidOther = (value) => value != null;15501551// Function to get the correct validity checking function based on type1552function getTypeValidator(colType) {1553switch (colType) {1554case "string":1555return isValidString;1556case "bigint":1557return isValidBigint;1558case "boolean":1559return isValidBoolean;1560case "number":1561return isValidNumber;1562case "integer":1563return isValidInteger;1564case "date":1565return isValidDate;1566case "buffer":1567return isValidBuffer;1568case "array":1569return isValidArray;1570case "object":1571return isValidObject;1572case "other":1573default:1574return isValidOther;1575}1576}15771578// Accepts dates in the form of ISOString and LocaleDateString, with or without time1579const DATE_TEST = /^(([-+]\d{2})?\d{4}(-\d{2}(-\d{2}))|(\d{1,2})\/(\d{1,2})\/(\d{2,4}))([T ]\d{2}:\d{2}(:\d{2}(\.\d{3})?)?(Z|[-+]\d{2}:\d{2})?)?$/;15801581function coerceToType(value, type) {1582switch (type) {1583case "string":1584return typeof value === "string" || value == null ? value : String(value);1585case "boolean":1586if (typeof value === "string") {1587const trimValue = value.trim().toLowerCase();1588return trimValue === "true"1589? true1590: trimValue === "false"1591? false1592: null;1593}1594return typeof value === "boolean" || value == null1595? value1596: Boolean(value);1597case "bigint":1598return typeof value === "bigint" || value == null1599? value1600: Number.isInteger(typeof value === "string" && !value.trim() ? NaN : +value)1601? BigInt(value) // eslint-disable-line no-undef1602: undefined;1603case "integer": // not a target type for coercion, but can be inferred1604case "number": {1605return typeof value === "number"1606? value1607: value == null || (typeof value === "string" && !value.trim())1608? NaN1609: Number(value);1610}1611case "date": {1612if (value instanceof Date || value == null) return value;1613if (typeof value === "number") return new Date(value);1614const trimValue = String(value).trim();1615if (typeof value === "string" && !trimValue) return null;1616return new Date(DATE_TEST.test(trimValue) ? trimValue : NaN);1617}1618case "array":1619case "object":1620case "buffer":1621case "other":1622return value;1623default:1624throw new Error(`Unable to coerce to type: ${type}`);1625}1626}16271628function getSchema(source) {1629const {columns} = source;1630let {schema} = source;1631if (!isQueryResultSetSchema(schema)) {1632schema = inferSchema(source, isQueryResultSetColumns(columns) ? columns : undefined);1633return {schema, inferred: true};1634}1635return {schema, inferred: false};1636}16371638// This function infers a schema from the source data, if one doesn't already1639// exist, and merges type assertions into that schema. If the schema was1640// inferred or if there are type assertions, it then coerces the rows in the1641// source data to the types specified in the schema.1642function applyTypes(source, operations) {1643const input = source;1644let {schema, inferred} = getSchema(source);1645const types = new Map(schema.map(({name, type}) => [name, type]));1646if (operations.types) {1647for (const {name, type} of operations.types) {1648types.set(name, type);1649// update schema with user-selected type1650if (schema === input.schema) schema = schema.slice(); // copy on write1651const colIndex = schema.findIndex((col) => col.name === name);1652if (colIndex > -1) schema[colIndex] = {...schema[colIndex], type};1653}1654source = source.map(d => coerceRow(d, types, schema));1655} else if (inferred) {1656// Coerce data according to new schema, unless that happened due to1657// operations.types, above.1658source = source.map(d => coerceRow(d, types, schema));1659}1660return {source, schema};1661}16621663function applyNames(source, operations) {1664if (!operations.names) return source;1665const overridesByName = new Map(operations.names.map((n) => [n.column, n]));1666return source.map((d) =>1667Object.fromEntries(Object.keys(d).map((k) => {1668const override = overridesByName.get(k);1669return [override?.name ?? k, d[k]];1670}))1671);1672}16731674// This function applies table cell operations to an in-memory table (array of1675// objects); it should be equivalent to the corresponding SQL query. TODO Use1676// DuckDBClient for data arrays, too, and then we wouldn’t need our own __table1677// function to do table operations on in-memory data?1678function __table(source, operations) {1679const errors = new Map();1680const input = source;1681const typed = applyTypes(source, operations);1682source = typed.source;1683let schema = typed.schema;1684if (operations.derive) {1685// Derived columns may depend on coerced values from the original data source,1686// so we must evaluate derivations after the initial inference and coercion1687// step.1688const derivedSource = [];1689operations.derive.map(({name, value}) => {1690let columnErrors = [];1691// Derived column formulas may reference renamed columns, so we must1692// compute derivations on the renamed source. However, we don't modify the1693// source itself with renamed names until after the other operations are1694// applied, because operations like filter and sort reference original1695// column names.1696// TODO Allow derived columns to reference other derived columns.1697applyNames(source, operations).map((row, index) => {1698let resolved;1699try {1700// TODO Support referencing `index` and `rows` in the derive function.1701resolved = value(row);1702} catch (error) {1703columnErrors.push({index, error});1704resolved = undefined;1705}1706if (derivedSource[index]) {1707derivedSource[index] = {...derivedSource[index], [name]: resolved};1708} else {1709derivedSource.push({[name]: resolved});1710}1711});1712if (columnErrors.length) errors.set(name, columnErrors);1713});1714// Since derived columns are untyped by default, we do a pass of type1715// inference and coercion after computing the derived values.1716const typedDerived = applyTypes(derivedSource, operations);1717// Merge derived source and schema with the source dataset.1718source = source.map((row, i) => ({...row, ...typedDerived.source[i]}));1719schema = [...schema, ...typedDerived.schema];1720}1721for (const {type, operands} of operations.filter) {1722const [{value: column}] = operands;1723const values = operands.slice(1).map(({value}) => value);1724switch (type) {1725// valid (matches the column type)1726case "v": {1727const [colType] = values;1728const isValid = getTypeValidator(colType);1729source = source.filter(d => isValid(d[column]));1730break;1731}1732// not valid (doesn't match the column type)1733case "nv": {1734const [colType] = values;1735const isValid = getTypeValidator(colType);1736source = source.filter(d => !isValid(d[column]));1737break;1738}1739case "eq": {1740const [value] = values;1741if (value instanceof Date) {1742const time = +value; // compare as primitive1743source = source.filter((d) => +d[column] === time);1744} else {1745source = source.filter((d) => d[column] === value);1746}1747break;1748}1749case "ne": {1750const [value] = values;1751source = source.filter((d) => d[column] !== value);1752break;1753}1754case "c": {1755const [value] = values;1756source = source.filter(1757(d) => typeof d[column] === "string" && d[column].includes(value)1758);1759break;1760}1761case "nc": {1762const [value] = values;1763source = source.filter(1764(d) => typeof d[column] === "string" && !d[column].includes(value)1765);1766break;1767}1768case "in": {1769const set = new Set(values); // TODO support dates?1770source = source.filter((d) => set.has(d[column]));1771break;1772}1773case "nin": {1774const set = new Set(values); // TODO support dates?1775source = source.filter((d) => !set.has(d[column]));1776break;1777}1778case "n": {1779source = source.filter((d) => d[column] == null);1780break;1781}1782case "nn": {1783source = source.filter((d) => d[column] != null);1784break;1785}1786case "lt": {1787const [value] = values;1788source = source.filter((d) => d[column] < value);1789break;1790}1791case "lte": {1792const [value] = values;1793source = source.filter((d) => d[column] <= value);1794break;1795}1796case "gt": {1797const [value] = values;1798source = source.filter((d) => d[column] > value);1799break;1800}1801case "gte": {1802const [value] = values;1803source = source.filter((d) => d[column] >= value);1804break;1805}1806default:1807throw new Error(`unknown filter type: ${type}`);1808}1809}1810for (const {column, direction} of reverse(operations.sort)) {1811const compare = direction === "desc" ? descendingDefined : ascendingDefined;1812if (source === input) source = source.slice(); // defensive copy1813source.sort((a, b) => compare(a[column], b[column]));1814}1815let {from, to} = operations.slice;1816from = from == null ? 0 : Math.max(0, from);1817to = to == null ? Infinity : Math.max(0, to);1818if (from > 0 || to < Infinity) {1819source = source.slice(Math.max(0, from), Math.max(0, to));1820}1821// Preserve the schema for all columns.1822let fullSchema = schema.slice();1823if (operations.select.columns) {1824if (schema) {1825const schemaByName = new Map(schema.map((s) => [s.name, s]));1826schema = operations.select.columns.map((c) => schemaByName.get(c));1827}1828source = source.map((d) =>1829Object.fromEntries(operations.select.columns.map((c) => [c, d[c]]))1830);1831}1832if (operations.names) {1833const overridesByName = new Map(operations.names.map((n) => [n.column, n]));1834if (schema) {1835schema = schema.map((s) => {1836const override = overridesByName.get(s.name);1837return ({...s, ...(override ? {name: override.name} : null)});1838});1839}1840if (fullSchema) {1841fullSchema = fullSchema.map((s) => {1842const override = overridesByName.get(s.name);1843return ({...s, ...(override ? {name: override.name} : null)});1844});1845}1846source = applyNames(source, operations);1847}1848if (source !== input) {1849if (schema) source.schema = schema;1850}1851source.fullSchema = fullSchema;1852source.errors = errors;1853return source;1854}18551856function coerceRow(object, types, schema) {1857const coerced = {};1858for (const col of schema) {1859const type = types.get(col.name);1860const value = object[col.name];1861coerced[col.name] = type === "raw" ? value : coerceToType(value, type);1862}1863return coerced;1864}18651866function createTypeCount() {1867return {1868boolean: 0,1869integer: 0,1870number: 0,1871date: 0,1872string: 0,1873array: 0,1874object: 0,1875bigint: 0,1876buffer: 0,1877defined: 01878};1879}18801881// Caution: the order below matters! 🌶️ The first one that passes the ≥90% test1882// should be the one that we chose, and therefore these types should be listed1883// from most specific to least specific.1884const types$2 = [1885"boolean",1886"integer",1887"number",1888"date",1889"bigint",1890"array",1891"object",1892"buffer"1893// Note: "other" and "string" are intentionally omitted; see below!1894];18951896// We need to show *all* keys present in the array of Objects1897function getAllKeys(rows) {1898const keys = new Set();1899for (const row of rows) {1900// avoid crash if row is null or undefined1901if (row) {1902// only enumerable properties1903for (const key in row) {1904// only own properties1905if (Object.prototype.hasOwnProperty.call(row, key)) {1906// unique properties, in the order they appear1907keys.add(key);1908}1909}1910}1911}1912return Array.from(keys);1913}19141915function inferSchema(source, columns = getAllKeys(source)) {1916const schema = [];1917const sampleSize = 100;1918const sample = source.slice(0, sampleSize);1919for (const col of columns) {1920const colCount = createTypeCount();1921for (const d of sample) {1922let value = d[col];1923if (value == null) continue;1924const type = typeof value;1925if (type !== "string") {1926++colCount.defined;1927if (Array.isArray(value)) ++colCount.array;1928else if (value instanceof Date) ++colCount.date;1929else if (value instanceof ArrayBuffer) ++colCount.buffer;1930else if (type === "number") {1931++colCount.number;1932if (Number.isInteger(value)) ++colCount.integer;1933}1934// bigint, boolean, or object1935else if (type in colCount) ++colCount[type];1936} else {1937value = value.trim();1938if (!value) continue;1939++colCount.defined;1940++colCount.string;1941if (/^(true|false)$/i.test(value)) {1942++colCount.boolean;1943} else if (value && !isNaN(value)) {1944++colCount.number;1945if (Number.isInteger(+value)) ++colCount.integer;1946} else if (DATE_TEST.test(value)) ++colCount.date;1947}1948}1949// Chose the non-string, non-other type with the greatest count that is also1950// ≥90%; or if no such type meets that criterion, fallback to string if1951// ≥90%; and lastly fallback to other.1952const minCount = Math.max(1, colCount.defined * 0.9);1953const type =1954greatest(types$2, (type) =>1955colCount[type] >= minCount ? colCount[type] : NaN1956) ?? (colCount.string >= minCount ? "string" : "other");1957schema.push({1958name: col,1959type: type,1960inferred: type1961});1962}1963return schema;1964}19651966class Workbook {1967constructor(workbook) {1968Object.defineProperties(this, {1969_: {value: workbook},1970sheetNames: {1971value: workbook.worksheets.map((s) => s.name),1972enumerable: true1973}1974});1975}1976sheet(name, options) {1977const sname =1978typeof name === "number"1979? this.sheetNames[name]1980: this.sheetNames.includes((name += ""))1981? name1982: null;1983if (sname == null) throw new Error(`Sheet not found: ${name}`);1984const sheet = this._.getWorksheet(sname);1985return extract(sheet, options);1986}1987}19881989function extract(sheet, {range, headers} = {}) {1990let [[c0, r0], [c1, r1]] = parseRange(range, sheet);1991const headerRow = headers ? sheet._rows[r0++] : null;1992let names = new Set(["#"]);1993for (let n = c0; n <= c1; n++) {1994const value = headerRow ? valueOf(headerRow.findCell(n + 1)) : null;1995let name = (value && value + "") || toColumn(n);1996while (names.has(name)) name += "_";1997names.add(name);1998}1999names = new Array(c0).concat(Array.from(names));20002001const output = new Array(r1 - r0 + 1);2002for (let r = r0; r <= r1; r++) {2003const row = (output[r - r0] = Object.create(null, {"#": {value: r + 1}}));2004const _row = sheet.getRow(r + 1);2005if (_row.hasValues)2006for (let c = c0; c <= c1; c++) {2007const value = valueOf(_row.findCell(c + 1));2008if (value != null) row[names[c + 1]] = value;2009}2010}20112012output.columns = names.filter(() => true); // Filter sparse columns2013return output;2014}20152016function valueOf(cell) {2017if (!cell) return;2018const {value} = cell;2019if (value && typeof value === "object" && !(value instanceof Date)) {2020if (value.formula || value.sharedFormula) {2021return value.result && value.result.error ? NaN : value.result;2022}2023if (value.richText) {2024return richText(value);2025}2026if (value.text) {2027let {text} = value;2028if (text.richText) text = richText(text);2029return value.hyperlink && value.hyperlink !== text2030? `${value.hyperlink} ${text}`2031: text;2032}2033return value;2034}2035return value;2036}20372038function richText(value) {2039return value.richText.map((d) => d.text).join("");2040}20412042function parseRange(specifier = ":", {columnCount, rowCount}) {2043specifier += "";2044if (!specifier.match(/^[A-Z]*\d*:[A-Z]*\d*$/))2045throw new Error("Malformed range specifier");2046const [[c0 = 0, r0 = 0], [c1 = columnCount - 1, r1 = rowCount - 1]] =2047specifier.split(":").map(fromCellReference);2048return [2049[c0, r0],2050[c1, r1]2051];2052}20532054// Returns the default column name for a zero-based column index.2055// For example: 0 -> "A", 1 -> "B", 25 -> "Z", 26 -> "AA", 27 -> "AB".2056function toColumn(c) {2057let sc = "";2058c++;2059do {2060sc = String.fromCharCode(64 + (c % 26 || 26)) + sc;2061} while ((c = Math.floor((c - 1) / 26)));2062return sc;2063}20642065// Returns the zero-based indexes from a cell reference.2066// For example: "A1" -> [0, 0], "B2" -> [1, 1], "AA10" -> [26, 9].2067function fromCellReference(s) {2068const [, sc, sr] = s.match(/^([A-Z]*)(\d*)$/);2069let c = 0;2070if (sc)2071for (let i = 0; i < sc.length; i++)2072c += Math.pow(26, sc.length - i - 1) * (sc.charCodeAt(i) - 64);2073return [c ? c - 1 : undefined, sr ? +sr - 1 : undefined];2074}20752076async function remote_fetch(file) {2077const response = await fetch(await file.url());2078if (!response.ok) throw new Error(`Unable to load file: ${file.name}`);2079return response;2080}20812082function enforceSchema(source, schema) {2083const types = new Map(schema.map(({name, type}) => [name, type]));2084return Object.assign(source.map(d => coerceRow(d, types, schema)), {schema});2085}20862087async function dsv(file, delimiter, {array = false, typed = false} = {}) {2088const text = await file.text();2089const parse = (delimiter === "\t"2090? (array ? tsvParseRows : tsvParse)2091: (array ? csvParseRows : csvParse));2092if (typed === "auto" && !array) {2093const source = parse(text);2094return enforceSchema(source, inferSchema(source, source.columns));2095}2096return parse(text, typed && autoType);2097}20982099class AbstractFile {2100constructor(name, mimeType) {2101Object.defineProperty(this, "name", {value: name, enumerable: true});2102if (mimeType !== undefined) Object.defineProperty(this, "mimeType", {value: mimeType + "", enumerable: true});2103}2104async blob() {2105return (await remote_fetch(this)).blob();2106}2107async arrayBuffer() {2108return (await remote_fetch(this)).arrayBuffer();2109}2110async text() {2111return (await remote_fetch(this)).text();2112}2113async json() {2114return (await remote_fetch(this)).json();2115}2116async stream() {2117return (await remote_fetch(this)).body;2118}2119async csv(options) {2120return dsv(this, ",", options);2121}2122async tsv(options) {2123return dsv(this, "\t", options);2124}2125async image(props) {2126const url = await this.url();2127return new Promise((resolve, reject) => {2128const i = new Image();2129if (new URL(url, document.baseURI).origin !== new URL(location).origin) {2130i.crossOrigin = "anonymous";2131}2132Object.assign(i, props);2133i.onload = () => resolve(i);2134i.onerror = () => reject(new Error(`Unable to load file: ${this.name}`));2135i.src = url;2136});2137}2138async arrow({version = 4} = {}) {2139switch (version) {2140case 4: {2141const [Arrow, response] = await Promise.all([requireDefault(arrow4.resolve()), remote_fetch(this)]);2142return Arrow.Table.from(response);2143}2144case 9: {2145const [Arrow, response] = await Promise.all([import(`${cdn}${arrow9.resolve()}`), remote_fetch(this)]);2146return Arrow.tableFromIPC(response);2147}2148case 11: {2149const [Arrow, response] = await Promise.all([import(`${cdn}${arrow11.resolve()}`), remote_fetch(this)]);2150return Arrow.tableFromIPC(response);2151}2152default: throw new Error(`unsupported arrow version: ${version}`);2153}2154}2155async sqlite() {2156return SQLiteDatabaseClient.open(remote_fetch(this));2157}2158async zip() {2159const [JSZip, buffer] = await Promise.all([requireDefault(jszip.resolve()), this.arrayBuffer()]);2160return new ZipArchive(await JSZip.loadAsync(buffer));2161}2162async xml(mimeType = "application/xml") {2163return (new DOMParser).parseFromString(await this.text(), mimeType);2164}2165async html() {2166return this.xml("text/html");2167}2168async xlsx() {2169const [ExcelJS, buffer] = await Promise.all([requireDefault(exceljs.resolve()), this.arrayBuffer()]);2170return new Workbook(await new ExcelJS.Workbook().xlsx.load(buffer));2171}2172}21732174class FileAttachment extends AbstractFile {2175constructor(url, name, mimeType) {2176super(name, mimeType);2177Object.defineProperty(this, "_url", {value: url});2178}2179async url() {2180return (await this._url) + "";2181}2182}21832184function NoFileAttachments(name) {2185throw new Error(`File not found: ${name}`);2186}21872188function FileAttachments(resolve) {2189return Object.assign(2190name => {2191const result = resolve(name += "");2192if (result == null) throw new Error(`File not found: ${name}`);2193if (typeof result === "object" && "url" in result) {2194const {url, mimeType} = result;2195return new FileAttachment(url, name, mimeType);2196}2197return new FileAttachment(result, name);2198},2199{prototype: FileAttachment.prototype} // instanceof2200);2201}22022203class ZipArchive {2204constructor(archive) {2205Object.defineProperty(this, "_", {value: archive});2206this.filenames = Object.keys(archive.files).filter(name => !archive.files[name].dir);2207}2208file(path) {2209const object = this._.file(path += "");2210if (!object || object.dir) throw new Error(`file not found: ${path}`);2211return new ZipArchiveEntry(object);2212}2213}22142215class ZipArchiveEntry extends AbstractFile {2216constructor(object) {2217super(object.name);2218Object.defineProperty(this, "_", {value: object});2219Object.defineProperty(this, "_url", {writable: true});2220}2221async url() {2222return this._url || (this._url = this.blob().then(URL.createObjectURL));2223}2224async blob() {2225return this._.async("blob");2226}2227async arrayBuffer() {2228return this._.async("arraybuffer");2229}2230async text() {2231return this._.async("text");2232}2233async json() {2234return JSON.parse(await this.text());2235}2236}22372238function canvas(width, height) {2239var canvas = document.createElement("canvas");2240canvas.width = width;2241canvas.height = height;2242return canvas;2243}22442245function context2d(width, height, dpi) {2246if (dpi == null) dpi = devicePixelRatio;2247var canvas = document.createElement("canvas");2248canvas.width = width * dpi;2249canvas.height = height * dpi;2250canvas.style.width = width + "px";2251var context = canvas.getContext("2d");2252context.scale(dpi, dpi);2253return context;2254}22552256function download(value, name = "untitled", label = "Save") {2257const a = document.createElement("a");2258const b = a.appendChild(document.createElement("button"));2259b.textContent = label;2260a.download = name;22612262async function reset() {2263await new Promise(requestAnimationFrame);2264URL.revokeObjectURL(a.href);2265a.removeAttribute("href");2266b.textContent = label;2267b.disabled = false;2268}22692270a.onclick = async event => {2271b.disabled = true;2272if (a.href) return reset(); // Already saved.2273b.textContent = "Saving…";2274try {2275const object = await (typeof value === "function" ? value() : value);2276b.textContent = "Download";2277a.href = URL.createObjectURL(object); // eslint-disable-line require-atomic-updates2278} catch (ignore) {2279b.textContent = label;2280}2281if (event.eventPhase) return reset(); // Already downloaded.2282b.disabled = false;2283};22842285return a;2286}22872288var namespaces = {2289math: "http://www.w3.org/1998/Math/MathML",2290svg: "http://www.w3.org/2000/svg",2291xhtml: "http://www.w3.org/1999/xhtml",2292xlink: "http://www.w3.org/1999/xlink",2293xml: "http://www.w3.org/XML/1998/namespace",2294xmlns: "http://www.w3.org/2000/xmlns/"2295};22962297function element(name, attributes) {2298var prefix = name += "", i = prefix.indexOf(":"), value;2299if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1);2300var element = namespaces.hasOwnProperty(prefix) // eslint-disable-line no-prototype-builtins2301? document.createElementNS(namespaces[prefix], name)2302: document.createElement(name);2303if (attributes) for (var key in attributes) {2304prefix = key, i = prefix.indexOf(":"), value = attributes[key];2305if (i >= 0 && (prefix = key.slice(0, i)) !== "xmlns") key = key.slice(i + 1);2306if (namespaces.hasOwnProperty(prefix)) element.setAttributeNS(namespaces[prefix], key, value); // eslint-disable-line no-prototype-builtins2307else element.setAttribute(key, value);2308}2309return element;2310}23112312function input$1(type) {2313var input = document.createElement("input");2314if (type != null) input.type = type;2315return input;2316}23172318function range$1(min, max, step) {2319if (arguments.length === 1) max = min, min = null;2320var input = document.createElement("input");2321input.min = min = min == null ? 0 : +min;2322input.max = max = max == null ? 1 : +max;2323input.step = step == null ? "any" : step = +step;2324input.type = "range";2325return input;2326}23272328function select(values) {2329var select = document.createElement("select");2330Array.prototype.forEach.call(values, function(value) {2331var option = document.createElement("option");2332option.value = option.textContent = value;2333select.appendChild(option);2334});2335return select;2336}23372338function svg$1(width, height) {2339var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");2340svg.setAttribute("viewBox", [0, 0, width, height]);2341svg.setAttribute("width", width);2342svg.setAttribute("height", height);2343return svg;2344}23452346function text$1(value) {2347return document.createTextNode(value);2348}23492350var count$1 = 0;23512352function uid(name) {2353return new Id("O-" + (name == null ? "" : name + "-") + ++count$1);2354}23552356function Id(id) {2357this.id = id;2358this.href = new URL(`#${id}`, location) + "";2359}23602361Id.prototype.toString = function() {2362return "url(" + this.href + ")";2363};23642365var DOM = /*#__PURE__*/Object.freeze({2366__proto__: null,2367canvas: canvas,2368context2d: context2d,2369download: download,2370element: element,2371input: input$1,2372range: range$1,2373select: select,2374svg: svg$1,2375text: text$1,2376uid: uid2377});23782379function buffer(file) {2380return new Promise(function(resolve, reject) {2381var reader = new FileReader;2382reader.onload = function() { resolve(reader.result); };2383reader.onerror = reject;2384reader.readAsArrayBuffer(file);2385});2386}23872388function text(file) {2389return new Promise(function(resolve, reject) {2390var reader = new FileReader;2391reader.onload = function() { resolve(reader.result); };2392reader.onerror = reject;2393reader.readAsText(file);2394});2395}23962397function url(file) {2398return new Promise(function(resolve, reject) {2399var reader = new FileReader;2400reader.onload = function() { resolve(reader.result); };2401reader.onerror = reject;2402reader.readAsDataURL(file);2403});2404}24052406var Files = /*#__PURE__*/Object.freeze({2407__proto__: null,2408buffer: buffer,2409text: text,2410url: url2411});24122413function that() {2414return this;2415}24162417function disposable(value, dispose) {2418let done = false;2419if (typeof dispose !== "function") {2420throw new Error("dispose is not a function");2421}2422return {2423[Symbol.iterator]: that,2424next: () => done ? {done: true} : (done = true, {done: false, value}),2425return: () => (done = true, dispose(value), {done: true}),2426throw: () => ({done: done = true})2427};2428}24292430function* filter(iterator, test) {2431var result, index = -1;2432while (!(result = iterator.next()).done) {2433if (test(result.value, ++index)) {2434yield result.value;2435}2436}2437}24382439function observe(initialize) {2440let stale = false;2441let value;2442let resolve;2443const dispose = initialize(change);24442445if (dispose != null && typeof dispose !== "function") {2446throw new Error(typeof dispose.then === "function"2447? "async initializers are not supported"2448: "initializer returned something, but not a dispose function");2449}24502451function change(x) {2452if (resolve) resolve(x), resolve = null;2453else stale = true;2454return value = x;2455}24562457function next() {2458return {done: false, value: stale2459? (stale = false, Promise.resolve(value))2460: new Promise(_ => (resolve = _))};2461}24622463return {2464[Symbol.iterator]: that,2465throw: () => ({done: true}),2466return: () => (dispose != null && dispose(), {done: true}),2467next2468};2469}24702471function input(input) {2472return observe(function(change) {2473var event = eventof(input), value = valueof$1(input);2474function inputted() { change(valueof$1(input)); }2475input.addEventListener(event, inputted);2476if (value !== undefined) change(value);2477return function() { input.removeEventListener(event, inputted); };2478});2479}24802481function valueof$1(input) {2482switch (input.type) {2483case "range":2484case "number": return input.valueAsNumber;2485case "date": return input.valueAsDate;2486case "checkbox": return input.checked;2487case "file": return input.multiple ? input.files : input.files[0];2488case "select-multiple": return Array.from(input.selectedOptions, o => o.value);2489default: return input.value;2490}2491}24922493function eventof(input) {2494switch (input.type) {2495case "button":2496case "submit":2497case "checkbox": return "click";2498case "file": return "change";2499default: return "input";2500}2501}25022503function* map$1(iterator, transform) {2504var result, index = -1;2505while (!(result = iterator.next()).done) {2506yield transform(result.value, ++index);2507}2508}25092510function queue(initialize) {2511let resolve;2512const queue = [];2513const dispose = initialize(push);25142515if (dispose != null && typeof dispose !== "function") {2516throw new Error(typeof dispose.then === "function"2517? "async initializers are not supported"2518: "initializer returned something, but not a dispose function");2519}25202521function push(x) {2522queue.push(x);2523if (resolve) resolve(queue.shift()), resolve = null;2524return x;2525}25262527function next() {2528return {done: false, value: queue.length2529? Promise.resolve(queue.shift())2530: new Promise(_ => (resolve = _))};2531}25322533return {2534[Symbol.iterator]: that,2535throw: () => ({done: true}),2536return: () => (dispose != null && dispose(), {done: true}),2537next2538};2539}25402541function* range(start, stop, step) {2542start = +start;2543stop = +stop;2544step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;2545var i = -1, n = Math.max(0, Math.ceil((stop - start) / step)) | 0;2546while (++i < n) {2547yield start + i * step;2548}2549}25502551function valueAt(iterator, i) {2552if (!isFinite(i = +i) || i < 0 || i !== i | 0) return;2553var result, index = -1;2554while (!(result = iterator.next()).done) {2555if (++index === i) {2556return result.value;2557}2558}2559}25602561function worker(source) {2562const url = URL.createObjectURL(new Blob([source], {type: "text/javascript"}));2563const worker = new Worker(url);2564return disposable(worker, () => {2565worker.terminate();2566URL.revokeObjectURL(url);2567});2568}25692570var Generators$1 = /*#__PURE__*/Object.freeze({2571__proto__: null,2572disposable: disposable,2573filter: filter,2574input: input,2575map: map$1,2576observe: observe,2577queue: queue,2578range: range,2579valueAt: valueAt,2580worker: worker2581});25822583function template(render, wrapper) {2584return function(strings) {2585var string = strings[0],2586parts = [], part,2587root = null,2588node, nodes,2589walker,2590i, n, j, m, k = -1;25912592// Concatenate the text using comments as placeholders.2593for (i = 1, n = arguments.length; i < n; ++i) {2594part = arguments[i];2595if (part instanceof Node) {2596parts[++k] = part;2597string += "<!--o:" + k + "-->";2598} else if (Array.isArray(part)) {2599for (j = 0, m = part.length; j < m; ++j) {2600node = part[j];2601if (node instanceof Node) {2602if (root === null) {2603parts[++k] = root = document.createDocumentFragment();2604string += "<!--o:" + k + "-->";2605}2606root.appendChild(node);2607} else {2608root = null;2609string += node;2610}2611}2612root = null;2613} else {2614string += part;2615}2616string += strings[i];2617}26182619// Render the text.2620root = render(string);26212622// Walk the rendered content to replace comment placeholders.2623if (++k > 0) {2624nodes = new Array(k);2625walker = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT, null, false);2626while (walker.nextNode()) {2627node = walker.currentNode;2628if (/^o:/.test(node.nodeValue)) {2629nodes[+node.nodeValue.slice(2)] = node;2630}2631}2632for (i = 0; i < k; ++i) {2633if (node = nodes[i]) {2634node.parentNode.replaceChild(parts[i], node);2635}2636}2637}26382639// Is the rendered content2640// … a parent of a single child? Detach and return the child.2641// … a document fragment? Replace the fragment with an element.2642// … some other node? Return it.2643return root.childNodes.length === 1 ? root.removeChild(root.firstChild)2644: root.nodeType === 11 ? ((node = wrapper()).appendChild(root), node)2645: root;2646};2647}26482649const html$1 = template(function(string) {2650var template = document.createElement("template");2651template.innerHTML = string.trim();2652return document.importNode(template.content, true);2653}, function() {2654return document.createElement("span");2655});26562657async function leaflet(require) {2658const L = await require(leaflet$1.resolve());2659if (!L._style) {2660const link = document.createElement("link");2661link.rel = "stylesheet";2662link.href = await require.resolve(leaflet$1.resolve("dist/leaflet.css"));2663L._style = document.head.appendChild(link);2664}2665return L;2666}26672668function md(require) {2669return require(marked.resolve()).then(function(marked) {2670return template(2671function(string) {2672var root = document.createElement("div");2673root.innerHTML = marked(string, {langPrefix: ""}).trim();2674var code = root.querySelectorAll("pre code[class]");2675if (code.length > 0) {2676require(highlight.resolve()).then(function(hl) {2677code.forEach(function(block) {2678function done() {2679hl.highlightBlock(block);2680block.parentNode.classList.add("observablehq--md-pre");2681}2682if (hl.getLanguage(block.className)) {2683done();2684} else {2685require(highlight.resolve("async-languages/index.js"))2686.then(index => {2687if (index.has(block.className)) {2688return require(highlight.resolve("async-languages/" + index.get(block.className))).then(language => {2689hl.registerLanguage(block.className, language);2690});2691}2692})2693.then(done, done);2694}2695});2696});2697}2698return root;2699},2700function() {2701return document.createElement("div");2702}2703);2704});2705}27062707async function mermaid(require) {2708const mer = await require(mermaid$1.resolve());2709mer.initialize({securityLevel: "loose", theme: "neutral"});2710return function mermaid() {2711const root = document.createElement("div");2712root.innerHTML = mer.render(uid().id, String.raw.apply(String, arguments));2713return root.removeChild(root.firstChild);2714};2715}27162717function Mutable(value) {2718let change;2719Object.defineProperties(this, {2720generator: {value: observe(_ => void (change = _))},2721value: {get: () => value, set: x => change(value = x)} // eslint-disable-line no-setter-return2722});2723if (value !== undefined) change(value);2724}27252726function* now() {2727while (true) {2728yield Date.now();2729}2730}27312732function delay(duration, value) {2733return new Promise(function(resolve) {2734setTimeout(function() {2735resolve(value);2736}, duration);2737});2738}27392740var timeouts = new Map;27412742function timeout(now, time) {2743var t = new Promise(function(resolve) {2744timeouts.delete(time);2745var delay = time - now;2746if (!(delay > 0)) throw new Error("invalid time");2747if (delay > 0x7fffffff) throw new Error("too long to wait");2748setTimeout(resolve, delay);2749});2750timeouts.set(time, t);2751return t;2752}27532754function when(time, value) {2755var now;2756return (now = timeouts.get(time = +time)) ? now.then(() => value)2757: (now = Date.now()) >= time ? Promise.resolve(value)2758: timeout(now, time).then(() => value);2759}27602761function tick(duration, value) {2762return when(Math.ceil((Date.now() + 1) / duration) * duration, value);2763}27642765var Promises = /*#__PURE__*/Object.freeze({2766__proto__: null,2767delay: delay,2768tick: tick,2769when: when2770});27712772function resolve(name, base) {2773if (/^(\w+:)|\/\//i.test(name)) return name;2774if (/^[.]{0,2}\//i.test(name)) return new URL(name, base == null ? location : base).href;2775if (!name.length || /^[\s._]/.test(name) || /\s$/.test(name)) throw new Error("illegal name");2776return "https://unpkg.com/" + name;2777}27782779const svg = template(function(string) {2780var root = document.createElementNS("http://www.w3.org/2000/svg", "g");2781root.innerHTML = string.trim();2782return root;2783}, function() {2784return document.createElementNS("http://www.w3.org/2000/svg", "g");2785});27862787var raw = String.raw;27882789function style(href) {2790return new Promise(function(resolve, reject) {2791var link = document.createElement("link");2792link.rel = "stylesheet";2793link.href = href;2794link.onerror = reject;2795link.onload = resolve;2796document.head.appendChild(link);2797});2798}27992800function tex(require) {2801return Promise.all([2802require(katex.resolve()),2803require.resolve(katex.resolve("dist/katex.min.css")).then(style)2804]).then(function(values) {2805var katex = values[0], tex = renderer();28062807function renderer(options) {2808return function() {2809var root = document.createElement("div");2810katex.render(raw.apply(String, arguments), root, options);2811return root.removeChild(root.firstChild);2812};2813}28142815tex.options = renderer;2816tex.block = renderer({displayMode: true});2817return tex;2818});2819}28202821async function vl(require) {2822const [v, vl, api] = await Promise.all([vega, vegalite, vegaliteApi].map(d => require(d.resolve())));2823return api.register(v, vl);2824}28252826function width() {2827return observe(function(change) {2828var width = change(document.body.clientWidth);2829function resized() {2830var w = document.body.clientWidth;2831if (w !== width) change(width = w);2832}2833window.addEventListener("resize", resized);2834return function() {2835window.removeEventListener("resize", resized);2836};2837});2838}28392840const Library = Object.assign(Object.defineProperties(function Library(resolver) {2841const require = requirer(resolver);2842Object.defineProperties(this, properties({2843FileAttachment: () => NoFileAttachments,2844Mutable: () => Mutable,2845now,2846width,28472848// Tagged template literals2849dot: () => require(graphviz.resolve()),2850htl: () => require(htl.resolve()),2851html: () => html$1,2852md: () => md(require),2853svg: () => svg,2854tex: () => tex(require),28552856// Recommended libraries2857// https://observablehq.com/@observablehq/recommended-libraries2858_: () => require(lodash.resolve()),2859aq: () => require.alias({"apache-arrow": arrow4.resolve()})(arquero.resolve()), // TODO upgrade to apache-arrow@92860Arrow: () => require(arrow4.resolve()), // TODO upgrade to apache-arrow@92861d3: () => require(d3.resolve()),2862DuckDBClient: () => DuckDBClient,2863Inputs: () => require(inputs.resolve()).then(Inputs => ({...Inputs, file: Inputs.fileOf(AbstractFile)})),2864L: () => leaflet(require),2865mermaid: () => mermaid(require),2866Plot: () => require(plot.resolve()),2867__query: () => __query,2868require: () => require,2869resolve: () => resolve, // deprecated; use async require.resolve instead2870SQLite: () => SQLite(require),2871SQLiteDatabaseClient: () => SQLiteDatabaseClient,2872topojson: () => require(topojson.resolve()),2873vl: () => vl(require),28742875// Sample datasets2876// https://observablehq.com/@observablehq/sample-datasets2877aapl: () => new FileAttachment("https://static.observableusercontent.com/files/3ccff97fd2d93da734e76829b2b066eafdaac6a1fafdec0faf6ebc443271cfc109d29e80dd217468fcb2aff1e6bffdc73f356cc48feb657f35378e6abbbb63b9").csv({typed: true}),2878alphabet: () => new FileAttachment("https://static.observableusercontent.com/files/75d52e6c3130b1cae83cda89305e17b50f33e7420ef205587a135e8562bcfd22e483cf4fa2fb5df6dff66f9c5d19740be1cfaf47406286e2eb6574b49ffc685d").csv({typed: true}),2879cars: () => new FileAttachment("https://static.observableusercontent.com/files/048ec3dfd528110c0665dfa363dd28bc516ffb7247231f3ab25005036717f5c4c232a5efc7bb74bc03037155cb72b1abe85a33d86eb9f1a336196030443be4f6").csv({typed: true}),2880citywages: () => new FileAttachment("https://static.observableusercontent.com/files/39837ec5121fcc163131dbc2fe8c1a2e0b3423a5d1e96b5ce371e2ac2e20a290d78b71a4fb08b9fa6a0107776e17fb78af313b8ea70f4cc6648fad68ddf06f7a").csv({typed: true}),2881diamonds: () => new FileAttachment("https://static.observableusercontent.com/files/87942b1f5d061a21fa4bb8f2162db44e3ef0f7391301f867ab5ba718b225a63091af20675f0bfe7f922db097b217b377135203a7eab34651e21a8d09f4e37252").csv({typed: true}),2882flare: () => new FileAttachment("https://static.observableusercontent.com/files/a6b0d94a7f5828fd133765a934f4c9746d2010e2f342d335923991f31b14120de96b5cb4f160d509d8dc627f0107d7f5b5070d2516f01e4c862b5b4867533000").csv({typed: true}),2883industries: () => new FileAttachment("https://static.observableusercontent.com/files/76f13741128340cc88798c0a0b7fa5a2df8370f57554000774ab8ee9ae785ffa2903010cad670d4939af3e9c17e5e18e7e05ed2b38b848ac2fc1a0066aa0005f").csv({typed: true}),2884miserables: () => new FileAttachment("https://static.observableusercontent.com/files/31d904f6e21d42d4963ece9c8cc4fbd75efcbdc404bf511bc79906f0a1be68b5a01e935f65123670ed04e35ca8cae3c2b943f82bf8db49c5a67c85cbb58db052").json(),2885olympians: () => new FileAttachment("https://static.observableusercontent.com/files/31ca24545a0603dce099d10ee89ee5ae72d29fa55e8fc7c9ffb5ded87ac83060d80f1d9e21f4ae8eb04c1e8940b7287d179fe8060d887fb1f055f430e210007c").csv({typed: true}),2886penguins: () => new FileAttachment("https://static.observableusercontent.com/files/715db1223e067f00500780077febc6cebbdd90c151d3d78317c802732252052ab0e367039872ab9c77d6ef99e5f55a0724b35ddc898a1c99cb14c31a379af80a").csv({typed: true}),2887pizza: () => new FileAttachment("https://static.observableusercontent.com/files/c653108ab176088cacbb338eaf2344c4f5781681702bd6afb55697a3f91b511c6686ff469f3e3a27c75400001a2334dbd39a4499fe46b50a8b3c278b7d2f7fb5").csv({typed: true}),2888weather: () => new FileAttachment("https://static.observableusercontent.com/files/693a46b22b33db0f042728700e0c73e836fa13d55446df89120682d55339c6db7cc9e574d3d73f24ecc9bc7eb9ac9a1e7e104a1ee52c00aab1e77eb102913c1f").csv({typed: true}),28892890// Note: these are namespace objects, and thus exposed directly rather than2891// being wrapped in a function. This allows library.Generators to resolve,2892// rather than needing module.value.2893DOM,2894Files,2895Generators: Generators$1,2896Promises2897}));2898}, {2899resolve: {2900get: () => requireDefault.resolve,2901enumerable: true,2902configurable: true2903},2904require: {2905get: () => requireDefault,2906set: setDefaultRequire,2907enumerable: true,2908configurable: true2909}2910}), {2911resolveFrom,2912requireFrom2913});29142915function properties(values) {2916return Object.fromEntries(Object.entries(values).map(property));2917}29182919function property([key, value]) {2920return [key, ({value, writable: true, enumerable: true})];2921}29222923// src/main.js2924class PandocCodeDecorator {2925constructor(node) {2926this._node = node;2927this._spans = [];2928this.normalizeCodeRange();2929this.initializeEntryPoints();2930}2931normalizeCodeRange() {2932const n = this._node;2933const lines = n.querySelectorAll("code > span");2934for (const line of lines) {2935Array.from(line.childNodes).filter((n2) => n2.nodeType === n2.TEXT_NODE).forEach((n2) => {2936const newSpan = document.createElement("span");2937newSpan.textContent = n2.wholeText;2938n2.replaceWith(newSpan);2939});2940}2941}2942initializeEntryPoints() {2943const lines = this._node.querySelectorAll("code > span");2944let result = [];2945let offset = this._node.parentElement.dataset.sourceOffset && -Number(this._node.parentElement.dataset.sourceOffset) || 0;2946for (const line of lines) {2947let lineNumber = Number(line.id.split("-").pop());2948let column = 1;2949Array.from(line.childNodes).filter((n) => n.nodeType === n.ELEMENT_NODE && n.nodeName === "SPAN").forEach((n) => {2950result.push({2951offset,2952line: lineNumber,2953column,2954node: n2955});2956offset += n.textContent.length;2957column += n.textContent.length;2958});2959offset += 1;2960}2961this._elementEntryPoints = result;2962}2963locateEntry(offset) {2964let candidate;2965if (offset === Infinity)2966return void 0;2967for (let i = 0; i < this._elementEntryPoints.length; ++i) {2968const entry = this._elementEntryPoints[i];2969if (entry.offset > offset) {2970return { entry: candidate, index: i - 1 };2971}2972candidate = entry;2973}2974if (offset < candidate.offset + candidate.node.textContent.length) {2975return { entry: candidate, index: this._elementEntryPoints.length - 1 };2976} else {2977return void 0;2978}2979}2980offsetToLineColumn(offset) {2981let entry = this.locateEntry(offset);2982if (entry === void 0) {2983const entries = this._elementEntryPoints;2984const last = entries[entries.length - 1];2985return {2986line: last.line,2987column: last.column + Math.min(last.node.textContent.length, offset - last.offset)2988};2989}2990return {2991line: entry.entry.line,2992column: entry.entry.column + offset - entry.entry.offset2993};2994}2995*spanSelection(start, end) {2996this.ensureExactSpan(start, end);2997const startEntry = this.locateEntry(start);2998const endEntry = this.locateEntry(end);2999if (startEntry === void 0) {3000return;3001}3002const startIndex = startEntry.index;3003const endIndex = endEntry && endEntry.index || this._elementEntryPoints.length;3004for (let i = startIndex; i < endIndex; ++i) {3005if (this._elementEntryPoints[i] !== void 0) {3006yield this._elementEntryPoints[i];3007}3008}3009}3010decorateSpan(start, end, classes) {3011for (const entryPoint of this.spanSelection(start, end)) {3012for (const cssClass of classes) {3013entryPoint.node.classList.add(cssClass);3014}3015}3016}3017clearSpan(start, end, classes) {3018for (const entryPoint of this.spanSelection(start, end)) {3019for (const cssClass of classes) {3020entryPoint.node.classList.remove(cssClass);3021}3022}3023}3024ensureExactSpan(start, end) {3025const splitEntry = (entry, offset) => {3026const newSpan = document.createElement("span");3027for (const cssClass of entry.node.classList) {3028newSpan.classList.add(cssClass);3029}3030const beforeText = entry.node.textContent.slice(0, offset - entry.offset);3031const afterText = entry.node.textContent.slice(offset - entry.offset);3032entry.node.textContent = beforeText;3033newSpan.textContent = afterText;3034entry.node.after(newSpan);3035this._elementEntryPoints.push({3036column: entry.column + offset - entry.offset,3037line: entry.line,3038node: newSpan,3039offset3040});3041this._elementEntryPoints.sort((a, b) => a.offset - b.offset);3042};3043const startEntry = this.locateEntry(start);3044if (startEntry !== void 0 && startEntry.entry !== void 0 && startEntry.entry.offset != start) {3045splitEntry(startEntry.entry, start);3046}3047const endEntry = this.locateEntry(end);3048if (endEntry !== void 0 && startEntry.entry !== void 0 && endEntry.entry.offset !== end) {3049splitEntry(endEntry.entry, end);3050}3051}3052clearSpan(start, end, classes) {3053this.ensureExactSpan(start, end);3054const startEntry = this.locateEntry(start);3055const endEntry = this.locateEntry(end);3056if (startEntry === void 0) {3057return;3058}3059const startIndex = startEntry.index;3060const endIndex = endEntry && endEntry.index || this._elementEntryPoints.length;3061for (let i = startIndex; i < endIndex; ++i) {3062for (const cssClass of classes) {3063this._elementEntryPoints[i].node.classList.remove(cssClass);3064}3065}3066}3067}30683069function dispatch(node, type, detail) {3070detail = detail || {};3071var document = node.ownerDocument, event = document.defaultView.CustomEvent;3072if (typeof event === "function") {3073event = new event(type, {detail: detail});3074} else {3075event = document.createEvent("Event");3076event.initEvent(type, false, false);3077event.detail = detail;3078}3079node.dispatchEvent(event);3080}30813082// TODO https://twitter.com/mbostock/status/7027370651217428483083function isarray(value) {3084return Array.isArray(value)3085|| value instanceof Int8Array3086|| value instanceof Int16Array3087|| value instanceof Int32Array3088|| value instanceof Uint8Array3089|| value instanceof Uint8ClampedArray3090|| value instanceof Uint16Array3091|| value instanceof Uint32Array3092|| value instanceof Float32Array3093|| value instanceof Float64Array;3094}30953096// Non-integer keys in arrays, e.g. [1, 2, 0.5: "value"].3097function isindex(key) {3098return key === (key | 0) + "";3099}31003101function inspectName(name) {3102const n = document.createElement("span");3103n.className = "observablehq--cellname";3104n.textContent = `${name} = `;3105return n;3106}31073108const symbolToString = Symbol.prototype.toString;31093110// Symbols do not coerce to strings; they must be explicitly converted.3111function formatSymbol(symbol) {3112return symbolToString.call(symbol);3113}31143115const {getOwnPropertySymbols, prototype: {hasOwnProperty: hasOwnProperty$1}} = Object;3116const {toStringTag} = Symbol;31173118const FORBIDDEN = {};31193120const symbolsof = getOwnPropertySymbols;31213122function isown(object, key) {3123return hasOwnProperty$1.call(object, key);3124}31253126function tagof(object) {3127return object[toStringTag]3128|| (object.constructor && object.constructor.name)3129|| "Object";3130}31313132function valueof(object, key) {3133try {3134const value = object[key];3135if (value) value.constructor; // Test for SecurityError.3136return value;3137} catch (ignore) {3138return FORBIDDEN;3139}3140}31413142const SYMBOLS = [3143{ symbol: "@@__IMMUTABLE_INDEXED__@@", name: "Indexed", modifier: true },3144{ symbol: "@@__IMMUTABLE_KEYED__@@", name: "Keyed", modifier: true },3145{ symbol: "@@__IMMUTABLE_LIST__@@", name: "List", arrayish: true },3146{ symbol: "@@__IMMUTABLE_MAP__@@", name: "Map" },3147{3148symbol: "@@__IMMUTABLE_ORDERED__@@",3149name: "Ordered",3150modifier: true,3151prefix: true3152},3153{ symbol: "@@__IMMUTABLE_RECORD__@@", name: "Record" },3154{3155symbol: "@@__IMMUTABLE_SET__@@",3156name: "Set",3157arrayish: true,3158setish: true3159},3160{ symbol: "@@__IMMUTABLE_STACK__@@", name: "Stack", arrayish: true }3161];31623163function immutableName(obj) {3164try {3165let symbols = SYMBOLS.filter(({ symbol }) => obj[symbol] === true);3166if (!symbols.length) return;31673168const name = symbols.find(s => !s.modifier);3169const prefix =3170name.name === "Map" && symbols.find(s => s.modifier && s.prefix);31713172const arrayish = symbols.some(s => s.arrayish);3173const setish = symbols.some(s => s.setish);31743175return {3176name: `${prefix ? prefix.name : ""}${name.name}`,3177symbols,3178arrayish: arrayish && !setish,3179setish3180};3181} catch (e) {3182return null;3183}3184}31853186const {getPrototypeOf, getOwnPropertyDescriptors} = Object;3187const objectPrototype = getPrototypeOf({});31883189function inspectExpanded(object, _, name, proto) {3190let arrayish = isarray(object);3191let tag, fields, next, n;31923193if (object instanceof Map) {3194if (object instanceof object.constructor) {3195tag = `Map(${object.size})`;3196fields = iterateMap$1;3197} else { // avoid incompatible receiver error for prototype3198tag = "Map()";3199fields = iterateObject$1;3200}3201} else if (object instanceof Set) {3202if (object instanceof object.constructor) {3203tag = `Set(${object.size})`;3204fields = iterateSet$1;3205} else { // avoid incompatible receiver error for prototype3206tag = "Set()";3207fields = iterateObject$1;3208}3209} else if (arrayish) {3210tag = `${object.constructor.name}(${object.length})`;3211fields = iterateArray$1;3212} else if ((n = immutableName(object))) {3213tag = `Immutable.${n.name}${n.name === "Record" ? "" : `(${object.size})`}`;3214arrayish = n.arrayish;3215fields = n.arrayish3216? iterateImArray$13217: n.setish3218? iterateImSet$13219: iterateImObject$1;3220} else if (proto) {3221tag = tagof(object);3222fields = iterateProto;3223} else {3224tag = tagof(object);3225fields = iterateObject$1;3226}32273228const span = document.createElement("span");3229span.className = "observablehq--expanded";3230if (name) {3231span.appendChild(inspectName(name));3232}3233const a = span.appendChild(document.createElement("a"));3234a.innerHTML = `<svg width=8 height=8 class='observablehq--caret'>3235<path d='M4 7L0 1h8z' fill='currentColor' />3236</svg>`;3237a.appendChild(document.createTextNode(`${tag}${arrayish ? " [" : " {"}`));3238a.addEventListener("mouseup", function(event) {3239event.stopPropagation();3240replace(span, inspectCollapsed(object, null, name, proto));3241});32423243fields = fields(object);3244for (let i = 0; !(next = fields.next()).done && i < 20; ++i) {3245span.appendChild(next.value);3246}32473248if (!next.done) {3249const a = span.appendChild(document.createElement("a"));3250a.className = "observablehq--field";3251a.style.display = "block";3252a.appendChild(document.createTextNode(` … more`));3253a.addEventListener("mouseup", function(event) {3254event.stopPropagation();3255span.insertBefore(next.value, span.lastChild.previousSibling);3256for (let i = 0; !(next = fields.next()).done && i < 19; ++i) {3257span.insertBefore(next.value, span.lastChild.previousSibling);3258}3259if (next.done) span.removeChild(span.lastChild.previousSibling);3260dispatch(span, "load");3261});3262}32633264span.appendChild(document.createTextNode(arrayish ? "]" : "}"));32653266return span;3267}32683269function* iterateMap$1(map) {3270for (const [key, value] of map) {3271yield formatMapField$1(key, value);3272}3273yield* iterateObject$1(map);3274}32753276function* iterateSet$1(set) {3277for (const value of set) {3278yield formatSetField(value);3279}3280yield* iterateObject$1(set);3281}32823283function* iterateImSet$1(set) {3284for (const value of set) {3285yield formatSetField(value);3286}3287}32883289function* iterateArray$1(array) {3290for (let i = 0, n = array.length; i < n; ++i) {3291if (i in array) {3292yield formatField$1(i, valueof(array, i), "observablehq--index");3293}3294}3295for (const key in array) {3296if (!isindex(key) && isown(array, key)) {3297yield formatField$1(key, valueof(array, key), "observablehq--key");3298}3299}3300for (const symbol of symbolsof(array)) {3301yield formatField$1(3302formatSymbol(symbol),3303valueof(array, symbol),3304"observablehq--symbol"3305);3306}3307}33083309function* iterateImArray$1(array) {3310let i1 = 0;3311for (const n = array.size; i1 < n; ++i1) {3312yield formatField$1(i1, array.get(i1), true);3313}3314}33153316function* iterateProto(object) {3317for (const key in getOwnPropertyDescriptors(object)) {3318yield formatField$1(key, valueof(object, key), "observablehq--key");3319}3320for (const symbol of symbolsof(object)) {3321yield formatField$1(3322formatSymbol(symbol),3323valueof(object, symbol),3324"observablehq--symbol"3325);3326}33273328const proto = getPrototypeOf(object);3329if (proto && proto !== objectPrototype) {3330yield formatPrototype(proto);3331}3332}33333334function* iterateObject$1(object) {3335for (const key in object) {3336if (isown(object, key)) {3337yield formatField$1(key, valueof(object, key), "observablehq--key");3338}3339}3340for (const symbol of symbolsof(object)) {3341yield formatField$1(3342formatSymbol(symbol),3343valueof(object, symbol),3344"observablehq--symbol"3345);3346}33473348const proto = getPrototypeOf(object);3349if (proto && proto !== objectPrototype) {3350yield formatPrototype(proto);3351}3352}33533354function* iterateImObject$1(object) {3355for (const [key, value] of object) {3356yield formatField$1(key, value, "observablehq--key");3357}3358}33593360function formatPrototype(value) {3361const item = document.createElement("div");3362const span = item.appendChild(document.createElement("span"));3363item.className = "observablehq--field";3364span.className = "observablehq--prototype-key";3365span.textContent = ` <prototype>`;3366item.appendChild(document.createTextNode(": "));3367item.appendChild(inspect(value, undefined, undefined, undefined, true));3368return item;3369}33703371function formatField$1(key, value, className) {3372const item = document.createElement("div");3373const span = item.appendChild(document.createElement("span"));3374item.className = "observablehq--field";3375span.className = className;3376span.textContent = ` ${key}`;3377item.appendChild(document.createTextNode(": "));3378item.appendChild(inspect(value));3379return item;3380}33813382function formatMapField$1(key, value) {3383const item = document.createElement("div");3384item.className = "observablehq--field";3385item.appendChild(document.createTextNode(" "));3386item.appendChild(inspect(key));3387item.appendChild(document.createTextNode(" => "));3388item.appendChild(inspect(value));3389return item;3390}33913392function formatSetField(value) {3393const item = document.createElement("div");3394item.className = "observablehq--field";3395item.appendChild(document.createTextNode(" "));3396item.appendChild(inspect(value));3397return item;3398}33993400function hasSelection(elem) {3401const sel = window.getSelection();3402return (3403sel.type === "Range" &&3404(sel.containsNode(elem, true) ||3405sel.anchorNode.isSelfOrDescendant(elem) ||3406sel.focusNode.isSelfOrDescendant(elem))3407);3408}34093410function inspectCollapsed(object, shallow, name, proto) {3411let arrayish = isarray(object);3412let tag, fields, next, n;34133414if (object instanceof Map) {3415if (object instanceof object.constructor) {3416tag = `Map(${object.size})`;3417fields = iterateMap;3418} else { // avoid incompatible receiver error for prototype3419tag = "Map()";3420fields = iterateObject;3421}3422} else if (object instanceof Set) {3423if (object instanceof object.constructor) {3424tag = `Set(${object.size})`;3425fields = iterateSet;3426} else { // avoid incompatible receiver error for prototype3427tag = "Set()";3428fields = iterateObject;3429}3430} else if (arrayish) {3431tag = `${object.constructor.name}(${object.length})`;3432fields = iterateArray;3433} else if ((n = immutableName(object))) {3434tag = `Immutable.${n.name}${n.name === 'Record' ? '' : `(${object.size})`}`;3435arrayish = n.arrayish;3436fields = n.arrayish ? iterateImArray : n.setish ? iterateImSet : iterateImObject;3437} else {3438tag = tagof(object);3439fields = iterateObject;3440}34413442if (shallow) {3443const span = document.createElement("span");3444span.className = "observablehq--shallow";3445if (name) {3446span.appendChild(inspectName(name));3447}3448span.appendChild(document.createTextNode(tag));3449span.addEventListener("mouseup", function(event) {3450if (hasSelection(span)) return;3451event.stopPropagation();3452replace(span, inspectCollapsed(object));3453});3454return span;3455}34563457const span = document.createElement("span");3458span.className = "observablehq--collapsed";3459if (name) {3460span.appendChild(inspectName(name));3461}3462const a = span.appendChild(document.createElement("a"));3463a.innerHTML = `<svg width=8 height=8 class='observablehq--caret'>3464<path d='M7 4L1 8V0z' fill='currentColor' />3465</svg>`;3466a.appendChild(document.createTextNode(`${tag}${arrayish ? " [" : " {"}`));3467span.addEventListener("mouseup", function(event) {3468if (hasSelection(span)) return;3469event.stopPropagation();3470replace(span, inspectExpanded(object, null, name, proto));3471}, true);34723473fields = fields(object);3474for (let i = 0; !(next = fields.next()).done && i < 20; ++i) {3475if (i > 0) span.appendChild(document.createTextNode(", "));3476span.appendChild(next.value);3477}34783479if (!next.done) span.appendChild(document.createTextNode(", …"));3480span.appendChild(document.createTextNode(arrayish ? "]" : "}"));34813482return span;3483}34843485function* iterateMap(map) {3486for (const [key, value] of map) {3487yield formatMapField(key, value);3488}3489yield* iterateObject(map);3490}34913492function* iterateSet(set) {3493for (const value of set) {3494yield inspect(value, true);3495}3496yield* iterateObject(set);3497}34983499function* iterateImSet(set) {3500for (const value of set) {3501yield inspect(value, true);3502}3503}35043505function* iterateImArray(array) {3506let i0 = -1, i1 = 0;3507for (const n = array.size; i1 < n; ++i1) {3508if (i1 > i0 + 1) yield formatEmpty(i1 - i0 - 1);3509yield inspect(array.get(i1), true);3510i0 = i1;3511}3512if (i1 > i0 + 1) yield formatEmpty(i1 - i0 - 1);3513}35143515function* iterateArray(array) {3516let i0 = -1, i1 = 0;3517for (const n = array.length; i1 < n; ++i1) {3518if (i1 in array) {3519if (i1 > i0 + 1) yield formatEmpty(i1 - i0 - 1);3520yield inspect(valueof(array, i1), true);3521i0 = i1;3522}3523}3524if (i1 > i0 + 1) yield formatEmpty(i1 - i0 - 1);3525for (const key in array) {3526if (!isindex(key) && isown(array, key)) {3527yield formatField(key, valueof(array, key), "observablehq--key");3528}3529}3530for (const symbol of symbolsof(array)) {3531yield formatField(formatSymbol(symbol), valueof(array, symbol), "observablehq--symbol");3532}3533}35343535function* iterateObject(object) {3536for (const key in object) {3537if (isown(object, key)) {3538yield formatField(key, valueof(object, key), "observablehq--key");3539}3540}3541for (const symbol of symbolsof(object)) {3542yield formatField(formatSymbol(symbol), valueof(object, symbol), "observablehq--symbol");3543}3544}35453546function* iterateImObject(object) {3547for (const [key, value] of object) {3548yield formatField(key, value, "observablehq--key");3549}3550}35513552function formatEmpty(e) {3553const span = document.createElement("span");3554span.className = "observablehq--empty";3555span.textContent = e === 1 ? "empty" : `empty × ${e}`;3556return span;3557}35583559function formatField(key, value, className) {3560const fragment = document.createDocumentFragment();3561const span = fragment.appendChild(document.createElement("span"));3562span.className = className;3563span.textContent = key;3564fragment.appendChild(document.createTextNode(": "));3565fragment.appendChild(inspect(value, true));3566return fragment;3567}35683569function formatMapField(key, value) {3570const fragment = document.createDocumentFragment();3571fragment.appendChild(inspect(key, true));3572fragment.appendChild(document.createTextNode(" => "));3573fragment.appendChild(inspect(value, true));3574return fragment;3575}35763577function format(date, fallback) {3578if (!(date instanceof Date)) date = new Date(+date);3579if (isNaN(date)) return typeof fallback === "function" ? fallback(date) : fallback;3580const hours = date.getUTCHours();3581const minutes = date.getUTCMinutes();3582const seconds = date.getUTCSeconds();3583const milliseconds = date.getUTCMilliseconds();3584return `${formatYear(date.getUTCFullYear())}-${pad(date.getUTCMonth() + 1, 2)}-${pad(date.getUTCDate(), 2)}${3585hours || minutes || seconds || milliseconds ? `T${pad(hours, 2)}:${pad(minutes, 2)}${3586seconds || milliseconds ? `:${pad(seconds, 2)}${3587milliseconds ? `.${pad(milliseconds, 3)}` : ``3588}` : ``3589}Z` : ``3590}`;3591}35923593function formatYear(year) {3594return year < 0 ? `-${pad(-year, 6)}`3595: year > 9999 ? `+${pad(year, 6)}`3596: pad(year, 4);3597}35983599function pad(value, width) {3600return `${value}`.padStart(width, "0");3601}36023603function formatDate$1(date) {3604return format(date, "Invalid Date");3605}36063607var errorToString = Error.prototype.toString;36083609function formatError(value) {3610return value.stack || errorToString.call(value);3611}36123613var regExpToString = RegExp.prototype.toString;36143615function formatRegExp(value) {3616return regExpToString.call(value);3617}36183619/* eslint-disable no-control-regex */3620const NEWLINE_LIMIT = 20;36213622function formatString(string, shallow, expanded, name) {3623if (shallow === false) {3624// String has fewer escapes displayed with double quotes3625if (count(string, /["\n]/g) <= count(string, /`|\${/g)) {3626const span = document.createElement("span");3627if (name) span.appendChild(inspectName(name));3628const textValue = span.appendChild(document.createElement("span"));3629textValue.className = "observablehq--string";3630textValue.textContent = JSON.stringify(string);3631return span;3632}3633const lines = string.split("\n");3634if (lines.length > NEWLINE_LIMIT && !expanded) {3635const div = document.createElement("div");3636if (name) div.appendChild(inspectName(name));3637const textValue = div.appendChild(document.createElement("span"));3638textValue.className = "observablehq--string";3639textValue.textContent = "`" + templatify(lines.slice(0, NEWLINE_LIMIT).join("\n"));3640const splitter = div.appendChild(document.createElement("span"));3641const truncatedCount = lines.length - NEWLINE_LIMIT;3642splitter.textContent = `Show ${truncatedCount} truncated line${truncatedCount > 1 ? "s": ""}`; splitter.className = "observablehq--string-expand";3643splitter.addEventListener("mouseup", function (event) {3644event.stopPropagation();3645replace(div, inspect(string, shallow, true, name));3646});3647return div;3648}3649const span = document.createElement("span");3650if (name) span.appendChild(inspectName(name));3651const textValue = span.appendChild(document.createElement("span"));3652textValue.className = `observablehq--string${expanded ? " observablehq--expanded" : ""}`;3653textValue.textContent = "`" + templatify(string) + "`";3654return span;3655}36563657const span = document.createElement("span");3658if (name) span.appendChild(inspectName(name));3659const textValue = span.appendChild(document.createElement("span"));3660textValue.className = "observablehq--string";3661textValue.textContent = JSON.stringify(string.length > 100 ?3662`${string.slice(0, 50)}…${string.slice(-49)}` : string);3663return span;3664}36653666function templatify(string) {3667return string.replace(/[\\`\x00-\x09\x0b-\x19]|\${/g, templatifyChar);3668}36693670function templatifyChar(char) {3671var code = char.charCodeAt(0);3672switch (code) {3673case 0x8: return "\\b";3674case 0x9: return "\\t";3675case 0xb: return "\\v";3676case 0xc: return "\\f";3677case 0xd: return "\\r";3678}3679return code < 0x10 ? "\\x0" + code.toString(16)3680: code < 0x20 ? "\\x" + code.toString(16)3681: "\\" + char;3682}36833684function count(string, re) {3685var n = 0;3686while (re.exec(string)) ++n;3687return n;3688}36893690var toString$2 = Function.prototype.toString,3691TYPE_ASYNC = {prefix: "async ƒ"},3692TYPE_ASYNC_GENERATOR = {prefix: "async ƒ*"},3693TYPE_CLASS = {prefix: "class"},3694TYPE_FUNCTION = {prefix: "ƒ"},3695TYPE_GENERATOR = {prefix: "ƒ*"};36963697function inspectFunction(f, name) {3698var type, m, t = toString$2.call(f);36993700switch (f.constructor && f.constructor.name) {3701case "AsyncFunction": type = TYPE_ASYNC; break;3702case "AsyncGeneratorFunction": type = TYPE_ASYNC_GENERATOR; break;3703case "GeneratorFunction": type = TYPE_GENERATOR; break;3704default: type = /^class\b/.test(t) ? TYPE_CLASS : TYPE_FUNCTION; break;3705}37063707// A class, possibly named.3708// class Name3709if (type === TYPE_CLASS) {3710return formatFunction(type, "", name);3711}37123713// An arrow function with a single argument.3714// foo =>3715// async foo =>3716if ((m = /^(?:async\s*)?(\w+)\s*=>/.exec(t))) {3717return formatFunction(type, "(" + m[1] + ")", name);3718}37193720// An arrow function with parenthesized arguments.3721// (…)3722// async (…)3723if ((m = /^(?:async\s*)?\(\s*(\w+(?:\s*,\s*\w+)*)?\s*\)/.exec(t))) {3724return formatFunction(type, m[1] ? "(" + m[1].replace(/\s*,\s*/g, ", ") + ")" : "()", name);3725}37263727// A function, possibly: async, generator, anonymous, simply arguments.3728// function name(…)3729// function* name(…)3730// async function name(…)3731// async function* name(…)3732if ((m = /^(?:async\s*)?function(?:\s*\*)?(?:\s*\w+)?\s*\(\s*(\w+(?:\s*,\s*\w+)*)?\s*\)/.exec(t))) {3733return formatFunction(type, m[1] ? "(" + m[1].replace(/\s*,\s*/g, ", ") + ")" : "()", name);3734}37353736// Something else, like destructuring, comments or default values.3737return formatFunction(type, "(…)", name);3738}37393740function formatFunction(type, args, cellname) {3741var span = document.createElement("span");3742span.className = "observablehq--function";3743if (cellname) {3744span.appendChild(inspectName(cellname));3745}3746var spanType = span.appendChild(document.createElement("span"));3747spanType.className = "observablehq--keyword";3748spanType.textContent = type.prefix;3749span.appendChild(document.createTextNode(args));3750return span;3751}37523753const {prototype: {toString: toString$1}} = Object;37543755function inspect(value, shallow, expand, name, proto) {3756let type = typeof value;3757switch (type) {3758case "boolean":3759case "undefined": { value += ""; break; }3760case "number": { value = value === 0 && 1 / value < 0 ? "-0" : value + ""; break; }3761case "bigint": { value = value + "n"; break; }3762case "symbol": { value = formatSymbol(value); break; }3763case "function": { return inspectFunction(value, name); }3764case "string": { return formatString(value, shallow, expand, name); }3765default: {3766if (value === null) { type = null, value = "null"; break; }3767if (value instanceof Date) { type = "date", value = formatDate$1(value); break; }3768if (value === FORBIDDEN) { type = "forbidden", value = "[forbidden]"; break; }3769switch (toString$1.call(value)) {3770case "[object RegExp]": { type = "regexp", value = formatRegExp(value); break; }3771case "[object Error]": // https://github.com/lodash/lodash/blob/master/isError.js#L263772case "[object DOMException]": { type = "error", value = formatError(value); break; }3773default: return (expand ? inspectExpanded : inspectCollapsed)(value, shallow, name, proto);3774}3775break;3776}3777}3778const span = document.createElement("span");3779if (name) span.appendChild(inspectName(name));3780const n = span.appendChild(document.createElement("span"));3781n.className = `observablehq--${type}`;3782n.textContent = value;3783return span;3784}37853786function replace(spanOld, spanNew) {3787if (spanOld.classList.contains("observablehq--inspect")) spanNew.classList.add("observablehq--inspect");3788spanOld.parentNode.replaceChild(spanNew, spanOld);3789dispatch(spanNew, "load");3790}37913792const LOCATION_MATCH = /\s+\(\d+:\d+\)$/m;37933794class Inspector {3795constructor(node) {3796if (!node) throw new Error("invalid node");3797this._node = node;3798node.classList.add("observablehq");3799}3800pending() {3801const {_node} = this;3802_node.classList.remove("observablehq--error");3803_node.classList.add("observablehq--running");3804}3805fulfilled(value, name) {3806const {_node} = this;3807if (!isnode(value) || (value.parentNode && value.parentNode !== _node)) {3808value = inspect(value, false, _node.firstChild // TODO Do this better.3809&& _node.firstChild.classList3810&& _node.firstChild.classList.contains("observablehq--expanded"), name);3811value.classList.add("observablehq--inspect");3812}3813_node.classList.remove("observablehq--running", "observablehq--error");3814if (_node.firstChild !== value) {3815if (_node.firstChild) {3816while (_node.lastChild !== _node.firstChild) _node.removeChild(_node.lastChild);3817_node.replaceChild(value, _node.firstChild);3818} else {3819_node.appendChild(value);3820}3821}3822dispatch(_node, "update");3823}3824rejected(error, name) {3825const {_node} = this;3826_node.classList.remove("observablehq--running");3827_node.classList.add("observablehq--error");3828while (_node.lastChild) _node.removeChild(_node.lastChild);3829var div = document.createElement("div");3830div.className = "observablehq--inspect";3831if (name) div.appendChild(inspectName(name));3832div.appendChild(document.createTextNode((error + "").replace(LOCATION_MATCH, "")));3833_node.appendChild(div);3834dispatch(_node, "error", {error: error});3835}3836}38373838Inspector.into = function(container) {3839if (typeof container === "string") {3840container = document.querySelector(container);3841if (container == null) throw new Error("container not found");3842}3843return function() {3844return new Inspector(container.appendChild(document.createElement("div")));3845};3846};38473848// Returns true if the given value is something that should be added to the DOM3849// by the inspector, rather than being inspected. This deliberately excludes3850// DocumentFragment since appending a fragment “dissolves” (mutates) the3851// fragment, and we wish for the inspector to not have side-effects. Also,3852// HTMLElement.prototype is an instanceof Element, but not an element!3853function isnode(value) {3854return (value instanceof Element || value instanceof Text)3855&& (value instanceof value.constructor);3856}38573858class RuntimeError extends Error {3859constructor(message, input) {3860super(message);3861this.input = input;3862}3863}38643865RuntimeError.prototype.name = "RuntimeError";38663867function generatorish(value) {3868return value3869&& typeof value.next === "function"3870&& typeof value.return === "function";3871}38723873function load(notebook, library, observer) {3874if (typeof library == "function") observer = library, library = null;3875if (typeof observer !== "function") throw new Error("invalid observer");3876if (library == null) library = new Library();38773878const {modules, id} = notebook;3879const map = new Map;3880const runtime = new Runtime(library);3881const main = runtime_module(id);38823883function runtime_module(id) {3884let module = map.get(id);3885if (!module) map.set(id, module = runtime.module());3886return module;3887}38883889for (const m of modules) {3890const module = runtime_module(m.id);3891let i = 0;3892for (const v of m.variables) {3893if (v.from) module.import(v.remote, v.name, runtime_module(v.from));3894else if (module === main) module.variable(observer(v, i, m.variables)).define(v.name, v.inputs, v.value);3895else module.define(v.name, v.inputs, v.value);3896++i;3897}3898}38993900return runtime;3901}39023903function constant(x) {3904return () => x;3905}39063907function identity$1(x) {3908return x;3909}39103911function rethrow(error) {3912return () => {3913throw error;3914};3915}39163917const prototype = Array.prototype;3918const map = prototype.map;39193920function noop() {}39213922const TYPE_NORMAL = 1; // a normal variable3923const TYPE_IMPLICIT = 2; // created on reference3924const TYPE_DUPLICATE = 3; // created on duplicate definition39253926const no_observer = Symbol("no-observer");39273928function Variable(type, module, observer, options) {3929if (!observer) observer = no_observer;3930Object.defineProperties(this, {3931_observer: {value: observer, writable: true},3932_definition: {value: variable_undefined, writable: true},3933_duplicate: {value: undefined, writable: true},3934_duplicates: {value: undefined, writable: true},3935_indegree: {value: NaN, writable: true}, // The number of computing inputs.3936_inputs: {value: [], writable: true},3937_invalidate: {value: noop, writable: true},3938_module: {value: module},3939_name: {value: null, writable: true},3940_outputs: {value: new Set, writable: true},3941_promise: {value: Promise.resolve(undefined), writable: true},3942_reachable: {value: observer !== no_observer, writable: true}, // Is this variable transitively visible?3943_rejector: {value: variable_rejector(this)},3944_shadow: {value: initShadow(module, options)},3945_type: {value: type},3946_value: {value: undefined, writable: true},3947_version: {value: 0, writable: true}3948});3949}39503951Object.defineProperties(Variable.prototype, {3952_pending: {value: variable_pending, writable: true, configurable: true},3953_fulfilled: {value: variable_fulfilled, writable: true, configurable: true},3954_rejected: {value: variable_rejected, writable: true, configurable: true},3955_resolve: {value: variable_resolve, writable: true, configurable: true},3956define: {value: variable_define, writable: true, configurable: true},3957delete: {value: variable_delete, writable: true, configurable: true},3958import: {value: variable_import, writable: true, configurable: true}3959});39603961function initShadow(module, options) {3962if (!options?.shadow) return null;3963return new Map(3964Object.entries(options.shadow)3965.map(([name, definition]) => [name, (new Variable(TYPE_IMPLICIT, module)).define([], definition)])3966);3967}39683969function variable_attach(variable) {3970variable._module._runtime._dirty.add(variable);3971variable._outputs.add(this);3972}39733974function variable_detach(variable) {3975variable._module._runtime._dirty.add(variable);3976variable._outputs.delete(this);3977}39783979function variable_undefined() {3980throw variable_undefined;3981}39823983function variable_stale() {3984throw variable_stale;3985}39863987function variable_rejector(variable) {3988return (error) => {3989if (error === variable_stale) throw error;3990if (error === variable_undefined) throw new RuntimeError(`${variable._name} is not defined`, variable._name);3991if (error instanceof Error && error.message) throw new RuntimeError(error.message, variable._name);3992throw new RuntimeError(`${variable._name} could not be resolved`, variable._name);3993};3994}39953996function variable_duplicate(name) {3997return () => {3998throw new RuntimeError(`${name} is defined more than once`);3999};4000}40014002function variable_define(name, inputs, definition) {4003switch (arguments.length) {4004case 1: {4005definition = name, name = inputs = null;4006break;4007}4008case 2: {4009definition = inputs;4010if (typeof name === "string") inputs = null;4011else inputs = name, name = null;4012break;4013}4014}4015return variable_defineImpl.call(this,4016name == null ? null : String(name),4017inputs == null ? [] : map.call(inputs, this._resolve, this),4018typeof definition === "function" ? definition : constant(definition)4019);4020}40214022function variable_resolve(name) {4023return this._shadow?.get(name) ?? this._module._resolve(name);4024}40254026function variable_defineImpl(name, inputs, definition) {4027const scope = this._module._scope, runtime = this._module._runtime;40284029this._inputs.forEach(variable_detach, this);4030inputs.forEach(variable_attach, this);4031this._inputs = inputs;4032this._definition = definition;4033this._value = undefined;40344035// Is this an active variable (that may require disposal)?4036if (definition === noop) runtime._variables.delete(this);4037else runtime._variables.add(this);40384039// Did the variable’s name change? Time to patch references!4040if (name !== this._name || scope.get(name) !== this) {4041let error, found;40424043if (this._name) { // Did this variable previously have a name?4044if (this._outputs.size) { // And did other variables reference this variable?4045scope.delete(this._name);4046found = this._module._resolve(this._name);4047found._outputs = this._outputs, this._outputs = new Set;4048found._outputs.forEach(function(output) { output._inputs[output._inputs.indexOf(this)] = found; }, this);4049found._outputs.forEach(runtime._updates.add, runtime._updates);4050runtime._dirty.add(found).add(this);4051scope.set(this._name, found);4052} else if ((found = scope.get(this._name)) === this) { // Do no other variables reference this variable?4053scope.delete(this._name); // It’s safe to delete!4054} else if (found._type === TYPE_DUPLICATE) { // Do other variables assign this name?4055found._duplicates.delete(this); // This variable no longer assigns this name.4056this._duplicate = undefined;4057if (found._duplicates.size === 1) { // Is there now only one variable assigning this name?4058found = found._duplicates.keys().next().value; // Any references are now fixed!4059error = scope.get(this._name);4060found._outputs = error._outputs, error._outputs = new Set;4061found._outputs.forEach(function(output) { output._inputs[output._inputs.indexOf(error)] = found; });4062found._definition = found._duplicate, found._duplicate = undefined;4063runtime._dirty.add(error).add(found);4064runtime._updates.add(found);4065scope.set(this._name, found);4066}4067} else {4068throw new Error;4069}4070}40714072if (this._outputs.size) throw new Error;40734074if (name) { // Does this variable have a new name?4075if (found = scope.get(name)) { // Do other variables reference or assign this name?4076if (found._type === TYPE_DUPLICATE) { // Do multiple other variables already define this name?4077this._definition = variable_duplicate(name), this._duplicate = definition;4078found._duplicates.add(this);4079} else if (found._type === TYPE_IMPLICIT) { // Are the variable references broken?4080this._outputs = found._outputs, found._outputs = new Set; // Now they’re fixed!4081this._outputs.forEach(function(output) { output._inputs[output._inputs.indexOf(found)] = this; }, this);4082runtime._dirty.add(found).add(this);4083scope.set(name, this);4084} else { // Does another variable define this name?4085found._duplicate = found._definition, this._duplicate = definition; // Now they’re duplicates.4086error = new Variable(TYPE_DUPLICATE, this._module);4087error._name = name;4088error._definition = this._definition = found._definition = variable_duplicate(name);4089error._outputs = found._outputs, found._outputs = new Set;4090error._outputs.forEach(function(output) { output._inputs[output._inputs.indexOf(found)] = error; });4091error._duplicates = new Set([this, found]);4092runtime._dirty.add(found).add(error);4093runtime._updates.add(found).add(error);4094scope.set(name, error);4095}4096} else {4097scope.set(name, this);4098}4099}41004101this._name = name;4102}41034104// If this redefined variable was previously evaluated, invalidate it. (If the4105// variable was never evaluated, then the invalidated value could never have4106// been exposed and we can avoid this extra work.)4107if (this._version > 0) ++this._version;41084109runtime._updates.add(this);4110runtime._compute();4111return this;4112}41134114function variable_import(remote, name, module) {4115if (arguments.length < 3) module = name, name = remote;4116return variable_defineImpl.call(this, String(name), [module._resolve(String(remote))], identity$1);4117}41184119function variable_delete() {4120return variable_defineImpl.call(this, null, [], noop);4121}41224123function variable_pending() {4124if (this._observer.pending) this._observer.pending();4125}41264127function variable_fulfilled(value) {4128if (this._observer.fulfilled) this._observer.fulfilled(value, this._name);4129}41304131function variable_rejected(error) {4132if (this._observer.rejected) this._observer.rejected(error, this._name);4133}41344135const variable_variable = Symbol("variable");4136const variable_invalidation = Symbol("invalidation");4137const variable_visibility = Symbol("visibility");41384139function Module(runtime, builtins = []) {4140Object.defineProperties(this, {4141_runtime: {value: runtime},4142_scope: {value: new Map},4143_builtins: {value: new Map([4144["@variable", variable_variable],4145["invalidation", variable_invalidation],4146["visibility", variable_visibility],4147...builtins4148])},4149_source: {value: null, writable: true}4150});4151}41524153Object.defineProperties(Module.prototype, {4154_resolve: {value: module_resolve, writable: true, configurable: true},4155redefine: {value: module_redefine, writable: true, configurable: true},4156define: {value: module_define, writable: true, configurable: true},4157derive: {value: module_derive, writable: true, configurable: true},4158import: {value: module_import, writable: true, configurable: true},4159value: {value: module_value, writable: true, configurable: true},4160variable: {value: module_variable, writable: true, configurable: true},4161builtin: {value: module_builtin, writable: true, configurable: true}4162});41634164function module_redefine(name) {4165const v = this._scope.get(name);4166if (!v) throw new RuntimeError(`${name} is not defined`);4167if (v._type === TYPE_DUPLICATE) throw new RuntimeError(`${name} is defined more than once`);4168return v.define.apply(v, arguments);4169}41704171function module_define() {4172const v = new Variable(TYPE_NORMAL, this);4173return v.define.apply(v, arguments);4174}41754176function module_import() {4177const v = new Variable(TYPE_NORMAL, this);4178return v.import.apply(v, arguments);4179}41804181function module_variable(observer, options) {4182return new Variable(TYPE_NORMAL, this, observer, options);4183}41844185async function module_value(name) {4186let v = this._scope.get(name);4187if (!v) throw new RuntimeError(`${name} is not defined`);4188if (v._observer === no_observer) {4189v = this.variable(true).define([name], identity$1);4190try {4191return await module_revalue(this._runtime, v);4192} finally {4193v.delete();4194}4195} else {4196return module_revalue(this._runtime, v);4197}4198}41994200// If the variable is redefined before its value resolves, try again.4201async function module_revalue(runtime, variable) {4202await runtime._compute();4203try {4204return await variable._promise;4205} catch (error) {4206if (error === variable_stale) return module_revalue(runtime, variable);4207throw error;4208}4209}42104211function module_derive(injects, injectModule) {4212const map = new Map();4213const modules = new Set();4214const copies = [];42154216// Given a module, derives an alias of that module with an initially-empty4217// definition. The variables will be copied later in a second pass below.4218function alias(source) {4219let target = map.get(source);4220if (target) return target;4221target = new Module(source._runtime, source._builtins);4222target._source = source;4223map.set(source, target);4224copies.push([target, source]);4225modules.add(source);4226return target;4227}42284229// Inject the given variables as reverse imports into the derived module.4230const derive = alias(this);4231for (const inject of injects) {4232const {alias, name} = typeof inject === "object" ? inject : {name: inject};4233derive.import(name, alias == null ? name : alias, injectModule);4234}42354236// Iterate over all the variables (currently) in this module. If any4237// represents an import-with (i.e., an import of a module with a _source), the4238// transitive import-with must be copied, too, as direct injections may affect4239// transitive injections. Note that an import-with can only be created with4240// module.derive and hence it’s not possible for an import-with to be added4241// later; therefore we only need to apply this check once, now.4242for (const module of modules) {4243for (const [name, variable] of module._scope) {4244if (variable._definition === identity$1) { // import4245if (module === this && derive._scope.has(name)) continue; // overridden by injection4246const importedModule = variable._inputs[0]._module;4247if (importedModule._source) alias(importedModule);4248}4249}4250}42514252// Finally, with the modules resolved, copy the variable definitions.4253for (const [target, source] of copies) {4254for (const [name, sourceVariable] of source._scope) {4255const targetVariable = target._scope.get(name);4256if (targetVariable && targetVariable._type !== TYPE_IMPLICIT) continue; // preserve injection4257if (sourceVariable._definition === identity$1) { // import4258const sourceInput = sourceVariable._inputs[0];4259const sourceModule = sourceInput._module;4260target.import(sourceInput._name, name, map.get(sourceModule) || sourceModule);4261} else { // non-import4262target.define(name, sourceVariable._inputs.map(variable_name), sourceVariable._definition);4263}4264}4265}42664267return derive;4268}42694270function module_resolve(name) {4271let variable = this._scope.get(name), value;4272if (!variable) {4273variable = new Variable(TYPE_IMPLICIT, this);4274if (this._builtins.has(name)) {4275variable.define(name, constant(this._builtins.get(name)));4276} else if (this._runtime._builtin._scope.has(name)) {4277variable.import(name, this._runtime._builtin);4278} else {4279try {4280value = this._runtime._global(name);4281} catch (error) {4282return variable.define(name, rethrow(error));4283}4284if (value === undefined) {4285this._scope.set(variable._name = name, variable);4286} else {4287variable.define(name, constant(value));4288}4289}4290}4291return variable;4292}42934294function module_builtin(name, value) {4295this._builtins.set(name, value);4296}42974298function variable_name(variable) {4299return variable._name;4300}43014302const frame = typeof requestAnimationFrame === "function" ? requestAnimationFrame4303: typeof setImmediate === "function" ? setImmediate4304: f => setTimeout(f, 0);43054306function Runtime(builtins = new Library, global = window_global) {4307const builtin = this.module();4308Object.defineProperties(this, {4309_dirty: {value: new Set},4310_updates: {value: new Set},4311_precomputes: {value: [], writable: true},4312_computing: {value: null, writable: true},4313_init: {value: null, writable: true},4314_modules: {value: new Map},4315_variables: {value: new Set},4316_disposed: {value: false, writable: true},4317_builtin: {value: builtin},4318_global: {value: global}4319});4320if (builtins) for (const name in builtins) {4321(new Variable(TYPE_IMPLICIT, builtin)).define(name, [], builtins[name]);4322}4323}43244325Object.defineProperties(Runtime.prototype, {4326_precompute: {value: runtime_precompute, writable: true, configurable: true},4327_compute: {value: runtime_compute, writable: true, configurable: true},4328_computeSoon: {value: runtime_computeSoon, writable: true, configurable: true},4329_computeNow: {value: runtime_computeNow, writable: true, configurable: true},4330dispose: {value: runtime_dispose, writable: true, configurable: true},4331module: {value: runtime_module, writable: true, configurable: true},4332fileAttachments: {value: FileAttachments, writable: true, configurable: true},4333load: {value: load, writable: true, configurable: true}4334});43354336function runtime_dispose() {4337this._computing = Promise.resolve();4338this._disposed = true;4339this._variables.forEach(v => {4340v._invalidate();4341v._version = NaN;4342});4343}43444345function runtime_module(define, observer = noop) {4346let module;4347if (define === undefined) {4348if (module = this._init) {4349this._init = null;4350return module;4351}4352return new Module(this);4353}4354module = this._modules.get(define);4355if (module) return module;4356this._init = module = new Module(this);4357this._modules.set(define, module);4358try {4359define(this, observer);4360} finally {4361this._init = null;4362}4363return module;4364}43654366function runtime_precompute(callback) {4367this._precomputes.push(callback);4368this._compute();4369}43704371function runtime_compute() {4372return this._computing || (this._computing = this._computeSoon());4373}43744375function runtime_computeSoon() {4376return new Promise(frame).then(() => this._disposed ? undefined : this._computeNow());4377}43784379async function runtime_computeNow() {4380let queue = [],4381variables,4382variable,4383precomputes = this._precomputes;43844385// If there are any paused generators, resume them before computing so they4386// can update (if synchronous) before computing downstream variables.4387if (precomputes.length) {4388this._precomputes = [];4389for (const callback of precomputes) callback();4390await runtime_defer(3);4391}43924393// Compute the reachability of the transitive closure of dirty variables.4394// Any newly-reachable variable must also be recomputed.4395// Any no-longer-reachable variable must be terminated.4396variables = new Set(this._dirty);4397variables.forEach(function(variable) {4398variable._inputs.forEach(variables.add, variables);4399const reachable = variable_reachable(variable);4400if (reachable > variable._reachable) {4401this._updates.add(variable);4402} else if (reachable < variable._reachable) {4403variable._invalidate();4404}4405variable._reachable = reachable;4406}, this);44074408// Compute the transitive closure of updating, reachable variables.4409variables = new Set(this._updates);4410variables.forEach(function(variable) {4411if (variable._reachable) {4412variable._indegree = 0;4413variable._outputs.forEach(variables.add, variables);4414} else {4415variable._indegree = NaN;4416variables.delete(variable);4417}4418});44194420this._computing = null;4421this._updates.clear();4422this._dirty.clear();44234424// Compute the indegree of updating variables.4425variables.forEach(function(variable) {4426variable._outputs.forEach(variable_increment);4427});44284429do {4430// Identify the root variables (those with no updating inputs).4431variables.forEach(function(variable) {4432if (variable._indegree === 0) {4433queue.push(variable);4434}4435});44364437// Compute the variables in topological order.4438while (variable = queue.pop()) {4439variable_compute(variable);4440variable._outputs.forEach(postqueue);4441variables.delete(variable);4442}44434444// Any remaining variables are circular, or depend on them.4445variables.forEach(function(variable) {4446if (variable_circular(variable)) {4447variable_error(variable, new RuntimeError("circular definition"));4448variable._outputs.forEach(variable_decrement);4449variables.delete(variable);4450}4451});4452} while (variables.size);44534454function postqueue(variable) {4455if (--variable._indegree === 0) {4456queue.push(variable);4457}4458}4459}44604461// We want to give generators, if they’re defined synchronously, a chance to4462// update before computing downstream variables. This creates a synchronous4463// promise chain of the given depth that we’ll await before recomputing4464// downstream variables.4465function runtime_defer(depth = 0) {4466let p = Promise.resolve();4467for (let i = 0; i < depth; ++i) p = p.then(() => {});4468return p;4469}44704471function variable_circular(variable) {4472const inputs = new Set(variable._inputs);4473for (const i of inputs) {4474if (i === variable) return true;4475i._inputs.forEach(inputs.add, inputs);4476}4477return false;4478}44794480function variable_increment(variable) {4481++variable._indegree;4482}44834484function variable_decrement(variable) {4485--variable._indegree;4486}44874488function variable_value(variable) {4489return variable._promise.catch(variable._rejector);4490}44914492function variable_invalidator(variable) {4493return new Promise(function(resolve) {4494variable._invalidate = resolve;4495});4496}44974498function variable_intersector(invalidation, variable) {4499let node = typeof IntersectionObserver === "function" && variable._observer && variable._observer._node;4500let visible = !node, resolve = noop, reject = noop, promise, observer;4501if (node) {4502observer = new IntersectionObserver(([entry]) => (visible = entry.isIntersecting) && (promise = null, resolve()));4503observer.observe(node);4504invalidation.then(() => (observer.disconnect(), observer = null, reject()));4505}4506return function(value) {4507if (visible) return Promise.resolve(value);4508if (!observer) return Promise.reject();4509if (!promise) promise = new Promise((y, n) => (resolve = y, reject = n));4510return promise.then(() => value);4511};4512}45134514function variable_compute(variable) {4515variable._invalidate();4516variable._invalidate = noop;4517variable._pending();45184519const value0 = variable._value;4520const version = ++variable._version;45214522// Lazily-constructed invalidation variable; only constructed if referenced as an input.4523let invalidation = null;45244525// If the variable doesn’t have any inputs, we can optimize slightly.4526const promise = variable._promise = (variable._inputs.length4527? Promise.all(variable._inputs.map(variable_value)).then(define)4528: new Promise(resolve => resolve(variable._definition.call(value0))))4529.then(generate);45304531// Compute the initial value of the variable.4532function define(inputs) {4533if (variable._version !== version) throw variable_stale;45344535// Replace any reference to invalidation with the promise, lazily.4536for (let i = 0, n = inputs.length; i < n; ++i) {4537switch (inputs[i]) {4538case variable_invalidation: {4539inputs[i] = invalidation = variable_invalidator(variable);4540break;4541}4542case variable_visibility: {4543if (!invalidation) invalidation = variable_invalidator(variable);4544inputs[i] = variable_intersector(invalidation, variable);4545break;4546}4547case variable_variable: {4548inputs[i] = variable;4549break;4550}4551}4552}45534554return variable._definition.apply(value0, inputs);4555}45564557// If the value is a generator, then retrieve its first value, and dispose of4558// the generator if the variable is invalidated. Note that the cell may4559// already have been invalidated here, in which case we need to terminate the4560// generator immediately!4561function generate(value) {4562if (variable._version !== version) throw variable_stale;4563if (generatorish(value)) {4564(invalidation || variable_invalidator(variable)).then(variable_return(value));4565return variable_generate(variable, version, value);4566}4567return value;4568}45694570promise.then((value) => {4571variable._value = value;4572variable._fulfilled(value);4573}, (error) => {4574if (error === variable_stale || variable._version !== version) return;4575variable._value = undefined;4576variable._rejected(error);4577});4578}45794580function variable_generate(variable, version, generator) {4581const runtime = variable._module._runtime;4582let currentValue; // so that yield resolves to the yielded value45834584// Retrieve the next value from the generator; if successful, invoke the4585// specified callback. The returned promise resolves to the yielded value, or4586// to undefined if the generator is done.4587function compute(onfulfilled) {4588return new Promise(resolve => resolve(generator.next(currentValue))).then(({done, value}) => {4589return done ? undefined : Promise.resolve(value).then(onfulfilled);4590});4591}45924593// Retrieve the next value from the generator; if successful, fulfill the4594// variable, compute downstream variables, and schedule the next value to be4595// pulled from the generator at the start of the next animation frame. If not4596// successful, reject the variable, compute downstream variables, and return.4597function recompute() {4598const promise = compute((value) => {4599if (variable._version !== version) throw variable_stale;4600currentValue = value;4601postcompute(value, promise).then(() => runtime._precompute(recompute));4602variable._fulfilled(value);4603return value;4604});4605promise.catch((error) => {4606if (error === variable_stale || variable._version !== version) return;4607postcompute(undefined, promise);4608variable._rejected(error);4609});4610}46114612// After the generator fulfills or rejects, set its current value, promise,4613// and schedule any downstream variables for update.4614function postcompute(value, promise) {4615variable._value = value;4616variable._promise = promise;4617variable._outputs.forEach(runtime._updates.add, runtime._updates);4618return runtime._compute();4619}46204621// When retrieving the first value from the generator, the promise graph is4622// already established, so we only need to queue the next pull.4623return compute((value) => {4624if (variable._version !== version) throw variable_stale;4625currentValue = value;4626runtime._precompute(recompute);4627return value;4628});4629}46304631function variable_error(variable, error) {4632variable._invalidate();4633variable._invalidate = noop;4634variable._pending();4635++variable._version;4636variable._indegree = NaN;4637(variable._promise = Promise.reject(error)).catch(noop);4638variable._value = undefined;4639variable._rejected(error);4640}46414642function variable_return(generator) {4643return function() {4644generator.return();4645};4646}46474648function variable_reachable(variable) {4649if (variable._observer !== no_observer) return true; // Directly reachable.4650const outputs = new Set(variable._outputs);4651for (const output of outputs) {4652if (output._observer !== no_observer) return true;4653output._outputs.forEach(outputs.add, outputs);4654}4655return false;4656}46574658function window_global(name) {4659return globalThis[name];4660}46614662function renderHtml(string) {4663const template = document.createElement("template");4664template.innerHTML = string;4665return document.importNode(template.content, true);4666}46674668function renderSvg(string) {4669const g = document.createElementNS("http://www.w3.org/2000/svg", "g");4670g.innerHTML = string;4671return g;4672}46734674const html = Object.assign(hypertext(renderHtml, fragment => {4675if (fragment.firstChild === null) return null;4676if (fragment.firstChild === fragment.lastChild) return fragment.removeChild(fragment.firstChild);4677const span = document.createElement("span");4678span.appendChild(fragment);4679return span;4680}), {fragment: hypertext(renderHtml, fragment => fragment)});46814682Object.assign(hypertext(renderSvg, g => {4683if (g.firstChild === null) return null;4684if (g.firstChild === g.lastChild) return g.removeChild(g.firstChild);4685return g;4686}), {fragment: hypertext(renderSvg, g => {4687const fragment = document.createDocumentFragment();4688while (g.firstChild) fragment.appendChild(g.firstChild);4689return fragment;4690})});46914692const4693CODE_TAB = 9,4694CODE_LF = 10,4695CODE_FF = 12,4696CODE_CR = 13,4697CODE_SPACE = 32,4698CODE_UPPER_A = 65,4699CODE_UPPER_Z = 90,4700CODE_LOWER_A = 97,4701CODE_LOWER_Z = 122,4702CODE_LT = 60,4703CODE_GT = 62,4704CODE_SLASH = 47,4705CODE_DASH = 45,4706CODE_BANG = 33,4707CODE_EQ = 61,4708CODE_DQUOTE = 34,4709CODE_SQUOTE = 39,4710CODE_QUESTION = 63,4711STATE_DATA = 1,4712STATE_TAG_OPEN = 2,4713STATE_END_TAG_OPEN = 3,4714STATE_TAG_NAME = 4,4715STATE_BOGUS_COMMENT = 5,4716STATE_BEFORE_ATTRIBUTE_NAME = 6,4717STATE_AFTER_ATTRIBUTE_NAME = 7,4718STATE_ATTRIBUTE_NAME = 8,4719STATE_BEFORE_ATTRIBUTE_VALUE = 9,4720STATE_ATTRIBUTE_VALUE_DOUBLE_QUOTED = 10,4721STATE_ATTRIBUTE_VALUE_SINGLE_QUOTED = 11,4722STATE_ATTRIBUTE_VALUE_UNQUOTED = 12,4723STATE_AFTER_ATTRIBUTE_VALUE_QUOTED = 13,4724STATE_SELF_CLOSING_START_TAG = 14,4725STATE_COMMENT_START = 15,4726STATE_COMMENT_START_DASH = 16,4727STATE_COMMENT = 17,4728STATE_COMMENT_LESS_THAN_SIGN = 18,4729STATE_COMMENT_LESS_THAN_SIGN_BANG = 19,4730STATE_COMMENT_LESS_THAN_SIGN_BANG_DASH = 20,4731STATE_COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH = 21,4732STATE_COMMENT_END_DASH = 22,4733STATE_COMMENT_END = 23,4734STATE_COMMENT_END_BANG = 24,4735STATE_MARKUP_DECLARATION_OPEN = 25,4736STATE_RAWTEXT = 26,4737STATE_RAWTEXT_LESS_THAN_SIGN = 27,4738STATE_RAWTEXT_END_TAG_OPEN = 28,4739STATE_RAWTEXT_END_TAG_NAME = 29,4740SHOW_COMMENT = 128,4741SHOW_ELEMENT = 1,4742TYPE_COMMENT = 8,4743TYPE_ELEMENT = 1,4744NS_SVG = "http://www.w3.org/2000/svg",4745NS_XLINK = "http://www.w3.org/1999/xlink",4746NS_XML = "http://www.w3.org/XML/1998/namespace",4747NS_XMLNS = "http://www.w3.org/2000/xmlns/";47484749const svgAdjustAttributes = new Map([4750"attributeName",4751"attributeType",4752"baseFrequency",4753"baseProfile",4754"calcMode",4755"clipPathUnits",4756"diffuseConstant",4757"edgeMode",4758"filterUnits",4759"glyphRef",4760"gradientTransform",4761"gradientUnits",4762"kernelMatrix",4763"kernelUnitLength",4764"keyPoints",4765"keySplines",4766"keyTimes",4767"lengthAdjust",4768"limitingConeAngle",4769"markerHeight",4770"markerUnits",4771"markerWidth",4772"maskContentUnits",4773"maskUnits",4774"numOctaves",4775"pathLength",4776"patternContentUnits",4777"patternTransform",4778"patternUnits",4779"pointsAtX",4780"pointsAtY",4781"pointsAtZ",4782"preserveAlpha",4783"preserveAspectRatio",4784"primitiveUnits",4785"refX",4786"refY",4787"repeatCount",4788"repeatDur",4789"requiredExtensions",4790"requiredFeatures",4791"specularConstant",4792"specularExponent",4793"spreadMethod",4794"startOffset",4795"stdDeviation",4796"stitchTiles",4797"surfaceScale",4798"systemLanguage",4799"tableValues",4800"targetX",4801"targetY",4802"textLength",4803"viewBox",4804"viewTarget",4805"xChannelSelector",4806"yChannelSelector",4807"zoomAndPan"4808].map(name => [name.toLowerCase(), name]));48094810const svgForeignAttributes = new Map([4811["xlink:actuate", NS_XLINK],4812["xlink:arcrole", NS_XLINK],4813["xlink:href", NS_XLINK],4814["xlink:role", NS_XLINK],4815["xlink:show", NS_XLINK],4816["xlink:title", NS_XLINK],4817["xlink:type", NS_XLINK],4818["xml:lang", NS_XML],4819["xml:space", NS_XML],4820["xmlns", NS_XMLNS],4821["xmlns:xlink", NS_XMLNS]4822]);48234824function hypertext(render, postprocess) {4825return function({raw: strings}) {4826let state = STATE_DATA;4827let string = "";4828let tagNameStart; // either an open tag or an end tag4829let tagName; // only open; beware nesting! used only for rawtext4830let attributeNameStart;4831let attributeNameEnd;4832let nodeFilter = 0;48334834for (let j = 0, m = arguments.length; j < m; ++j) {4835const input = strings[j];48364837if (j > 0) {4838const value = arguments[j];4839switch (state) {4840case STATE_RAWTEXT: {4841if (value != null) {4842const text = `${value}`;4843if (isEscapableRawText(tagName)) {4844string += text.replace(/[<]/g, entity);4845} else if (new RegExp(`</${tagName}[\\s>/]`, "i").test(string.slice(-tagName.length - 2) + text)) {4846throw new Error("unsafe raw text"); // appropriate end tag4847} else {4848string += text;4849}4850}4851break;4852}4853case STATE_DATA: {4854if (value == null) ; else if (value instanceof Node4855|| (typeof value !== "string" && value[Symbol.iterator])4856|| (/(?:^|>)$/.test(strings[j - 1]) && /^(?:<|$)/.test(input))) {4857string += "<!--::" + j + "-->";4858nodeFilter |= SHOW_COMMENT;4859} else {4860string += `${value}`.replace(/[<&]/g, entity);4861}4862break;4863}4864case STATE_BEFORE_ATTRIBUTE_VALUE: {4865state = STATE_ATTRIBUTE_VALUE_UNQUOTED;4866let text;4867if (/^[\s>]/.test(input)) {4868if (value == null || value === false) {4869string = string.slice(0, attributeNameStart - strings[j - 1].length);4870break;4871}4872if (value === true || (text = `${value}`) === "") {4873string += "''";4874break;4875}4876const name = strings[j - 1].slice(attributeNameStart, attributeNameEnd);4877if ((name === "style" && isObjectLiteral(value)) || typeof value === "function") {4878string += "::" + j;4879nodeFilter |= SHOW_ELEMENT;4880break;4881}4882}4883if (text === undefined) text = `${value}`;4884if (text === "") throw new Error("unsafe unquoted empty string");4885string += text.replace(/^['"]|[\s>&]/g, entity);4886break;4887}4888case STATE_ATTRIBUTE_VALUE_UNQUOTED: {4889string += `${value}`.replace(/[\s>&]/g, entity);4890break;4891}4892case STATE_ATTRIBUTE_VALUE_SINGLE_QUOTED: {4893string += `${value}`.replace(/['&]/g, entity);4894break;4895}4896case STATE_ATTRIBUTE_VALUE_DOUBLE_QUOTED: {4897string += `${value}`.replace(/["&]/g, entity);4898break;4899}4900case STATE_BEFORE_ATTRIBUTE_NAME: {4901if (isObjectLiteral(value)) {4902string += "::" + j + "=''";4903nodeFilter |= SHOW_ELEMENT;4904break;4905}4906throw new Error("invalid binding");4907}4908case STATE_COMMENT: break;4909default: throw new Error("invalid binding");4910}4911}49124913for (let i = 0, n = input.length; i < n; ++i) {4914const code = input.charCodeAt(i);49154916switch (state) {4917case STATE_DATA: {4918if (code === CODE_LT) {4919state = STATE_TAG_OPEN;4920}4921break;4922}4923case STATE_TAG_OPEN: {4924if (code === CODE_BANG) {4925state = STATE_MARKUP_DECLARATION_OPEN;4926} else if (code === CODE_SLASH) {4927state = STATE_END_TAG_OPEN;4928} else if (isAsciiAlphaCode(code)) {4929tagNameStart = i, tagName = undefined;4930state = STATE_TAG_NAME, --i;4931} else if (code === CODE_QUESTION) {4932state = STATE_BOGUS_COMMENT, --i;4933} else {4934state = STATE_DATA, --i;4935}4936break;4937}4938case STATE_END_TAG_OPEN: {4939if (isAsciiAlphaCode(code)) {4940state = STATE_TAG_NAME, --i;4941} else if (code === CODE_GT) {4942state = STATE_DATA;4943} else {4944state = STATE_BOGUS_COMMENT, --i;4945}4946break;4947}4948case STATE_TAG_NAME: {4949if (isSpaceCode(code)) {4950state = STATE_BEFORE_ATTRIBUTE_NAME;4951tagName = lower(input, tagNameStart, i);4952} else if (code === CODE_SLASH) {4953state = STATE_SELF_CLOSING_START_TAG;4954} else if (code === CODE_GT) {4955tagName = lower(input, tagNameStart, i);4956state = isRawText(tagName) ? STATE_RAWTEXT : STATE_DATA;4957}4958break;4959}4960case STATE_BEFORE_ATTRIBUTE_NAME: {4961if (isSpaceCode(code)) ; else if (code === CODE_SLASH || code === CODE_GT) {4962state = STATE_AFTER_ATTRIBUTE_NAME, --i;4963} else if (code === CODE_EQ) {4964state = STATE_ATTRIBUTE_NAME;4965attributeNameStart = i + 1, attributeNameEnd = undefined;4966} else {4967state = STATE_ATTRIBUTE_NAME, --i;4968attributeNameStart = i + 1, attributeNameEnd = undefined;4969}4970break;4971}4972case STATE_ATTRIBUTE_NAME: {4973if (isSpaceCode(code) || code === CODE_SLASH || code === CODE_GT) {4974state = STATE_AFTER_ATTRIBUTE_NAME, --i;4975attributeNameEnd = i;4976} else if (code === CODE_EQ) {4977state = STATE_BEFORE_ATTRIBUTE_VALUE;4978attributeNameEnd = i;4979}4980break;4981}4982case STATE_AFTER_ATTRIBUTE_NAME: {4983if (isSpaceCode(code)) ; else if (code === CODE_SLASH) {4984state = STATE_SELF_CLOSING_START_TAG;4985} else if (code === CODE_EQ) {4986state = STATE_BEFORE_ATTRIBUTE_VALUE;4987} else if (code === CODE_GT) {4988state = isRawText(tagName) ? STATE_RAWTEXT : STATE_DATA;4989} else {4990state = STATE_ATTRIBUTE_NAME, --i;4991attributeNameStart = i + 1, attributeNameEnd = undefined;4992}4993break;4994}4995case STATE_BEFORE_ATTRIBUTE_VALUE: {4996if (isSpaceCode(code)) ; else if (code === CODE_DQUOTE) {4997state = STATE_ATTRIBUTE_VALUE_DOUBLE_QUOTED;4998} else if (code === CODE_SQUOTE) {4999state = STATE_ATTRIBUTE_VALUE_SINGLE_QUOTED;5000} else if (code === CODE_GT) {5001state = isRawText(tagName) ? STATE_RAWTEXT : STATE_DATA;5002} else {5003state = STATE_ATTRIBUTE_VALUE_UNQUOTED, --i;5004}5005break;5006}5007case STATE_ATTRIBUTE_VALUE_DOUBLE_QUOTED: {5008if (code === CODE_DQUOTE) {5009state = STATE_AFTER_ATTRIBUTE_VALUE_QUOTED;5010}5011break;5012}5013case STATE_ATTRIBUTE_VALUE_SINGLE_QUOTED: {5014if (code === CODE_SQUOTE) {5015state = STATE_AFTER_ATTRIBUTE_VALUE_QUOTED;5016}5017break;5018}5019case STATE_ATTRIBUTE_VALUE_UNQUOTED: {5020if (isSpaceCode(code)) {5021state = STATE_BEFORE_ATTRIBUTE_NAME;5022} else if (code === CODE_GT) {5023state = isRawText(tagName) ? STATE_RAWTEXT : STATE_DATA;5024}5025break;5026}5027case STATE_AFTER_ATTRIBUTE_VALUE_QUOTED: {5028if (isSpaceCode(code)) {5029state = STATE_BEFORE_ATTRIBUTE_NAME;5030} else if (code === CODE_SLASH) {5031state = STATE_SELF_CLOSING_START_TAG;5032} else if (code === CODE_GT) {5033state = isRawText(tagName) ? STATE_RAWTEXT : STATE_DATA;5034} else {5035state = STATE_BEFORE_ATTRIBUTE_NAME, --i;5036}5037break;5038}5039case STATE_SELF_CLOSING_START_TAG: {5040if (code === CODE_GT) {5041state = STATE_DATA;5042} else {5043state = STATE_BEFORE_ATTRIBUTE_NAME, --i;5044}5045break;5046}5047case STATE_BOGUS_COMMENT: {5048if (code === CODE_GT) {5049state = STATE_DATA;5050}5051break;5052}5053case STATE_COMMENT_START: {5054if (code === CODE_DASH) {5055state = STATE_COMMENT_START_DASH;5056} else if (code === CODE_GT) {5057state = STATE_DATA;5058} else {5059state = STATE_COMMENT, --i;5060}5061break;5062}5063case STATE_COMMENT_START_DASH: {5064if (code === CODE_DASH) {5065state = STATE_COMMENT_END;5066} else if (code === CODE_GT) {5067state = STATE_DATA;5068} else {5069state = STATE_COMMENT, --i;5070}5071break;5072}5073case STATE_COMMENT: {5074if (code === CODE_LT) {5075state = STATE_COMMENT_LESS_THAN_SIGN;5076} else if (code === CODE_DASH) {5077state = STATE_COMMENT_END_DASH;5078}5079break;5080}5081case STATE_COMMENT_LESS_THAN_SIGN: {5082if (code === CODE_BANG) {5083state = STATE_COMMENT_LESS_THAN_SIGN_BANG;5084} else if (code !== CODE_LT) {5085state = STATE_COMMENT, --i;5086}5087break;5088}5089case STATE_COMMENT_LESS_THAN_SIGN_BANG: {5090if (code === CODE_DASH) {5091state = STATE_COMMENT_LESS_THAN_SIGN_BANG_DASH;5092} else {5093state = STATE_COMMENT, --i;5094}5095break;5096}5097case STATE_COMMENT_LESS_THAN_SIGN_BANG_DASH: {5098if (code === CODE_DASH) {5099state = STATE_COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH;5100} else {5101state = STATE_COMMENT_END, --i;5102}5103break;5104}5105case STATE_COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH: {5106state = STATE_COMMENT_END, --i;5107break;5108}5109case STATE_COMMENT_END_DASH: {5110if (code === CODE_DASH) {5111state = STATE_COMMENT_END;5112} else {5113state = STATE_COMMENT, --i;5114}5115break;5116}5117case STATE_COMMENT_END: {5118if (code === CODE_GT) {5119state = STATE_DATA;5120} else if (code === CODE_BANG) {5121state = STATE_COMMENT_END_BANG;5122} else if (code !== CODE_DASH) {5123state = STATE_COMMENT, --i;5124}5125break;5126}5127case STATE_COMMENT_END_BANG: {5128if (code === CODE_DASH) {5129state = STATE_COMMENT_END_DASH;5130} else if (code === CODE_GT) {5131state = STATE_DATA;5132} else {5133state = STATE_COMMENT, --i;5134}5135break;5136}5137case STATE_MARKUP_DECLARATION_OPEN: {5138if (code === CODE_DASH && input.charCodeAt(i + 1) === CODE_DASH) {5139state = STATE_COMMENT_START, ++i;5140} else { // Note: CDATA and DOCTYPE unsupported!5141state = STATE_BOGUS_COMMENT, --i;5142}5143break;5144}5145case STATE_RAWTEXT: {5146if (code === CODE_LT) {5147state = STATE_RAWTEXT_LESS_THAN_SIGN;5148}5149break;5150}5151case STATE_RAWTEXT_LESS_THAN_SIGN: {5152if (code === CODE_SLASH) {5153state = STATE_RAWTEXT_END_TAG_OPEN;5154} else {5155state = STATE_RAWTEXT, --i;5156}5157break;5158}5159case STATE_RAWTEXT_END_TAG_OPEN: {5160if (isAsciiAlphaCode(code)) {5161tagNameStart = i;5162state = STATE_RAWTEXT_END_TAG_NAME, --i;5163} else {5164state = STATE_RAWTEXT, --i;5165}5166break;5167}5168case STATE_RAWTEXT_END_TAG_NAME: {5169if (isSpaceCode(code) && tagName === lower(input, tagNameStart, i)) {5170state = STATE_BEFORE_ATTRIBUTE_NAME;5171} else if (code === CODE_SLASH && tagName === lower(input, tagNameStart, i)) {5172state = STATE_SELF_CLOSING_START_TAG;5173} else if (code === CODE_GT && tagName === lower(input, tagNameStart, i)) {5174state = STATE_DATA;5175} else if (!isAsciiAlphaCode(code)) {5176state = STATE_RAWTEXT, --i;5177}5178break;5179}5180default: {5181state = undefined;5182break;5183}5184}5185}51865187string += input;5188}51895190const root = render(string);51915192const walker = document.createTreeWalker(root, nodeFilter, null, false);5193const removeNodes = [];5194while (walker.nextNode()) {5195const node = walker.currentNode;5196switch (node.nodeType) {5197case TYPE_ELEMENT: {5198const attributes = node.attributes;5199for (let i = 0, n = attributes.length; i < n; ++i) {5200const {name, value: currentValue} = attributes[i];5201if (/^::/.test(name)) {5202const value = arguments[+name.slice(2)];5203removeAttribute(node, name), --i, --n;5204for (const key in value) {5205const subvalue = value[key];5206if (subvalue == null || subvalue === false) ; else if (typeof subvalue === "function") {5207node[key] = subvalue;5208} else if (key === "style" && isObjectLiteral(subvalue)) {5209setStyles(node[key], subvalue);5210} else {5211setAttribute(node, key, subvalue === true ? "" : subvalue);5212}5213}5214} else if (/^::/.test(currentValue)) {5215const value = arguments[+currentValue.slice(2)];5216removeAttribute(node, name), --i, --n;5217if (typeof value === "function") {5218node[name] = value;5219} else { // style5220setStyles(node[name], value);5221}5222}5223}5224break;5225}5226case TYPE_COMMENT: {5227if (/^::/.test(node.data)) {5228const parent = node.parentNode;5229const value = arguments[+node.data.slice(2)];5230if (value instanceof Node) {5231parent.insertBefore(value, node);5232} else if (typeof value !== "string" && value[Symbol.iterator]) {5233if (value instanceof NodeList || value instanceof HTMLCollection) {5234for (let i = value.length - 1, r = node; i >= 0; --i) {5235r = parent.insertBefore(value[i], r);5236}5237} else {5238for (const subvalue of value) {5239if (subvalue == null) continue;5240parent.insertBefore(subvalue instanceof Node ? subvalue : document.createTextNode(subvalue), node);5241}5242}5243} else {5244parent.insertBefore(document.createTextNode(value), node);5245}5246removeNodes.push(node);5247}5248break;5249}5250}5251}52525253for (const node of removeNodes) {5254node.parentNode.removeChild(node);5255}52565257return postprocess(root);5258};5259}52605261function entity(character) {5262return `&#${character.charCodeAt(0).toString()};`;5263}52645265function isAsciiAlphaCode(code) {5266return (CODE_UPPER_A <= code && code <= CODE_UPPER_Z)5267|| (CODE_LOWER_A <= code && code <= CODE_LOWER_Z);5268}52695270function isSpaceCode(code) {5271return code === CODE_TAB5272|| code === CODE_LF5273|| code === CODE_FF5274|| code === CODE_SPACE5275|| code === CODE_CR; // normalize newlines5276}52775278function isObjectLiteral(value) {5279return value && value.toString === Object.prototype.toString;5280}52815282function isRawText(tagName) {5283return tagName === "script" || tagName === "style" || isEscapableRawText(tagName);5284}52855286function isEscapableRawText(tagName) {5287return tagName === "textarea" || tagName === "title";5288}52895290function lower(input, start, end) {5291return input.slice(start, end).toLowerCase();5292}52935294function setAttribute(node, name, value) {5295if (node.namespaceURI === NS_SVG) {5296name = name.toLowerCase();5297name = svgAdjustAttributes.get(name) || name;5298if (svgForeignAttributes.has(name)) {5299node.setAttributeNS(svgForeignAttributes.get(name), name, value);5300return;5301}5302}5303node.setAttribute(name, value);5304}53055306function removeAttribute(node, name) {5307if (node.namespaceURI === NS_SVG) {5308name = name.toLowerCase();5309name = svgAdjustAttributes.get(name) || name;5310if (svgForeignAttributes.has(name)) {5311node.removeAttributeNS(svgForeignAttributes.get(name), name);5312return;5313}5314}5315node.removeAttribute(name);5316}53175318// We can’t use Object.assign because custom properties…5319function setStyles(style, values) {5320for (const name in values) {5321const value = values[name];5322if (name.startsWith("--")) style.setProperty(name, value);5323else style[name] = value;5324}5325}53265327function length(x) {5328return x == null ? null : typeof x === "number" ? `${x}px` : `${x}`;5329}53305331const bubbles = {bubbles: true};53325333function preventDefault(event) {5334event.preventDefault();5335}53365337function dispatchInput({currentTarget}) {5338(currentTarget.form || currentTarget).dispatchEvent(new Event("input", bubbles));5339}53405341function identity(x) {5342return x;5343}53445345let nextId = 0;53465347function newId() {5348return `__ns__-${++nextId}`;5349}53505351function maybeLabel(label, input) {5352if (!label) return;5353label = html`<label>${label}`;5354if (input !== undefined) label.htmlFor = input.id = newId();5355return label;5356}53575358function button(content = "≡", {5359label = "",5360value,5361reduce,5362disabled,5363required = false,5364width5365} = {}) {5366const solitary = typeof content === "string" || content instanceof Node;5367if (solitary) {5368if (!required && value === undefined) value = 0;5369if (reduce === undefined) reduce = (value = 0) => value + 1;5370disabled = new Set(disabled ? [content] : []);5371content = [[content, reduce]];5372} else {5373if (!required && value === undefined) value = null;5374disabled = new Set(disabled === true ? Array.from(content, ([content]) => content) : disabled || undefined);5375}5376const form = html`<form class=__ns__ onsubmit=${preventDefault}>`;5377const style = {width: length(width)};5378const buttons = Array.from(content, ([content, reduce = identity]) => {5379if (typeof reduce !== "function") throw new TypeError("reduce is not a function");5380return html`<button disabled=${disabled.has(content)} style=${style} onclick=${event => {5381form.value = reduce(form.value);5382dispatchInput(event);5383}}>${content}`;5384});5385if (label = maybeLabel(label, solitary ? buttons[0] : undefined)) form.append(label);5386form.append(...buttons);5387form.value = value;5388return form;5389}53905391const formatLocaleAuto = localize(locale => {5392const formatNumber = formatLocaleNumber(locale);5393return value => value == null ? ""5394: typeof value === "number" ? formatNumber(value)5395: value instanceof Date ? formatDate(value)5396: `${value}`;5397});53985399const formatLocaleNumber = localize(locale => {5400return value => value === 0 ? "0" : value.toLocaleString(locale); // handle negative zero5401});54025403formatLocaleAuto();54045405formatLocaleNumber();54065407function formatDate(date) {5408return format(date, "Invalid Date");5409}54105411// Memoize the last-returned locale.5412function localize(f) {5413let key = localize, value;5414return (locale = "en") => locale === key ? value : (value = f(key = locale));5415}54165417/*5418* quarto-inspector.js5419*5420* Copyright (C) 2022 RStudio, PBC5421*5422*/54235424class QuartoInspector extends Inspector {5425constructor(node, cellAst) {5426super(node);5427this._cellAst = cellAst;5428}5429rejected(error) {5430console.error(`Error evaluating OJS cell\n${this._cellAst.input}\n${String(error)}`);5431return super.rejected(error);5432}5433}54345435/*global Shiny, $5436*5437* quarto-observable-shiny.js5438*5439* Copyright (C) 2022 RStudio, PBC5440*/54415442const shinyInputVars = new Set();5443let shinyInitialValue = {};54445445function extendObservableStdlib(lib) {5446class NamedVariableOutputBinding extends Shiny.OutputBinding {5447constructor(name, change) {5448super();5449this._name = name;5450this._change = change;5451}5452find(scope) {5453return $(scope).find("#" + this._name);5454}5455getId(el) {5456return el.id;5457}5458renderValue(_el, data) {5459this._change(data);5460}5461onValueError(el, err) {5462const group = `Shiny error in ${el.id}`;5463console.groupCollapsed(`%c${group}`, "color:red");5464console.log(`${err.message}`);5465console.log(`call: ${err.call}`);5466console.groupEnd(group);5467}5468}54695470$(document).on("shiny:connected", function (_event) {5471Object.entries(shinyInitialValue).map(([k, v]) => {5472window.Shiny.setInputValue(k, v);5473});5474shinyInitialValue = {};5475});54765477lib.shinyInput = function () {5478return (name) => {5479shinyInputVars.add(name);5480window._ojs.ojsConnector.mainModule.value(name)5481.then((val) => {5482if (window.Shiny && window.Shiny.setInputValue) {5483window.Shiny.setInputValue(name, val);5484} else {5485shinyInitialValue[name] = val;5486}5487});5488};5489};54905491lib.shinyOutput = function () {5492return function (name) {5493const dummySpan = document.createElement("div");5494dummySpan.id = name;5495dummySpan.classList.add("ojs-variable-writer");5496window._ojs.shinyElementRoot.appendChild(dummySpan);5497return lib.Generators.observe((change) => {5498Shiny.outputBindings.register(5499new NamedVariableOutputBinding(name, change),5500);5501});5502};5503};5504}55055506class ShinyInspector extends QuartoInspector {5507constructor(node, cellAst) {5508super(node, cellAst);5509}5510fulfilled(value, name) {5511if (shinyInputVars.has(name) && window.Shiny) {5512if (window.Shiny.setInputValue === undefined) {5513shinyInitialValue[name] = value;5514} else {5515window.Shiny.setInputValue(name, value);5516}5517}5518return super.fulfilled(value, name);5519}5520}55215522const { Generators } = new Library();55235524class OjsButtonInput /*extends ShinyInput*/ {5525find(_scope) {5526return document.querySelectorAll(".ojs-inputs-button");5527}55285529init(el, change) {5530const btn = button(el.textContent);5531el.innerHTML = "";5532el.appendChild(btn);55335534const obs = Generators.input(el.firstChild);5535(async function () {5536// throw away the first value, it doesn't count for buttons5537await obs.next().value;5538for (const x of obs) {5539change(await x);5540}5541})();5542// TODO: error handling55435544return {5545onSetValue: (_value) => {5546},5547dispose: () => {5548obs.return();5549},5550};5551}5552}55535554function initOjsShinyRuntime() {5555const valueSym = Symbol("value");5556const callbackSym = Symbol("callback");5557const instanceSym = Symbol("instance");5558// const values = new WeakMap(); // unused?55595560class BindingAdapter extends Shiny.InputBinding {5561constructor(x) {5562super();5563this.x = x;5564}55655566find(scope) {5567const matches = this.x.find(scope);5568return $(matches);5569}5570getId(el) {5571if (this.x.getId) {5572return this.x.getId(el);5573} else {5574return super.getId(el);5575}5576}5577initialize(el) {5578const changeHandler = (value) => {5579el[valueSym] = value;5580el[callbackSym]();5581};5582const instance = this.x.init(el, changeHandler);5583el[instanceSym] = instance;5584}5585getValue(el) {5586return el[valueSym];5587}5588setValue(el, value) {5589el[valueSym] = value;5590el[instanceSym].onSetValue(value);5591}5592subscribe(el, callback) {5593el[callbackSym] = callback;5594}5595unsubscribe(el) {5596el[instanceSym].dispose();5597}5598}55995600class InspectorOutputBinding extends Shiny.OutputBinding {5601find(scope) {5602return $(scope).find(".observablehq-inspector");5603}5604getId(el) {5605return el.id;5606}5607renderValue(el, data) {5608(new Inspector(el)).fulfilled(data);5609}5610}56115612if (window.Shiny === undefined) {5613console.warn("Shiny runtime not found; Shiny features won't work.");5614return false;5615}56165617Shiny.inputBindings.register(new BindingAdapter(new OjsButtonInput()));5618Shiny.outputBindings.register(new InspectorOutputBinding());56195620// Handle requests from the server to export Shiny outputs to ojs.5621Shiny.addCustomMessageHandler("ojs-export", ({ name }) => {5622window._ojs.ojsConnector.mainModule.redefine(5623name,5624window._ojs.ojsConnector.library.shinyOutput()(name),5625);5626// shinyOutput() creates an output DOM element, but we have to cause it to5627// be actually bound. I don't love this code being here, I'd prefer if we5628// could receive Shiny outputs without using output bindings at all (for5629// this case, not for things that truly are DOM-oriented outputs).5630Shiny.bindAll(document.body);5631});56325633return true;5634}56355636var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};56375638var dist = {exports: {}};56395640(function (module, exports) {5641(function(g,f){f(exports);}(commonjsGlobal,(function(exports){5642var reservedWords = {56433: "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",56445: "class enum extends super const export import",56456: "enum",5646strict: "implements interface let package private protected public static yield",5647strictBind: "eval arguments"5648};56495650// And the keywords56515652var 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";56535654var keywords = {56555: ecma5AndLessKeywords,5656"5module": ecma5AndLessKeywords + " export import",56576: ecma5AndLessKeywords + " const class extends export import super"5658};56595660var keywordRelationalOperator = /^in(stanceof)?$/;56615662// ## Character categories56635664// Big ugly regular expressions that match characters in the5665// whitespace, identifier, and identifier-start categories. These5666// are only applied when a character is found to actually have a5667// code point above 128.5668// Generated by `bin/generate-identifier-regex.js`.5669var 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\u08a0-\u08b4\u08b6-\u08c7\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\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\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-\u170c\u170e-\u1711\u1720-\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-\u1b4b\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-\u2c2e\u2c30-\u2c5e\u2c60-\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-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\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";5670var 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\u08d3-\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\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\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-\u0ecd\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-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\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-\u1df9\u1dfb-\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";56715672var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");5673var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");56745675nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;56765677// These are a run-length and offset encoded representation of the5678// >0xffff code points that are a valid part of identifiers. The5679// offset starts at 0x10000, and each pair of numbers represents an5680// offset to the next range, and then a size of the range. They were5681// generated by bin/generate-identifier-regex.js56825683// eslint-disable-next-line comma-spacing5684var 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,157,310,10,21,11,7,153,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,107,20,28,22,13,52,76,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,85,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,230,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,35,56,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,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,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,8952,286,50,2,18,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,2357,44,11,6,17,0,370,43,1301,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,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938];56855686// eslint-disable-next-line comma-spacing5687var 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,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,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,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,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,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239];56885689// This has a complexity linear to the value of the code. The5690// assumption is that looking up astral identifier characters is5691// rare.5692function isInAstralSet(code, set) {5693var pos = 0x10000;5694for (var i = 0; i < set.length; i += 2) {5695pos += set[i];5696if (pos > code) { return false }5697pos += set[i + 1];5698if (pos >= code) { return true }5699}5700}57015702// Test whether a given character code starts an identifier.57035704function isIdentifierStart(code, astral) {5705if (code < 65) { return code === 36 }5706if (code < 91) { return true }5707if (code < 97) { return code === 95 }5708if (code < 123) { return true }5709if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }5710if (astral === false) { return false }5711return isInAstralSet(code, astralIdentifierStartCodes)5712}57135714// Test whether a given character is part of an identifier.57155716function isIdentifierChar(code, astral) {5717if (code < 48) { return code === 36 }5718if (code < 58) { return true }5719if (code < 65) { return false }5720if (code < 91) { return true }5721if (code < 97) { return code === 95 }5722if (code < 123) { return true }5723if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }5724if (astral === false) { return false }5725return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)5726}57275728// ## Token types57295730// The assignment of fine-grained, information-carrying type objects5731// allows the tokenizer to store the information it has about a5732// token in a way that is very cheap for the parser to look up.57335734// All token type variables start with an underscore, to make them5735// easy to recognize.57365737// The `beforeExpr` property is used to disambiguate between regular5738// expressions and divisions. It is set on all token types that can5739// be followed by an expression (thus, a slash after them would be a5740// regular expression).5741//5742// The `startsExpr` property is used to check if the token ends a5743// `yield` expression. It is set on all token types that either can5744// directly start an expression (like a quotation mark) or can5745// continue an expression (like the body of a string).5746//5747// `isLoop` marks a keyword as starting a loop, which is important5748// to know when parsing a label, in order to allow or disallow5749// continue jumps to that label.57505751var TokenType = function TokenType(label, conf) {5752if ( conf === void 0 ) conf = {};57535754this.label = label;5755this.keyword = conf.keyword;5756this.beforeExpr = !!conf.beforeExpr;5757this.startsExpr = !!conf.startsExpr;5758this.isLoop = !!conf.isLoop;5759this.isAssign = !!conf.isAssign;5760this.prefix = !!conf.prefix;5761this.postfix = !!conf.postfix;5762this.binop = conf.binop || null;5763this.updateContext = null;5764};57655766function binop(name, prec) {5767return new TokenType(name, {beforeExpr: true, binop: prec})5768}5769var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};57705771// Map keyword names to token types.57725773var keywords$1 = {};57745775// Succinct definitions of keyword token types5776function kw(name, options) {5777if ( options === void 0 ) options = {};57785779options.keyword = name;5780return keywords$1[name] = new TokenType(name, options)5781}57825783var types = {5784num: new TokenType("num", startsExpr),5785regexp: new TokenType("regexp", startsExpr),5786string: new TokenType("string", startsExpr),5787name: new TokenType("name", startsExpr),5788eof: new TokenType("eof"),57895790// Punctuation token types.5791bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),5792bracketR: new TokenType("]"),5793braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),5794braceR: new TokenType("}"),5795parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),5796parenR: new TokenType(")"),5797comma: new TokenType(",", beforeExpr),5798semi: new TokenType(";", beforeExpr),5799colon: new TokenType(":", beforeExpr),5800dot: new TokenType("."),5801question: new TokenType("?", beforeExpr),5802questionDot: new TokenType("?."),5803arrow: new TokenType("=>", beforeExpr),5804template: new TokenType("template"),5805invalidTemplate: new TokenType("invalidTemplate"),5806ellipsis: new TokenType("...", beforeExpr),5807backQuote: new TokenType("`", startsExpr),5808dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),58095810// Operators. These carry several kinds of properties to help the5811// parser use them properly (the presence of these properties is5812// what categorizes them as operators).5813//5814// `binop`, when present, specifies that this operator is a binary5815// operator, and will refer to its precedence.5816//5817// `prefix` and `postfix` mark the operator as a prefix or postfix5818// unary operator.5819//5820// `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as5821// binary operators with a very low precedence, that should result5822// in AssignmentExpression nodes.58235824eq: new TokenType("=", {beforeExpr: true, isAssign: true}),5825assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),5826incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),5827prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),5828logicalOR: binop("||", 1),5829logicalAND: binop("&&", 2),5830bitwiseOR: binop("|", 3),5831bitwiseXOR: binop("^", 4),5832bitwiseAND: binop("&", 5),5833equality: binop("==/!=/===/!==", 6),5834relational: binop("</>/<=/>=", 7),5835bitShift: binop("<</>>/>>>", 8),5836plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),5837modulo: binop("%", 10),5838star: binop("*", 10),5839slash: binop("/", 10),5840starstar: new TokenType("**", {beforeExpr: true}),5841coalesce: binop("??", 1),58425843// Keyword token types.5844_break: kw("break"),5845_case: kw("case", beforeExpr),5846_catch: kw("catch"),5847_continue: kw("continue"),5848_debugger: kw("debugger"),5849_default: kw("default", beforeExpr),5850_do: kw("do", {isLoop: true, beforeExpr: true}),5851_else: kw("else", beforeExpr),5852_finally: kw("finally"),5853_for: kw("for", {isLoop: true}),5854_function: kw("function", startsExpr),5855_if: kw("if"),5856_return: kw("return", beforeExpr),5857_switch: kw("switch"),5858_throw: kw("throw", beforeExpr),5859_try: kw("try"),5860_var: kw("var"),5861_const: kw("const"),5862_while: kw("while", {isLoop: true}),5863_with: kw("with"),5864_new: kw("new", {beforeExpr: true, startsExpr: true}),5865_this: kw("this", startsExpr),5866_super: kw("super", startsExpr),5867_class: kw("class", startsExpr),5868_extends: kw("extends", beforeExpr),5869_export: kw("export"),5870_import: kw("import", startsExpr),5871_null: kw("null", startsExpr),5872_true: kw("true", startsExpr),5873_false: kw("false", startsExpr),5874_in: kw("in", {beforeExpr: true, binop: 7}),5875_instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),5876_typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),5877_void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),5878_delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})5879};58805881// Matches a whole line break (where CRLF is considered a single5882// line break). Used to count lines.58835884var lineBreak = /\r\n?|\n|\u2028|\u2029/;5885var lineBreakG = new RegExp(lineBreak.source, "g");58865887function isNewLine(code, ecma2019String) {5888return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029))5889}58905891var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;58925893var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;58945895var ref = Object.prototype;5896var hasOwnProperty = ref.hasOwnProperty;5897var toString = ref.toString;58985899// Checks if an object has a property.59005901function has(obj, propName) {5902return hasOwnProperty.call(obj, propName)5903}59045905var isArray = Array.isArray || (function (obj) { return (5906toString.call(obj) === "[object Array]"5907); });59085909function wordsRegexp(words) {5910return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")5911}59125913// These are used when `options.locations` is on, for the5914// `startLoc` and `endLoc` properties.59155916var Position = function Position(line, col) {5917this.line = line;5918this.column = col;5919};59205921Position.prototype.offset = function offset (n) {5922return new Position(this.line, this.column + n)5923};59245925var SourceLocation = function SourceLocation(p, start, end) {5926this.start = start;5927this.end = end;5928if (p.sourceFile !== null) { this.source = p.sourceFile; }5929};59305931// The `getLineInfo` function is mostly useful when the5932// `locations` option is off (for performance reasons) and you5933// want to find the line/column position for a given character5934// offset. `input` should be the code string that the offset refers5935// into.59365937function getLineInfo(input, offset) {5938for (var line = 1, cur = 0;;) {5939lineBreakG.lastIndex = cur;5940var match = lineBreakG.exec(input);5941if (match && match.index < offset) {5942++line;5943cur = match.index + match[0].length;5944} else {5945return new Position(line, offset - cur)5946}5947}5948}59495950// A second optional argument can be given to further configure5951// the parser process. These options are recognized:59525953var defaultOptions = {5954// `ecmaVersion` indicates the ECMAScript version to parse. Must be5955// either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018), or 105956// (2019). This influences support for strict mode, the set of5957// reserved words, and support for new syntax features. The default5958// is 10.5959ecmaVersion: 10,5960// `sourceType` indicates the mode the code should be parsed in.5961// Can be either `"script"` or `"module"`. This influences global5962// strict mode and parsing of `import` and `export` declarations.5963sourceType: "script",5964// `onInsertedSemicolon` can be a callback that will be called5965// when a semicolon is automatically inserted. It will be passed5966// the position of the comma as an offset, and if `locations` is5967// enabled, it is given the location as a `{line, column}` object5968// as second argument.5969onInsertedSemicolon: null,5970// `onTrailingComma` is similar to `onInsertedSemicolon`, but for5971// trailing commas.5972onTrailingComma: null,5973// By default, reserved words are only enforced if ecmaVersion >= 5.5974// Set `allowReserved` to a boolean value to explicitly turn this on5975// an off. When this option has the value "never", reserved words5976// and keywords can also not be used as property names.5977allowReserved: null,5978// When enabled, a return at the top level is not considered an5979// error.5980allowReturnOutsideFunction: false,5981// When enabled, import/export statements are not constrained to5982// appearing at the top of the program.5983allowImportExportEverywhere: false,5984// When enabled, await identifiers are allowed to appear at the top-level scope,5985// but they are still not allowed in non-async functions.5986allowAwaitOutsideFunction: false,5987// When enabled, hashbang directive in the beginning of file5988// is allowed and treated as a line comment.5989allowHashBang: false,5990// When `locations` is on, `loc` properties holding objects with5991// `start` and `end` properties in `{line, column}` form (with5992// line being 1-based and column 0-based) will be attached to the5993// nodes.5994locations: false,5995// A function can be passed as `onToken` option, which will5996// cause Acorn to call that function with object in the same5997// format as tokens returned from `tokenizer().getToken()`. Note5998// that you are not allowed to call the parser from the5999// callback—that will corrupt its internal state.6000onToken: null,6001// A function can be passed as `onComment` option, which will6002// cause Acorn to call that function with `(block, text, start,6003// end)` parameters whenever a comment is skipped. `block` is a6004// boolean indicating whether this is a block (`/* */`) comment,6005// `text` is the content of the comment, and `start` and `end` are6006// character offsets that denote the start and end of the comment.6007// When the `locations` option is on, two more parameters are6008// passed, the full `{line, column}` locations of the start and6009// end of the comments. Note that you are not allowed to call the6010// parser from the callback—that will corrupt its internal state.6011onComment: null,6012// Nodes have their start and end characters offsets recorded in6013// `start` and `end` properties (directly on the node, rather than6014// the `loc` object, which holds line/column data. To also add a6015// [semi-standardized][range] `range` property holding a `[start,6016// end]` array with the same numbers, set the `ranges` option to6017// `true`.6018//6019// [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=7456786020ranges: false,6021// It is possible to parse multiple files into a single AST by6022// passing the tree produced by parsing the first file as6023// `program` option in subsequent parses. This will add the6024// toplevel forms of the parsed file to the `Program` (top) node6025// of an existing parse tree.6026program: null,6027// When `locations` is on, you can pass this to record the source6028// file in every node's `loc` object.6029sourceFile: null,6030// This value, if given, is stored in every node, whether6031// `locations` is on or off.6032directSourceFile: null,6033// When enabled, parenthesized expressions are represented by6034// (non-standard) ParenthesizedExpression nodes6035preserveParens: false6036};60376038// Interpret and default an options object60396040function getOptions(opts) {6041var options = {};60426043for (var opt in defaultOptions)6044{ options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }60456046if (options.ecmaVersion >= 2015)6047{ options.ecmaVersion -= 2009; }60486049if (options.allowReserved == null)6050{ options.allowReserved = options.ecmaVersion < 5; }60516052if (isArray(options.onToken)) {6053var tokens = options.onToken;6054options.onToken = function (token) { return tokens.push(token); };6055}6056if (isArray(options.onComment))6057{ options.onComment = pushComment(options, options.onComment); }60586059return options6060}60616062function pushComment(options, array) {6063return function(block, text, start, end, startLoc, endLoc) {6064var comment = {6065type: block ? "Block" : "Line",6066value: text,6067start: start,6068end: end6069};6070if (options.locations)6071{ comment.loc = new SourceLocation(this, startLoc, endLoc); }6072if (options.ranges)6073{ comment.range = [start, end]; }6074array.push(comment);6075}6076}60776078// Each scope gets a bitset that may contain these flags6079var6080SCOPE_TOP = 1,6081SCOPE_FUNCTION = 2,6082SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION,6083SCOPE_ASYNC = 4,6084SCOPE_GENERATOR = 8,6085SCOPE_ARROW = 16,6086SCOPE_SIMPLE_CATCH = 32,6087SCOPE_SUPER = 64,6088SCOPE_DIRECT_SUPER = 128;60896090function functionFlags(async, generator) {6091return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)6092}60936094// Used in checkLVal and declareName to determine the type of a binding6095var6096BIND_NONE = 0, // Not a binding6097BIND_VAR = 1, // Var-style binding6098BIND_LEXICAL = 2, // Let- or const-style binding6099BIND_FUNCTION = 3, // Function declaration6100BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding6101BIND_OUTSIDE = 5; // Special case for function names as bound inside the function61026103var Parser = function Parser(options, input, startPos) {6104this.options = options = getOptions(options);6105this.sourceFile = options.sourceFile;6106this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);6107var reserved = "";6108if (options.allowReserved !== true) {6109for (var v = options.ecmaVersion;; v--)6110{ if (reserved = reservedWords[v]) { break } }6111if (options.sourceType === "module") { reserved += " await"; }6112}6113this.reservedWords = wordsRegexp(reserved);6114var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;6115this.reservedWordsStrict = wordsRegexp(reservedStrict);6116this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);6117this.input = String(input);61186119// Used to signal to callers of `readWord1` whether the word6120// contained any escape sequences. This is needed because words with6121// escape sequences must not be interpreted as keywords.6122this.containsEsc = false;61236124// Set up token state61256126// The current position of the tokenizer in the input.6127if (startPos) {6128this.pos = startPos;6129this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;6130this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;6131} else {6132this.pos = this.lineStart = 0;6133this.curLine = 1;6134}61356136// Properties of the current token:6137// Its type6138this.type = types.eof;6139// For tokens that include more information than their type, the value6140this.value = null;6141// Its start and end offset6142this.start = this.end = this.pos;6143// And, if locations are used, the {line, column} object6144// corresponding to those offsets6145this.startLoc = this.endLoc = this.curPosition();61466147// Position information for the previous token6148this.lastTokEndLoc = this.lastTokStartLoc = null;6149this.lastTokStart = this.lastTokEnd = this.pos;61506151// The context stack is used to superficially track syntactic6152// context to predict whether a regular expression is allowed in a6153// given position.6154this.context = this.initialContext();6155this.exprAllowed = true;61566157// Figure out if it's a module code.6158this.inModule = options.sourceType === "module";6159this.strict = this.inModule || this.strictDirective(this.pos);61606161// Used to signify the start of a potential arrow function6162this.potentialArrowAt = -1;61636164// Positions to delayed-check that yield/await does not exist in default parameters.6165this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;6166// Labels in scope.6167this.labels = [];6168// Thus-far undefined exports.6169this.undefinedExports = {};61706171// If enabled, skip leading hashbang line.6172if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")6173{ this.skipLineComment(2); }61746175// Scope tracking for duplicate variable names (see scope.js)6176this.scopeStack = [];6177this.enterScope(SCOPE_TOP);61786179// For RegExp validation6180this.regexpState = null;6181};61826183var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true } };61846185Parser.prototype.parse = function parse () {6186var node = this.options.program || this.startNode();6187this.nextToken();6188return this.parseTopLevel(node)6189};61906191prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };6192prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 };6193prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 };6194prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 };6195prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };6196prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };61976198// Switch to a getter for 7.0.0.6199Parser.prototype.inNonArrowFunction = function inNonArrowFunction () { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0 };62006201Parser.extend = function extend () {6202var plugins = [], len = arguments.length;6203while ( len-- ) plugins[ len ] = arguments[ len ];62046205var cls = this;6206for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }6207return cls6208};62096210Parser.parse = function parse (input, options) {6211return new this(options, input).parse()6212};62136214Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {6215var parser = new this(options, input, pos);6216parser.nextToken();6217return parser.parseExpression()6218};62196220Parser.tokenizer = function tokenizer (input, options) {6221return new this(options, input)6222};62236224Object.defineProperties( Parser.prototype, prototypeAccessors );62256226var pp = Parser.prototype;62276228// ## Parser utilities62296230var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;6231pp.strictDirective = function(start) {6232for (;;) {6233// Try to find string literal.6234skipWhiteSpace.lastIndex = start;6235start += skipWhiteSpace.exec(this.input)[0].length;6236var match = literal.exec(this.input.slice(start));6237if (!match) { return false }6238if ((match[1] || match[2]) === "use strict") {6239skipWhiteSpace.lastIndex = start + match[0].length;6240var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;6241var next = this.input.charAt(end);6242return next === ";" || next === "}" ||6243(lineBreak.test(spaceAfter[0]) &&6244!(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))6245}6246start += match[0].length;62476248// Skip semicolon, if any.6249skipWhiteSpace.lastIndex = start;6250start += skipWhiteSpace.exec(this.input)[0].length;6251if (this.input[start] === ";")6252{ start++; }6253}6254};62556256// Predicate that tests whether the next token is of the given6257// type, and if yes, consumes it as a side effect.62586259pp.eat = function(type) {6260if (this.type === type) {6261this.next();6262return true6263} else {6264return false6265}6266};62676268// Tests whether parsed token is a contextual keyword.62696270pp.isContextual = function(name) {6271return this.type === types.name && this.value === name && !this.containsEsc6272};62736274// Consumes contextual keyword if possible.62756276pp.eatContextual = function(name) {6277if (!this.isContextual(name)) { return false }6278this.next();6279return true6280};62816282// Asserts that following token is given contextual keyword.62836284pp.expectContextual = function(name) {6285if (!this.eatContextual(name)) { this.unexpected(); }6286};62876288// Test whether a semicolon can be inserted at the current position.62896290pp.canInsertSemicolon = function() {6291return this.type === types.eof ||6292this.type === types.braceR ||6293lineBreak.test(this.input.slice(this.lastTokEnd, this.start))6294};62956296pp.insertSemicolon = function() {6297if (this.canInsertSemicolon()) {6298if (this.options.onInsertedSemicolon)6299{ this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }6300return true6301}6302};63036304// Consume a semicolon, or, failing that, see if we are allowed to6305// pretend that there is a semicolon at this position.63066307pp.semicolon = function() {6308if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); }6309};63106311pp.afterTrailingComma = function(tokType, notNext) {6312if (this.type === tokType) {6313if (this.options.onTrailingComma)6314{ this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }6315if (!notNext)6316{ this.next(); }6317return true6318}6319};63206321// Expect a token of a given type. If found, consume it, otherwise,6322// raise an unexpected token error.63236324pp.expect = function(type) {6325this.eat(type) || this.unexpected();6326};63276328// Raise an unexpected token error.63296330pp.unexpected = function(pos) {6331this.raise(pos != null ? pos : this.start, "Unexpected token");6332};63336334function DestructuringErrors() {6335this.shorthandAssign =6336this.trailingComma =6337this.parenthesizedAssign =6338this.parenthesizedBind =6339this.doubleProto =6340-1;6341}63426343pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {6344if (!refDestructuringErrors) { return }6345if (refDestructuringErrors.trailingComma > -1)6346{ this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }6347var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;6348if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }6349};63506351pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {6352if (!refDestructuringErrors) { return false }6353var shorthandAssign = refDestructuringErrors.shorthandAssign;6354var doubleProto = refDestructuringErrors.doubleProto;6355if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }6356if (shorthandAssign >= 0)6357{ this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }6358if (doubleProto >= 0)6359{ this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }6360};63616362pp.checkYieldAwaitInDefaultParams = function() {6363if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))6364{ this.raise(this.yieldPos, "Yield expression cannot be a default value"); }6365if (this.awaitPos)6366{ this.raise(this.awaitPos, "Await expression cannot be a default value"); }6367};63686369pp.isSimpleAssignTarget = function(expr) {6370if (expr.type === "ParenthesizedExpression")6371{ return this.isSimpleAssignTarget(expr.expression) }6372return expr.type === "Identifier" || expr.type === "MemberExpression"6373};63746375var pp$1 = Parser.prototype;63766377// ### Statement parsing63786379// Parse a program. Initializes the parser, reads any number of6380// statements, and wraps them in a Program node. Optionally takes a6381// `program` argument. If present, the statements will be appended6382// to its body instead of creating a new node.63836384pp$1.parseTopLevel = function(node) {6385var exports = {};6386if (!node.body) { node.body = []; }6387while (this.type !== types.eof) {6388var stmt = this.parseStatement(null, true, exports);6389node.body.push(stmt);6390}6391if (this.inModule)6392{ for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)6393{6394var name = list[i];63956396this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));6397} }6398this.adaptDirectivePrologue(node.body);6399this.next();6400node.sourceType = this.options.sourceType;6401return this.finishNode(node, "Program")6402};64036404var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};64056406pp$1.isLet = function(context) {6407if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }6408skipWhiteSpace.lastIndex = this.pos;6409var skip = skipWhiteSpace.exec(this.input);6410var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);6411// For ambiguous cases, determine if a LexicalDeclaration (or only a6412// Statement) is allowed here. If context is not empty then only a Statement6413// is allowed. However, `let [` is an explicit negative lookahead for6414// ExpressionStatement, so special-case it first.6415if (nextCh === 91) { return true } // '['6416if (context) { return false }64176418if (nextCh === 123) { return true } // '{'6419if (isIdentifierStart(nextCh, true)) {6420var pos = next + 1;6421while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; }6422var ident = this.input.slice(next, pos);6423if (!keywordRelationalOperator.test(ident)) { return true }6424}6425return false6426};64276428// check 'async [no LineTerminator here] function'6429// - 'async /*foo*/ function' is OK.6430// - 'async /*\n*/ function' is invalid.6431pp$1.isAsyncFunction = function() {6432if (this.options.ecmaVersion < 8 || !this.isContextual("async"))6433{ return false }64346435skipWhiteSpace.lastIndex = this.pos;6436var skip = skipWhiteSpace.exec(this.input);6437var next = this.pos + skip[0].length;6438return !lineBreak.test(this.input.slice(this.pos, next)) &&6439this.input.slice(next, next + 8) === "function" &&6440(next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8)))6441};64426443// Parse a single statement.6444//6445// If expecting a statement and finding a slash operator, parse a6446// regular expression literal. This is to handle cases like6447// `if (foo) /blah/.exec(foo)`, where looking at the previous token6448// does not help.64496450pp$1.parseStatement = function(context, topLevel, exports) {6451var starttype = this.type, node = this.startNode(), kind;64526453if (this.isLet(context)) {6454starttype = types._var;6455kind = "let";6456}64576458// Most types of statements are recognized by the keyword they6459// start with. Many are trivial to parse, some require a bit of6460// complexity.64616462switch (starttype) {6463case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)6464case types._debugger: return this.parseDebuggerStatement(node)6465case types._do: return this.parseDoStatement(node)6466case types._for: return this.parseForStatement(node)6467case types._function:6468// Function as sole body of either an if statement or a labeled statement6469// works, but not when it is part of a labeled statement that is the sole6470// body of an if statement.6471if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }6472return this.parseFunctionStatement(node, false, !context)6473case types._class:6474if (context) { this.unexpected(); }6475return this.parseClass(node, true)6476case types._if: return this.parseIfStatement(node)6477case types._return: return this.parseReturnStatement(node)6478case types._switch: return this.parseSwitchStatement(node)6479case types._throw: return this.parseThrowStatement(node)6480case types._try: return this.parseTryStatement(node)6481case types._const: case types._var:6482kind = kind || this.value;6483if (context && kind !== "var") { this.unexpected(); }6484return this.parseVarStatement(node, kind)6485case types._while: return this.parseWhileStatement(node)6486case types._with: return this.parseWithStatement(node)6487case types.braceL: return this.parseBlock(true, node)6488case types.semi: return this.parseEmptyStatement(node)6489case types._export:6490case types._import:6491if (this.options.ecmaVersion > 10 && starttype === types._import) {6492skipWhiteSpace.lastIndex = this.pos;6493var skip = skipWhiteSpace.exec(this.input);6494var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);6495if (nextCh === 40 || nextCh === 46) // '(' or '.'6496{ return this.parseExpressionStatement(node, this.parseExpression()) }6497}64986499if (!this.options.allowImportExportEverywhere) {6500if (!topLevel)6501{ this.raise(this.start, "'import' and 'export' may only appear at the top level"); }6502if (!this.inModule)6503{ this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }6504}6505return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports)65066507// If the statement does not start with a statement keyword or a6508// brace, it's an ExpressionStatement or LabeledStatement. We6509// simply start parsing an expression, and afterwards, if the6510// next token is a colon and the expression was a simple6511// Identifier node, we switch to interpreting it as a label.6512default:6513if (this.isAsyncFunction()) {6514if (context) { this.unexpected(); }6515this.next();6516return this.parseFunctionStatement(node, true, !context)6517}65186519var maybeName = this.value, expr = this.parseExpression();6520if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon))6521{ return this.parseLabeledStatement(node, maybeName, expr, context) }6522else { return this.parseExpressionStatement(node, expr) }6523}6524};65256526pp$1.parseBreakContinueStatement = function(node, keyword) {6527var isBreak = keyword === "break";6528this.next();6529if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; }6530else if (this.type !== types.name) { this.unexpected(); }6531else {6532node.label = this.parseIdent();6533this.semicolon();6534}65356536// Verify that there is an actual destination to break or6537// continue to.6538var i = 0;6539for (; i < this.labels.length; ++i) {6540var lab = this.labels[i];6541if (node.label == null || lab.name === node.label.name) {6542if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }6543if (node.label && isBreak) { break }6544}6545}6546if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }6547return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")6548};65496550pp$1.parseDebuggerStatement = function(node) {6551this.next();6552this.semicolon();6553return this.finishNode(node, "DebuggerStatement")6554};65556556pp$1.parseDoStatement = function(node) {6557this.next();6558this.labels.push(loopLabel);6559node.body = this.parseStatement("do");6560this.labels.pop();6561this.expect(types._while);6562node.test = this.parseParenExpression();6563if (this.options.ecmaVersion >= 6)6564{ this.eat(types.semi); }6565else6566{ this.semicolon(); }6567return this.finishNode(node, "DoWhileStatement")6568};65696570// Disambiguating between a `for` and a `for`/`in` or `for`/`of`6571// loop is non-trivial. Basically, we have to parse the init `var`6572// statement or expression, disallowing the `in` operator (see6573// the second parameter to `parseExpression`), and then check6574// whether the next token is `in` or `of`. When there is no init6575// part (semicolon immediately after the opening parenthesis), it6576// is a regular `for` loop.65776578pp$1.parseForStatement = function(node) {6579this.next();6580var awaitAt = (this.options.ecmaVersion >= 9 && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) && this.eatContextual("await")) ? this.lastTokStart : -1;6581this.labels.push(loopLabel);6582this.enterScope(0);6583this.expect(types.parenL);6584if (this.type === types.semi) {6585if (awaitAt > -1) { this.unexpected(awaitAt); }6586return this.parseFor(node, null)6587}6588var isLet = this.isLet();6589if (this.type === types._var || this.type === types._const || isLet) {6590var init$1 = this.startNode(), kind = isLet ? "let" : this.value;6591this.next();6592this.parseVar(init$1, true, kind);6593this.finishNode(init$1, "VariableDeclaration");6594if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {6595if (this.options.ecmaVersion >= 9) {6596if (this.type === types._in) {6597if (awaitAt > -1) { this.unexpected(awaitAt); }6598} else { node.await = awaitAt > -1; }6599}6600return this.parseForIn(node, init$1)6601}6602if (awaitAt > -1) { this.unexpected(awaitAt); }6603return this.parseFor(node, init$1)6604}6605var refDestructuringErrors = new DestructuringErrors;6606var init = this.parseExpression(true, refDestructuringErrors);6607if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {6608if (this.options.ecmaVersion >= 9) {6609if (this.type === types._in) {6610if (awaitAt > -1) { this.unexpected(awaitAt); }6611} else { node.await = awaitAt > -1; }6612}6613this.toAssignable(init, false, refDestructuringErrors);6614this.checkLVal(init);6615return this.parseForIn(node, init)6616} else {6617this.checkExpressionErrors(refDestructuringErrors, true);6618}6619if (awaitAt > -1) { this.unexpected(awaitAt); }6620return this.parseFor(node, init)6621};66226623pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) {6624this.next();6625return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)6626};66276628pp$1.parseIfStatement = function(node) {6629this.next();6630node.test = this.parseParenExpression();6631// allow function declarations in branches, but only in non-strict mode6632node.consequent = this.parseStatement("if");6633node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;6634return this.finishNode(node, "IfStatement")6635};66366637pp$1.parseReturnStatement = function(node) {6638if (!this.inFunction && !this.options.allowReturnOutsideFunction)6639{ this.raise(this.start, "'return' outside of function"); }6640this.next();66416642// In `return` (and `break`/`continue`), the keywords with6643// optional arguments, we eagerly look for a semicolon or the6644// possibility to insert one.66456646if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; }6647else { node.argument = this.parseExpression(); this.semicolon(); }6648return this.finishNode(node, "ReturnStatement")6649};66506651pp$1.parseSwitchStatement = function(node) {6652this.next();6653node.discriminant = this.parseParenExpression();6654node.cases = [];6655this.expect(types.braceL);6656this.labels.push(switchLabel);6657this.enterScope(0);66586659// Statements under must be grouped (by label) in SwitchCase6660// nodes. `cur` is used to keep the node that we are currently6661// adding statements to.66626663var cur;6664for (var sawDefault = false; this.type !== types.braceR;) {6665if (this.type === types._case || this.type === types._default) {6666var isCase = this.type === types._case;6667if (cur) { this.finishNode(cur, "SwitchCase"); }6668node.cases.push(cur = this.startNode());6669cur.consequent = [];6670this.next();6671if (isCase) {6672cur.test = this.parseExpression();6673} else {6674if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }6675sawDefault = true;6676cur.test = null;6677}6678this.expect(types.colon);6679} else {6680if (!cur) { this.unexpected(); }6681cur.consequent.push(this.parseStatement(null));6682}6683}6684this.exitScope();6685if (cur) { this.finishNode(cur, "SwitchCase"); }6686this.next(); // Closing brace6687this.labels.pop();6688return this.finishNode(node, "SwitchStatement")6689};66906691pp$1.parseThrowStatement = function(node) {6692this.next();6693if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))6694{ this.raise(this.lastTokEnd, "Illegal newline after throw"); }6695node.argument = this.parseExpression();6696this.semicolon();6697return this.finishNode(node, "ThrowStatement")6698};66996700// Reused empty array added for node fields that are always empty.67016702var empty = [];67036704pp$1.parseTryStatement = function(node) {6705this.next();6706node.block = this.parseBlock();6707node.handler = null;6708if (this.type === types._catch) {6709var clause = this.startNode();6710this.next();6711if (this.eat(types.parenL)) {6712clause.param = this.parseBindingAtom();6713var simple = clause.param.type === "Identifier";6714this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);6715this.checkLVal(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);6716this.expect(types.parenR);6717} else {6718if (this.options.ecmaVersion < 10) { this.unexpected(); }6719clause.param = null;6720this.enterScope(0);6721}6722clause.body = this.parseBlock(false);6723this.exitScope();6724node.handler = this.finishNode(clause, "CatchClause");6725}6726node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;6727if (!node.handler && !node.finalizer)6728{ this.raise(node.start, "Missing catch or finally clause"); }6729return this.finishNode(node, "TryStatement")6730};67316732pp$1.parseVarStatement = function(node, kind) {6733this.next();6734this.parseVar(node, false, kind);6735this.semicolon();6736return this.finishNode(node, "VariableDeclaration")6737};67386739pp$1.parseWhileStatement = function(node) {6740this.next();6741node.test = this.parseParenExpression();6742this.labels.push(loopLabel);6743node.body = this.parseStatement("while");6744this.labels.pop();6745return this.finishNode(node, "WhileStatement")6746};67476748pp$1.parseWithStatement = function(node) {6749if (this.strict) { this.raise(this.start, "'with' in strict mode"); }6750this.next();6751node.object = this.parseParenExpression();6752node.body = this.parseStatement("with");6753return this.finishNode(node, "WithStatement")6754};67556756pp$1.parseEmptyStatement = function(node) {6757this.next();6758return this.finishNode(node, "EmptyStatement")6759};67606761pp$1.parseLabeledStatement = function(node, maybeName, expr, context) {6762for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)6763{6764var label = list[i$1];67656766if (label.name === maybeName)6767{ this.raise(expr.start, "Label '" + maybeName + "' is already declared");6768} }6769var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null;6770for (var i = this.labels.length - 1; i >= 0; i--) {6771var label$1 = this.labels[i];6772if (label$1.statementStart === node.start) {6773// Update information about previous labels on this node6774label$1.statementStart = this.start;6775label$1.kind = kind;6776} else { break }6777}6778this.labels.push({name: maybeName, kind: kind, statementStart: this.start});6779node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");6780this.labels.pop();6781node.label = expr;6782return this.finishNode(node, "LabeledStatement")6783};67846785pp$1.parseExpressionStatement = function(node, expr) {6786node.expression = expr;6787this.semicolon();6788return this.finishNode(node, "ExpressionStatement")6789};67906791// Parse a semicolon-enclosed block of statements, handling `"use6792// strict"` declarations when `allowStrict` is true (used for6793// function bodies).67946795pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) {6796if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;6797if ( node === void 0 ) node = this.startNode();67986799node.body = [];6800this.expect(types.braceL);6801if (createNewLexicalScope) { this.enterScope(0); }6802while (this.type !== types.braceR) {6803var stmt = this.parseStatement(null);6804node.body.push(stmt);6805}6806if (exitStrict) { this.strict = false; }6807this.next();6808if (createNewLexicalScope) { this.exitScope(); }6809return this.finishNode(node, "BlockStatement")6810};68116812// Parse a regular `for` loop. The disambiguation code in6813// `parseStatement` will already have parsed the init statement or6814// expression.68156816pp$1.parseFor = function(node, init) {6817node.init = init;6818this.expect(types.semi);6819node.test = this.type === types.semi ? null : this.parseExpression();6820this.expect(types.semi);6821node.update = this.type === types.parenR ? null : this.parseExpression();6822this.expect(types.parenR);6823node.body = this.parseStatement("for");6824this.exitScope();6825this.labels.pop();6826return this.finishNode(node, "ForStatement")6827};68286829// Parse a `for`/`in` and `for`/`of` loop, which are almost6830// same from parser's perspective.68316832pp$1.parseForIn = function(node, init) {6833var isForIn = this.type === types._in;6834this.next();68356836if (6837init.type === "VariableDeclaration" &&6838init.declarations[0].init != null &&6839(6840!isForIn ||6841this.options.ecmaVersion < 8 ||6842this.strict ||6843init.kind !== "var" ||6844init.declarations[0].id.type !== "Identifier"6845)6846) {6847this.raise(6848init.start,6849((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")6850);6851} else if (init.type === "AssignmentPattern") {6852this.raise(init.start, "Invalid left-hand side in for-loop");6853}6854node.left = init;6855node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();6856this.expect(types.parenR);6857node.body = this.parseStatement("for");6858this.exitScope();6859this.labels.pop();6860return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")6861};68626863// Parse a list of variable declarations.68646865pp$1.parseVar = function(node, isFor, kind) {6866node.declarations = [];6867node.kind = kind;6868for (;;) {6869var decl = this.startNode();6870this.parseVarId(decl, kind);6871if (this.eat(types.eq)) {6872decl.init = this.parseMaybeAssign(isFor);6873} else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {6874this.unexpected();6875} else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) {6876this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");6877} else {6878decl.init = null;6879}6880node.declarations.push(this.finishNode(decl, "VariableDeclarator"));6881if (!this.eat(types.comma)) { break }6882}6883return node6884};68856886pp$1.parseVarId = function(decl, kind) {6887decl.id = this.parseBindingAtom();6888this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);6889};68906891var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;68926893// Parse a function declaration or literal (depending on the6894// `statement & FUNC_STATEMENT`).68956896// Remove `allowExpressionBody` for 7.0.0, as it is only called with false6897pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) {6898this.initFunction(node);6899if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {6900if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT))6901{ this.unexpected(); }6902node.generator = this.eat(types.star);6903}6904if (this.options.ecmaVersion >= 8)6905{ node.async = !!isAsync; }69066907if (statement & FUNC_STATEMENT) {6908node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent();6909if (node.id && !(statement & FUNC_HANGING_STATEMENT))6910// If it is a regular function declaration in sloppy mode, then it is6911// subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding6912// mode depends on properties of the current scope (see6913// treatFunctionsAsVar).6914{ this.checkLVal(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }6915}69166917var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;6918this.yieldPos = 0;6919this.awaitPos = 0;6920this.awaitIdentPos = 0;6921this.enterScope(functionFlags(node.async, node.generator));69226923if (!(statement & FUNC_STATEMENT))6924{ node.id = this.type === types.name ? this.parseIdent() : null; }69256926this.parseFunctionParams(node);6927this.parseFunctionBody(node, allowExpressionBody, false);69286929this.yieldPos = oldYieldPos;6930this.awaitPos = oldAwaitPos;6931this.awaitIdentPos = oldAwaitIdentPos;6932return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")6933};69346935pp$1.parseFunctionParams = function(node) {6936this.expect(types.parenL);6937node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);6938this.checkYieldAwaitInDefaultParams();6939};69406941// Parse a class declaration or literal (depending on the6942// `isStatement` parameter).69436944pp$1.parseClass = function(node, isStatement) {6945this.next();69466947// ecma-262 14.6 Class Definitions6948// A class definition is always strict mode code.6949var oldStrict = this.strict;6950this.strict = true;69516952this.parseClassId(node, isStatement);6953this.parseClassSuper(node);6954var classBody = this.startNode();6955var hadConstructor = false;6956classBody.body = [];6957this.expect(types.braceL);6958while (this.type !== types.braceR) {6959var element = this.parseClassElement(node.superClass !== null);6960if (element) {6961classBody.body.push(element);6962if (element.type === "MethodDefinition" && element.kind === "constructor") {6963if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }6964hadConstructor = true;6965}6966}6967}6968this.strict = oldStrict;6969this.next();6970node.body = this.finishNode(classBody, "ClassBody");6971return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")6972};69736974pp$1.parseClassElement = function(constructorAllowsSuper) {6975var this$1$1 = this;69766977if (this.eat(types.semi)) { return null }69786979var method = this.startNode();6980var tryContextual = function (k, noLineBreak) {6981if ( noLineBreak === void 0 ) noLineBreak = false;69826983var start = this$1$1.start, startLoc = this$1$1.startLoc;6984if (!this$1$1.eatContextual(k)) { return false }6985if (this$1$1.type !== types.parenL && (!noLineBreak || !this$1$1.canInsertSemicolon())) { return true }6986if (method.key) { this$1$1.unexpected(); }6987method.computed = false;6988method.key = this$1$1.startNodeAt(start, startLoc);6989method.key.name = k;6990this$1$1.finishNode(method.key, "Identifier");6991return false6992};69936994method.kind = "method";6995method.static = tryContextual("static");6996var isGenerator = this.eat(types.star);6997var isAsync = false;6998if (!isGenerator) {6999if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) {7000isAsync = true;7001isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);7002} else if (tryContextual("get")) {7003method.kind = "get";7004} else if (tryContextual("set")) {7005method.kind = "set";7006}7007}7008if (!method.key) { this.parsePropertyName(method); }7009var key = method.key;7010var allowsDirectSuper = false;7011if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" ||7012key.type === "Literal" && key.value === "constructor")) {7013if (method.kind !== "method") { this.raise(key.start, "Constructor can't have get/set modifier"); }7014if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }7015if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }7016method.kind = "constructor";7017allowsDirectSuper = constructorAllowsSuper;7018} else if (method.static && key.type === "Identifier" && key.name === "prototype") {7019this.raise(key.start, "Classes may not have a static property named prototype");7020}7021this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper);7022if (method.kind === "get" && method.value.params.length !== 0)7023{ this.raiseRecoverable(method.value.start, "getter should have no params"); }7024if (method.kind === "set" && method.value.params.length !== 1)7025{ this.raiseRecoverable(method.value.start, "setter should have exactly one param"); }7026if (method.kind === "set" && method.value.params[0].type === "RestElement")7027{ this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); }7028return method7029};70307031pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {7032method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);7033return this.finishNode(method, "MethodDefinition")7034};70357036pp$1.parseClassId = function(node, isStatement) {7037if (this.type === types.name) {7038node.id = this.parseIdent();7039if (isStatement)7040{ this.checkLVal(node.id, BIND_LEXICAL, false); }7041} else {7042if (isStatement === true)7043{ this.unexpected(); }7044node.id = null;7045}7046};70477048pp$1.parseClassSuper = function(node) {7049node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;7050};70517052// Parses module export declaration.70537054pp$1.parseExport = function(node, exports) {7055this.next();7056// export * from '...'7057if (this.eat(types.star)) {7058if (this.options.ecmaVersion >= 11) {7059if (this.eatContextual("as")) {7060node.exported = this.parseIdent(true);7061this.checkExport(exports, node.exported.name, this.lastTokStart);7062} else {7063node.exported = null;7064}7065}7066this.expectContextual("from");7067if (this.type !== types.string) { this.unexpected(); }7068node.source = this.parseExprAtom();7069this.semicolon();7070return this.finishNode(node, "ExportAllDeclaration")7071}7072if (this.eat(types._default)) { // export default ...7073this.checkExport(exports, "default", this.lastTokStart);7074var isAsync;7075if (this.type === types._function || (isAsync = this.isAsyncFunction())) {7076var fNode = this.startNode();7077this.next();7078if (isAsync) { this.next(); }7079node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);7080} else if (this.type === types._class) {7081var cNode = this.startNode();7082node.declaration = this.parseClass(cNode, "nullableID");7083} else {7084node.declaration = this.parseMaybeAssign();7085this.semicolon();7086}7087return this.finishNode(node, "ExportDefaultDeclaration")7088}7089// export var|const|let|function|class ...7090if (this.shouldParseExportStatement()) {7091node.declaration = this.parseStatement(null);7092if (node.declaration.type === "VariableDeclaration")7093{ this.checkVariableExport(exports, node.declaration.declarations); }7094else7095{ this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }7096node.specifiers = [];7097node.source = null;7098} else { // export { x, y as z } [from '...']7099node.declaration = null;7100node.specifiers = this.parseExportSpecifiers(exports);7101if (this.eatContextual("from")) {7102if (this.type !== types.string) { this.unexpected(); }7103node.source = this.parseExprAtom();7104} else {7105for (var i = 0, list = node.specifiers; i < list.length; i += 1) {7106// check for keywords used as local names7107var spec = list[i];71087109this.checkUnreserved(spec.local);7110// check if export is defined7111this.checkLocalExport(spec.local);7112}71137114node.source = null;7115}7116this.semicolon();7117}7118return this.finishNode(node, "ExportNamedDeclaration")7119};71207121pp$1.checkExport = function(exports, name, pos) {7122if (!exports) { return }7123if (has(exports, name))7124{ this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }7125exports[name] = true;7126};71277128pp$1.checkPatternExport = function(exports, pat) {7129var type = pat.type;7130if (type === "Identifier")7131{ this.checkExport(exports, pat.name, pat.start); }7132else if (type === "ObjectPattern")7133{ for (var i = 0, list = pat.properties; i < list.length; i += 1)7134{7135var prop = list[i];71367137this.checkPatternExport(exports, prop);7138} }7139else if (type === "ArrayPattern")7140{ for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {7141var elt = list$1[i$1];71427143if (elt) { this.checkPatternExport(exports, elt); }7144} }7145else if (type === "Property")7146{ this.checkPatternExport(exports, pat.value); }7147else if (type === "AssignmentPattern")7148{ this.checkPatternExport(exports, pat.left); }7149else if (type === "RestElement")7150{ this.checkPatternExport(exports, pat.argument); }7151else if (type === "ParenthesizedExpression")7152{ this.checkPatternExport(exports, pat.expression); }7153};71547155pp$1.checkVariableExport = function(exports, decls) {7156if (!exports) { return }7157for (var i = 0, list = decls; i < list.length; i += 1)7158{7159var decl = list[i];71607161this.checkPatternExport(exports, decl.id);7162}7163};71647165pp$1.shouldParseExportStatement = function() {7166return this.type.keyword === "var" ||7167this.type.keyword === "const" ||7168this.type.keyword === "class" ||7169this.type.keyword === "function" ||7170this.isLet() ||7171this.isAsyncFunction()7172};71737174// Parses a comma-separated list of module exports.71757176pp$1.parseExportSpecifiers = function(exports) {7177var nodes = [], first = true;7178// export { x, y as z } [from '...']7179this.expect(types.braceL);7180while (!this.eat(types.braceR)) {7181if (!first) {7182this.expect(types.comma);7183if (this.afterTrailingComma(types.braceR)) { break }7184} else { first = false; }71857186var node = this.startNode();7187node.local = this.parseIdent(true);7188node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;7189this.checkExport(exports, node.exported.name, node.exported.start);7190nodes.push(this.finishNode(node, "ExportSpecifier"));7191}7192return nodes7193};71947195// Parses import declaration.71967197pp$1.parseImport = function(node) {7198this.next();7199// import '...'7200if (this.type === types.string) {7201node.specifiers = empty;7202node.source = this.parseExprAtom();7203} else {7204node.specifiers = this.parseImportSpecifiers();7205this.expectContextual("from");7206node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();7207}7208this.semicolon();7209return this.finishNode(node, "ImportDeclaration")7210};72117212// Parses a comma-separated list of module imports.72137214pp$1.parseImportSpecifiers = function() {7215var nodes = [], first = true;7216if (this.type === types.name) {7217// import defaultObj, { x, y as z } from '...'7218var node = this.startNode();7219node.local = this.parseIdent();7220this.checkLVal(node.local, BIND_LEXICAL);7221nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));7222if (!this.eat(types.comma)) { return nodes }7223}7224if (this.type === types.star) {7225var node$1 = this.startNode();7226this.next();7227this.expectContextual("as");7228node$1.local = this.parseIdent();7229this.checkLVal(node$1.local, BIND_LEXICAL);7230nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));7231return nodes7232}7233this.expect(types.braceL);7234while (!this.eat(types.braceR)) {7235if (!first) {7236this.expect(types.comma);7237if (this.afterTrailingComma(types.braceR)) { break }7238} else { first = false; }72397240var node$2 = this.startNode();7241node$2.imported = this.parseIdent(true);7242if (this.eatContextual("as")) {7243node$2.local = this.parseIdent();7244} else {7245this.checkUnreserved(node$2.imported);7246node$2.local = node$2.imported;7247}7248this.checkLVal(node$2.local, BIND_LEXICAL);7249nodes.push(this.finishNode(node$2, "ImportSpecifier"));7250}7251return nodes7252};72537254// Set `ExpressionStatement#directive` property for directive prologues.7255pp$1.adaptDirectivePrologue = function(statements) {7256for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {7257statements[i].directive = statements[i].expression.raw.slice(1, -1);7258}7259};7260pp$1.isDirectiveCandidate = function(statement) {7261return (7262statement.type === "ExpressionStatement" &&7263statement.expression.type === "Literal" &&7264typeof statement.expression.value === "string" &&7265// Reject parenthesized strings.7266(this.input[statement.start] === "\"" || this.input[statement.start] === "'")7267)7268};72697270var pp$2 = Parser.prototype;72717272// Convert existing expression atom to assignable pattern7273// if possible.72747275pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) {7276if (this.options.ecmaVersion >= 6 && node) {7277switch (node.type) {7278case "Identifier":7279if (this.inAsync && node.name === "await")7280{ this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }7281break72827283case "ObjectPattern":7284case "ArrayPattern":7285case "RestElement":7286break72877288case "ObjectExpression":7289node.type = "ObjectPattern";7290if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }7291for (var i = 0, list = node.properties; i < list.length; i += 1) {7292var prop = list[i];72937294this.toAssignable(prop, isBinding);7295// Early error:7296// AssignmentRestProperty[Yield, Await] :7297// `...` DestructuringAssignmentTarget[Yield, Await]7298//7299// It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.7300if (7301prop.type === "RestElement" &&7302(prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")7303) {7304this.raise(prop.argument.start, "Unexpected token");7305}7306}7307break73087309case "Property":7310// AssignmentProperty has type === "Property"7311if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }7312this.toAssignable(node.value, isBinding);7313break73147315case "ArrayExpression":7316node.type = "ArrayPattern";7317if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }7318this.toAssignableList(node.elements, isBinding);7319break73207321case "SpreadElement":7322node.type = "RestElement";7323this.toAssignable(node.argument, isBinding);7324if (node.argument.type === "AssignmentPattern")7325{ this.raise(node.argument.start, "Rest elements cannot have a default value"); }7326break73277328case "AssignmentExpression":7329if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }7330node.type = "AssignmentPattern";7331delete node.operator;7332this.toAssignable(node.left, isBinding);7333// falls through to AssignmentPattern73347335case "AssignmentPattern":7336break73377338case "ParenthesizedExpression":7339this.toAssignable(node.expression, isBinding, refDestructuringErrors);7340break73417342case "ChainExpression":7343this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");7344break73457346case "MemberExpression":7347if (!isBinding) { break }73487349default:7350this.raise(node.start, "Assigning to rvalue");7351}7352} else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }7353return node7354};73557356// Convert list of expression atoms to binding list.73577358pp$2.toAssignableList = function(exprList, isBinding) {7359var end = exprList.length;7360for (var i = 0; i < end; i++) {7361var elt = exprList[i];7362if (elt) { this.toAssignable(elt, isBinding); }7363}7364if (end) {7365var last = exprList[end - 1];7366if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")7367{ this.unexpected(last.argument.start); }7368}7369return exprList7370};73717372// Parses spread element.73737374pp$2.parseSpread = function(refDestructuringErrors) {7375var node = this.startNode();7376this.next();7377node.argument = this.parseMaybeAssign(false, refDestructuringErrors);7378return this.finishNode(node, "SpreadElement")7379};73807381pp$2.parseRestBinding = function() {7382var node = this.startNode();7383this.next();73847385// RestElement inside of a function parameter must be an identifier7386if (this.options.ecmaVersion === 6 && this.type !== types.name)7387{ this.unexpected(); }73887389node.argument = this.parseBindingAtom();73907391return this.finishNode(node, "RestElement")7392};73937394// Parses lvalue (assignable) atom.73957396pp$2.parseBindingAtom = function() {7397if (this.options.ecmaVersion >= 6) {7398switch (this.type) {7399case types.bracketL:7400var node = this.startNode();7401this.next();7402node.elements = this.parseBindingList(types.bracketR, true, true);7403return this.finishNode(node, "ArrayPattern")74047405case types.braceL:7406return this.parseObj(true)7407}7408}7409return this.parseIdent()7410};74117412pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {7413var elts = [], first = true;7414while (!this.eat(close)) {7415if (first) { first = false; }7416else { this.expect(types.comma); }7417if (allowEmpty && this.type === types.comma) {7418elts.push(null);7419} else if (allowTrailingComma && this.afterTrailingComma(close)) {7420break7421} else if (this.type === types.ellipsis) {7422var rest = this.parseRestBinding();7423this.parseBindingListItem(rest);7424elts.push(rest);7425if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }7426this.expect(close);7427break7428} else {7429var elem = this.parseMaybeDefault(this.start, this.startLoc);7430this.parseBindingListItem(elem);7431elts.push(elem);7432}7433}7434return elts7435};74367437pp$2.parseBindingListItem = function(param) {7438return param7439};74407441// Parses assignment pattern around given atom if possible.74427443pp$2.parseMaybeDefault = function(startPos, startLoc, left) {7444left = left || this.parseBindingAtom();7445if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left }7446var node = this.startNodeAt(startPos, startLoc);7447node.left = left;7448node.right = this.parseMaybeAssign();7449return this.finishNode(node, "AssignmentPattern")7450};74517452// Verify that a node is an lval — something that can be assigned7453// to.7454// bindingType can be either:7455// 'var' indicating that the lval creates a 'var' binding7456// 'let' indicating that the lval creates a lexical ('let' or 'const') binding7457// 'none' indicating that the binding should be checked for illegal identifiers, but not for duplicate references74587459pp$2.checkLVal = function(expr, bindingType, checkClashes) {7460if ( bindingType === void 0 ) bindingType = BIND_NONE;74617462switch (expr.type) {7463case "Identifier":7464if (bindingType === BIND_LEXICAL && expr.name === "let")7465{ this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }7466if (this.strict && this.reservedWordsStrictBind.test(expr.name))7467{ this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }7468if (checkClashes) {7469if (has(checkClashes, expr.name))7470{ this.raiseRecoverable(expr.start, "Argument name clash"); }7471checkClashes[expr.name] = true;7472}7473if (bindingType !== BIND_NONE && bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }7474break74757476case "ChainExpression":7477this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");7478break74797480case "MemberExpression":7481if (bindingType) { this.raiseRecoverable(expr.start, "Binding member expression"); }7482break74837484case "ObjectPattern":7485for (var i = 0, list = expr.properties; i < list.length; i += 1)7486{7487var prop = list[i];74887489this.checkLVal(prop, bindingType, checkClashes);7490}7491break74927493case "Property":7494// AssignmentProperty has type === "Property"7495this.checkLVal(expr.value, bindingType, checkClashes);7496break74977498case "ArrayPattern":7499for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {7500var elem = list$1[i$1];75017502if (elem) { this.checkLVal(elem, bindingType, checkClashes); }7503}7504break75057506case "AssignmentPattern":7507this.checkLVal(expr.left, bindingType, checkClashes);7508break75097510case "RestElement":7511this.checkLVal(expr.argument, bindingType, checkClashes);7512break75137514case "ParenthesizedExpression":7515this.checkLVal(expr.expression, bindingType, checkClashes);7516break75177518default:7519this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue");7520}7521};75227523// A recursive descent parser operates by defining functions for all75247525var pp$3 = Parser.prototype;75267527// Check if property name clashes with already added.7528// Object/class getters and setters are not allowed to clash —7529// either with each other or with an init property — and in7530// strict mode, init properties are also not allowed to be repeated.75317532pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) {7533if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")7534{ return }7535if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))7536{ return }7537var key = prop.key;7538var name;7539switch (key.type) {7540case "Identifier": name = key.name; break7541case "Literal": name = String(key.value); break7542default: return7543}7544var kind = prop.kind;7545if (this.options.ecmaVersion >= 6) {7546if (name === "__proto__" && kind === "init") {7547if (propHash.proto) {7548if (refDestructuringErrors) {7549if (refDestructuringErrors.doubleProto < 0)7550{ refDestructuringErrors.doubleProto = key.start; }7551// Backwards-compat kludge. Can be removed in version 6.07552} else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); }7553}7554propHash.proto = true;7555}7556return7557}7558name = "$" + name;7559var other = propHash[name];7560if (other) {7561var redefinition;7562if (kind === "init") {7563redefinition = this.strict && other.init || other.get || other.set;7564} else {7565redefinition = other.init || other[kind];7566}7567if (redefinition)7568{ this.raiseRecoverable(key.start, "Redefinition of property"); }7569} else {7570other = propHash[name] = {7571init: false,7572get: false,7573set: false7574};7575}7576other[kind] = true;7577};75787579// ### Expression parsing75807581// These nest, from the most general expression type at the top to7582// 'atomic', nondivisible expression types at the bottom. Most of7583// the functions will simply let the function(s) below them parse,7584// and, *if* the syntactic construct they handle is present, wrap7585// the AST node that the inner parser gave them in another node.75867587// Parse a full expression. The optional arguments are used to7588// forbid the `in` operator (in for loops initalization expressions)7589// and provide reference for storing '=' operator inside shorthand7590// property assignment in contexts where both object expression7591// and object pattern might appear (so it's possible to raise7592// delayed syntax error at correct position).75937594pp$3.parseExpression = function(noIn, refDestructuringErrors) {7595var startPos = this.start, startLoc = this.startLoc;7596var expr = this.parseMaybeAssign(noIn, refDestructuringErrors);7597if (this.type === types.comma) {7598var node = this.startNodeAt(startPos, startLoc);7599node.expressions = [expr];7600while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors)); }7601return this.finishNode(node, "SequenceExpression")7602}7603return expr7604};76057606// Parse an assignment expression. This includes applications of7607// operators like `+=`.76087609pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) {7610if (this.isContextual("yield")) {7611if (this.inGenerator) { return this.parseYield(noIn) }7612// The tokenizer will assume an expression is allowed after7613// `yield`, but this isn't that kind of yield7614else { this.exprAllowed = false; }7615}76167617var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1;7618if (refDestructuringErrors) {7619oldParenAssign = refDestructuringErrors.parenthesizedAssign;7620oldTrailingComma = refDestructuringErrors.trailingComma;7621refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;7622} else {7623refDestructuringErrors = new DestructuringErrors;7624ownDestructuringErrors = true;7625}76267627var startPos = this.start, startLoc = this.startLoc;7628if (this.type === types.parenL || this.type === types.name)7629{ this.potentialArrowAt = this.start; }7630var left = this.parseMaybeConditional(noIn, refDestructuringErrors);7631if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }7632if (this.type.isAssign) {7633var node = this.startNodeAt(startPos, startLoc);7634node.operator = this.value;7635node.left = this.type === types.eq ? this.toAssignable(left, false, refDestructuringErrors) : left;7636if (!ownDestructuringErrors) {7637refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;7638}7639if (refDestructuringErrors.shorthandAssign >= node.left.start)7640{ refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly7641this.checkLVal(left);7642this.next();7643node.right = this.parseMaybeAssign(noIn);7644return this.finishNode(node, "AssignmentExpression")7645} else {7646if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }7647}7648if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }7649if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }7650return left7651};76527653// Parse a ternary conditional (`?:`) operator.76547655pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) {7656var startPos = this.start, startLoc = this.startLoc;7657var expr = this.parseExprOps(noIn, refDestructuringErrors);7658if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }7659if (this.eat(types.question)) {7660var node = this.startNodeAt(startPos, startLoc);7661node.test = expr;7662node.consequent = this.parseMaybeAssign();7663this.expect(types.colon);7664node.alternate = this.parseMaybeAssign(noIn);7665return this.finishNode(node, "ConditionalExpression")7666}7667return expr7668};76697670// Start the precedence parser.76717672pp$3.parseExprOps = function(noIn, refDestructuringErrors) {7673var startPos = this.start, startLoc = this.startLoc;7674var expr = this.parseMaybeUnary(refDestructuringErrors, false);7675if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }7676return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn)7677};76787679// Parse binary operators with the operator precedence parsing7680// algorithm. `left` is the left-hand side of the operator.7681// `minPrec` provides context that allows the function to stop and7682// defer further parser to one of its callers when it encounters an7683// operator that has a lower precedence than the set it is parsing.76847685pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) {7686var prec = this.type.binop;7687if (prec != null && (!noIn || this.type !== types._in)) {7688if (prec > minPrec) {7689var logical = this.type === types.logicalOR || this.type === types.logicalAND;7690var coalesce = this.type === types.coalesce;7691if (coalesce) {7692// Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.7693// In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.7694prec = types.logicalAND.binop;7695}7696var op = this.value;7697this.next();7698var startPos = this.start, startLoc = this.startLoc;7699var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn);7700var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);7701if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) {7702this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");7703}7704return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn)7705}7706}7707return left7708};77097710pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {7711var node = this.startNodeAt(startPos, startLoc);7712node.left = left;7713node.operator = op;7714node.right = right;7715return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")7716};77177718// Parse unary operators, both prefix and postfix.77197720pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) {7721var startPos = this.start, startLoc = this.startLoc, expr;7722if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) {7723expr = this.parseAwait();7724sawUnary = true;7725} else if (this.type.prefix) {7726var node = this.startNode(), update = this.type === types.incDec;7727node.operator = this.value;7728node.prefix = true;7729this.next();7730node.argument = this.parseMaybeUnary(null, true);7731this.checkExpressionErrors(refDestructuringErrors, true);7732if (update) { this.checkLVal(node.argument); }7733else if (this.strict && node.operator === "delete" &&7734node.argument.type === "Identifier")7735{ this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }7736else { sawUnary = true; }7737expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");7738} else {7739expr = this.parseExprSubscripts(refDestructuringErrors);7740if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }7741while (this.type.postfix && !this.canInsertSemicolon()) {7742var node$1 = this.startNodeAt(startPos, startLoc);7743node$1.operator = this.value;7744node$1.prefix = false;7745node$1.argument = expr;7746this.checkLVal(expr);7747this.next();7748expr = this.finishNode(node$1, "UpdateExpression");7749}7750}77517752if (!sawUnary && this.eat(types.starstar))7753{ return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) }7754else7755{ return expr }7756};77577758// Parse call, dot, and `[]`-subscript expressions.77597760pp$3.parseExprSubscripts = function(refDestructuringErrors) {7761var startPos = this.start, startLoc = this.startLoc;7762var expr = this.parseExprAtom(refDestructuringErrors);7763if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")7764{ return expr }7765var result = this.parseSubscripts(expr, startPos, startLoc);7766if (refDestructuringErrors && result.type === "MemberExpression") {7767if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }7768if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }7769}7770return result7771};77727773pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {7774var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&7775this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&7776this.potentialArrowAt === base.start;7777var optionalChained = false;77787779while (true) {7780var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained);77817782if (element.optional) { optionalChained = true; }7783if (element === base || element.type === "ArrowFunctionExpression") {7784if (optionalChained) {7785var chainNode = this.startNodeAt(startPos, startLoc);7786chainNode.expression = element;7787element = this.finishNode(chainNode, "ChainExpression");7788}7789return element7790}77917792base = element;7793}7794};77957796pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) {7797var optionalSupported = this.options.ecmaVersion >= 11;7798var optional = optionalSupported && this.eat(types.questionDot);7799if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }78007801var computed = this.eat(types.bracketL);7802if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) {7803var node = this.startNodeAt(startPos, startLoc);7804node.object = base;7805node.property = computed ? this.parseExpression() : this.parseIdent(this.options.allowReserved !== "never");7806node.computed = !!computed;7807if (computed) { this.expect(types.bracketR); }7808if (optionalSupported) {7809node.optional = optional;7810}7811base = this.finishNode(node, "MemberExpression");7812} else if (!noCalls && this.eat(types.parenL)) {7813var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;7814this.yieldPos = 0;7815this.awaitPos = 0;7816this.awaitIdentPos = 0;7817var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);7818if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) {7819this.checkPatternErrors(refDestructuringErrors, false);7820this.checkYieldAwaitInDefaultParams();7821if (this.awaitIdentPos > 0)7822{ this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }7823this.yieldPos = oldYieldPos;7824this.awaitPos = oldAwaitPos;7825this.awaitIdentPos = oldAwaitIdentPos;7826return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true)7827}7828this.checkExpressionErrors(refDestructuringErrors, true);7829this.yieldPos = oldYieldPos || this.yieldPos;7830this.awaitPos = oldAwaitPos || this.awaitPos;7831this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;7832var node$1 = this.startNodeAt(startPos, startLoc);7833node$1.callee = base;7834node$1.arguments = exprList;7835if (optionalSupported) {7836node$1.optional = optional;7837}7838base = this.finishNode(node$1, "CallExpression");7839} else if (this.type === types.backQuote) {7840if (optional || optionalChained) {7841this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");7842}7843var node$2 = this.startNodeAt(startPos, startLoc);7844node$2.tag = base;7845node$2.quasi = this.parseTemplate({isTagged: true});7846base = this.finishNode(node$2, "TaggedTemplateExpression");7847}7848return base7849};78507851// Parse an atomic expression — either a single token that is an7852// expression, an expression started by a keyword like `function` or7853// `new`, or an expression wrapped in punctuation like `()`, `[]`,7854// or `{}`.78557856pp$3.parseExprAtom = function(refDestructuringErrors) {7857// If a division operator appears in an expression position, the7858// tokenizer got confused, and we force it to read a regexp instead.7859if (this.type === types.slash) { this.readRegexp(); }78607861var node, canBeArrow = this.potentialArrowAt === this.start;7862switch (this.type) {7863case types._super:7864if (!this.allowSuper)7865{ this.raise(this.start, "'super' keyword outside a method"); }7866node = this.startNode();7867this.next();7868if (this.type === types.parenL && !this.allowDirectSuper)7869{ this.raise(node.start, "super() call outside constructor of a subclass"); }7870// The `super` keyword can appear at below:7871// SuperProperty:7872// super [ Expression ]7873// super . IdentifierName7874// SuperCall:7875// super ( Arguments )7876if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL)7877{ this.unexpected(); }7878return this.finishNode(node, "Super")78797880case types._this:7881node = this.startNode();7882this.next();7883return this.finishNode(node, "ThisExpression")78847885case types.name:7886var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;7887var id = this.parseIdent(false);7888if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function))7889{ return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) }7890if (canBeArrow && !this.canInsertSemicolon()) {7891if (this.eat(types.arrow))7892{ return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) }7893if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc) {7894id = this.parseIdent(false);7895if (this.canInsertSemicolon() || !this.eat(types.arrow))7896{ this.unexpected(); }7897return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)7898}7899}7900return id79017902case types.regexp:7903var value = this.value;7904node = this.parseLiteral(value.value);7905node.regex = {pattern: value.pattern, flags: value.flags};7906return node79077908case types.num: case types.string:7909return this.parseLiteral(this.value)79107911case types._null: case types._true: case types._false:7912node = this.startNode();7913node.value = this.type === types._null ? null : this.type === types._true;7914node.raw = this.type.keyword;7915this.next();7916return this.finishNode(node, "Literal")79177918case types.parenL:7919var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);7920if (refDestructuringErrors) {7921if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))7922{ refDestructuringErrors.parenthesizedAssign = start; }7923if (refDestructuringErrors.parenthesizedBind < 0)7924{ refDestructuringErrors.parenthesizedBind = start; }7925}7926return expr79277928case types.bracketL:7929node = this.startNode();7930this.next();7931node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors);7932return this.finishNode(node, "ArrayExpression")79337934case types.braceL:7935return this.parseObj(false, refDestructuringErrors)79367937case types._function:7938node = this.startNode();7939this.next();7940return this.parseFunction(node, 0)79417942case types._class:7943return this.parseClass(this.startNode(), false)79447945case types._new:7946return this.parseNew()79477948case types.backQuote:7949return this.parseTemplate()79507951case types._import:7952if (this.options.ecmaVersion >= 11) {7953return this.parseExprImport()7954} else {7955return this.unexpected()7956}79577958default:7959this.unexpected();7960}7961};79627963pp$3.parseExprImport = function() {7964var node = this.startNode();79657966// Consume `import` as an identifier for `import.meta`.7967// Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.7968if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }7969var meta = this.parseIdent(true);79707971switch (this.type) {7972case types.parenL:7973return this.parseDynamicImport(node)7974case types.dot:7975node.meta = meta;7976return this.parseImportMeta(node)7977default:7978this.unexpected();7979}7980};79817982pp$3.parseDynamicImport = function(node) {7983this.next(); // skip `(`79847985// Parse node.source.7986node.source = this.parseMaybeAssign();79877988// Verify ending.7989if (!this.eat(types.parenR)) {7990var errorPos = this.start;7991if (this.eat(types.comma) && this.eat(types.parenR)) {7992this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");7993} else {7994this.unexpected(errorPos);7995}7996}79977998return this.finishNode(node, "ImportExpression")7999};80008001pp$3.parseImportMeta = function(node) {8002this.next(); // skip `.`80038004var containsEsc = this.containsEsc;8005node.property = this.parseIdent(true);80068007if (node.property.name !== "meta")8008{ this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }8009if (containsEsc)8010{ this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }8011if (this.options.sourceType !== "module")8012{ this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }80138014return this.finishNode(node, "MetaProperty")8015};80168017pp$3.parseLiteral = function(value) {8018var node = this.startNode();8019node.value = value;8020node.raw = this.input.slice(this.start, this.end);8021if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }8022this.next();8023return this.finishNode(node, "Literal")8024};80258026pp$3.parseParenExpression = function() {8027this.expect(types.parenL);8028var val = this.parseExpression();8029this.expect(types.parenR);8030return val8031};80328033pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {8034var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;8035if (this.options.ecmaVersion >= 6) {8036this.next();80378038var innerStartPos = this.start, innerStartLoc = this.startLoc;8039var exprList = [], first = true, lastIsComma = false;8040var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;8041this.yieldPos = 0;8042this.awaitPos = 0;8043// Do not save awaitIdentPos to allow checking awaits nested in parameters8044while (this.type !== types.parenR) {8045first ? first = false : this.expect(types.comma);8046if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) {8047lastIsComma = true;8048break8049} else if (this.type === types.ellipsis) {8050spreadStart = this.start;8051exprList.push(this.parseParenItem(this.parseRestBinding()));8052if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }8053break8054} else {8055exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));8056}8057}8058var innerEndPos = this.start, innerEndLoc = this.startLoc;8059this.expect(types.parenR);80608061if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {8062this.checkPatternErrors(refDestructuringErrors, false);8063this.checkYieldAwaitInDefaultParams();8064this.yieldPos = oldYieldPos;8065this.awaitPos = oldAwaitPos;8066return this.parseParenArrowList(startPos, startLoc, exprList)8067}80688069if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }8070if (spreadStart) { this.unexpected(spreadStart); }8071this.checkExpressionErrors(refDestructuringErrors, true);8072this.yieldPos = oldYieldPos || this.yieldPos;8073this.awaitPos = oldAwaitPos || this.awaitPos;80748075if (exprList.length > 1) {8076val = this.startNodeAt(innerStartPos, innerStartLoc);8077val.expressions = exprList;8078this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);8079} else {8080val = exprList[0];8081}8082} else {8083val = this.parseParenExpression();8084}80858086if (this.options.preserveParens) {8087var par = this.startNodeAt(startPos, startLoc);8088par.expression = val;8089return this.finishNode(par, "ParenthesizedExpression")8090} else {8091return val8092}8093};80948095pp$3.parseParenItem = function(item) {8096return item8097};80988099pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {8100return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)8101};81028103// New's precedence is slightly tricky. It must allow its argument to8104// be a `[]` or dot subscript expression, but not a call — at least,8105// not without wrapping it in parentheses. Thus, it uses the noCalls8106// argument to parseSubscripts to prevent it from consuming the8107// argument list.81088109var empty$1 = [];81108111pp$3.parseNew = function() {8112if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }8113var node = this.startNode();8114var meta = this.parseIdent(true);8115if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) {8116node.meta = meta;8117var containsEsc = this.containsEsc;8118node.property = this.parseIdent(true);8119if (node.property.name !== "target")8120{ this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }8121if (containsEsc)8122{ this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }8123if (!this.inNonArrowFunction())8124{ this.raiseRecoverable(node.start, "'new.target' can only be used in functions"); }8125return this.finishNode(node, "MetaProperty")8126}8127var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import;8128node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);8129if (isImport && node.callee.type === "ImportExpression") {8130this.raise(startPos, "Cannot use new with import()");8131}8132if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); }8133else { node.arguments = empty$1; }8134return this.finishNode(node, "NewExpression")8135};81368137// Parse template expression.81388139pp$3.parseTemplateElement = function(ref) {8140var isTagged = ref.isTagged;81418142var elem = this.startNode();8143if (this.type === types.invalidTemplate) {8144if (!isTagged) {8145this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");8146}8147elem.value = {8148raw: this.value,8149cooked: null8150};8151} else {8152elem.value = {8153raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),8154cooked: this.value8155};8156}8157this.next();8158elem.tail = this.type === types.backQuote;8159return this.finishNode(elem, "TemplateElement")8160};81618162pp$3.parseTemplate = function(ref) {8163if ( ref === void 0 ) ref = {};8164var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;81658166var node = this.startNode();8167this.next();8168node.expressions = [];8169var curElt = this.parseTemplateElement({isTagged: isTagged});8170node.quasis = [curElt];8171while (!curElt.tail) {8172if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); }8173this.expect(types.dollarBraceL);8174node.expressions.push(this.parseExpression());8175this.expect(types.braceR);8176node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));8177}8178this.next();8179return this.finishNode(node, "TemplateLiteral")8180};81818182pp$3.isAsyncProp = function(prop) {8183return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&8184(this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) &&8185!lineBreak.test(this.input.slice(this.lastTokEnd, this.start))8186};81878188// Parse an object literal or binding pattern.81898190pp$3.parseObj = function(isPattern, refDestructuringErrors) {8191var node = this.startNode(), first = true, propHash = {};8192node.properties = [];8193this.next();8194while (!this.eat(types.braceR)) {8195if (!first) {8196this.expect(types.comma);8197if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break }8198} else { first = false; }81998200var prop = this.parseProperty(isPattern, refDestructuringErrors);8201if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }8202node.properties.push(prop);8203}8204return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")8205};82068207pp$3.parseProperty = function(isPattern, refDestructuringErrors) {8208var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;8209if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) {8210if (isPattern) {8211prop.argument = this.parseIdent(false);8212if (this.type === types.comma) {8213this.raise(this.start, "Comma is not permitted after the rest element");8214}8215return this.finishNode(prop, "RestElement")8216}8217// To disallow parenthesized identifier via `this.toAssignable()`.8218if (this.type === types.parenL && refDestructuringErrors) {8219if (refDestructuringErrors.parenthesizedAssign < 0) {8220refDestructuringErrors.parenthesizedAssign = this.start;8221}8222if (refDestructuringErrors.parenthesizedBind < 0) {8223refDestructuringErrors.parenthesizedBind = this.start;8224}8225}8226// Parse argument.8227prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);8228// To disallow trailing comma via `this.toAssignable()`.8229if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {8230refDestructuringErrors.trailingComma = this.start;8231}8232// Finish8233return this.finishNode(prop, "SpreadElement")8234}8235if (this.options.ecmaVersion >= 6) {8236prop.method = false;8237prop.shorthand = false;8238if (isPattern || refDestructuringErrors) {8239startPos = this.start;8240startLoc = this.startLoc;8241}8242if (!isPattern)8243{ isGenerator = this.eat(types.star); }8244}8245var containsEsc = this.containsEsc;8246this.parsePropertyName(prop);8247if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {8248isAsync = true;8249isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);8250this.parsePropertyName(prop, refDestructuringErrors);8251} else {8252isAsync = false;8253}8254this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);8255return this.finishNode(prop, "Property")8256};82578258pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {8259if ((isGenerator || isAsync) && this.type === types.colon)8260{ this.unexpected(); }82618262if (this.eat(types.colon)) {8263prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);8264prop.kind = "init";8265} else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) {8266if (isPattern) { this.unexpected(); }8267prop.kind = "init";8268prop.method = true;8269prop.value = this.parseMethod(isGenerator, isAsync);8270} else if (!isPattern && !containsEsc &&8271this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&8272(prop.key.name === "get" || prop.key.name === "set") &&8273(this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) {8274if (isGenerator || isAsync) { this.unexpected(); }8275prop.kind = prop.key.name;8276this.parsePropertyName(prop);8277prop.value = this.parseMethod(false);8278var paramCount = prop.kind === "get" ? 0 : 1;8279if (prop.value.params.length !== paramCount) {8280var start = prop.value.start;8281if (prop.kind === "get")8282{ this.raiseRecoverable(start, "getter should have no params"); }8283else8284{ this.raiseRecoverable(start, "setter should have exactly one param"); }8285} else {8286if (prop.kind === "set" && prop.value.params[0].type === "RestElement")8287{ this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }8288}8289} else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {8290if (isGenerator || isAsync) { this.unexpected(); }8291this.checkUnreserved(prop.key);8292if (prop.key.name === "await" && !this.awaitIdentPos)8293{ this.awaitIdentPos = startPos; }8294prop.kind = "init";8295if (isPattern) {8296prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);8297} else if (this.type === types.eq && refDestructuringErrors) {8298if (refDestructuringErrors.shorthandAssign < 0)8299{ refDestructuringErrors.shorthandAssign = this.start; }8300prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);8301} else {8302prop.value = prop.key;8303}8304prop.shorthand = true;8305} else { this.unexpected(); }8306};83078308pp$3.parsePropertyName = function(prop) {8309if (this.options.ecmaVersion >= 6) {8310if (this.eat(types.bracketL)) {8311prop.computed = true;8312prop.key = this.parseMaybeAssign();8313this.expect(types.bracketR);8314return prop.key8315} else {8316prop.computed = false;8317}8318}8319return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")8320};83218322// Initialize empty function node.83238324pp$3.initFunction = function(node) {8325node.id = null;8326if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }8327if (this.options.ecmaVersion >= 8) { node.async = false; }8328};83298330// Parse object or class method.83318332pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {8333var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;83348335this.initFunction(node);8336if (this.options.ecmaVersion >= 6)8337{ node.generator = isGenerator; }8338if (this.options.ecmaVersion >= 8)8339{ node.async = !!isAsync; }83408341this.yieldPos = 0;8342this.awaitPos = 0;8343this.awaitIdentPos = 0;8344this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));83458346this.expect(types.parenL);8347node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);8348this.checkYieldAwaitInDefaultParams();8349this.parseFunctionBody(node, false, true);83508351this.yieldPos = oldYieldPos;8352this.awaitPos = oldAwaitPos;8353this.awaitIdentPos = oldAwaitIdentPos;8354return this.finishNode(node, "FunctionExpression")8355};83568357// Parse arrow function expression with given parameters.83588359pp$3.parseArrowExpression = function(node, params, isAsync) {8360var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;83618362this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);8363this.initFunction(node);8364if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }83658366this.yieldPos = 0;8367this.awaitPos = 0;8368this.awaitIdentPos = 0;83698370node.params = this.toAssignableList(params, true);8371this.parseFunctionBody(node, true, false);83728373this.yieldPos = oldYieldPos;8374this.awaitPos = oldAwaitPos;8375this.awaitIdentPos = oldAwaitIdentPos;8376return this.finishNode(node, "ArrowFunctionExpression")8377};83788379// Parse function body and check parameters.83808381pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) {8382var isExpression = isArrowFunction && this.type !== types.braceL;8383var oldStrict = this.strict, useStrict = false;83848385if (isExpression) {8386node.body = this.parseMaybeAssign();8387node.expression = true;8388this.checkParams(node, false);8389} else {8390var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);8391if (!oldStrict || nonSimple) {8392useStrict = this.strictDirective(this.end);8393// If this is a strict mode function, verify that argument names8394// are not repeated, and it does not try to bind the words `eval`8395// or `arguments`.8396if (useStrict && nonSimple)8397{ this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }8398}8399// Start a new scope with regard to labels and the `inFunction`8400// flag (restore them to their old value afterwards).8401var oldLabels = this.labels;8402this.labels = [];8403if (useStrict) { this.strict = true; }84048405// Add the params to varDeclaredNames to ensure that an error is thrown8406// if a let/const declaration in the function clashes with one of the params.8407this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));8408// Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'8409if (this.strict && node.id) { this.checkLVal(node.id, BIND_OUTSIDE); }8410node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);8411node.expression = false;8412this.adaptDirectivePrologue(node.body.body);8413this.labels = oldLabels;8414}8415this.exitScope();8416};84178418pp$3.isSimpleParamList = function(params) {8419for (var i = 0, list = params; i < list.length; i += 1)8420{8421var param = list[i];84228423if (param.type !== "Identifier") { return false8424} }8425return true8426};84278428// Checks function params for various disallowed patterns such as using "eval"8429// or "arguments" and duplicate parameters.84308431pp$3.checkParams = function(node, allowDuplicates) {8432var nameHash = {};8433for (var i = 0, list = node.params; i < list.length; i += 1)8434{8435var param = list[i];84368437this.checkLVal(param, BIND_VAR, allowDuplicates ? null : nameHash);8438}8439};84408441// Parses a comma-separated list of expressions, and returns them as8442// an array. `close` is the token type that ends the list, and8443// `allowEmpty` can be turned on to allow subsequent commas with8444// nothing in between them to be parsed as `null` (which is needed8445// for array literals).84468447pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {8448var elts = [], first = true;8449while (!this.eat(close)) {8450if (!first) {8451this.expect(types.comma);8452if (allowTrailingComma && this.afterTrailingComma(close)) { break }8453} else { first = false; }84548455var elt = (void 0);8456if (allowEmpty && this.type === types.comma)8457{ elt = null; }8458else if (this.type === types.ellipsis) {8459elt = this.parseSpread(refDestructuringErrors);8460if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0)8461{ refDestructuringErrors.trailingComma = this.start; }8462} else {8463elt = this.parseMaybeAssign(false, refDestructuringErrors);8464}8465elts.push(elt);8466}8467return elts8468};84698470pp$3.checkUnreserved = function(ref) {8471var start = ref.start;8472var end = ref.end;8473var name = ref.name;84748475if (this.inGenerator && name === "yield")8476{ this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }8477if (this.inAsync && name === "await")8478{ this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }8479if (this.keywords.test(name))8480{ this.raise(start, ("Unexpected keyword '" + name + "'")); }8481if (this.options.ecmaVersion < 6 &&8482this.input.slice(start, end).indexOf("\\") !== -1) { return }8483var re = this.strict ? this.reservedWordsStrict : this.reservedWords;8484if (re.test(name)) {8485if (!this.inAsync && name === "await")8486{ this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }8487this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));8488}8489};84908491// Parse the next token as an identifier. If `liberal` is true (used8492// when parsing properties), it will also convert keywords into8493// identifiers.84948495pp$3.parseIdent = function(liberal, isBinding) {8496var node = this.startNode();8497if (this.type === types.name) {8498node.name = this.value;8499} else if (this.type.keyword) {8500node.name = this.type.keyword;85018502// To fix https://github.com/acornjs/acorn/issues/5758503// `class` and `function` keywords push new context into this.context.8504// But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.8505// If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword8506if ((node.name === "class" || node.name === "function") &&8507(this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {8508this.context.pop();8509}8510} else {8511this.unexpected();8512}8513this.next(!!liberal);8514this.finishNode(node, "Identifier");8515if (!liberal) {8516this.checkUnreserved(node);8517if (node.name === "await" && !this.awaitIdentPos)8518{ this.awaitIdentPos = node.start; }8519}8520return node8521};85228523// Parses yield expression inside generator.85248525pp$3.parseYield = function(noIn) {8526if (!this.yieldPos) { this.yieldPos = this.start; }85278528var node = this.startNode();8529this.next();8530if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) {8531node.delegate = false;8532node.argument = null;8533} else {8534node.delegate = this.eat(types.star);8535node.argument = this.parseMaybeAssign(noIn);8536}8537return this.finishNode(node, "YieldExpression")8538};85398540pp$3.parseAwait = function() {8541if (!this.awaitPos) { this.awaitPos = this.start; }85428543var node = this.startNode();8544this.next();8545node.argument = this.parseMaybeUnary(null, false);8546return this.finishNode(node, "AwaitExpression")8547};85488549var pp$4 = Parser.prototype;85508551// This function is used to raise exceptions on parse errors. It8552// takes an offset integer (into the current `input`) to indicate8553// the location of the error, attaches the position to the end8554// of the error message, and then raises a `SyntaxError` with that8555// message.85568557pp$4.raise = function(pos, message) {8558var loc = getLineInfo(this.input, pos);8559message += " (" + loc.line + ":" + loc.column + ")";8560var err = new SyntaxError(message);8561err.pos = pos; err.loc = loc; err.raisedAt = this.pos;8562throw err8563};85648565pp$4.raiseRecoverable = pp$4.raise;85668567pp$4.curPosition = function() {8568if (this.options.locations) {8569return new Position(this.curLine, this.pos - this.lineStart)8570}8571};85728573var pp$5 = Parser.prototype;85748575var Scope = function Scope(flags) {8576this.flags = flags;8577// A list of var-declared names in the current lexical scope8578this.var = [];8579// A list of lexically-declared names in the current lexical scope8580this.lexical = [];8581// A list of lexically-declared FunctionDeclaration names in the current lexical scope8582this.functions = [];8583};85848585// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.85868587pp$5.enterScope = function(flags) {8588this.scopeStack.push(new Scope(flags));8589};85908591pp$5.exitScope = function() {8592this.scopeStack.pop();8593};85948595// The spec says:8596// > At the top level of a function, or script, function declarations are8597// > treated like var declarations rather than like lexical declarations.8598pp$5.treatFunctionsAsVarInScope = function(scope) {8599return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)8600};86018602pp$5.declareName = function(name, bindingType, pos) {8603var redeclared = false;8604if (bindingType === BIND_LEXICAL) {8605var scope = this.currentScope();8606redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;8607scope.lexical.push(name);8608if (this.inModule && (scope.flags & SCOPE_TOP))8609{ delete this.undefinedExports[name]; }8610} else if (bindingType === BIND_SIMPLE_CATCH) {8611var scope$1 = this.currentScope();8612scope$1.lexical.push(name);8613} else if (bindingType === BIND_FUNCTION) {8614var scope$2 = this.currentScope();8615if (this.treatFunctionsAsVar)8616{ redeclared = scope$2.lexical.indexOf(name) > -1; }8617else8618{ redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }8619scope$2.functions.push(name);8620} else {8621for (var i = this.scopeStack.length - 1; i >= 0; --i) {8622var scope$3 = this.scopeStack[i];8623if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||8624!this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {8625redeclared = true;8626break8627}8628scope$3.var.push(name);8629if (this.inModule && (scope$3.flags & SCOPE_TOP))8630{ delete this.undefinedExports[name]; }8631if (scope$3.flags & SCOPE_VAR) { break }8632}8633}8634if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }8635};86368637pp$5.checkLocalExport = function(id) {8638// scope.functions must be empty as Module code is always strict.8639if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&8640this.scopeStack[0].var.indexOf(id.name) === -1) {8641this.undefinedExports[id.name] = id;8642}8643};86448645pp$5.currentScope = function() {8646return this.scopeStack[this.scopeStack.length - 1]8647};86488649pp$5.currentVarScope = function() {8650for (var i = this.scopeStack.length - 1;; i--) {8651var scope = this.scopeStack[i];8652if (scope.flags & SCOPE_VAR) { return scope }8653}8654};86558656// Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.8657pp$5.currentThisScope = function() {8658for (var i = this.scopeStack.length - 1;; i--) {8659var scope = this.scopeStack[i];8660if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }8661}8662};86638664var Node = function Node(parser, pos, loc) {8665this.type = "";8666this.start = pos;8667this.end = 0;8668if (parser.options.locations)8669{ this.loc = new SourceLocation(parser, loc); }8670if (parser.options.directSourceFile)8671{ this.sourceFile = parser.options.directSourceFile; }8672if (parser.options.ranges)8673{ this.range = [pos, 0]; }8674};86758676// Start an AST node, attaching a start offset.86778678var pp$6 = Parser.prototype;86798680pp$6.startNode = function() {8681return new Node(this, this.start, this.startLoc)8682};86838684pp$6.startNodeAt = function(pos, loc) {8685return new Node(this, pos, loc)8686};86878688// Finish an AST node, adding `type` and `end` properties.86898690function finishNodeAt(node, type, pos, loc) {8691node.type = type;8692node.end = pos;8693if (this.options.locations)8694{ node.loc.end = loc; }8695if (this.options.ranges)8696{ node.range[1] = pos; }8697return node8698}86998700pp$6.finishNode = function(node, type) {8701return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)8702};87038704// Finish node at given position87058706pp$6.finishNodeAt = function(node, type, pos, loc) {8707return finishNodeAt.call(this, node, type, pos, loc)8708};87098710// The algorithm used to determine whether a regexp can appear at a87118712var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {8713this.token = token;8714this.isExpr = !!isExpr;8715this.preserveSpace = !!preserveSpace;8716this.override = override;8717this.generator = !!generator;8718};87198720var types$1 = {8721b_stat: new TokContext("{", false),8722b_expr: new TokContext("{", true),8723b_tmpl: new TokContext("${", false),8724p_stat: new TokContext("(", false),8725p_expr: new TokContext("(", true),8726q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),8727f_stat: new TokContext("function", false),8728f_expr: new TokContext("function", true),8729f_expr_gen: new TokContext("function", true, false, null, true),8730f_gen: new TokContext("function", false, false, null, true)8731};87328733var pp$7 = Parser.prototype;87348735pp$7.initialContext = function() {8736return [types$1.b_stat]8737};87388739pp$7.braceIsBlock = function(prevType) {8740var parent = this.curContext();8741if (parent === types$1.f_expr || parent === types$1.f_stat)8742{ return true }8743if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr))8744{ return !parent.isExpr }87458746// The check for `tt.name && exprAllowed` detects whether we are8747// after a `yield` or `of` construct. See the `updateContext` for8748// `tt.name`.8749if (prevType === types._return || prevType === types.name && this.exprAllowed)8750{ return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }8751if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow)8752{ return true }8753if (prevType === types.braceL)8754{ return parent === types$1.b_stat }8755if (prevType === types._var || prevType === types._const || prevType === types.name)8756{ return false }8757return !this.exprAllowed8758};87598760pp$7.inGeneratorContext = function() {8761for (var i = this.context.length - 1; i >= 1; i--) {8762var context = this.context[i];8763if (context.token === "function")8764{ return context.generator }8765}8766return false8767};87688769pp$7.updateContext = function(prevType) {8770var update, type = this.type;8771if (type.keyword && prevType === types.dot)8772{ this.exprAllowed = false; }8773else if (update = type.updateContext)8774{ update.call(this, prevType); }8775else8776{ this.exprAllowed = type.beforeExpr; }8777};87788779// Token-specific context update code87808781types.parenR.updateContext = types.braceR.updateContext = function() {8782if (this.context.length === 1) {8783this.exprAllowed = true;8784return8785}8786var out = this.context.pop();8787if (out === types$1.b_stat && this.curContext().token === "function") {8788out = this.context.pop();8789}8790this.exprAllowed = !out.isExpr;8791};87928793types.braceL.updateContext = function(prevType) {8794this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);8795this.exprAllowed = true;8796};87978798types.dollarBraceL.updateContext = function() {8799this.context.push(types$1.b_tmpl);8800this.exprAllowed = true;8801};88028803types.parenL.updateContext = function(prevType) {8804var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;8805this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);8806this.exprAllowed = true;8807};88088809types.incDec.updateContext = function() {8810// tokExprAllowed stays unchanged8811};88128813types._function.updateContext = types._class.updateContext = function(prevType) {8814if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else &&8815!(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&8816!((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat))8817{ this.context.push(types$1.f_expr); }8818else8819{ this.context.push(types$1.f_stat); }8820this.exprAllowed = false;8821};88228823types.backQuote.updateContext = function() {8824if (this.curContext() === types$1.q_tmpl)8825{ this.context.pop(); }8826else8827{ this.context.push(types$1.q_tmpl); }8828this.exprAllowed = false;8829};88308831types.star.updateContext = function(prevType) {8832if (prevType === types._function) {8833var index = this.context.length - 1;8834if (this.context[index] === types$1.f_expr)8835{ this.context[index] = types$1.f_expr_gen; }8836else8837{ this.context[index] = types$1.f_gen; }8838}8839this.exprAllowed = true;8840};88418842types.name.updateContext = function(prevType) {8843var allowed = false;8844if (this.options.ecmaVersion >= 6 && prevType !== types.dot) {8845if (this.value === "of" && !this.exprAllowed ||8846this.value === "yield" && this.inGeneratorContext())8847{ allowed = true; }8848}8849this.exprAllowed = allowed;8850};88518852// This file contains Unicode properties extracted from the ECMAScript8853// specification. The lists are extracted like so:8854// $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)88558856// #table-binary-unicode-properties8857var 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";8858var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";8859var ecma11BinaryProperties = ecma10BinaryProperties;8860var unicodeBinaryProperties = {88619: ecma9BinaryProperties,886210: ecma10BinaryProperties,886311: ecma11BinaryProperties8864};88658866// #table-unicode-general-category-values8867var 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";88688869// #table-unicode-script-values8870var ecma9ScriptValues = "Adlam Adlm Ahom 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 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";8871var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";8872var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";8873var unicodeScriptValues = {88749: ecma9ScriptValues,887510: ecma10ScriptValues,887611: ecma11ScriptValues8877};88788879var data = {};8880function buildUnicodeData(ecmaVersion) {8881var d = data[ecmaVersion] = {8882binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),8883nonBinary: {8884General_Category: wordsRegexp(unicodeGeneralCategoryValues),8885Script: wordsRegexp(unicodeScriptValues[ecmaVersion])8886}8887};8888d.nonBinary.Script_Extensions = d.nonBinary.Script;88898890d.nonBinary.gc = d.nonBinary.General_Category;8891d.nonBinary.sc = d.nonBinary.Script;8892d.nonBinary.scx = d.nonBinary.Script_Extensions;8893}8894buildUnicodeData(9);8895buildUnicodeData(10);8896buildUnicodeData(11);88978898var pp$8 = Parser.prototype;88998900var RegExpValidationState = function RegExpValidationState(parser) {8901this.parser = parser;8902this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "");8903this.unicodeProperties = data[parser.options.ecmaVersion >= 11 ? 11 : parser.options.ecmaVersion];8904this.source = "";8905this.flags = "";8906this.start = 0;8907this.switchU = false;8908this.switchN = false;8909this.pos = 0;8910this.lastIntValue = 0;8911this.lastStringValue = "";8912this.lastAssertionIsQuantifiable = false;8913this.numCapturingParens = 0;8914this.maxBackReference = 0;8915this.groupNames = [];8916this.backReferenceNames = [];8917};89188919RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {8920var unicode = flags.indexOf("u") !== -1;8921this.start = start | 0;8922this.source = pattern + "";8923this.flags = flags;8924this.switchU = unicode && this.parser.options.ecmaVersion >= 6;8925this.switchN = unicode && this.parser.options.ecmaVersion >= 9;8926};89278928RegExpValidationState.prototype.raise = function raise (message) {8929this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));8930};89318932// If u flag is given, this returns the code point at the index (it combines a surrogate pair).8933// Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).8934RegExpValidationState.prototype.at = function at (i, forceU) {8935if ( forceU === void 0 ) forceU = false;89368937var s = this.source;8938var l = s.length;8939if (i >= l) {8940return -18941}8942var c = s.charCodeAt(i);8943if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {8944return c8945}8946var next = s.charCodeAt(i + 1);8947return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c8948};89498950RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {8951if ( forceU === void 0 ) forceU = false;89528953var s = this.source;8954var l = s.length;8955if (i >= l) {8956return l8957}8958var c = s.charCodeAt(i), next;8959if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||8960(next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {8961return i + 18962}8963return i + 28964};89658966RegExpValidationState.prototype.current = function current (forceU) {8967if ( forceU === void 0 ) forceU = false;89688969return this.at(this.pos, forceU)8970};89718972RegExpValidationState.prototype.lookahead = function lookahead (forceU) {8973if ( forceU === void 0 ) forceU = false;89748975return this.at(this.nextIndex(this.pos, forceU), forceU)8976};89778978RegExpValidationState.prototype.advance = function advance (forceU) {8979if ( forceU === void 0 ) forceU = false;89808981this.pos = this.nextIndex(this.pos, forceU);8982};89838984RegExpValidationState.prototype.eat = function eat (ch, forceU) {8985if ( forceU === void 0 ) forceU = false;89868987if (this.current(forceU) === ch) {8988this.advance(forceU);8989return true8990}8991return false8992};89938994function codePointToString(ch) {8995if (ch <= 0xFFFF) { return String.fromCharCode(ch) }8996ch -= 0x10000;8997return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00)8998}89999000/**9001* Validate the flags part of a given RegExpLiteral.9002*9003* @param {RegExpValidationState} state The state to validate RegExp.9004* @returns {void}9005*/9006pp$8.validateRegExpFlags = function(state) {9007var validFlags = state.validFlags;9008var flags = state.flags;90099010for (var i = 0; i < flags.length; i++) {9011var flag = flags.charAt(i);9012if (validFlags.indexOf(flag) === -1) {9013this.raise(state.start, "Invalid regular expression flag");9014}9015if (flags.indexOf(flag, i + 1) > -1) {9016this.raise(state.start, "Duplicate regular expression flag");9017}9018}9019};90209021/**9022* Validate the pattern part of a given RegExpLiteral.9023*9024* @param {RegExpValidationState} state The state to validate RegExp.9025* @returns {void}9026*/9027pp$8.validateRegExpPattern = function(state) {9028this.regexp_pattern(state);90299030// The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of9031// parsing contains a |GroupName|, reparse with the goal symbol9032// |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*9033// exception if _P_ did not conform to the grammar, if any elements of _P_9034// were not matched by the parse, or if any Early Error conditions exist.9035if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {9036state.switchN = true;9037this.regexp_pattern(state);9038}9039};90409041// https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern9042pp$8.regexp_pattern = function(state) {9043state.pos = 0;9044state.lastIntValue = 0;9045state.lastStringValue = "";9046state.lastAssertionIsQuantifiable = false;9047state.numCapturingParens = 0;9048state.maxBackReference = 0;9049state.groupNames.length = 0;9050state.backReferenceNames.length = 0;90519052this.regexp_disjunction(state);90539054if (state.pos !== state.source.length) {9055// Make the same messages as V8.9056if (state.eat(0x29 /* ) */)) {9057state.raise("Unmatched ')'");9058}9059if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {9060state.raise("Lone quantifier brackets");9061}9062}9063if (state.maxBackReference > state.numCapturingParens) {9064state.raise("Invalid escape");9065}9066for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {9067var name = list[i];90689069if (state.groupNames.indexOf(name) === -1) {9070state.raise("Invalid named capture referenced");9071}9072}9073};90749075// https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction9076pp$8.regexp_disjunction = function(state) {9077this.regexp_alternative(state);9078while (state.eat(0x7C /* | */)) {9079this.regexp_alternative(state);9080}90819082// Make the same message as V8.9083if (this.regexp_eatQuantifier(state, true)) {9084state.raise("Nothing to repeat");9085}9086if (state.eat(0x7B /* { */)) {9087state.raise("Lone quantifier brackets");9088}9089};90909091// https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative9092pp$8.regexp_alternative = function(state) {9093while (state.pos < state.source.length && this.regexp_eatTerm(state))9094{ }9095};90969097// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term9098pp$8.regexp_eatTerm = function(state) {9099if (this.regexp_eatAssertion(state)) {9100// Handle `QuantifiableAssertion Quantifier` alternative.9101// `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion9102// is a QuantifiableAssertion.9103if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {9104// Make the same message as V8.9105if (state.switchU) {9106state.raise("Invalid quantifier");9107}9108}9109return true9110}91119112if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {9113this.regexp_eatQuantifier(state);9114return true9115}91169117return false9118};91199120// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion9121pp$8.regexp_eatAssertion = function(state) {9122var start = state.pos;9123state.lastAssertionIsQuantifiable = false;91249125// ^, $9126if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {9127return true9128}91299130// \b \B9131if (state.eat(0x5C /* \ */)) {9132if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {9133return true9134}9135state.pos = start;9136}91379138// Lookahead / Lookbehind9139if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {9140var lookbehind = false;9141if (this.options.ecmaVersion >= 9) {9142lookbehind = state.eat(0x3C /* < */);9143}9144if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {9145this.regexp_disjunction(state);9146if (!state.eat(0x29 /* ) */)) {9147state.raise("Unterminated group");9148}9149state.lastAssertionIsQuantifiable = !lookbehind;9150return true9151}9152}91539154state.pos = start;9155return false9156};91579158// https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier9159pp$8.regexp_eatQuantifier = function(state, noError) {9160if ( noError === void 0 ) noError = false;91619162if (this.regexp_eatQuantifierPrefix(state, noError)) {9163state.eat(0x3F /* ? */);9164return true9165}9166return false9167};91689169// https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix9170pp$8.regexp_eatQuantifierPrefix = function(state, noError) {9171return (9172state.eat(0x2A /* * */) ||9173state.eat(0x2B /* + */) ||9174state.eat(0x3F /* ? */) ||9175this.regexp_eatBracedQuantifier(state, noError)9176)9177};9178pp$8.regexp_eatBracedQuantifier = function(state, noError) {9179var start = state.pos;9180if (state.eat(0x7B /* { */)) {9181var min = 0, max = -1;9182if (this.regexp_eatDecimalDigits(state)) {9183min = state.lastIntValue;9184if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {9185max = state.lastIntValue;9186}9187if (state.eat(0x7D /* } */)) {9188// SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term9189if (max !== -1 && max < min && !noError) {9190state.raise("numbers out of order in {} quantifier");9191}9192return true9193}9194}9195if (state.switchU && !noError) {9196state.raise("Incomplete quantifier");9197}9198state.pos = start;9199}9200return false9201};92029203// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom9204pp$8.regexp_eatAtom = function(state) {9205return (9206this.regexp_eatPatternCharacters(state) ||9207state.eat(0x2E /* . */) ||9208this.regexp_eatReverseSolidusAtomEscape(state) ||9209this.regexp_eatCharacterClass(state) ||9210this.regexp_eatUncapturingGroup(state) ||9211this.regexp_eatCapturingGroup(state)9212)9213};9214pp$8.regexp_eatReverseSolidusAtomEscape = function(state) {9215var start = state.pos;9216if (state.eat(0x5C /* \ */)) {9217if (this.regexp_eatAtomEscape(state)) {9218return true9219}9220state.pos = start;9221}9222return false9223};9224pp$8.regexp_eatUncapturingGroup = function(state) {9225var start = state.pos;9226if (state.eat(0x28 /* ( */)) {9227if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {9228this.regexp_disjunction(state);9229if (state.eat(0x29 /* ) */)) {9230return true9231}9232state.raise("Unterminated group");9233}9234state.pos = start;9235}9236return false9237};9238pp$8.regexp_eatCapturingGroup = function(state) {9239if (state.eat(0x28 /* ( */)) {9240if (this.options.ecmaVersion >= 9) {9241this.regexp_groupSpecifier(state);9242} else if (state.current() === 0x3F /* ? */) {9243state.raise("Invalid group");9244}9245this.regexp_disjunction(state);9246if (state.eat(0x29 /* ) */)) {9247state.numCapturingParens += 1;9248return true9249}9250state.raise("Unterminated group");9251}9252return false9253};92549255// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom9256pp$8.regexp_eatExtendedAtom = function(state) {9257return (9258state.eat(0x2E /* . */) ||9259this.regexp_eatReverseSolidusAtomEscape(state) ||9260this.regexp_eatCharacterClass(state) ||9261this.regexp_eatUncapturingGroup(state) ||9262this.regexp_eatCapturingGroup(state) ||9263this.regexp_eatInvalidBracedQuantifier(state) ||9264this.regexp_eatExtendedPatternCharacter(state)9265)9266};92679268// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier9269pp$8.regexp_eatInvalidBracedQuantifier = function(state) {9270if (this.regexp_eatBracedQuantifier(state, true)) {9271state.raise("Nothing to repeat");9272}9273return false9274};92759276// https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter9277pp$8.regexp_eatSyntaxCharacter = function(state) {9278var ch = state.current();9279if (isSyntaxCharacter(ch)) {9280state.lastIntValue = ch;9281state.advance();9282return true9283}9284return false9285};9286function isSyntaxCharacter(ch) {9287return (9288ch === 0x24 /* $ */ ||9289ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||9290ch === 0x2E /* . */ ||9291ch === 0x3F /* ? */ ||9292ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||9293ch >= 0x7B /* { */ && ch <= 0x7D /* } */9294)9295}92969297// https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter9298// But eat eager.9299pp$8.regexp_eatPatternCharacters = function(state) {9300var start = state.pos;9301var ch = 0;9302while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {9303state.advance();9304}9305return state.pos !== start9306};93079308// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter9309pp$8.regexp_eatExtendedPatternCharacter = function(state) {9310var ch = state.current();9311if (9312ch !== -1 &&9313ch !== 0x24 /* $ */ &&9314!(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&9315ch !== 0x2E /* . */ &&9316ch !== 0x3F /* ? */ &&9317ch !== 0x5B /* [ */ &&9318ch !== 0x5E /* ^ */ &&9319ch !== 0x7C /* | */9320) {9321state.advance();9322return true9323}9324return false9325};93269327// GroupSpecifier ::9328// [empty]9329// `?` GroupName9330pp$8.regexp_groupSpecifier = function(state) {9331if (state.eat(0x3F /* ? */)) {9332if (this.regexp_eatGroupName(state)) {9333if (state.groupNames.indexOf(state.lastStringValue) !== -1) {9334state.raise("Duplicate capture group name");9335}9336state.groupNames.push(state.lastStringValue);9337return9338}9339state.raise("Invalid group");9340}9341};93429343// GroupName ::9344// `<` RegExpIdentifierName `>`9345// Note: this updates `state.lastStringValue` property with the eaten name.9346pp$8.regexp_eatGroupName = function(state) {9347state.lastStringValue = "";9348if (state.eat(0x3C /* < */)) {9349if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {9350return true9351}9352state.raise("Invalid capture group name");9353}9354return false9355};93569357// RegExpIdentifierName ::9358// RegExpIdentifierStart9359// RegExpIdentifierName RegExpIdentifierPart9360// Note: this updates `state.lastStringValue` property with the eaten name.9361pp$8.regexp_eatRegExpIdentifierName = function(state) {9362state.lastStringValue = "";9363if (this.regexp_eatRegExpIdentifierStart(state)) {9364state.lastStringValue += codePointToString(state.lastIntValue);9365while (this.regexp_eatRegExpIdentifierPart(state)) {9366state.lastStringValue += codePointToString(state.lastIntValue);9367}9368return true9369}9370return false9371};93729373// RegExpIdentifierStart ::9374// UnicodeIDStart9375// `$`9376// `_`9377// `\` RegExpUnicodeEscapeSequence[+U]9378pp$8.regexp_eatRegExpIdentifierStart = function(state) {9379var start = state.pos;9380var forceU = this.options.ecmaVersion >= 11;9381var ch = state.current(forceU);9382state.advance(forceU);93839384if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {9385ch = state.lastIntValue;9386}9387if (isRegExpIdentifierStart(ch)) {9388state.lastIntValue = ch;9389return true9390}93919392state.pos = start;9393return false9394};9395function isRegExpIdentifierStart(ch) {9396return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */9397}93989399// RegExpIdentifierPart ::9400// UnicodeIDContinue9401// `$`9402// `_`9403// `\` RegExpUnicodeEscapeSequence[+U]9404// <ZWNJ>9405// <ZWJ>9406pp$8.regexp_eatRegExpIdentifierPart = function(state) {9407var start = state.pos;9408var forceU = this.options.ecmaVersion >= 11;9409var ch = state.current(forceU);9410state.advance(forceU);94119412if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {9413ch = state.lastIntValue;9414}9415if (isRegExpIdentifierPart(ch)) {9416state.lastIntValue = ch;9417return true9418}94199420state.pos = start;9421return false9422};9423function isRegExpIdentifierPart(ch) {9424return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */9425}94269427// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape9428pp$8.regexp_eatAtomEscape = function(state) {9429if (9430this.regexp_eatBackReference(state) ||9431this.regexp_eatCharacterClassEscape(state) ||9432this.regexp_eatCharacterEscape(state) ||9433(state.switchN && this.regexp_eatKGroupName(state))9434) {9435return true9436}9437if (state.switchU) {9438// Make the same message as V8.9439if (state.current() === 0x63 /* c */) {9440state.raise("Invalid unicode escape");9441}9442state.raise("Invalid escape");9443}9444return false9445};9446pp$8.regexp_eatBackReference = function(state) {9447var start = state.pos;9448if (this.regexp_eatDecimalEscape(state)) {9449var n = state.lastIntValue;9450if (state.switchU) {9451// For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape9452if (n > state.maxBackReference) {9453state.maxBackReference = n;9454}9455return true9456}9457if (n <= state.numCapturingParens) {9458return true9459}9460state.pos = start;9461}9462return false9463};9464pp$8.regexp_eatKGroupName = function(state) {9465if (state.eat(0x6B /* k */)) {9466if (this.regexp_eatGroupName(state)) {9467state.backReferenceNames.push(state.lastStringValue);9468return true9469}9470state.raise("Invalid named reference");9471}9472return false9473};94749475// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape9476pp$8.regexp_eatCharacterEscape = function(state) {9477return (9478this.regexp_eatControlEscape(state) ||9479this.regexp_eatCControlLetter(state) ||9480this.regexp_eatZero(state) ||9481this.regexp_eatHexEscapeSequence(state) ||9482this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||9483(!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||9484this.regexp_eatIdentityEscape(state)9485)9486};9487pp$8.regexp_eatCControlLetter = function(state) {9488var start = state.pos;9489if (state.eat(0x63 /* c */)) {9490if (this.regexp_eatControlLetter(state)) {9491return true9492}9493state.pos = start;9494}9495return false9496};9497pp$8.regexp_eatZero = function(state) {9498if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {9499state.lastIntValue = 0;9500state.advance();9501return true9502}9503return false9504};95059506// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape9507pp$8.regexp_eatControlEscape = function(state) {9508var ch = state.current();9509if (ch === 0x74 /* t */) {9510state.lastIntValue = 0x09; /* \t */9511state.advance();9512return true9513}9514if (ch === 0x6E /* n */) {9515state.lastIntValue = 0x0A; /* \n */9516state.advance();9517return true9518}9519if (ch === 0x76 /* v */) {9520state.lastIntValue = 0x0B; /* \v */9521state.advance();9522return true9523}9524if (ch === 0x66 /* f */) {9525state.lastIntValue = 0x0C; /* \f */9526state.advance();9527return true9528}9529if (ch === 0x72 /* r */) {9530state.lastIntValue = 0x0D; /* \r */9531state.advance();9532return true9533}9534return false9535};95369537// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter9538pp$8.regexp_eatControlLetter = function(state) {9539var ch = state.current();9540if (isControlLetter(ch)) {9541state.lastIntValue = ch % 0x20;9542state.advance();9543return true9544}9545return false9546};9547function isControlLetter(ch) {9548return (9549(ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||9550(ch >= 0x61 /* a */ && ch <= 0x7A /* z */)9551)9552}95539554// https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence9555pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {9556if ( forceU === void 0 ) forceU = false;95579558var start = state.pos;9559var switchU = forceU || state.switchU;95609561if (state.eat(0x75 /* u */)) {9562if (this.regexp_eatFixedHexDigits(state, 4)) {9563var lead = state.lastIntValue;9564if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {9565var leadSurrogateEnd = state.pos;9566if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {9567var trail = state.lastIntValue;9568if (trail >= 0xDC00 && trail <= 0xDFFF) {9569state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;9570return true9571}9572}9573state.pos = leadSurrogateEnd;9574state.lastIntValue = lead;9575}9576return true9577}9578if (9579switchU &&9580state.eat(0x7B /* { */) &&9581this.regexp_eatHexDigits(state) &&9582state.eat(0x7D /* } */) &&9583isValidUnicode(state.lastIntValue)9584) {9585return true9586}9587if (switchU) {9588state.raise("Invalid unicode escape");9589}9590state.pos = start;9591}95929593return false9594};9595function isValidUnicode(ch) {9596return ch >= 0 && ch <= 0x10FFFF9597}95989599// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape9600pp$8.regexp_eatIdentityEscape = function(state) {9601if (state.switchU) {9602if (this.regexp_eatSyntaxCharacter(state)) {9603return true9604}9605if (state.eat(0x2F /* / */)) {9606state.lastIntValue = 0x2F; /* / */9607return true9608}9609return false9610}96119612var ch = state.current();9613if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {9614state.lastIntValue = ch;9615state.advance();9616return true9617}96189619return false9620};96219622// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape9623pp$8.regexp_eatDecimalEscape = function(state) {9624state.lastIntValue = 0;9625var ch = state.current();9626if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {9627do {9628state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);9629state.advance();9630} while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)9631return true9632}9633return false9634};96359636// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape9637pp$8.regexp_eatCharacterClassEscape = function(state) {9638var ch = state.current();96399640if (isCharacterClassEscape(ch)) {9641state.lastIntValue = -1;9642state.advance();9643return true9644}96459646if (9647state.switchU &&9648this.options.ecmaVersion >= 9 &&9649(ch === 0x50 /* P */ || ch === 0x70 /* p */)9650) {9651state.lastIntValue = -1;9652state.advance();9653if (9654state.eat(0x7B /* { */) &&9655this.regexp_eatUnicodePropertyValueExpression(state) &&9656state.eat(0x7D /* } */)9657) {9658return true9659}9660state.raise("Invalid property name");9661}96629663return false9664};9665function isCharacterClassEscape(ch) {9666return (9667ch === 0x64 /* d */ ||9668ch === 0x44 /* D */ ||9669ch === 0x73 /* s */ ||9670ch === 0x53 /* S */ ||9671ch === 0x77 /* w */ ||9672ch === 0x57 /* W */9673)9674}96759676// UnicodePropertyValueExpression ::9677// UnicodePropertyName `=` UnicodePropertyValue9678// LoneUnicodePropertyNameOrValue9679pp$8.regexp_eatUnicodePropertyValueExpression = function(state) {9680var start = state.pos;96819682// UnicodePropertyName `=` UnicodePropertyValue9683if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {9684var name = state.lastStringValue;9685if (this.regexp_eatUnicodePropertyValue(state)) {9686var value = state.lastStringValue;9687this.regexp_validateUnicodePropertyNameAndValue(state, name, value);9688return true9689}9690}9691state.pos = start;96929693// LoneUnicodePropertyNameOrValue9694if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {9695var nameOrValue = state.lastStringValue;9696this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);9697return true9698}9699return false9700};9701pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {9702if (!has(state.unicodeProperties.nonBinary, name))9703{ state.raise("Invalid property name"); }9704if (!state.unicodeProperties.nonBinary[name].test(value))9705{ state.raise("Invalid property value"); }9706};9707pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {9708if (!state.unicodeProperties.binary.test(nameOrValue))9709{ state.raise("Invalid property name"); }9710};97119712// UnicodePropertyName ::9713// UnicodePropertyNameCharacters9714pp$8.regexp_eatUnicodePropertyName = function(state) {9715var ch = 0;9716state.lastStringValue = "";9717while (isUnicodePropertyNameCharacter(ch = state.current())) {9718state.lastStringValue += codePointToString(ch);9719state.advance();9720}9721return state.lastStringValue !== ""9722};9723function isUnicodePropertyNameCharacter(ch) {9724return isControlLetter(ch) || ch === 0x5F /* _ */9725}97269727// UnicodePropertyValue ::9728// UnicodePropertyValueCharacters9729pp$8.regexp_eatUnicodePropertyValue = function(state) {9730var ch = 0;9731state.lastStringValue = "";9732while (isUnicodePropertyValueCharacter(ch = state.current())) {9733state.lastStringValue += codePointToString(ch);9734state.advance();9735}9736return state.lastStringValue !== ""9737};9738function isUnicodePropertyValueCharacter(ch) {9739return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)9740}97419742// LoneUnicodePropertyNameOrValue ::9743// UnicodePropertyValueCharacters9744pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {9745return this.regexp_eatUnicodePropertyValue(state)9746};97479748// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass9749pp$8.regexp_eatCharacterClass = function(state) {9750if (state.eat(0x5B /* [ */)) {9751state.eat(0x5E /* ^ */);9752this.regexp_classRanges(state);9753if (state.eat(0x5D /* ] */)) {9754return true9755}9756// Unreachable since it threw "unterminated regular expression" error before.9757state.raise("Unterminated character class");9758}9759return false9760};97619762// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges9763// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges9764// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash9765pp$8.regexp_classRanges = function(state) {9766while (this.regexp_eatClassAtom(state)) {9767var left = state.lastIntValue;9768if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {9769var right = state.lastIntValue;9770if (state.switchU && (left === -1 || right === -1)) {9771state.raise("Invalid character class");9772}9773if (left !== -1 && right !== -1 && left > right) {9774state.raise("Range out of order in character class");9775}9776}9777}9778};97799780// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom9781// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash9782pp$8.regexp_eatClassAtom = function(state) {9783var start = state.pos;97849785if (state.eat(0x5C /* \ */)) {9786if (this.regexp_eatClassEscape(state)) {9787return true9788}9789if (state.switchU) {9790// Make the same message as V8.9791var ch$1 = state.current();9792if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {9793state.raise("Invalid class escape");9794}9795state.raise("Invalid escape");9796}9797state.pos = start;9798}97999800var ch = state.current();9801if (ch !== 0x5D /* ] */) {9802state.lastIntValue = ch;9803state.advance();9804return true9805}98069807return false9808};98099810// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape9811pp$8.regexp_eatClassEscape = function(state) {9812var start = state.pos;98139814if (state.eat(0x62 /* b */)) {9815state.lastIntValue = 0x08; /* <BS> */9816return true9817}98189819if (state.switchU && state.eat(0x2D /* - */)) {9820state.lastIntValue = 0x2D; /* - */9821return true9822}98239824if (!state.switchU && state.eat(0x63 /* c */)) {9825if (this.regexp_eatClassControlLetter(state)) {9826return true9827}9828state.pos = start;9829}98309831return (9832this.regexp_eatCharacterClassEscape(state) ||9833this.regexp_eatCharacterEscape(state)9834)9835};98369837// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter9838pp$8.regexp_eatClassControlLetter = function(state) {9839var ch = state.current();9840if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {9841state.lastIntValue = ch % 0x20;9842state.advance();9843return true9844}9845return false9846};98479848// https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence9849pp$8.regexp_eatHexEscapeSequence = function(state) {9850var start = state.pos;9851if (state.eat(0x78 /* x */)) {9852if (this.regexp_eatFixedHexDigits(state, 2)) {9853return true9854}9855if (state.switchU) {9856state.raise("Invalid escape");9857}9858state.pos = start;9859}9860return false9861};98629863// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits9864pp$8.regexp_eatDecimalDigits = function(state) {9865var start = state.pos;9866var ch = 0;9867state.lastIntValue = 0;9868while (isDecimalDigit(ch = state.current())) {9869state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);9870state.advance();9871}9872return state.pos !== start9873};9874function isDecimalDigit(ch) {9875return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */9876}98779878// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits9879pp$8.regexp_eatHexDigits = function(state) {9880var start = state.pos;9881var ch = 0;9882state.lastIntValue = 0;9883while (isHexDigit(ch = state.current())) {9884state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);9885state.advance();9886}9887return state.pos !== start9888};9889function isHexDigit(ch) {9890return (9891(ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||9892(ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||9893(ch >= 0x61 /* a */ && ch <= 0x66 /* f */)9894)9895}9896function hexToInt(ch) {9897if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {9898return 10 + (ch - 0x41 /* A */)9899}9900if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {9901return 10 + (ch - 0x61 /* a */)9902}9903return ch - 0x30 /* 0 */9904}99059906// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence9907// Allows only 0-377(octal) i.e. 0-255(decimal).9908pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) {9909if (this.regexp_eatOctalDigit(state)) {9910var n1 = state.lastIntValue;9911if (this.regexp_eatOctalDigit(state)) {9912var n2 = state.lastIntValue;9913if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {9914state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;9915} else {9916state.lastIntValue = n1 * 8 + n2;9917}9918} else {9919state.lastIntValue = n1;9920}9921return true9922}9923return false9924};99259926// https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit9927pp$8.regexp_eatOctalDigit = function(state) {9928var ch = state.current();9929if (isOctalDigit(ch)) {9930state.lastIntValue = ch - 0x30; /* 0 */9931state.advance();9932return true9933}9934state.lastIntValue = 0;9935return false9936};9937function isOctalDigit(ch) {9938return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */9939}99409941// https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits9942// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit9943// And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence9944pp$8.regexp_eatFixedHexDigits = function(state, length) {9945var start = state.pos;9946state.lastIntValue = 0;9947for (var i = 0; i < length; ++i) {9948var ch = state.current();9949if (!isHexDigit(ch)) {9950state.pos = start;9951return false9952}9953state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);9954state.advance();9955}9956return true9957};99589959// Object type used to represent tokens. Note that normally, tokens9960// simply exist as properties on the parser object. This is only9961// used for the onToken callback and the external tokenizer.99629963var Token = function Token(p) {9964this.type = p.type;9965this.value = p.value;9966this.start = p.start;9967this.end = p.end;9968if (p.options.locations)9969{ this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }9970if (p.options.ranges)9971{ this.range = [p.start, p.end]; }9972};99739974// ## Tokenizer99759976var pp$9 = Parser.prototype;99779978// Move to the next token99799980pp$9.next = function(ignoreEscapeSequenceInKeyword) {9981if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)9982{ this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }9983if (this.options.onToken)9984{ this.options.onToken(new Token(this)); }99859986this.lastTokEnd = this.end;9987this.lastTokStart = this.start;9988this.lastTokEndLoc = this.endLoc;9989this.lastTokStartLoc = this.startLoc;9990this.nextToken();9991};99929993pp$9.getToken = function() {9994this.next();9995return new Token(this)9996};99979998// If we're in an ES6 environment, make parsers iterable9999if (typeof Symbol !== "undefined")10000{ pp$9[Symbol.iterator] = function() {10001var this$1$1 = this;1000210003return {10004next: function () {10005var token = this$1$1.getToken();10006return {10007done: token.type === types.eof,10008value: token10009}10010}10011}10012}; }1001310014// Toggle strict mode. Re-reads the next number or string to please10015// pedantic tests (`"use strict"; 010;` should fail).1001610017pp$9.curContext = function() {10018return this.context[this.context.length - 1]10019};1002010021// Read a single token, updating the parser object's token-related10022// properties.1002310024pp$9.nextToken = function() {10025var curContext = this.curContext();10026if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }1002710028this.start = this.pos;10029if (this.options.locations) { this.startLoc = this.curPosition(); }10030if (this.pos >= this.input.length) { return this.finishToken(types.eof) }1003110032if (curContext.override) { return curContext.override(this) }10033else { this.readToken(this.fullCharCodeAtPos()); }10034};1003510036pp$9.readToken = function(code) {10037// Identifier or keyword. '\uXXXX' sequences are allowed in10038// identifiers, so '\' also dispatches to that.10039if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)10040{ return this.readWord() }1004110042return this.getTokenFromCode(code)10043};1004410045pp$9.fullCharCodeAtPos = function() {10046var code = this.input.charCodeAt(this.pos);10047if (code <= 0xd7ff || code >= 0xe000) { return code }10048var next = this.input.charCodeAt(this.pos + 1);10049return (code << 10) + next - 0x35fdc0010050};1005110052pp$9.skipBlockComment = function() {10053var startLoc = this.options.onComment && this.curPosition();10054var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);10055if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }10056this.pos = end + 2;10057if (this.options.locations) {10058lineBreakG.lastIndex = start;10059var match;10060while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {10061++this.curLine;10062this.lineStart = match.index + match[0].length;10063}10064}10065if (this.options.onComment)10066{ this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,10067startLoc, this.curPosition()); }10068};1006910070pp$9.skipLineComment = function(startSkip) {10071var start = this.pos;10072var startLoc = this.options.onComment && this.curPosition();10073var ch = this.input.charCodeAt(this.pos += startSkip);10074while (this.pos < this.input.length && !isNewLine(ch)) {10075ch = this.input.charCodeAt(++this.pos);10076}10077if (this.options.onComment)10078{ this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,10079startLoc, this.curPosition()); }10080};1008110082// Called at the start of the parse and after every token. Skips10083// whitespace and comments, and.1008410085pp$9.skipSpace = function() {10086loop: while (this.pos < this.input.length) {10087var ch = this.input.charCodeAt(this.pos);10088switch (ch) {10089case 32: case 160: // ' '10090++this.pos;10091break10092case 13:10093if (this.input.charCodeAt(this.pos + 1) === 10) {10094++this.pos;10095}10096case 10: case 8232: case 8233:10097++this.pos;10098if (this.options.locations) {10099++this.curLine;10100this.lineStart = this.pos;10101}10102break10103case 47: // '/'10104switch (this.input.charCodeAt(this.pos + 1)) {10105case 42: // '*'10106this.skipBlockComment();10107break10108case 47:10109this.skipLineComment(2);10110break10111default:10112break loop10113}10114break10115default:10116if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {10117++this.pos;10118} else {10119break loop10120}10121}10122}10123};1012410125// Called at the end of every token. Sets `end`, `val`, and10126// maintains `context` and `exprAllowed`, and skips the space after10127// the token, so that the next one's `start` will point at the10128// right position.1012910130pp$9.finishToken = function(type, val) {10131this.end = this.pos;10132if (this.options.locations) { this.endLoc = this.curPosition(); }10133var prevType = this.type;10134this.type = type;10135this.value = val;1013610137this.updateContext(prevType);10138};1013910140// ### Token reading1014110142// This is the function that is called to fetch the next token. It10143// is somewhat obscure, because it works in character codes rather10144// than characters, and because operator parsing has been inlined10145// into it.10146//10147// All in the name of speed.10148//10149pp$9.readToken_dot = function() {10150var next = this.input.charCodeAt(this.pos + 1);10151if (next >= 48 && next <= 57) { return this.readNumber(true) }10152var next2 = this.input.charCodeAt(this.pos + 2);10153if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'10154this.pos += 3;10155return this.finishToken(types.ellipsis)10156} else {10157++this.pos;10158return this.finishToken(types.dot)10159}10160};1016110162pp$9.readToken_slash = function() { // '/'10163var next = this.input.charCodeAt(this.pos + 1);10164if (this.exprAllowed) { ++this.pos; return this.readRegexp() }10165if (next === 61) { return this.finishOp(types.assign, 2) }10166return this.finishOp(types.slash, 1)10167};1016810169pp$9.readToken_mult_modulo_exp = function(code) { // '%*'10170var next = this.input.charCodeAt(this.pos + 1);10171var size = 1;10172var tokentype = code === 42 ? types.star : types.modulo;1017310174// exponentiation operator ** and **=10175if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {10176++size;10177tokentype = types.starstar;10178next = this.input.charCodeAt(this.pos + 2);10179}1018010181if (next === 61) { return this.finishOp(types.assign, size + 1) }10182return this.finishOp(tokentype, size)10183};1018410185pp$9.readToken_pipe_amp = function(code) { // '|&'10186var next = this.input.charCodeAt(this.pos + 1);10187if (next === code) {10188if (this.options.ecmaVersion >= 12) {10189var next2 = this.input.charCodeAt(this.pos + 2);10190if (next2 === 61) { return this.finishOp(types.assign, 3) }10191}10192return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2)10193}10194if (next === 61) { return this.finishOp(types.assign, 2) }10195return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1)10196};1019710198pp$9.readToken_caret = function() { // '^'10199var next = this.input.charCodeAt(this.pos + 1);10200if (next === 61) { return this.finishOp(types.assign, 2) }10201return this.finishOp(types.bitwiseXOR, 1)10202};1020310204pp$9.readToken_plus_min = function(code) { // '+-'10205var next = this.input.charCodeAt(this.pos + 1);10206if (next === code) {10207if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&10208(this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {10209// A `-->` line comment10210this.skipLineComment(3);10211this.skipSpace();10212return this.nextToken()10213}10214return this.finishOp(types.incDec, 2)10215}10216if (next === 61) { return this.finishOp(types.assign, 2) }10217return this.finishOp(types.plusMin, 1)10218};1021910220pp$9.readToken_lt_gt = function(code) { // '<>'10221var next = this.input.charCodeAt(this.pos + 1);10222var size = 1;10223if (next === code) {10224size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;10225if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) }10226return this.finishOp(types.bitShift, size)10227}10228if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&10229this.input.charCodeAt(this.pos + 3) === 45) {10230// `<!--`, an XML-style comment that should be interpreted as a line comment10231this.skipLineComment(4);10232this.skipSpace();10233return this.nextToken()10234}10235if (next === 61) { size = 2; }10236return this.finishOp(types.relational, size)10237};1023810239pp$9.readToken_eq_excl = function(code) { // '=!'10240var next = this.input.charCodeAt(this.pos + 1);10241if (next === 61) { return this.finishOp(types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }10242if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'10243this.pos += 2;10244return this.finishToken(types.arrow)10245}10246return this.finishOp(code === 61 ? types.eq : types.prefix, 1)10247};1024810249pp$9.readToken_question = function() { // '?'10250var ecmaVersion = this.options.ecmaVersion;10251if (ecmaVersion >= 11) {10252var next = this.input.charCodeAt(this.pos + 1);10253if (next === 46) {10254var next2 = this.input.charCodeAt(this.pos + 2);10255if (next2 < 48 || next2 > 57) { return this.finishOp(types.questionDot, 2) }10256}10257if (next === 63) {10258if (ecmaVersion >= 12) {10259var next2$1 = this.input.charCodeAt(this.pos + 2);10260if (next2$1 === 61) { return this.finishOp(types.assign, 3) }10261}10262return this.finishOp(types.coalesce, 2)10263}10264}10265return this.finishOp(types.question, 1)10266};1026710268pp$9.getTokenFromCode = function(code) {10269switch (code) {10270// The interpretation of a dot depends on whether it is followed10271// by a digit or another two dots.10272case 46: // '.'10273return this.readToken_dot()1027410275// Punctuation tokens.10276case 40: ++this.pos; return this.finishToken(types.parenL)10277case 41: ++this.pos; return this.finishToken(types.parenR)10278case 59: ++this.pos; return this.finishToken(types.semi)10279case 44: ++this.pos; return this.finishToken(types.comma)10280case 91: ++this.pos; return this.finishToken(types.bracketL)10281case 93: ++this.pos; return this.finishToken(types.bracketR)10282case 123: ++this.pos; return this.finishToken(types.braceL)10283case 125: ++this.pos; return this.finishToken(types.braceR)10284case 58: ++this.pos; return this.finishToken(types.colon)1028510286case 96: // '`'10287if (this.options.ecmaVersion < 6) { break }10288++this.pos;10289return this.finishToken(types.backQuote)1029010291case 48: // '0'10292var next = this.input.charCodeAt(this.pos + 1);10293if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number10294if (this.options.ecmaVersion >= 6) {10295if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number10296if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number10297}1029810299// Anything else beginning with a digit is an integer, octal10300// number, or float.10301case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-910302return this.readNumber(false)1030310304// Quotes produce strings.10305case 34: case 39: // '"', "'"10306return this.readString(code)1030710308// Operators are parsed inline in tiny state machines. '=' (61) is10309// often referred to. `finishOp` simply skips the amount of10310// characters it is given as second argument, and returns a token10311// of the type given by its first argument.1031210313case 47: // '/'10314return this.readToken_slash()1031510316case 37: case 42: // '%*'10317return this.readToken_mult_modulo_exp(code)1031810319case 124: case 38: // '|&'10320return this.readToken_pipe_amp(code)1032110322case 94: // '^'10323return this.readToken_caret()1032410325case 43: case 45: // '+-'10326return this.readToken_plus_min(code)1032710328case 60: case 62: // '<>'10329return this.readToken_lt_gt(code)1033010331case 61: case 33: // '=!'10332return this.readToken_eq_excl(code)1033310334case 63: // '?'10335return this.readToken_question()1033610337case 126: // '~'10338return this.finishOp(types.prefix, 1)10339}1034010341this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");10342};1034310344pp$9.finishOp = function(type, size) {10345var str = this.input.slice(this.pos, this.pos + size);10346this.pos += size;10347return this.finishToken(type, str)10348};1034910350pp$9.readRegexp = function() {10351var escaped, inClass, start = this.pos;10352for (;;) {10353if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }10354var ch = this.input.charAt(this.pos);10355if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }10356if (!escaped) {10357if (ch === "[") { inClass = true; }10358else if (ch === "]" && inClass) { inClass = false; }10359else if (ch === "/" && !inClass) { break }10360escaped = ch === "\\";10361} else { escaped = false; }10362++this.pos;10363}10364var pattern = this.input.slice(start, this.pos);10365++this.pos;10366var flagsStart = this.pos;10367var flags = this.readWord1();10368if (this.containsEsc) { this.unexpected(flagsStart); }1036910370// Validate pattern10371var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));10372state.reset(start, pattern, flags);10373this.validateRegExpFlags(state);10374this.validateRegExpPattern(state);1037510376// Create Literal#value property value.10377var value = null;10378try {10379value = new RegExp(pattern, flags);10380} catch (e) {10381// ESTree requires null if it failed to instantiate RegExp object.10382// https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral10383}1038410385return this.finishToken(types.regexp, {pattern: pattern, flags: flags, value: value})10386};1038710388// Read an integer in the given radix. Return null if zero digits10389// were read, the integer value otherwise. When `len` is given, this10390// will return `null` unless the integer has exactly `len` digits.1039110392pp$9.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {10393// `len` is used for character escape sequences. In that case, disallow separators.10394var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;1039510396// `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)10397// and isn't fraction part nor exponent part. In that case, if the first digit10398// is zero then disallow separators.10399var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;1040010401var start = this.pos, total = 0, lastCode = 0;10402for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {10403var code = this.input.charCodeAt(this.pos), val = (void 0);1040410405if (allowSeparators && code === 95) {10406if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }10407if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }10408if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }10409lastCode = code;10410continue10411}1041210413if (code >= 97) { val = code - 97 + 10; } // a10414else if (code >= 65) { val = code - 65 + 10; } // A10415else if (code >= 48 && code <= 57) { val = code - 48; } // 0-910416else { val = Infinity; }10417if (val >= radix) { break }10418lastCode = code;10419total = total * radix + val;10420}1042110422if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }10423if (this.pos === start || len != null && this.pos - start !== len) { return null }1042410425return total10426};1042710428function stringToNumber(str, isLegacyOctalNumericLiteral) {10429if (isLegacyOctalNumericLiteral) {10430return parseInt(str, 8)10431}1043210433// `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.10434return parseFloat(str.replace(/_/g, ""))10435}1043610437function stringToBigInt(str) {10438if (typeof BigInt !== "function") {10439return null10440}1044110442// `BigInt(value)` throws syntax error if the string contains numeric separators.10443return BigInt(str.replace(/_/g, ""))10444}1044510446pp$9.readRadixNumber = function(radix) {10447var start = this.pos;10448this.pos += 2; // 0x10449var val = this.readInt(radix);10450if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }10451if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {10452val = stringToBigInt(this.input.slice(start, this.pos));10453++this.pos;10454} else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }10455return this.finishToken(types.num, val)10456};1045710458// Read an integer, octal integer, or floating-point number.1045910460pp$9.readNumber = function(startsWithDot) {10461var start = this.pos;10462if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }10463var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;10464if (octal && this.strict) { this.raise(start, "Invalid number"); }10465var next = this.input.charCodeAt(this.pos);10466if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {10467var val$1 = stringToBigInt(this.input.slice(start, this.pos));10468++this.pos;10469if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }10470return this.finishToken(types.num, val$1)10471}10472if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }10473if (next === 46 && !octal) { // '.'10474++this.pos;10475this.readInt(10);10476next = this.input.charCodeAt(this.pos);10477}10478if ((next === 69 || next === 101) && !octal) { // 'eE'10479next = this.input.charCodeAt(++this.pos);10480if (next === 43 || next === 45) { ++this.pos; } // '+-'10481if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }10482}10483if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }1048410485var val = stringToNumber(this.input.slice(start, this.pos), octal);10486return this.finishToken(types.num, val)10487};1048810489// Read a string value, interpreting backslash-escapes.1049010491pp$9.readCodePoint = function() {10492var ch = this.input.charCodeAt(this.pos), code;1049310494if (ch === 123) { // '{'10495if (this.options.ecmaVersion < 6) { this.unexpected(); }10496var codePos = ++this.pos;10497code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);10498++this.pos;10499if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }10500} else {10501code = this.readHexChar(4);10502}10503return code10504};1050510506function codePointToString$1(code) {10507// UTF-16 Decoding10508if (code <= 0xFFFF) { return String.fromCharCode(code) }10509code -= 0x10000;10510return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)10511}1051210513pp$9.readString = function(quote) {10514var out = "", chunkStart = ++this.pos;10515for (;;) {10516if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }10517var ch = this.input.charCodeAt(this.pos);10518if (ch === quote) { break }10519if (ch === 92) { // '\'10520out += this.input.slice(chunkStart, this.pos);10521out += this.readEscapedChar(false);10522chunkStart = this.pos;10523} else {10524if (isNewLine(ch, this.options.ecmaVersion >= 10)) { this.raise(this.start, "Unterminated string constant"); }10525++this.pos;10526}10527}10528out += this.input.slice(chunkStart, this.pos++);10529return this.finishToken(types.string, out)10530};1053110532// Reads template string tokens.1053310534var INVALID_TEMPLATE_ESCAPE_ERROR = {};1053510536pp$9.tryReadTemplateToken = function() {10537this.inTemplateElement = true;10538try {10539this.readTmplToken();10540} catch (err) {10541if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {10542this.readInvalidTemplateToken();10543} else {10544throw err10545}10546}1054710548this.inTemplateElement = false;10549};1055010551pp$9.invalidStringToken = function(position, message) {10552if (this.inTemplateElement && this.options.ecmaVersion >= 9) {10553throw INVALID_TEMPLATE_ESCAPE_ERROR10554} else {10555this.raise(position, message);10556}10557};1055810559pp$9.readTmplToken = function() {10560var out = "", chunkStart = this.pos;10561for (;;) {10562if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }10563var ch = this.input.charCodeAt(this.pos);10564if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'10565if (this.pos === this.start && (this.type === types.template || this.type === types.invalidTemplate)) {10566if (ch === 36) {10567this.pos += 2;10568return this.finishToken(types.dollarBraceL)10569} else {10570++this.pos;10571return this.finishToken(types.backQuote)10572}10573}10574out += this.input.slice(chunkStart, this.pos);10575return this.finishToken(types.template, out)10576}10577if (ch === 92) { // '\'10578out += this.input.slice(chunkStart, this.pos);10579out += this.readEscapedChar(true);10580chunkStart = this.pos;10581} else if (isNewLine(ch)) {10582out += this.input.slice(chunkStart, this.pos);10583++this.pos;10584switch (ch) {10585case 13:10586if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }10587case 10:10588out += "\n";10589break10590default:10591out += String.fromCharCode(ch);10592break10593}10594if (this.options.locations) {10595++this.curLine;10596this.lineStart = this.pos;10597}10598chunkStart = this.pos;10599} else {10600++this.pos;10601}10602}10603};1060410605// Reads a template token to search for the end, without validating any escape sequences10606pp$9.readInvalidTemplateToken = function() {10607for (; this.pos < this.input.length; this.pos++) {10608switch (this.input[this.pos]) {10609case "\\":10610++this.pos;10611break1061210613case "$":10614if (this.input[this.pos + 1] !== "{") {10615break10616}10617// falls through1061810619case "`":10620return this.finishToken(types.invalidTemplate, this.input.slice(this.start, this.pos))1062110622// no default10623}10624}10625this.raise(this.start, "Unterminated template");10626};1062710628// Used to read escaped characters1062910630pp$9.readEscapedChar = function(inTemplate) {10631var ch = this.input.charCodeAt(++this.pos);10632++this.pos;10633switch (ch) {10634case 110: return "\n" // 'n' -> '\n'10635case 114: return "\r" // 'r' -> '\r'10636case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'10637case 117: return codePointToString$1(this.readCodePoint()) // 'u'10638case 116: return "\t" // 't' -> '\t'10639case 98: return "\b" // 'b' -> '\b'10640case 118: return "\u000b" // 'v' -> '\u000b'10641case 102: return "\f" // 'f' -> '\f'10642case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'10643case 10: // ' \n'10644if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }10645return ""10646case 56:10647case 57:10648if (inTemplate) {10649var codePos = this.pos - 1;1065010651this.invalidStringToken(10652codePos,10653"Invalid escape sequence in template string"10654);1065510656return null10657}10658default:10659if (ch >= 48 && ch <= 55) {10660var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];10661var octal = parseInt(octalStr, 8);10662if (octal > 255) {10663octalStr = octalStr.slice(0, -1);10664octal = parseInt(octalStr, 8);10665}10666this.pos += octalStr.length - 1;10667ch = this.input.charCodeAt(this.pos);10668if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {10669this.invalidStringToken(10670this.pos - 1 - octalStr.length,10671inTemplate10672? "Octal literal in template string"10673: "Octal literal in strict mode"10674);10675}10676return String.fromCharCode(octal)10677}10678if (isNewLine(ch)) {10679// Unicode new line characters after \ get removed from output in both10680// template literals and strings10681return ""10682}10683return String.fromCharCode(ch)10684}10685};1068610687// Used to read character escape sequences ('\x', '\u', '\U').1068810689pp$9.readHexChar = function(len) {10690var codePos = this.pos;10691var n = this.readInt(16, len);10692if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }10693return n10694};1069510696// Read an identifier, and return it as a string. Sets `this.containsEsc`10697// to whether the word contained a '\u' escape.10698//10699// Incrementally adds only escaped chars, adding other chunks as-is10700// as a micro-optimization.1070110702pp$9.readWord1 = function() {10703this.containsEsc = false;10704var word = "", first = true, chunkStart = this.pos;10705var astral = this.options.ecmaVersion >= 6;10706while (this.pos < this.input.length) {10707var ch = this.fullCharCodeAtPos();10708if (isIdentifierChar(ch, astral)) {10709this.pos += ch <= 0xffff ? 1 : 2;10710} else if (ch === 92) { // "\"10711this.containsEsc = true;10712word += this.input.slice(chunkStart, this.pos);10713var escStart = this.pos;10714if (this.input.charCodeAt(++this.pos) !== 117) // "u"10715{ this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }10716++this.pos;10717var esc = this.readCodePoint();10718if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))10719{ this.invalidStringToken(escStart, "Invalid Unicode escape"); }10720word += codePointToString$1(esc);10721chunkStart = this.pos;10722} else {10723break10724}10725first = false;10726}10727return word + this.input.slice(chunkStart, this.pos)10728};1072910730// Read an identifier or keyword token. Will check for reserved10731// words when necessary.1073210733pp$9.readWord = function() {10734var word = this.readWord1();10735var type = types.name;10736if (this.keywords.test(word)) {10737type = keywords$1[word];10738}10739return this.finishToken(type, word)10740};1074110742// Acorn is a tiny, fast JavaScript parser written in JavaScript.1074310744var version = "7.4.1";1074510746Parser.acorn = {10747Parser: Parser,10748version: version,10749defaultOptions: defaultOptions,10750Position: Position,10751SourceLocation: SourceLocation,10752getLineInfo: getLineInfo,10753Node: Node,10754TokenType: TokenType,10755tokTypes: types,10756keywordTypes: keywords$1,10757TokContext: TokContext,10758tokContexts: types$1,10759isIdentifierChar: isIdentifierChar,10760isIdentifierStart: isIdentifierStart,10761Token: Token,10762isNewLine: isNewLine,10763lineBreak: lineBreak,10764lineBreakG: lineBreakG,10765nonASCIIwhitespace: nonASCIIwhitespace10766};var defaultGlobals = new Set([10767"Array",10768"ArrayBuffer",10769"atob",10770"AudioContext",10771"Blob",10772"Boolean",10773"BigInt",10774"btoa",10775"clearInterval",10776"clearTimeout",10777"console",10778"crypto",10779"CustomEvent",10780"DataView",10781"Date",10782"decodeURI",10783"decodeURIComponent",10784"devicePixelRatio",10785"document",10786"encodeURI",10787"encodeURIComponent",10788"Error",10789"escape",10790"eval",10791"fetch",10792"File",10793"FileList",10794"FileReader",10795"Float32Array",10796"Float64Array",10797"Function",10798"Headers",10799"Image",10800"ImageData",10801"Infinity",10802"Int16Array",10803"Int32Array",10804"Int8Array",10805"Intl",10806"isFinite",10807"isNaN",10808"JSON",10809"Map",10810"Math",10811"NaN",10812"Number",10813"navigator",10814"Object",10815"parseFloat",10816"parseInt",10817"performance",10818"Path2D",10819"Promise",10820"Proxy",10821"RangeError",10822"ReferenceError",10823"Reflect",10824"RegExp",10825"cancelAnimationFrame",10826"requestAnimationFrame",10827"Set",10828"setInterval",10829"setTimeout",10830"String",10831"Symbol",10832"SyntaxError",10833"TextDecoder",10834"TextEncoder",10835"this",10836"TypeError",10837"Uint16Array",10838"Uint32Array",10839"Uint8Array",10840"Uint8ClampedArray",10841"undefined",10842"unescape",10843"URIError",10844"URL",10845"WeakMap",10846"WeakSet",10847"WebSocket",10848"Worker",10849"window"10850]);// AST walker module for Mozilla Parser API compatible trees1085110852// A simple walk is one where you simply specify callbacks to be10853// called on specific nodes. The last two arguments are optional. A10854// simple use would be10855//10856// walk.simple(myTree, {10857// Expression: function(node) { ... }10858// });10859//10860// to do something with all expressions. All Parser API node types10861// can be used to identify node types, as well as Expression and10862// Statement, which denote categories of nodes.10863//10864// The base argument can be used to pass a custom (recursive)10865// walker, and state can be used to give this walked an initial10866// state.1086710868function simple(node, visitors, baseVisitor, state, override) {10869if (!baseVisitor) { baseVisitor = base10870; }(function c(node, st, override) {10871var type = override || node.type, found = visitors[type];10872baseVisitor[type](node, st, c);10873if (found) { found(node, st); }10874})(node, state, override);10875}1087610877// An ancestor walk keeps an array of ancestor nodes (including the10878// current node) and passes them to the callback as third parameter10879// (and also as state parameter when no other state is present).10880function ancestor(node, visitors, baseVisitor, state, override) {10881var ancestors = [];10882if (!baseVisitor) { baseVisitor = base10883; }(function c(node, st, override) {10884var type = override || node.type, found = visitors[type];10885var isNew = node !== ancestors[ancestors.length - 1];10886if (isNew) { ancestors.push(node); }10887baseVisitor[type](node, st, c);10888if (found) { found(node, st || ancestors, ancestors); }10889if (isNew) { ancestors.pop(); }10890})(node, state, override);10891}1089210893// Fallback to an Object.create polyfill for older environments.10894var create = Object.create || function(proto) {10895function Ctor() {}10896Ctor.prototype = proto;10897return new Ctor10898};1089910900// Used to create a custom walker. Will fill in all missing node10901// type properties with the defaults.10902function make(funcs, baseVisitor) {10903var visitor = create(baseVisitor || base);10904for (var type in funcs) { visitor[type] = funcs[type]; }10905return visitor10906}1090710908function skipThrough(node, st, c) { c(node, st); }10909function ignore(_node, _st, _c) {}1091010911// Node walkers.1091210913var base = {};1091410915base.Program = base.BlockStatement = function (node, st, c) {10916for (var i = 0, list = node.body; i < list.length; i += 1)10917{10918var stmt = list[i];1091910920c(stmt, st, "Statement");10921}10922};10923base.Statement = skipThrough;10924base.EmptyStatement = ignore;10925base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression =10926function (node, st, c) { return c(node.expression, st, "Expression"); };10927base.IfStatement = function (node, st, c) {10928c(node.test, st, "Expression");10929c(node.consequent, st, "Statement");10930if (node.alternate) { c(node.alternate, st, "Statement"); }10931};10932base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };10933base.BreakStatement = base.ContinueStatement = ignore;10934base.WithStatement = function (node, st, c) {10935c(node.object, st, "Expression");10936c(node.body, st, "Statement");10937};10938base.SwitchStatement = function (node, st, c) {10939c(node.discriminant, st, "Expression");10940for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {10941var cs = list$1[i$1];1094210943if (cs.test) { c(cs.test, st, "Expression"); }10944for (var i = 0, list = cs.consequent; i < list.length; i += 1)10945{10946var cons = list[i];1094710948c(cons, st, "Statement");10949}10950}10951};10952base.SwitchCase = function (node, st, c) {10953if (node.test) { c(node.test, st, "Expression"); }10954for (var i = 0, list = node.consequent; i < list.length; i += 1)10955{10956var cons = list[i];1095710958c(cons, st, "Statement");10959}10960};10961base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {10962if (node.argument) { c(node.argument, st, "Expression"); }10963};10964base.ThrowStatement = base.SpreadElement =10965function (node, st, c) { return c(node.argument, st, "Expression"); };10966base.TryStatement = function (node, st, c) {10967c(node.block, st, "Statement");10968if (node.handler) { c(node.handler, st); }10969if (node.finalizer) { c(node.finalizer, st, "Statement"); }10970};10971base.CatchClause = function (node, st, c) {10972if (node.param) { c(node.param, st, "Pattern"); }10973c(node.body, st, "Statement");10974};10975base.WhileStatement = base.DoWhileStatement = function (node, st, c) {10976c(node.test, st, "Expression");10977c(node.body, st, "Statement");10978};10979base.ForStatement = function (node, st, c) {10980if (node.init) { c(node.init, st, "ForInit"); }10981if (node.test) { c(node.test, st, "Expression"); }10982if (node.update) { c(node.update, st, "Expression"); }10983c(node.body, st, "Statement");10984};10985base.ForInStatement = base.ForOfStatement = function (node, st, c) {10986c(node.left, st, "ForInit");10987c(node.right, st, "Expression");10988c(node.body, st, "Statement");10989};10990base.ForInit = function (node, st, c) {10991if (node.type === "VariableDeclaration") { c(node, st); }10992else { c(node, st, "Expression"); }10993};10994base.DebuggerStatement = ignore;1099510996base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };10997base.VariableDeclaration = function (node, st, c) {10998for (var i = 0, list = node.declarations; i < list.length; i += 1)10999{11000var decl = list[i];1100111002c(decl, st);11003}11004};11005base.VariableDeclarator = function (node, st, c) {11006c(node.id, st, "Pattern");11007if (node.init) { c(node.init, st, "Expression"); }11008};1100911010base.Function = function (node, st, c) {11011if (node.id) { c(node.id, st, "Pattern"); }11012for (var i = 0, list = node.params; i < list.length; i += 1)11013{11014var param = list[i];1101511016c(param, st, "Pattern");11017}11018c(node.body, st, node.expression ? "Expression" : "Statement");11019};1102011021base.Pattern = function (node, st, c) {11022if (node.type === "Identifier")11023{ c(node, st, "VariablePattern"); }11024else if (node.type === "MemberExpression")11025{ c(node, st, "MemberPattern"); }11026else11027{ c(node, st); }11028};11029base.VariablePattern = ignore;11030base.MemberPattern = skipThrough;11031base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };11032base.ArrayPattern = function (node, st, c) {11033for (var i = 0, list = node.elements; i < list.length; i += 1) {11034var elt = list[i];1103511036if (elt) { c(elt, st, "Pattern"); }11037}11038};11039base.ObjectPattern = function (node, st, c) {11040for (var i = 0, list = node.properties; i < list.length; i += 1) {11041var prop = list[i];1104211043if (prop.type === "Property") {11044if (prop.computed) { c(prop.key, st, "Expression"); }11045c(prop.value, st, "Pattern");11046} else if (prop.type === "RestElement") {11047c(prop.argument, st, "Pattern");11048}11049}11050};1105111052base.Expression = skipThrough;11053base.ThisExpression = base.Super = base.MetaProperty = ignore;11054base.ArrayExpression = function (node, st, c) {11055for (var i = 0, list = node.elements; i < list.length; i += 1) {11056var elt = list[i];1105711058if (elt) { c(elt, st, "Expression"); }11059}11060};11061base.ObjectExpression = function (node, st, c) {11062for (var i = 0, list = node.properties; i < list.length; i += 1)11063{11064var prop = list[i];1106511066c(prop, st);11067}11068};11069base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;11070base.SequenceExpression = function (node, st, c) {11071for (var i = 0, list = node.expressions; i < list.length; i += 1)11072{11073var expr = list[i];1107411075c(expr, st, "Expression");11076}11077};11078base.TemplateLiteral = function (node, st, c) {11079for (var i = 0, list = node.quasis; i < list.length; i += 1)11080{11081var quasi = list[i];1108211083c(quasi, st);11084}1108511086for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)11087{11088var expr = list$1[i$1];1108911090c(expr, st, "Expression");11091}11092};11093base.TemplateElement = ignore;11094base.UnaryExpression = base.UpdateExpression = function (node, st, c) {11095c(node.argument, st, "Expression");11096};11097base.BinaryExpression = base.LogicalExpression = function (node, st, c) {11098c(node.left, st, "Expression");11099c(node.right, st, "Expression");11100};11101base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {11102c(node.left, st, "Pattern");11103c(node.right, st, "Expression");11104};11105base.ConditionalExpression = function (node, st, c) {11106c(node.test, st, "Expression");11107c(node.consequent, st, "Expression");11108c(node.alternate, st, "Expression");11109};11110base.NewExpression = base.CallExpression = function (node, st, c) {11111c(node.callee, st, "Expression");11112if (node.arguments)11113{ for (var i = 0, list = node.arguments; i < list.length; i += 1)11114{11115var arg = list[i];1111611117c(arg, st, "Expression");11118} }11119};11120base.MemberExpression = function (node, st, c) {11121c(node.object, st, "Expression");11122if (node.computed) { c(node.property, st, "Expression"); }11123};11124base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {11125if (node.declaration)11126{ c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }11127if (node.source) { c(node.source, st, "Expression"); }11128};11129base.ExportAllDeclaration = function (node, st, c) {11130if (node.exported)11131{ c(node.exported, st); }11132c(node.source, st, "Expression");11133};11134base.ImportDeclaration = function (node, st, c) {11135for (var i = 0, list = node.specifiers; i < list.length; i += 1)11136{11137var spec = list[i];1113811139c(spec, st);11140}11141c(node.source, st, "Expression");11142};11143base.ImportExpression = function (node, st, c) {11144c(node.source, st, "Expression");11145};11146base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.Literal = ignore;1114711148base.TaggedTemplateExpression = function (node, st, c) {11149c(node.tag, st, "Expression");11150c(node.quasi, st, "Expression");11151};11152base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };11153base.Class = function (node, st, c) {11154if (node.id) { c(node.id, st, "Pattern"); }11155if (node.superClass) { c(node.superClass, st, "Expression"); }11156c(node.body, st);11157};11158base.ClassBody = function (node, st, c) {11159for (var i = 0, list = node.body; i < list.length; i += 1)11160{11161var elt = list[i];1116211163c(elt, st);11164}11165};11166base.MethodDefinition = base.Property = function (node, st, c) {11167if (node.computed) { c(node.key, st, "Expression"); }11168c(node.value, st, "Expression");11169};var walk = make({11170Import() {},11171ViewExpression(node, st, c) {11172c(node.id, st, "Identifier");11173},11174MutableExpression(node, st, c) {11175c(node.id, st, "Identifier");11176}11177});// Based on https://github.com/ForbesLindesay/acorn-globals1117811179function isScope(node) {11180return node.type === "FunctionExpression"11181|| node.type === "FunctionDeclaration"11182|| node.type === "ArrowFunctionExpression"11183|| node.type === "Program";11184}1118511186function isBlockScope(node) {11187return node.type === "BlockStatement"11188|| node.type === "ForInStatement"11189|| node.type === "ForOfStatement"11190|| node.type === "ForStatement"11191|| isScope(node);11192}1119311194function declaresArguments(node) {11195return node.type === "FunctionExpression"11196|| node.type === "FunctionDeclaration";11197}1119811199function findReferences(cell, globals) {11200const ast = {type: "Program", body: [cell.body]};11201const locals = new Map;11202const globalSet = new Set(globals);11203const references = [];1120411205function hasLocal(node, name) {11206const l = locals.get(node);11207return l ? l.has(name) : false;11208}1120911210function declareLocal(node, id) {11211const l = locals.get(node);11212if (l) l.add(id.name);11213else locals.set(node, new Set([id.name]));11214}1121511216function declareClass(node) {11217if (node.id) declareLocal(node, node.id);11218}1121911220function declareFunction(node) {11221node.params.forEach(param => declarePattern(param, node));11222if (node.id) declareLocal(node, node.id);11223}1122411225function declareCatchClause(node) {11226if (node.param) declarePattern(node.param, node);11227}1122811229function declarePattern(node, parent) {11230switch (node.type) {11231case "Identifier":11232declareLocal(parent, node);11233break;11234case "ObjectPattern":11235node.properties.forEach(node => declarePattern(node, parent));11236break;11237case "ArrayPattern":11238node.elements.forEach(node => node && declarePattern(node, parent));11239break;11240case "Property":11241declarePattern(node.value, parent);11242break;11243case "RestElement":11244declarePattern(node.argument, parent);11245break;11246case "AssignmentPattern":11247declarePattern(node.left, parent);11248break;11249default:11250throw new Error("Unrecognized pattern type: " + node.type);11251}11252}1125311254function declareModuleSpecifier(node) {11255declareLocal(ast, node.local);11256}1125711258ancestor(11259ast,11260{11261VariableDeclaration: (node, parents) => {11262let parent = null;11263for (let i = parents.length - 1; i >= 0 && parent === null; --i) {11264if (node.kind === "var" ? isScope(parents[i]) : isBlockScope(parents[i])) {11265parent = parents[i];11266}11267}11268node.declarations.forEach(declaration => declarePattern(declaration.id, parent));11269},11270FunctionDeclaration: (node, parents) => {11271let parent = null;11272for (let i = parents.length - 2; i >= 0 && parent === null; --i) {11273if (isScope(parents[i])) {11274parent = parents[i];11275}11276}11277declareLocal(parent, node.id);11278declareFunction(node);11279},11280Function: declareFunction,11281ClassDeclaration: (node, parents) => {11282let parent = null;11283for (let i = parents.length - 2; i >= 0 && parent === null; i--) {11284if (isScope(parents[i])) {11285parent = parents[i];11286}11287}11288declareLocal(parent, node.id);11289},11290Class: declareClass,11291CatchClause: declareCatchClause,11292ImportDefaultSpecifier: declareModuleSpecifier,11293ImportSpecifier: declareModuleSpecifier,11294ImportNamespaceSpecifier: declareModuleSpecifier11295},11296walk11297);1129811299function identifier(node, parents) {11300let name = node.name;11301if (name === "undefined") return;11302for (let i = parents.length - 2; i >= 0; --i) {11303if (name === "arguments") {11304if (declaresArguments(parents[i])) {11305return;11306}11307}11308if (hasLocal(parents[i], name)) {11309return;11310}11311if (parents[i].type === "ViewExpression") {11312node = parents[i];11313name = `viewof ${node.id.name}`;11314}11315if (parents[i].type === "MutableExpression") {11316node = parents[i];11317name = `mutable ${node.id.name}`;11318}11319}11320if (!globalSet.has(name)) {11321if (name === "arguments") {11322throw Object.assign(new SyntaxError(`arguments is not allowed`), {node});11323}11324references.push(node);11325}11326}1132711328ancestor(11329ast,11330{11331VariablePattern: identifier,11332Identifier: identifier11333},11334walk11335);1133611337function checkConst(node, parents) {11338switch (node.type) {11339case "Identifier":11340case "VariablePattern": {11341identifier(node, parents);11342break;11343}11344case "ArrayPattern":11345case "ObjectPattern": {11346ancestor(11347node,11348{11349Identifier: identifier,11350VariablePattern: identifier11351},11352walk11353);11354break;11355}11356}11357function identifier(node, nodeParents) {11358for (const parent of parents) {11359if (hasLocal(parent, node.name)) {11360return;11361}11362}11363if (nodeParents[nodeParents.length - 2].type === "MutableExpression") {11364return;11365}11366throw Object.assign(new SyntaxError(`Assignment to constant variable ${node.name}`), {node});11367}11368}1136911370function checkConstArgument(node, parents) {11371checkConst(node.argument, parents);11372}1137311374function checkConstLeft(node, parents) {11375checkConst(node.left, parents);11376}1137711378ancestor(11379ast,11380{11381AssignmentExpression: checkConstLeft,11382UpdateExpression: checkConstArgument,11383ForOfStatement: checkConstLeft,11384ForInStatement: checkConstLeft11385},11386walk11387);1138811389return references;11390}function findFeatures(cell, featureName) {11391const ast = {type: "Program", body: [cell.body]};11392const features = new Map();11393const {references} = cell;1139411395simple(11396ast,11397{11398CallExpression: node => {11399const {callee, arguments: args} = node;1140011401// Ignore function calls that are not references to the feature.11402if (11403callee.type !== "Identifier" ||11404callee.name !== featureName ||11405references.indexOf(callee) < 011406) return;1140711408// Forbid dynamic calls.11409if (11410args.length !== 1 ||11411!((args[0].type === "Literal" && /^['"]/.test(args[0].raw)) ||11412(args[0].type === "TemplateLiteral" && args[0].expressions.length === 0))11413) {11414throw Object.assign(new SyntaxError(`${featureName} requires a single literal string argument`), {node});11415}1141611417const [arg] = args;11418const name = arg.type === "Literal" ? arg.value : arg.quasis[0].value.cooked;11419const location = {start: arg.start, end: arg.end};11420if (features.has(name)) features.get(name).push(location);11421else features.set(name, [location]);11422}11423},11424walk11425);1142611427return features;11428}const SCOPE_FUNCTION$1 = 2;11429const SCOPE_ASYNC$1 = 4;11430const SCOPE_GENERATOR$1 = 8;1143111432const STATE_START = Symbol("start");11433const STATE_MODIFIER = Symbol("modifier");11434const STATE_FUNCTION = Symbol("function");11435const STATE_NAME = Symbol("name");1143611437function parseCell(input, {globals} = {}) {11438const cell = CellParser.parse(input);11439parseReferences(cell, input, globals);11440parseFeatures(cell);11441return cell;11442}1144311444/*11445┌─────┐11446┌───────────│START│─function|class11447│ └─────┘ │11448viewof|mutable|async │ ▼11449│ │ ┌────────┐ ┌─┐11450▼ │ │FUNCTION│◀───▶│*│11451┌────────┐ │ └────────┘ └─┘11452│MODIFIER│ │ │11453└────────┘ name name11454│ │ │11455└──name─┐ │ ▼11456▼ │ ┌─────────────┐11457┌────────┐ │ │FUNCTION_NAME│11458│ NAME │◀─┘ └─────────────┘11459└────────┘11460│11461=11462▼11463┌────────┐11464│ EQ │11465└────────┘11466*/1146711468function peekId(input) {11469let state = STATE_START;11470let name;11471try {11472for (const token of Parser.tokenizer(input, {ecmaVersion: 11})) {11473switch (state) {11474case STATE_START:11475case STATE_MODIFIER: {11476if (token.type === types.name) {11477if (11478state === STATE_START &&11479(token.value === "viewof" ||11480token.value === "mutable" ||11481token.value === "async")11482) {11483state = STATE_MODIFIER;11484continue;11485}11486state = STATE_NAME;11487name = token;11488continue;11489}11490if (token.type === types._function || token.type === types._class) {11491state = STATE_FUNCTION;11492continue;11493}11494break;11495}11496case STATE_NAME: {11497if (token.type === types.eq) return name.value;11498break;11499}11500case STATE_FUNCTION: {11501if (token.type === types.star) continue;11502if (token.type === types.name && token.end < input.length)11503return token.value;11504break;11505}11506}11507return;11508}11509} catch (ignore) {11510return;11511}11512}1151311514class CellParser extends Parser {11515constructor(options, ...args) {11516super(Object.assign({ecmaVersion: 12}, options), ...args);11517}11518enterScope(flags) {11519if (flags & SCOPE_FUNCTION$1) ++this.O_function;11520return super.enterScope(flags);11521}11522exitScope() {11523if (this.currentScope().flags & SCOPE_FUNCTION$1) --this.O_function;11524return super.exitScope();11525}11526parseForIn(node, init) {11527if (this.O_function === 1 && node.await) this.O_async = true;11528return super.parseForIn(node, init);11529}11530parseAwait() {11531if (this.O_function === 1) this.O_async = true;11532return super.parseAwait();11533}11534parseYield(noIn) {11535if (this.O_function === 1) this.O_generator = true;11536return super.parseYield(noIn);11537}11538parseImport(node) {11539this.next();11540node.specifiers = this.parseImportSpecifiers();11541if (this.type === types._with) {11542this.next();11543node.injections = this.parseImportSpecifiers();11544}11545this.expectContextual("from");11546node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();11547return this.finishNode(node, "ImportDeclaration");11548}11549parseImportSpecifiers() {11550const nodes = [];11551const identifiers = new Set;11552let first = true;11553this.expect(types.braceL);11554while (!this.eat(types.braceR)) {11555if (first) {11556first = false;11557} else {11558this.expect(types.comma);11559if (this.afterTrailingComma(types.braceR)) break;11560}11561const node = this.startNode();11562node.view = this.eatContextual("viewof");11563node.mutable = node.view ? false : this.eatContextual("mutable");11564node.imported = this.parseIdent();11565this.checkUnreserved(node.imported);11566this.checkLocal(node.imported);11567if (this.eatContextual("as")) {11568node.local = this.parseIdent();11569this.checkUnreserved(node.local);11570this.checkLocal(node.local);11571} else {11572node.local = node.imported;11573}11574this.checkLVal(node.local, "let");11575if (identifiers.has(node.local.name)) {11576this.raise(node.local.start, `Identifier '${node.local.name}' has already been declared`);11577}11578identifiers.add(node.local.name);11579nodes.push(this.finishNode(node, "ImportSpecifier"));11580}11581return nodes;11582}11583parseExprAtom(refDestructuringErrors) {11584return (11585this.parseMaybeKeywordExpression("viewof", "ViewExpression") ||11586this.parseMaybeKeywordExpression("mutable", "MutableExpression") ||11587super.parseExprAtom(refDestructuringErrors)11588);11589}11590parseCell(node, eof) {11591const lookahead = new CellParser({}, this.input, this.start);11592let token = lookahead.getToken();11593let body = null;11594let id = null;1159511596this.O_function = 0;11597this.O_async = false;11598this.O_generator = false;11599this.strict = true;11600this.enterScope(SCOPE_FUNCTION$1 | SCOPE_ASYNC$1 | SCOPE_GENERATOR$1);1160111602// An import?11603if (token.type === types._import && lookahead.getToken().type !== types.parenL) {11604body = this.parseImport(this.startNode());11605}1160611607// A non-empty cell?11608else if (token.type !== types.eof && token.type !== types.semi) {11609// A named cell?11610if (token.type === types.name) {11611if (token.value === "viewof" || token.value === "mutable") {11612token = lookahead.getToken();11613if (token.type !== types.name) {11614lookahead.unexpected();11615}11616}11617token = lookahead.getToken();11618if (token.type === types.eq) {11619id =11620this.parseMaybeKeywordExpression("viewof", "ViewExpression") ||11621this.parseMaybeKeywordExpression("mutable", "MutableExpression") ||11622this.parseIdent();11623token = lookahead.getToken();11624this.expect(types.eq);11625}11626}1162711628// A block?11629if (token.type === types.braceL) {11630body = this.parseBlock();11631}1163211633// An expression?11634// Possibly a function or class declaration?11635else {11636body = this.parseExpression();11637if (11638id === null &&11639(body.type === "FunctionExpression" ||11640body.type === "ClassExpression")11641) {11642id = body.id;11643}11644}11645}1164611647this.semicolon();11648if (eof) this.expect(types.eof); // TODO1164911650if (id) this.checkLocal(id);11651node.id = id;11652node.async = this.O_async;11653node.generator = this.O_generator;11654node.body = body;11655this.exitScope();11656return this.finishNode(node, "Cell");11657}11658parseTopLevel(node) {11659return this.parseCell(node, true);11660}11661toAssignable(node, isBinding, refDestructuringErrors) {11662return node.type === "MutableExpression"11663? node11664: super.toAssignable(node, isBinding, refDestructuringErrors);11665}11666checkLocal(id) {11667const node = id.id || id;11668if (defaultGlobals.has(node.name) || node.name === "arguments") {11669this.raise(node.start, `Identifier '${node.name}' is reserved`);11670}11671}11672checkUnreserved(node) {11673if (node.name === "viewof" || node.name === "mutable") {11674this.raise(node.start, `Unexpected keyword '${node.name}'`);11675}11676return super.checkUnreserved(node);11677}11678checkLVal(expr, bindingType, checkClashes) {11679return super.checkLVal(11680expr.type === "MutableExpression" ? expr.id : expr,11681bindingType,11682checkClashes11683);11684}11685unexpected(pos) {11686this.raise(11687pos != null ? pos : this.start,11688this.type === types.eof ? "Unexpected end of input" : "Unexpected token"11689);11690}11691parseMaybeKeywordExpression(keyword, type) {11692if (this.isContextual(keyword)) {11693const node = this.startNode();11694this.next();11695node.id = this.parseIdent();11696return this.finishNode(node, type);11697}11698}11699}1170011701function parseModule(input, {globals} = {}) {11702const program = ModuleParser.parse(input);11703for (const cell of program.cells) {11704parseReferences(cell, input, globals);11705parseFeatures(cell, input);11706}11707return program;11708}1170911710class ModuleParser extends CellParser {11711parseTopLevel(node) {11712if (!node.cells) node.cells = [];11713while (this.type !== types.eof) {11714const cell = this.parseCell(this.startNode());11715cell.input = this.input;11716node.cells.push(cell);11717}11718this.next();11719return this.finishNode(node, "Program");11720}11721}1172211723// Find references.11724// Check for illegal references to arguments.11725// Check for illegal assignments to global references.11726function parseReferences(cell, input, globals = defaultGlobals) {11727if (cell.body && cell.body.type !== "ImportDeclaration") {11728try {11729cell.references = findReferences(cell, globals);11730} catch (error) {11731if (error.node) {11732const loc = getLineInfo(input, error.node.start);11733error.message += ` (${loc.line}:${loc.column})`;11734error.pos = error.node.start;11735error.loc = loc;11736delete error.node;11737}11738throw error;11739}11740}11741return cell;11742}1174311744// Find features: file attachments, secrets, database clients.11745// Check for illegal references to arguments.11746// Check for illegal assignments to global references.11747function parseFeatures(cell, input) {11748if (cell.body && cell.body.type !== "ImportDeclaration") {11749try {11750cell.fileAttachments = findFeatures(cell, "FileAttachment");11751cell.databaseClients = findFeatures(cell, "DatabaseClient");11752cell.secrets = findFeatures(cell, "Secret");11753} catch (error) {11754if (error.node) {11755const loc = getLineInfo(input, error.node.start);11756error.message += ` (${loc.line}:${loc.column})`;11757error.pos = error.node.start;11758error.loc = loc;11759delete error.node;11760}11761throw error;11762}11763} else {11764cell.fileAttachments = new Map();11765cell.databaseClients = new Map();11766cell.secrets = new Map();11767}11768return cell;11769}var index=/*#__PURE__*/Object.freeze({__proto__:null,parseCell: parseCell,peekId: peekId,CellParser: CellParser,parseModule: parseModule,ModuleParser: ModuleParser,walk: walk});// AST walker module for Mozilla Parser API compatible trees1177011771// A full walk triggers the callback on each node11772function full(node, callback, baseVisitor, state, override) {11773if (!baseVisitor) { baseVisitor = base$111774; }(function c(node, st, override) {11775var type = override || node.type;11776baseVisitor[type](node, st, c);11777if (!override) { callback(node, st, type); }11778})(node, state, override);11779}1178011781function skipThrough$1(node, st, c) { c(node, st); }11782function ignore$1(_node, _st, _c) {}1178311784// Node walkers.1178511786var base$1 = {};1178711788base$1.Program = base$1.BlockStatement = function (node, st, c) {11789for (var i = 0, list = node.body; i < list.length; i += 1)11790{11791var stmt = list[i];1179211793c(stmt, st, "Statement");11794}11795};11796base$1.Statement = skipThrough$1;11797base$1.EmptyStatement = ignore$1;11798base$1.ExpressionStatement = base$1.ParenthesizedExpression = base$1.ChainExpression =11799function (node, st, c) { return c(node.expression, st, "Expression"); };11800base$1.IfStatement = function (node, st, c) {11801c(node.test, st, "Expression");11802c(node.consequent, st, "Statement");11803if (node.alternate) { c(node.alternate, st, "Statement"); }11804};11805base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };11806base$1.BreakStatement = base$1.ContinueStatement = ignore$1;11807base$1.WithStatement = function (node, st, c) {11808c(node.object, st, "Expression");11809c(node.body, st, "Statement");11810};11811base$1.SwitchStatement = function (node, st, c) {11812c(node.discriminant, st, "Expression");11813for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {11814var cs = list$1[i$1];1181511816if (cs.test) { c(cs.test, st, "Expression"); }11817for (var i = 0, list = cs.consequent; i < list.length; i += 1)11818{11819var cons = list[i];1182011821c(cons, st, "Statement");11822}11823}11824};11825base$1.SwitchCase = function (node, st, c) {11826if (node.test) { c(node.test, st, "Expression"); }11827for (var i = 0, list = node.consequent; i < list.length; i += 1)11828{11829var cons = list[i];1183011831c(cons, st, "Statement");11832}11833};11834base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {11835if (node.argument) { c(node.argument, st, "Expression"); }11836};11837base$1.ThrowStatement = base$1.SpreadElement =11838function (node, st, c) { return c(node.argument, st, "Expression"); };11839base$1.TryStatement = function (node, st, c) {11840c(node.block, st, "Statement");11841if (node.handler) { c(node.handler, st); }11842if (node.finalizer) { c(node.finalizer, st, "Statement"); }11843};11844base$1.CatchClause = function (node, st, c) {11845if (node.param) { c(node.param, st, "Pattern"); }11846c(node.body, st, "Statement");11847};11848base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {11849c(node.test, st, "Expression");11850c(node.body, st, "Statement");11851};11852base$1.ForStatement = function (node, st, c) {11853if (node.init) { c(node.init, st, "ForInit"); }11854if (node.test) { c(node.test, st, "Expression"); }11855if (node.update) { c(node.update, st, "Expression"); }11856c(node.body, st, "Statement");11857};11858base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {11859c(node.left, st, "ForInit");11860c(node.right, st, "Expression");11861c(node.body, st, "Statement");11862};11863base$1.ForInit = function (node, st, c) {11864if (node.type === "VariableDeclaration") { c(node, st); }11865else { c(node, st, "Expression"); }11866};11867base$1.DebuggerStatement = ignore$1;1186811869base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };11870base$1.VariableDeclaration = function (node, st, c) {11871for (var i = 0, list = node.declarations; i < list.length; i += 1)11872{11873var decl = list[i];1187411875c(decl, st);11876}11877};11878base$1.VariableDeclarator = function (node, st, c) {11879c(node.id, st, "Pattern");11880if (node.init) { c(node.init, st, "Expression"); }11881};1188211883base$1.Function = function (node, st, c) {11884if (node.id) { c(node.id, st, "Pattern"); }11885for (var i = 0, list = node.params; i < list.length; i += 1)11886{11887var param = list[i];1188811889c(param, st, "Pattern");11890}11891c(node.body, st, node.expression ? "Expression" : "Statement");11892};1189311894base$1.Pattern = function (node, st, c) {11895if (node.type === "Identifier")11896{ c(node, st, "VariablePattern"); }11897else if (node.type === "MemberExpression")11898{ c(node, st, "MemberPattern"); }11899else11900{ c(node, st); }11901};11902base$1.VariablePattern = ignore$1;11903base$1.MemberPattern = skipThrough$1;11904base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };11905base$1.ArrayPattern = function (node, st, c) {11906for (var i = 0, list = node.elements; i < list.length; i += 1) {11907var elt = list[i];1190811909if (elt) { c(elt, st, "Pattern"); }11910}11911};11912base$1.ObjectPattern = function (node, st, c) {11913for (var i = 0, list = node.properties; i < list.length; i += 1) {11914var prop = list[i];1191511916if (prop.type === "Property") {11917if (prop.computed) { c(prop.key, st, "Expression"); }11918c(prop.value, st, "Pattern");11919} else if (prop.type === "RestElement") {11920c(prop.argument, st, "Pattern");11921}11922}11923};1192411925base$1.Expression = skipThrough$1;11926base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore$1;11927base$1.ArrayExpression = function (node, st, c) {11928for (var i = 0, list = node.elements; i < list.length; i += 1) {11929var elt = list[i];1193011931if (elt) { c(elt, st, "Expression"); }11932}11933};11934base$1.ObjectExpression = function (node, st, c) {11935for (var i = 0, list = node.properties; i < list.length; i += 1)11936{11937var prop = list[i];1193811939c(prop, st);11940}11941};11942base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;11943base$1.SequenceExpression = function (node, st, c) {11944for (var i = 0, list = node.expressions; i < list.length; i += 1)11945{11946var expr = list[i];1194711948c(expr, st, "Expression");11949}11950};11951base$1.TemplateLiteral = function (node, st, c) {11952for (var i = 0, list = node.quasis; i < list.length; i += 1)11953{11954var quasi = list[i];1195511956c(quasi, st);11957}1195811959for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)11960{11961var expr = list$1[i$1];1196211963c(expr, st, "Expression");11964}11965};11966base$1.TemplateElement = ignore$1;11967base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {11968c(node.argument, st, "Expression");11969};11970base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {11971c(node.left, st, "Expression");11972c(node.right, st, "Expression");11973};11974base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {11975c(node.left, st, "Pattern");11976c(node.right, st, "Expression");11977};11978base$1.ConditionalExpression = function (node, st, c) {11979c(node.test, st, "Expression");11980c(node.consequent, st, "Expression");11981c(node.alternate, st, "Expression");11982};11983base$1.NewExpression = base$1.CallExpression = function (node, st, c) {11984c(node.callee, st, "Expression");11985if (node.arguments)11986{ for (var i = 0, list = node.arguments; i < list.length; i += 1)11987{11988var arg = list[i];1198911990c(arg, st, "Expression");11991} }11992};11993base$1.MemberExpression = function (node, st, c) {11994c(node.object, st, "Expression");11995if (node.computed) { c(node.property, st, "Expression"); }11996};11997base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {11998if (node.declaration)11999{ c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }12000if (node.source) { c(node.source, st, "Expression"); }12001};12002base$1.ExportAllDeclaration = function (node, st, c) {12003if (node.exported)12004{ c(node.exported, st); }12005c(node.source, st, "Expression");12006};12007base$1.ImportDeclaration = function (node, st, c) {12008for (var i = 0, list = node.specifiers; i < list.length; i += 1)12009{12010var spec = list[i];1201112012c(spec, st);12013}12014c(node.source, st, "Expression");12015};12016base$1.ImportExpression = function (node, st, c) {12017c(node.source, st, "Expression");12018};12019base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.Literal = ignore$1;1202012021base$1.TaggedTemplateExpression = function (node, st, c) {12022c(node.tag, st, "Expression");12023c(node.quasi, st, "Expression");12024};12025base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };12026base$1.Class = function (node, st, c) {12027if (node.id) { c(node.id, st, "Pattern"); }12028if (node.superClass) { c(node.superClass, st, "Expression"); }12029c(node.body, st);12030};12031base$1.ClassBody = function (node, st, c) {12032for (var i = 0, list = node.body; i < list.length; i += 1)12033{12034var elt = list[i];1203512036c(elt, st);12037}12038};12039base$1.MethodDefinition = base$1.Property = function (node, st, c) {12040if (node.computed) { c(node.key, st, "Expression"); }12041c(node.value, st, "Expression");12042};/**12043* FINISH REPLACING THE SIMPLE WALKER WITH A FULL WALKER THAT DOES SUBSTITUTION ALL AT ONCE.12044*12045*/1204612047const extractPath = path => {12048let source = path;12049let m;1205012051// "https://api.observablehq.com/@jashkenas/inputs.js?v=3" => strip off ".js"12052if ((m = /\.js(\?|$)/i.exec(source))) source = source.slice(0, m.index);1205312054// "74f872c4fde62e35" => "d/..."12055if ((m = /^[0-9a-f]{16}$/i.test(source))) source = `d/${source}`;1205612057// link of notebook12058if ((m = /^https:\/\/(api\.|beta\.|)observablehq\.com\//i.exec(source)))12059source = source.slice(m[0].length);12060return source;12061};1206212063function setupImportCell(cell) {12064const specifiers = [];1206512066if (cell.body.specifiers)12067for (const specifier of cell.body.specifiers) {12068if (specifier.view) {12069specifiers.push({12070name: "viewof " + specifier.imported.name,12071alias: "viewof " + specifier.local.name12072});12073} else if (specifier.mutable) {12074specifiers.push({12075name: "mutable " + specifier.imported.name,12076alias: "mutable " + specifier.local.name12077});12078}12079specifiers.push({12080name: specifier.imported.name,12081alias: specifier.local.name12082});12083}12084// If injections is undefined, do not derive!12085const hasInjections = cell.body.injections !== undefined;12086const injections = [];12087if (hasInjections)12088for (const injection of cell.body.injections) {12089// This currently behaves like notebooks on observablehq.com12090// Commenting out the if & else if blocks result in behavior like Example 3 here: https://observablehq.com/d/7ccad009e4d8996912091if (injection.view) {12092injections.push({12093name: "viewof " + injection.imported.name,12094alias: "viewof " + injection.local.name12095});12096} else if (injection.mutable) {12097injections.push({12098name: "mutable " + injection.imported.name,12099alias: "mutable " + injection.local.name12100});12101}12102injections.push({12103name: injection.imported.name,12104alias: injection.local.name12105});12106}12107const importString = `import {${specifiers12108.map(specifier => `${specifier.name} as ${specifier.alias}`)12109.join(", ")}} ${12110hasInjections12111? `with {${injections12112.map(injection => `${injection.name} as ${injection.alias}`)12113.join(", ")}} `12114: ``12115}from "${cell.body.source.value}"`;1211612117return { specifiers, hasInjections, injections, importString };12118}1211912120function setupRegularCell(cell) {12121let name = null;12122if (cell.id && cell.id.name) name = cell.id.name;12123else if (cell.id && cell.id.id && cell.id.id.name) name = cell.id.id.name;12124let bodyText = cell.input.substring(cell.body.start, cell.body.end);12125let expressionMap = {};12126let references = [];12127let counter = 0;12128const cellReferences = Array.from(new Set((cell.references || []).map(ref => {12129if (ref.type === "ViewExpression") {12130if (expressionMap[ref.id.name] === undefined) {12131const newName = `$${counter++}`;12132expressionMap[ref.id.name] = newName;12133references.push(newName);12134}12135return "viewof " + ref.id.name;12136} else if (ref.type === "MutableExpression") {12137if (expressionMap[ref.id.name] === undefined) {12138const newName = `$${counter++}`;12139expressionMap[ref.id.name] = newName;12140references.push(newName);12141}12142return "mutable " + ref.id.name;12143} else {12144references.push(ref.name);12145return ref.name;12146}12147})));12148const uniq = (lst) => {12149const result = [];12150const s = new Set();12151for (const v of lst) {12152if (s.has(v)) continue;12153s.add(v);12154result.push(v);12155}12156return result;12157};12158const patches = [];12159let latestPatch = { newStr: "", span: [cell.body.start, cell.body.start] };12160full(cell.body, node => {12161if (node.type === "ViewExpression" || node.type === "MutableExpression") {12162// cover previous ground?12163if (node.start !== latestPatch.span[1]) {12164patches.push({ newStr: cell.input.substring(latestPatch.span[1], node.start)});12165}12166const suffix = node.type === "MutableExpression" ? ".value" : "";12167const newStr = `${expressionMap[node.id.name]}${suffix}`;12168const patch = {12169newStr,12170span: [node.start, node.end]12171};12172latestPatch = patch;12173patches.push(patch);12174}12175}, walk);12176patches.push({newStr: cell.input.substring(latestPatch.span[1], cell.body.end), span: [latestPatch.span[1], cell.body.end]});12177bodyText = patches.map(x => x.newStr).join("");1217812179return {12180cellName: name,12181references: uniq(references),12182bodyText,12183cellReferences: uniq(cellReferences)12184};12185}function names(cell) {12186if (cell.body && cell.body.specifiers)12187return cell.body.specifiers.map(12188d => `${d.view ? "viewof " : d.mutable ? "mutable " : ""}${d.local.name}`12189);1219012191if (cell.id && cell.id.type && cell.id) {12192if (cell.id.type === "ViewExpression") return [`viewof ${cell.id.id.name}`];12193if (cell.id.type === "MutableExpression")12194return [`mutable ${cell.id.id.name}`];12195if (cell.id.name) return [cell.id.name];12196}1219712198return [];12199}1220012201function references(cell) {12202if (cell.references)12203return cell.references.map(d => {12204if (d.name) return d.name;12205if (d.type === "ViewExpression") return `viewof ${d.id.name}`;12206if (d.type === "MutableExpression") return `mutable ${d.id.name}`;12207return null;12208});1220912210if (cell.body && cell.body.injections)12211return cell.body.injections.map(12212d =>12213`${d.view ? "viewof " : d.mutable ? "mutable " : ""}${d.imported.name}`12214);1221512216return [];12217}1221812219function getCellRefs(module) {12220const cells = [];12221for (const cell of module.cells) {12222const ns = names(cell);12223const refs = references(cell);12224if (!ns || !ns.length) continue;12225for (const name of ns) {12226cells.push([name, refs]);12227if (name.startsWith("viewof "))12228cells.push([name.substring("viewof ".length), [name]]);12229}12230}12231return new Map(cells);12232}1223312234function treeShakeModule(module, targets) {12235const cellRefs = getCellRefs(module);1223612237const embed = new Set();12238const todo = targets.slice();12239while (todo.length) {12240const d = todo.pop();12241embed.add(d);12242// happens when 1) d is an stdlib cell, 2) d doesnt have a defintion,12243// or 3) d is in the window/global object. Let's be forgiving12244// and let it happen12245if (!cellRefs.has(d)) continue;12246const refs = cellRefs.get(d);12247for (const ref of refs) if (!embed.has(ref)) todo.push(ref);12248}12249return {12250cells: module.cells.filter(12251cell => names(cell).filter(name => embed.has(name)).length12252)12253};12254}function ESMImports(moduleObject, resolveImportPath) {12255const importMap = new Map();12256let importSrc = "";12257let j = 0;1225812259for (const { body } of moduleObject.cells) {12260if (body.type !== "ImportDeclaration" || importMap.has(body.source.value))12261continue;1226212263const defineName = `define${++j}`;12264// TODO get cell specififiers here and pass in as 2nd param to resolveImportPath12265// need to use same logic as tree-shake name()s12266const specifiers = body.specifiers.map(d => {12267const prefix = d.view ? "viewof " : d.mutable ? "mutable " : "";12268return `${prefix}${d.imported.name}`;12269});12270const fromPath = resolveImportPath(body.source.value, specifiers);12271importMap.set(body.source.value, { defineName, fromPath });12272importSrc += `import ${defineName} from "${fromPath}";\n`;12273}1227412275if (importSrc.length) importSrc += "\n";12276return { importSrc, importMap };12277}1227812279// by default, file attachments get resolved like:12280// [ ["a", "https://example.com/files/a"] ]12281// but sometimes, you'll want to write JS code when resolving12282// instead of being limiting by strings. The third param12283// enables that, allowing for resolving like:12284// [ ["a", new URL("./files/a", import.meta.url)] ]12285function ESMAttachments(12286moduleObject,12287resolveFileAttachments,12288UNSAFE_allowJavascriptFileAttachments = false12289) {12290let mapValue;12291if (UNSAFE_allowJavascriptFileAttachments) {12292const attachmentMapEntries = [];12293for (const cell of moduleObject.cells) {12294if (cell.fileAttachments.size === 0) continue;12295for (const file of cell.fileAttachments.keys())12296attachmentMapEntries.push([file, resolveFileAttachments(file)]);12297}12298if (attachmentMapEntries.length)12299mapValue = `[${attachmentMapEntries12300.map(([key, value]) => `[${JSON.stringify(key)}, ${value}]`)12301.join(",")}]`;12302} else {12303const attachmentMapEntries = [];12304// loop over cells with fileAttachments12305for (const cell of moduleObject.cells) {12306if (cell.fileAttachments.size === 0) continue;12307// add filenames and resolved URLs to array12308for (const file of cell.fileAttachments.keys())12309attachmentMapEntries.push([file, resolveFileAttachments(file)]);12310}12311if (attachmentMapEntries.length)12312mapValue = JSON.stringify(attachmentMapEntries);12313}1231412315if (!mapValue) return "";12316return ` const fileAttachments = new Map(${mapValue});12317main.builtin("FileAttachment", runtime.fileAttachments(name => fileAttachments.get(name)));`;12318}1231912320function ESMVariables(moduleObject, importMap, params) {12321const {12322defineImportMarkdown,12323observeViewofValues,12324observeMutableValues12325} = params;1232612327let childJ = 0;12328return moduleObject.cells12329.map(cell => {12330let src = "";1233112332if (cell.body.type === "ImportDeclaration") {12333const {12334specifiers,12335hasInjections,12336injections,12337importString12338} = setupImportCell(cell);1233912340if (defineImportMarkdown)12341src +=12342` main.variable(observer()).define(12343null,12344["md"],12345md => md\`~~~javascript12346${importString}12347~~~\`12348);` + "\n";1234912350// name imported notebook define functions12351const childName = `child${++childJ}`;12352src += ` const ${childName} = runtime.module(${12353importMap.get(cell.body.source.value).defineName12354})${12355hasInjections ? `.derive(${JSON.stringify(injections)}, main)` : ""12356};12357${specifiers12358.map(12359specifier =>12360` main.import("${specifier.name}", "${specifier.alias}", ${childName});`12361)12362.join("\n")}`;12363} else {12364const {12365cellName,12366references,12367bodyText,12368cellReferences12369} = setupRegularCell(cell);1237012371const cellNameString = cellName ? `"${cellName}"` : "";12372const referenceString = references.join(",");12373let code = "";12374if (cell.body.type !== "BlockStatement")12375code = `{return(12376${bodyText}12377)}`;12378else code = "\n" + bodyText + "\n";12379const cellReferencesString = cellReferences.length12380? JSON.stringify(cellReferences) + ", "12381: "";12382let cellFunction = "";12383if (cell.generator && cell.async)12384cellFunction = `async function*(${referenceString})${code}`;12385else if (cell.async)12386cellFunction = `async function(${referenceString})${code}`;12387else if (cell.generator)12388cellFunction = `function*(${referenceString})${code}`;12389else cellFunction = `function(${referenceString})${code}`;1239012391if (cell.id && cell.id.type === "ViewExpression") {12392const reference = `"viewof ${cellName}"`;12393src += ` main.variable(observer(${reference})).define(${reference}, ${cellReferencesString}${cellFunction});12394main.variable(${12395observeViewofValues ? `observer("${cellName}")` : `null`12396}).define("${cellName}", ["Generators", ${reference}], (G, _) => G.input(_));`;12397} else if (cell.id && cell.id.type === "MutableExpression") {12398const initialName = `"initial ${cellName}"`;12399const mutableName = `"mutable ${cellName}"`;12400src += ` main.define(${initialName}, ${cellReferencesString}${cellFunction});12401main.variable(observer(${mutableName})).define(${mutableName}, ["Mutable", ${initialName}], (M, _) => new M(_));12402main.variable(${12403observeMutableValues ? `observer("${cellName}")` : `null`12404}).define("${cellName}", [${mutableName}], _ => _.generator);`;12405} else {12406src += ` main.variable(observer(${cellNameString})).define(${12407cellName ? cellNameString + ", " : ""12408}${cellReferencesString}${cellFunction});`;12409}12410}12411return src;12412})12413.join("\n");12414}12415function createESModule(moduleObject, params = {}) {12416const {12417resolveImportPath,12418resolveFileAttachments,12419defineImportMarkdown,12420observeViewofValues,12421observeMutableValues,12422UNSAFE_allowJavascriptFileAttachments12423} = params;12424const { importSrc, importMap } = ESMImports(moduleObject, resolveImportPath);12425return `${importSrc}export default function define(runtime, observer) {12426const main = runtime.module();12427${ESMAttachments(12428moduleObject,12429resolveFileAttachments,12430UNSAFE_allowJavascriptFileAttachments12431)}12432${ESMVariables(moduleObject, importMap, {12433defineImportMarkdown,12434observeViewofValues,12435observeMutableValues12436}) || ""}12437return main;12438}`;12439}1244012441function defaultResolveImportPath(path) {12442const source = extractPath(path);12443return `https://api.observablehq.com/${source}.js?v=3`;12444}1244512446function defaultResolveFileAttachments(name) {12447return name;12448}12449class Compiler {12450constructor(params = {}) {12451const {12452resolveFileAttachments = defaultResolveFileAttachments,12453resolveImportPath = defaultResolveImportPath,12454defineImportMarkdown = true,12455observeViewofValues = true,12456observeMutableValues = true,12457UNSAFE_allowJavascriptFileAttachments = false12458} = params;12459this.resolveFileAttachments = resolveFileAttachments;12460this.resolveImportPath = resolveImportPath;12461this.defineImportMarkdown = defineImportMarkdown;12462this.observeViewofValues = observeViewofValues;12463this.observeMutableValues = observeMutableValues;12464this.UNSAFE_allowJavascriptFileAttachments = UNSAFE_allowJavascriptFileAttachments;12465}12466module(input, params = {}) {12467let m1 = typeof input === "string" ? parseModule(input) : input;1246812469if (params.treeShake) m1 = treeShakeModule(m1, params.treeShake);1247012471return createESModule(m1, {12472resolveImportPath: this.resolveImportPath,12473resolveFileAttachments: this.resolveFileAttachments,12474defineImportMarkdown: this.defineImportMarkdown,12475observeViewofValues: this.observeViewofValues,12476observeMutableValues: this.observeMutableValues,12477UNSAFE_allowJavascriptFileAttachments: this12478.UNSAFE_allowJavascriptFileAttachments12479});12480}12481notebook(obj) {12482const cells = obj.nodes.map(({ value }) => {12483const cell = parseCell(value);12484cell.input = value;12485return cell;12486});12487return createESModule(12488{ cells },12489{12490resolveImportPath: this.resolveImportPath,12491resolveFileAttachments: this.resolveFileAttachments,12492defineImportMarkdown: this.defineImportMarkdown,12493observeViewofValues: this.observeViewofValues,12494observeMutableValues: this.observeMutableValues12495}12496);12497}12498}const AsyncFunction = Object.getPrototypeOf(async function() {}).constructor;12499const GeneratorFunction = Object.getPrototypeOf(function*() {}).constructor;12500const AsyncGeneratorFunction = Object.getPrototypeOf(async function*() {})12501.constructor;1250212503function createRegularCellDefinition(cell) {12504const { cellName, references, bodyText, cellReferences } = setupRegularCell(12505cell12506);1250712508let code;12509if (cell.body.type !== "BlockStatement") {12510if (cell.async)12511code = `return (async function(){ return (${bodyText});})()`;12512else code = `return (function(){ return (${bodyText});})()`;12513} else code = bodyText;1251412515let f;12516if (cell.generator && cell.async)12517f = new AsyncGeneratorFunction(...references, code);12518else if (cell.async) f = new AsyncFunction(...references, code);12519else if (cell.generator) f = new GeneratorFunction(...references, code);12520else f = new Function(...references, code);12521return {12522cellName,12523cellFunction: f,12524cellReferences12525};12526}1252712528function defaultResolveImportPath$1(path) {12529const source = extractPath(path);12530return import(`https://api.observablehq.com/${source}.js?v=3`).then(12531m => m.default12532);12533}1253412535function defaultResolveFileAttachments$1(name) {12536return name;12537}1253812539class Interpreter {12540constructor(params = {}) {12541const {12542module = null,12543observer = null,12544resolveImportPath = defaultResolveImportPath$1,12545resolveFileAttachments = defaultResolveFileAttachments$1,12546defineImportMarkdown = true,12547observeViewofValues = true,12548observeMutableValues = true12549} = params;1255012551// can't be this.module bc of async module().12552// so make defaultObserver follow same convention.12553this.defaultModule = module;12554this.defaultObserver = observer;1255512556this.resolveImportPath = resolveImportPath;12557this.resolveFileAttachments = resolveFileAttachments;12558this.defineImportMarkdown = defineImportMarkdown;12559this.observeViewofValues = observeViewofValues;12560this.observeMutableValues = observeMutableValues;12561}1256212563async module(input, module, observer) {12564module = module || this.defaultModule;12565observer = observer || this.defaultObserver;1256612567if (!module) throw Error("No module provided.");12568if (!observer) throw Error("No observer provided.");1256912570const parsedModule = parseModule(input);12571const cellPromises = [];12572for (const cell of parsedModule.cells) {12573cell.input = input;12574cellPromises.push(this.cell(cell, module, observer));12575}12576return Promise.all(cellPromises);12577}1257812579async cell(input, module, observer) {12580module = module || this.defaultModule;12581observer = observer || this.defaultObserver;1258212583if (!module) throw Error("No module provided.");12584if (!observer) throw Error("No observer provided.");1258512586let cell;12587if (typeof input === "string") {12588cell = parseCell(input);12589cell.input = input;12590} else {12591cell = input;12592}1259312594if (cell.body.type === "ImportDeclaration") {12595const path = cell.body.source.value;12596const specs = cell.body.specifiers.map(d => {12597const prefix = d.view ? "viewof " : d.mutable ? "mutable " : "";12598return `${prefix}${d.imported.name}`;12599});12600const fromModule = await this.resolveImportPath(path, specs);12601let mdVariable, vars;1260212603const {12604specifiers,12605hasInjections,12606injections,12607importString12608} = setupImportCell(cell);1260912610const other = module._runtime.module(fromModule);1261112612if (this.defineImportMarkdown)12613mdVariable = module.variable(observer()).define(12614null,12615["md"],12616md => md`~~~javascript12617${importString}12618~~~`12619);12620if (hasInjections) {12621const child = other.derive(injections, module);12622vars = specifiers.map(({ name, alias }) =>12623module.import(name, alias, child)12624);12625} else {12626vars = specifiers.map(({ name, alias }) =>12627module.import(name, alias, other)12628);12629}12630return mdVariable ? [mdVariable, ...vars] : vars;12631} else {12632const {12633cellName,12634cellFunction,12635cellReferences12636} = createRegularCellDefinition(cell);12637if (cell.id && cell.id.type === "ViewExpression") {12638const reference = `viewof ${cellName}`;12639return [12640module12641.variable(observer(reference))12642.define(reference, cellReferences, cellFunction.bind(this)),12643module12644.variable(this.observeViewofValues ? observer(cellName) : null)12645.define(cellName, ["Generators", reference], (G, _) => G.input(_))12646];12647} else if (cell.id && cell.id.type === "MutableExpression") {12648const initialName = `initial ${cellName}`;12649const mutableName = `mutable ${cellName}`;12650return [12651module12652.variable(null)12653.define(initialName, cellReferences, cellFunction),12654module12655.variable(observer(mutableName))12656.define(mutableName, ["Mutable", initialName], (M, _) => new M(_)),12657module12658.variable(this.observeMutableValues ? observer(cellName) : null)12659.define(cellName, [mutableName], _ => _.generator)12660];12661} else {12662return [12663module12664.variable(observer(cellName))12665.define(cellName, cellReferences, cellFunction.bind(this))12666];12667}12668}12669}12670}exports.Compiler=Compiler;exports.Interpreter=Interpreter;exports.parser=index;exports.treeShakeModule=treeShakeModule;Object.defineProperty(exports,'__esModule',{value:true});})));12671} (dist, dist.exports));1267212673// This file was generated. Do not modify manually!12674var 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, 154, 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, 161, 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, 19306, 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, 262, 6, 10, 9, 357, 0, 62, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];1267512676// This file was generated. Do not modify manually!12677var 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, 85, 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, 190, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1070, 4050, 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, 46, 2, 18, 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, 482, 44, 11, 6, 17, 0, 322, 29, 19, 43, 1269, 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, 4152, 8, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938];1267812679// This file was generated. Do not modify manually!12680var 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\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-\u0ecd\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";1268112682// This file was generated. Do not modify manually!12683var 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";1268412685// These are a run-length and offset encoded representation of the1268612687// Reserved word lists for various dialects of the language1268812689var reservedWords = {126903: "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",126915: "class enum extends super const export import",126926: "enum",12693strict: "implements interface let package private protected public static yield",12694strictBind: "eval arguments"12695};1269612697// And the keywords1269812699var 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";1270012701var keywords$1 = {127025: ecma5AndLessKeywords,12703"5module": ecma5AndLessKeywords + " export import",127046: ecma5AndLessKeywords + " const class extends export import super"12705};1270612707var keywordRelationalOperator = /^in(stanceof)?$/;1270812709// ## Character categories1271012711var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");12712var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");1271312714// This has a complexity linear to the value of the code. The12715// assumption is that looking up astral identifier characters is12716// rare.12717function isInAstralSet(code, set) {12718var pos = 0x10000;12719for (var i = 0; i < set.length; i += 2) {12720pos += set[i];12721if (pos > code) { return false }12722pos += set[i + 1];12723if (pos >= code) { return true }12724}12725}1272612727// Test whether a given character code starts an identifier.1272812729function isIdentifierStart(code, astral) {12730if (code < 65) { return code === 36 }12731if (code < 91) { return true }12732if (code < 97) { return code === 95 }12733if (code < 123) { return true }12734if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }12735if (astral === false) { return false }12736return isInAstralSet(code, astralIdentifierStartCodes)12737}1273812739// Test whether a given character is part of an identifier.1274012741function isIdentifierChar(code, astral) {12742if (code < 48) { return code === 36 }12743if (code < 58) { return true }12744if (code < 65) { return false }12745if (code < 91) { return true }12746if (code < 97) { return code === 95 }12747if (code < 123) { return true }12748if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }12749if (astral === false) { return false }12750return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)12751}1275212753// ## Token types1275412755// The assignment of fine-grained, information-carrying type objects12756// allows the tokenizer to store the information it has about a12757// token in a way that is very cheap for the parser to look up.1275812759// All token type variables start with an underscore, to make them12760// easy to recognize.1276112762// The `beforeExpr` property is used to disambiguate between regular12763// expressions and divisions. It is set on all token types that can12764// be followed by an expression (thus, a slash after them would be a12765// regular expression).12766//12767// The `startsExpr` property is used to check if the token ends a12768// `yield` expression. It is set on all token types that either can12769// directly start an expression (like a quotation mark) or can12770// continue an expression (like the body of a string).12771//12772// `isLoop` marks a keyword as starting a loop, which is important12773// to know when parsing a label, in order to allow or disallow12774// continue jumps to that label.1277512776var TokenType = function TokenType(label, conf) {12777if ( conf === void 0 ) conf = {};1277812779this.label = label;12780this.keyword = conf.keyword;12781this.beforeExpr = !!conf.beforeExpr;12782this.startsExpr = !!conf.startsExpr;12783this.isLoop = !!conf.isLoop;12784this.isAssign = !!conf.isAssign;12785this.prefix = !!conf.prefix;12786this.postfix = !!conf.postfix;12787this.binop = conf.binop || null;12788this.updateContext = null;12789};1279012791function binop(name, prec) {12792return new TokenType(name, {beforeExpr: true, binop: prec})12793}12794var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};1279512796// Map keyword names to token types.1279712798var keywords = {};1279912800// Succinct definitions of keyword token types12801function kw(name, options) {12802if ( options === void 0 ) options = {};1280312804options.keyword = name;12805return keywords[name] = new TokenType(name, options)12806}1280712808var types$1 = {12809num: new TokenType("num", startsExpr),12810regexp: new TokenType("regexp", startsExpr),12811string: new TokenType("string", startsExpr),12812name: new TokenType("name", startsExpr),12813privateId: new TokenType("privateId", startsExpr),12814eof: new TokenType("eof"),1281512816// Punctuation token types.12817bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),12818bracketR: new TokenType("]"),12819braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),12820braceR: new TokenType("}"),12821parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),12822parenR: new TokenType(")"),12823comma: new TokenType(",", beforeExpr),12824semi: new TokenType(";", beforeExpr),12825colon: new TokenType(":", beforeExpr),12826dot: new TokenType("."),12827question: new TokenType("?", beforeExpr),12828questionDot: new TokenType("?."),12829arrow: new TokenType("=>", beforeExpr),12830template: new TokenType("template"),12831invalidTemplate: new TokenType("invalidTemplate"),12832ellipsis: new TokenType("...", beforeExpr),12833backQuote: new TokenType("`", startsExpr),12834dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),1283512836// Operators. These carry several kinds of properties to help the12837// parser use them properly (the presence of these properties is12838// what categorizes them as operators).12839//12840// `binop`, when present, specifies that this operator is a binary12841// operator, and will refer to its precedence.12842//12843// `prefix` and `postfix` mark the operator as a prefix or postfix12844// unary operator.12845//12846// `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as12847// binary operators with a very low precedence, that should result12848// in AssignmentExpression nodes.1284912850eq: new TokenType("=", {beforeExpr: true, isAssign: true}),12851assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),12852incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),12853prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),12854logicalOR: binop("||", 1),12855logicalAND: binop("&&", 2),12856bitwiseOR: binop("|", 3),12857bitwiseXOR: binop("^", 4),12858bitwiseAND: binop("&", 5),12859equality: binop("==/!=/===/!==", 6),12860relational: binop("</>/<=/>=", 7),12861bitShift: binop("<</>>/>>>", 8),12862plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),12863modulo: binop("%", 10),12864star: binop("*", 10),12865slash: binop("/", 10),12866starstar: new TokenType("**", {beforeExpr: true}),12867coalesce: binop("??", 1),1286812869// Keyword token types.12870_break: kw("break"),12871_case: kw("case", beforeExpr),12872_catch: kw("catch"),12873_continue: kw("continue"),12874_debugger: kw("debugger"),12875_default: kw("default", beforeExpr),12876_do: kw("do", {isLoop: true, beforeExpr: true}),12877_else: kw("else", beforeExpr),12878_finally: kw("finally"),12879_for: kw("for", {isLoop: true}),12880_function: kw("function", startsExpr),12881_if: kw("if"),12882_return: kw("return", beforeExpr),12883_switch: kw("switch"),12884_throw: kw("throw", beforeExpr),12885_try: kw("try"),12886_var: kw("var"),12887_const: kw("const"),12888_while: kw("while", {isLoop: true}),12889_with: kw("with"),12890_new: kw("new", {beforeExpr: true, startsExpr: true}),12891_this: kw("this", startsExpr),12892_super: kw("super", startsExpr),12893_class: kw("class", startsExpr),12894_extends: kw("extends", beforeExpr),12895_export: kw("export"),12896_import: kw("import", startsExpr),12897_null: kw("null", startsExpr),12898_true: kw("true", startsExpr),12899_false: kw("false", startsExpr),12900_in: kw("in", {beforeExpr: true, binop: 7}),12901_instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),12902_typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),12903_void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),12904_delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})12905};1290612907// Matches a whole line break (where CRLF is considered a single12908// line break). Used to count lines.1290912910var lineBreak = /\r\n?|\n|\u2028|\u2029/;12911var lineBreakG = new RegExp(lineBreak.source, "g");1291212913function isNewLine(code) {12914return code === 10 || code === 13 || code === 0x2028 || code === 0x202912915}1291612917function nextLineBreak(code, from, end) {12918if ( end === void 0 ) end = code.length;1291912920for (var i = from; i < end; i++) {12921var next = code.charCodeAt(i);12922if (isNewLine(next))12923{ return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 }12924}12925return -112926}1292712928var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;1292912930var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;1293112932var ref = Object.prototype;12933var hasOwnProperty = ref.hasOwnProperty;12934var toString = ref.toString;1293512936var hasOwn = Object.hasOwn || (function (obj, propName) { return (12937hasOwnProperty.call(obj, propName)12938); });1293912940var isArray = Array.isArray || (function (obj) { return (12941toString.call(obj) === "[object Array]"12942); });1294312944function wordsRegexp(words) {12945return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")12946}1294712948function codePointToString(code) {12949// UTF-16 Decoding12950if (code <= 0xFFFF) { return String.fromCharCode(code) }12951code -= 0x10000;12952return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)12953}1295412955var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;1295612957// These are used when `options.locations` is on, for the12958// `startLoc` and `endLoc` properties.1295912960var Position = function Position(line, col) {12961this.line = line;12962this.column = col;12963};1296412965Position.prototype.offset = function offset (n) {12966return new Position(this.line, this.column + n)12967};1296812969var SourceLocation = function SourceLocation(p, start, end) {12970this.start = start;12971this.end = end;12972if (p.sourceFile !== null) { this.source = p.sourceFile; }12973};1297412975// The `getLineInfo` function is mostly useful when the12976// `locations` option is off (for performance reasons) and you12977// want to find the line/column position for a given character12978// offset. `input` should be the code string that the offset refers12979// into.1298012981function getLineInfo(input, offset) {12982for (var line = 1, cur = 0;;) {12983var nextBreak = nextLineBreak(input, cur, offset);12984if (nextBreak < 0) { return new Position(line, offset - cur) }12985++line;12986cur = nextBreak;12987}12988}1298912990// A second argument must be given to configure the parser process.12991// These options are recognized (only `ecmaVersion` is required):1299212993var defaultOptions = {12994// `ecmaVersion` indicates the ECMAScript version to parse. Must be12995// either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 1012996// (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"`12997// (the latest version the library supports). This influences12998// support for strict mode, the set of reserved words, and support12999// for new syntax features.13000ecmaVersion: null,13001// `sourceType` indicates the mode the code should be parsed in.13002// Can be either `"script"` or `"module"`. This influences global13003// strict mode and parsing of `import` and `export` declarations.13004sourceType: "script",13005// `onInsertedSemicolon` can be a callback that will be called13006// when a semicolon is automatically inserted. It will be passed13007// the position of the comma as an offset, and if `locations` is13008// enabled, it is given the location as a `{line, column}` object13009// as second argument.13010onInsertedSemicolon: null,13011// `onTrailingComma` is similar to `onInsertedSemicolon`, but for13012// trailing commas.13013onTrailingComma: null,13014// By default, reserved words are only enforced if ecmaVersion >= 5.13015// Set `allowReserved` to a boolean value to explicitly turn this on13016// an off. When this option has the value "never", reserved words13017// and keywords can also not be used as property names.13018allowReserved: null,13019// When enabled, a return at the top level is not considered an13020// error.13021allowReturnOutsideFunction: false,13022// When enabled, import/export statements are not constrained to13023// appearing at the top of the program, and an import.meta expression13024// in a script isn't considered an error.13025allowImportExportEverywhere: false,13026// By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.13027// When enabled, await identifiers are allowed to appear at the top-level scope,13028// but they are still not allowed in non-async functions.13029allowAwaitOutsideFunction: null,13030// When enabled, super identifiers are not constrained to13031// appearing in methods and do not raise an error when they appear elsewhere.13032allowSuperOutsideMethod: null,13033// When enabled, hashbang directive in the beginning of file is13034// allowed and treated as a line comment. Enabled by default when13035// `ecmaVersion` >= 2023.13036allowHashBang: false,13037// When `locations` is on, `loc` properties holding objects with13038// `start` and `end` properties in `{line, column}` form (with13039// line being 1-based and column 0-based) will be attached to the13040// nodes.13041locations: false,13042// A function can be passed as `onToken` option, which will13043// cause Acorn to call that function with object in the same13044// format as tokens returned from `tokenizer().getToken()`. Note13045// that you are not allowed to call the parser from the13046// callback—that will corrupt its internal state.13047onToken: null,13048// A function can be passed as `onComment` option, which will13049// cause Acorn to call that function with `(block, text, start,13050// end)` parameters whenever a comment is skipped. `block` is a13051// boolean indicating whether this is a block (`/* */`) comment,13052// `text` is the content of the comment, and `start` and `end` are13053// character offsets that denote the start and end of the comment.13054// When the `locations` option is on, two more parameters are13055// passed, the full `{line, column}` locations of the start and13056// end of the comments. Note that you are not allowed to call the13057// parser from the callback—that will corrupt its internal state.13058onComment: null,13059// Nodes have their start and end characters offsets recorded in13060// `start` and `end` properties (directly on the node, rather than13061// the `loc` object, which holds line/column data. To also add a13062// [semi-standardized][range] `range` property holding a `[start,13063// end]` array with the same numbers, set the `ranges` option to13064// `true`.13065//13066// [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=74567813067ranges: false,13068// It is possible to parse multiple files into a single AST by13069// passing the tree produced by parsing the first file as13070// `program` option in subsequent parses. This will add the13071// toplevel forms of the parsed file to the `Program` (top) node13072// of an existing parse tree.13073program: null,13074// When `locations` is on, you can pass this to record the source13075// file in every node's `loc` object.13076sourceFile: null,13077// This value, if given, is stored in every node, whether13078// `locations` is on or off.13079directSourceFile: null,13080// When enabled, parenthesized expressions are represented by13081// (non-standard) ParenthesizedExpression nodes13082preserveParens: false13083};1308413085// Interpret and default an options object1308613087var warnedAboutEcmaVersion = false;1308813089function getOptions(opts) {13090var options = {};1309113092for (var opt in defaultOptions)13093{ options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; }1309413095if (options.ecmaVersion === "latest") {13096options.ecmaVersion = 1e8;13097} else if (options.ecmaVersion == null) {13098if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {13099warnedAboutEcmaVersion = true;13100console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");13101}13102options.ecmaVersion = 11;13103} else if (options.ecmaVersion >= 2015) {13104options.ecmaVersion -= 2009;13105}1310613107if (options.allowReserved == null)13108{ options.allowReserved = options.ecmaVersion < 5; }1310913110if (opts.allowHashBang == null)13111{ options.allowHashBang = options.ecmaVersion >= 14; }1311213113if (isArray(options.onToken)) {13114var tokens = options.onToken;13115options.onToken = function (token) { return tokens.push(token); };13116}13117if (isArray(options.onComment))13118{ options.onComment = pushComment(options, options.onComment); }1311913120return options13121}1312213123function pushComment(options, array) {13124return function(block, text, start, end, startLoc, endLoc) {13125var comment = {13126type: block ? "Block" : "Line",13127value: text,13128start: start,13129end: end13130};13131if (options.locations)13132{ comment.loc = new SourceLocation(this, startLoc, endLoc); }13133if (options.ranges)13134{ comment.range = [start, end]; }13135array.push(comment);13136}13137}1313813139// Each scope gets a bitset that may contain these flags13140var13141SCOPE_TOP = 1,13142SCOPE_FUNCTION$1 = 2,13143SCOPE_ASYNC$1 = 4,13144SCOPE_GENERATOR$1 = 8,13145SCOPE_ARROW = 16,13146SCOPE_SIMPLE_CATCH = 32,13147SCOPE_SUPER = 64,13148SCOPE_DIRECT_SUPER = 128,13149SCOPE_CLASS_STATIC_BLOCK = 256,13150SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION$1 | SCOPE_CLASS_STATIC_BLOCK;1315113152function functionFlags(async, generator) {13153return SCOPE_FUNCTION$1 | (async ? SCOPE_ASYNC$1 : 0) | (generator ? SCOPE_GENERATOR$1 : 0)13154}1315513156// Used in checkLVal* and declareName to determine the type of a binding13157var13158BIND_NONE = 0, // Not a binding13159BIND_VAR = 1, // Var-style binding13160BIND_LEXICAL = 2, // Let- or const-style binding13161BIND_FUNCTION = 3, // Function declaration13162BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding13163BIND_OUTSIDE = 5; // Special case for function names as bound inside the function1316413165var Parser = function Parser(options, input, startPos) {13166this.options = options = getOptions(options);13167this.sourceFile = options.sourceFile;13168this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);13169var reserved = "";13170if (options.allowReserved !== true) {13171reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];13172if (options.sourceType === "module") { reserved += " await"; }13173}13174this.reservedWords = wordsRegexp(reserved);13175var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;13176this.reservedWordsStrict = wordsRegexp(reservedStrict);13177this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);13178this.input = String(input);1317913180// Used to signal to callers of `readWord1` whether the word13181// contained any escape sequences. This is needed because words with13182// escape sequences must not be interpreted as keywords.13183this.containsEsc = false;1318413185// Set up token state1318613187// The current position of the tokenizer in the input.13188if (startPos) {13189this.pos = startPos;13190this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;13191this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;13192} else {13193this.pos = this.lineStart = 0;13194this.curLine = 1;13195}1319613197// Properties of the current token:13198// Its type13199this.type = types$1.eof;13200// For tokens that include more information than their type, the value13201this.value = null;13202// Its start and end offset13203this.start = this.end = this.pos;13204// And, if locations are used, the {line, column} object13205// corresponding to those offsets13206this.startLoc = this.endLoc = this.curPosition();1320713208// Position information for the previous token13209this.lastTokEndLoc = this.lastTokStartLoc = null;13210this.lastTokStart = this.lastTokEnd = this.pos;1321113212// The context stack is used to superficially track syntactic13213// context to predict whether a regular expression is allowed in a13214// given position.13215this.context = this.initialContext();13216this.exprAllowed = true;1321713218// Figure out if it's a module code.13219this.inModule = options.sourceType === "module";13220this.strict = this.inModule || this.strictDirective(this.pos);1322113222// Used to signify the start of a potential arrow function13223this.potentialArrowAt = -1;13224this.potentialArrowInForAwait = false;1322513226// Positions to delayed-check that yield/await does not exist in default parameters.13227this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;13228// Labels in scope.13229this.labels = [];13230// Thus-far undefined exports.13231this.undefinedExports = Object.create(null);1323213233// If enabled, skip leading hashbang line.13234if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")13235{ this.skipLineComment(2); }1323613237// Scope tracking for duplicate variable names (see scope.js)13238this.scopeStack = [];13239this.enterScope(SCOPE_TOP);1324013241// For RegExp validation13242this.regexpState = null;1324313244// The stack of private names.13245// Each element has two properties: 'declared' and 'used'.13246// When it exited from the outermost class definition, all used private names must be declared.13247this.privateNameStack = [];13248};1324913250var 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 } };1325113252Parser.prototype.parse = function parse () {13253var node = this.options.program || this.startNode();13254this.nextToken();13255return this.parseTopLevel(node)13256};1325713258prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION$1) > 0 };1325913260prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR$1) > 0 && !this.currentVarScope().inClassFieldInit };1326113262prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC$1) > 0 && !this.currentVarScope().inClassFieldInit };1326313264prototypeAccessors.canAwait.get = function () {13265for (var i = this.scopeStack.length - 1; i >= 0; i--) {13266var scope = this.scopeStack[i];13267if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false }13268if (scope.flags & SCOPE_FUNCTION$1) { return (scope.flags & SCOPE_ASYNC$1) > 0 }13269}13270return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction13271};1327213273prototypeAccessors.allowSuper.get = function () {13274var ref = this.currentThisScope();13275var flags = ref.flags;13276var inClassFieldInit = ref.inClassFieldInit;13277return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod13278};1327913280prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };1328113282prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };1328313284prototypeAccessors.allowNewDotTarget.get = function () {13285var ref = this.currentThisScope();13286var flags = ref.flags;13287var inClassFieldInit = ref.inClassFieldInit;13288return (flags & (SCOPE_FUNCTION$1 | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit13289};1329013291prototypeAccessors.inClassStaticBlock.get = function () {13292return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 013293};1329413295Parser.extend = function extend () {13296var plugins = [], len = arguments.length;13297while ( len-- ) plugins[ len ] = arguments[ len ];1329813299var cls = this;13300for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }13301return cls13302};1330313304Parser.parse = function parse (input, options) {13305return new this(options, input).parse()13306};1330713308Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {13309var parser = new this(options, input, pos);13310parser.nextToken();13311return parser.parseExpression()13312};1331313314Parser.tokenizer = function tokenizer (input, options) {13315return new this(options, input)13316};1331713318Object.defineProperties( Parser.prototype, prototypeAccessors );1331913320var pp$9 = Parser.prototype;1332113322// ## Parser utilities1332313324var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;13325pp$9.strictDirective = function(start) {13326if (this.options.ecmaVersion < 5) { return false }13327for (;;) {13328// Try to find string literal.13329skipWhiteSpace.lastIndex = start;13330start += skipWhiteSpace.exec(this.input)[0].length;13331var match = literal.exec(this.input.slice(start));13332if (!match) { return false }13333if ((match[1] || match[2]) === "use strict") {13334skipWhiteSpace.lastIndex = start + match[0].length;13335var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;13336var next = this.input.charAt(end);13337return next === ";" || next === "}" ||13338(lineBreak.test(spaceAfter[0]) &&13339!(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))13340}13341start += match[0].length;1334213343// Skip semicolon, if any.13344skipWhiteSpace.lastIndex = start;13345start += skipWhiteSpace.exec(this.input)[0].length;13346if (this.input[start] === ";")13347{ start++; }13348}13349};1335013351// Predicate that tests whether the next token is of the given13352// type, and if yes, consumes it as a side effect.1335313354pp$9.eat = function(type) {13355if (this.type === type) {13356this.next();13357return true13358} else {13359return false13360}13361};1336213363// Tests whether parsed token is a contextual keyword.1336413365pp$9.isContextual = function(name) {13366return this.type === types$1.name && this.value === name && !this.containsEsc13367};1336813369// Consumes contextual keyword if possible.1337013371pp$9.eatContextual = function(name) {13372if (!this.isContextual(name)) { return false }13373this.next();13374return true13375};1337613377// Asserts that following token is given contextual keyword.1337813379pp$9.expectContextual = function(name) {13380if (!this.eatContextual(name)) { this.unexpected(); }13381};1338213383// Test whether a semicolon can be inserted at the current position.1338413385pp$9.canInsertSemicolon = function() {13386return this.type === types$1.eof ||13387this.type === types$1.braceR ||13388lineBreak.test(this.input.slice(this.lastTokEnd, this.start))13389};1339013391pp$9.insertSemicolon = function() {13392if (this.canInsertSemicolon()) {13393if (this.options.onInsertedSemicolon)13394{ this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }13395return true13396}13397};1339813399// Consume a semicolon, or, failing that, see if we are allowed to13400// pretend that there is a semicolon at this position.1340113402pp$9.semicolon = function() {13403if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); }13404};1340513406pp$9.afterTrailingComma = function(tokType, notNext) {13407if (this.type === tokType) {13408if (this.options.onTrailingComma)13409{ this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }13410if (!notNext)13411{ this.next(); }13412return true13413}13414};1341513416// Expect a token of a given type. If found, consume it, otherwise,13417// raise an unexpected token error.1341813419pp$9.expect = function(type) {13420this.eat(type) || this.unexpected();13421};1342213423// Raise an unexpected token error.1342413425pp$9.unexpected = function(pos) {13426this.raise(pos != null ? pos : this.start, "Unexpected token");13427};1342813429var DestructuringErrors = function DestructuringErrors() {13430this.shorthandAssign =13431this.trailingComma =13432this.parenthesizedAssign =13433this.parenthesizedBind =13434this.doubleProto =13435-1;13436};1343713438pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {13439if (!refDestructuringErrors) { return }13440if (refDestructuringErrors.trailingComma > -1)13441{ this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }13442var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;13443if (parens > -1) { this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); }13444};1344513446pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {13447if (!refDestructuringErrors) { return false }13448var shorthandAssign = refDestructuringErrors.shorthandAssign;13449var doubleProto = refDestructuringErrors.doubleProto;13450if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }13451if (shorthandAssign >= 0)13452{ this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }13453if (doubleProto >= 0)13454{ this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }13455};1345613457pp$9.checkYieldAwaitInDefaultParams = function() {13458if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))13459{ this.raise(this.yieldPos, "Yield expression cannot be a default value"); }13460if (this.awaitPos)13461{ this.raise(this.awaitPos, "Await expression cannot be a default value"); }13462};1346313464pp$9.isSimpleAssignTarget = function(expr) {13465if (expr.type === "ParenthesizedExpression")13466{ return this.isSimpleAssignTarget(expr.expression) }13467return expr.type === "Identifier" || expr.type === "MemberExpression"13468};1346913470var pp$8 = Parser.prototype;1347113472// ### Statement parsing1347313474// Parse a program. Initializes the parser, reads any number of13475// statements, and wraps them in a Program node. Optionally takes a13476// `program` argument. If present, the statements will be appended13477// to its body instead of creating a new node.1347813479pp$8.parseTopLevel = function(node) {13480var exports = Object.create(null);13481if (!node.body) { node.body = []; }13482while (this.type !== types$1.eof) {13483var stmt = this.parseStatement(null, true, exports);13484node.body.push(stmt);13485}13486if (this.inModule)13487{ for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)13488{13489var name = list[i];1349013491this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));13492} }13493this.adaptDirectivePrologue(node.body);13494this.next();13495node.sourceType = this.options.sourceType;13496return this.finishNode(node, "Program")13497};1349813499var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};1350013501pp$8.isLet = function(context) {13502if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }13503skipWhiteSpace.lastIndex = this.pos;13504var skip = skipWhiteSpace.exec(this.input);13505var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);13506// For ambiguous cases, determine if a LexicalDeclaration (or only a13507// Statement) is allowed here. If context is not empty then only a Statement13508// is allowed. However, `let [` is an explicit negative lookahead for13509// ExpressionStatement, so special-case it first.13510if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral13511if (context) { return false }1351213513if (nextCh === 123) { return true } // '{'13514if (isIdentifierStart(nextCh, true)) {13515var pos = next + 1;13516while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }13517if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }13518var ident = this.input.slice(next, pos);13519if (!keywordRelationalOperator.test(ident)) { return true }13520}13521return false13522};1352313524// check 'async [no LineTerminator here] function'13525// - 'async /*foo*/ function' is OK.13526// - 'async /*\n*/ function' is invalid.13527pp$8.isAsyncFunction = function() {13528if (this.options.ecmaVersion < 8 || !this.isContextual("async"))13529{ return false }1353013531skipWhiteSpace.lastIndex = this.pos;13532var skip = skipWhiteSpace.exec(this.input);13533var next = this.pos + skip[0].length, after;13534return !lineBreak.test(this.input.slice(this.pos, next)) &&13535this.input.slice(next, next + 8) === "function" &&13536(next + 8 === this.input.length ||13537!(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))13538};1353913540// Parse a single statement.13541//13542// If expecting a statement and finding a slash operator, parse a13543// regular expression literal. This is to handle cases like13544// `if (foo) /blah/.exec(foo)`, where looking at the previous token13545// does not help.1354613547pp$8.parseStatement = function(context, topLevel, exports) {13548var starttype = this.type, node = this.startNode(), kind;1354913550if (this.isLet(context)) {13551starttype = types$1._var;13552kind = "let";13553}1355413555// Most types of statements are recognized by the keyword they13556// start with. Many are trivial to parse, some require a bit of13557// complexity.1355813559switch (starttype) {13560case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword)13561case types$1._debugger: return this.parseDebuggerStatement(node)13562case types$1._do: return this.parseDoStatement(node)13563case types$1._for: return this.parseForStatement(node)13564case types$1._function:13565// Function as sole body of either an if statement or a labeled statement13566// works, but not when it is part of a labeled statement that is the sole13567// body of an if statement.13568if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }13569return this.parseFunctionStatement(node, false, !context)13570case types$1._class:13571if (context) { this.unexpected(); }13572return this.parseClass(node, true)13573case types$1._if: return this.parseIfStatement(node)13574case types$1._return: return this.parseReturnStatement(node)13575case types$1._switch: return this.parseSwitchStatement(node)13576case types$1._throw: return this.parseThrowStatement(node)13577case types$1._try: return this.parseTryStatement(node)13578case types$1._const: case types$1._var:13579kind = kind || this.value;13580if (context && kind !== "var") { this.unexpected(); }13581return this.parseVarStatement(node, kind)13582case types$1._while: return this.parseWhileStatement(node)13583case types$1._with: return this.parseWithStatement(node)13584case types$1.braceL: return this.parseBlock(true, node)13585case types$1.semi: return this.parseEmptyStatement(node)13586case types$1._export:13587case types$1._import:13588if (this.options.ecmaVersion > 10 && starttype === types$1._import) {13589skipWhiteSpace.lastIndex = this.pos;13590var skip = skipWhiteSpace.exec(this.input);13591var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);13592if (nextCh === 40 || nextCh === 46) // '(' or '.'13593{ return this.parseExpressionStatement(node, this.parseExpression()) }13594}1359513596if (!this.options.allowImportExportEverywhere) {13597if (!topLevel)13598{ this.raise(this.start, "'import' and 'export' may only appear at the top level"); }13599if (!this.inModule)13600{ this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }13601}13602return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports)1360313604// If the statement does not start with a statement keyword or a13605// brace, it's an ExpressionStatement or LabeledStatement. We13606// simply start parsing an expression, and afterwards, if the13607// next token is a colon and the expression was a simple13608// Identifier node, we switch to interpreting it as a label.13609default:13610if (this.isAsyncFunction()) {13611if (context) { this.unexpected(); }13612this.next();13613return this.parseFunctionStatement(node, true, !context)13614}1361513616var maybeName = this.value, expr = this.parseExpression();13617if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon))13618{ return this.parseLabeledStatement(node, maybeName, expr, context) }13619else { return this.parseExpressionStatement(node, expr) }13620}13621};1362213623pp$8.parseBreakContinueStatement = function(node, keyword) {13624var isBreak = keyword === "break";13625this.next();13626if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; }13627else if (this.type !== types$1.name) { this.unexpected(); }13628else {13629node.label = this.parseIdent();13630this.semicolon();13631}1363213633// Verify that there is an actual destination to break or13634// continue to.13635var i = 0;13636for (; i < this.labels.length; ++i) {13637var lab = this.labels[i];13638if (node.label == null || lab.name === node.label.name) {13639if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }13640if (node.label && isBreak) { break }13641}13642}13643if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }13644return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")13645};1364613647pp$8.parseDebuggerStatement = function(node) {13648this.next();13649this.semicolon();13650return this.finishNode(node, "DebuggerStatement")13651};1365213653pp$8.parseDoStatement = function(node) {13654this.next();13655this.labels.push(loopLabel);13656node.body = this.parseStatement("do");13657this.labels.pop();13658this.expect(types$1._while);13659node.test = this.parseParenExpression();13660if (this.options.ecmaVersion >= 6)13661{ this.eat(types$1.semi); }13662else13663{ this.semicolon(); }13664return this.finishNode(node, "DoWhileStatement")13665};1366613667// Disambiguating between a `for` and a `for`/`in` or `for`/`of`13668// loop is non-trivial. Basically, we have to parse the init `var`13669// statement or expression, disallowing the `in` operator (see13670// the second parameter to `parseExpression`), and then check13671// whether the next token is `in` or `of`. When there is no init13672// part (semicolon immediately after the opening parenthesis), it13673// is a regular `for` loop.1367413675pp$8.parseForStatement = function(node) {13676this.next();13677var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;13678this.labels.push(loopLabel);13679this.enterScope(0);13680this.expect(types$1.parenL);13681if (this.type === types$1.semi) {13682if (awaitAt > -1) { this.unexpected(awaitAt); }13683return this.parseFor(node, null)13684}13685var isLet = this.isLet();13686if (this.type === types$1._var || this.type === types$1._const || isLet) {13687var init$1 = this.startNode(), kind = isLet ? "let" : this.value;13688this.next();13689this.parseVar(init$1, true, kind);13690this.finishNode(init$1, "VariableDeclaration");13691if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {13692if (this.options.ecmaVersion >= 9) {13693if (this.type === types$1._in) {13694if (awaitAt > -1) { this.unexpected(awaitAt); }13695} else { node.await = awaitAt > -1; }13696}13697return this.parseForIn(node, init$1)13698}13699if (awaitAt > -1) { this.unexpected(awaitAt); }13700return this.parseFor(node, init$1)13701}13702var startsWithLet = this.isContextual("let"), isForOf = false;13703var refDestructuringErrors = new DestructuringErrors;13704var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);13705if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {13706if (this.options.ecmaVersion >= 9) {13707if (this.type === types$1._in) {13708if (awaitAt > -1) { this.unexpected(awaitAt); }13709} else { node.await = awaitAt > -1; }13710}13711if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); }13712this.toAssignable(init, false, refDestructuringErrors);13713this.checkLValPattern(init);13714return this.parseForIn(node, init)13715} else {13716this.checkExpressionErrors(refDestructuringErrors, true);13717}13718if (awaitAt > -1) { this.unexpected(awaitAt); }13719return this.parseFor(node, init)13720};1372113722pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {13723this.next();13724return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)13725};1372613727pp$8.parseIfStatement = function(node) {13728this.next();13729node.test = this.parseParenExpression();13730// allow function declarations in branches, but only in non-strict mode13731node.consequent = this.parseStatement("if");13732node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;13733return this.finishNode(node, "IfStatement")13734};1373513736pp$8.parseReturnStatement = function(node) {13737if (!this.inFunction && !this.options.allowReturnOutsideFunction)13738{ this.raise(this.start, "'return' outside of function"); }13739this.next();1374013741// In `return` (and `break`/`continue`), the keywords with13742// optional arguments, we eagerly look for a semicolon or the13743// possibility to insert one.1374413745if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; }13746else { node.argument = this.parseExpression(); this.semicolon(); }13747return this.finishNode(node, "ReturnStatement")13748};1374913750pp$8.parseSwitchStatement = function(node) {13751this.next();13752node.discriminant = this.parseParenExpression();13753node.cases = [];13754this.expect(types$1.braceL);13755this.labels.push(switchLabel);13756this.enterScope(0);1375713758// Statements under must be grouped (by label) in SwitchCase13759// nodes. `cur` is used to keep the node that we are currently13760// adding statements to.1376113762var cur;13763for (var sawDefault = false; this.type !== types$1.braceR;) {13764if (this.type === types$1._case || this.type === types$1._default) {13765var isCase = this.type === types$1._case;13766if (cur) { this.finishNode(cur, "SwitchCase"); }13767node.cases.push(cur = this.startNode());13768cur.consequent = [];13769this.next();13770if (isCase) {13771cur.test = this.parseExpression();13772} else {13773if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }13774sawDefault = true;13775cur.test = null;13776}13777this.expect(types$1.colon);13778} else {13779if (!cur) { this.unexpected(); }13780cur.consequent.push(this.parseStatement(null));13781}13782}13783this.exitScope();13784if (cur) { this.finishNode(cur, "SwitchCase"); }13785this.next(); // Closing brace13786this.labels.pop();13787return this.finishNode(node, "SwitchStatement")13788};1378913790pp$8.parseThrowStatement = function(node) {13791this.next();13792if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))13793{ this.raise(this.lastTokEnd, "Illegal newline after throw"); }13794node.argument = this.parseExpression();13795this.semicolon();13796return this.finishNode(node, "ThrowStatement")13797};1379813799// Reused empty array added for node fields that are always empty.1380013801var empty$1 = [];1380213803pp$8.parseTryStatement = function(node) {13804this.next();13805node.block = this.parseBlock();13806node.handler = null;13807if (this.type === types$1._catch) {13808var clause = this.startNode();13809this.next();13810if (this.eat(types$1.parenL)) {13811clause.param = this.parseBindingAtom();13812var simple = clause.param.type === "Identifier";13813this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);13814this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);13815this.expect(types$1.parenR);13816} else {13817if (this.options.ecmaVersion < 10) { this.unexpected(); }13818clause.param = null;13819this.enterScope(0);13820}13821clause.body = this.parseBlock(false);13822this.exitScope();13823node.handler = this.finishNode(clause, "CatchClause");13824}13825node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;13826if (!node.handler && !node.finalizer)13827{ this.raise(node.start, "Missing catch or finally clause"); }13828return this.finishNode(node, "TryStatement")13829};1383013831pp$8.parseVarStatement = function(node, kind) {13832this.next();13833this.parseVar(node, false, kind);13834this.semicolon();13835return this.finishNode(node, "VariableDeclaration")13836};1383713838pp$8.parseWhileStatement = function(node) {13839this.next();13840node.test = this.parseParenExpression();13841this.labels.push(loopLabel);13842node.body = this.parseStatement("while");13843this.labels.pop();13844return this.finishNode(node, "WhileStatement")13845};1384613847pp$8.parseWithStatement = function(node) {13848if (this.strict) { this.raise(this.start, "'with' in strict mode"); }13849this.next();13850node.object = this.parseParenExpression();13851node.body = this.parseStatement("with");13852return this.finishNode(node, "WithStatement")13853};1385413855pp$8.parseEmptyStatement = function(node) {13856this.next();13857return this.finishNode(node, "EmptyStatement")13858};1385913860pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {13861for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)13862{13863var label = list[i$1];1386413865if (label.name === maybeName)13866{ this.raise(expr.start, "Label '" + maybeName + "' is already declared");13867} }13868var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;13869for (var i = this.labels.length - 1; i >= 0; i--) {13870var label$1 = this.labels[i];13871if (label$1.statementStart === node.start) {13872// Update information about previous labels on this node13873label$1.statementStart = this.start;13874label$1.kind = kind;13875} else { break }13876}13877this.labels.push({name: maybeName, kind: kind, statementStart: this.start});13878node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");13879this.labels.pop();13880node.label = expr;13881return this.finishNode(node, "LabeledStatement")13882};1388313884pp$8.parseExpressionStatement = function(node, expr) {13885node.expression = expr;13886this.semicolon();13887return this.finishNode(node, "ExpressionStatement")13888};1388913890// Parse a semicolon-enclosed block of statements, handling `"use13891// strict"` declarations when `allowStrict` is true (used for13892// function bodies).1389313894pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {13895if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;13896if ( node === void 0 ) node = this.startNode();1389713898node.body = [];13899this.expect(types$1.braceL);13900if (createNewLexicalScope) { this.enterScope(0); }13901while (this.type !== types$1.braceR) {13902var stmt = this.parseStatement(null);13903node.body.push(stmt);13904}13905if (exitStrict) { this.strict = false; }13906this.next();13907if (createNewLexicalScope) { this.exitScope(); }13908return this.finishNode(node, "BlockStatement")13909};1391013911// Parse a regular `for` loop. The disambiguation code in13912// `parseStatement` will already have parsed the init statement or13913// expression.1391413915pp$8.parseFor = function(node, init) {13916node.init = init;13917this.expect(types$1.semi);13918node.test = this.type === types$1.semi ? null : this.parseExpression();13919this.expect(types$1.semi);13920node.update = this.type === types$1.parenR ? null : this.parseExpression();13921this.expect(types$1.parenR);13922node.body = this.parseStatement("for");13923this.exitScope();13924this.labels.pop();13925return this.finishNode(node, "ForStatement")13926};1392713928// Parse a `for`/`in` and `for`/`of` loop, which are almost13929// same from parser's perspective.1393013931pp$8.parseForIn = function(node, init) {13932var isForIn = this.type === types$1._in;13933this.next();1393413935if (13936init.type === "VariableDeclaration" &&13937init.declarations[0].init != null &&13938(13939!isForIn ||13940this.options.ecmaVersion < 8 ||13941this.strict ||13942init.kind !== "var" ||13943init.declarations[0].id.type !== "Identifier"13944)13945) {13946this.raise(13947init.start,13948((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")13949);13950}13951node.left = init;13952node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();13953this.expect(types$1.parenR);13954node.body = this.parseStatement("for");13955this.exitScope();13956this.labels.pop();13957return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")13958};1395913960// Parse a list of variable declarations.1396113962pp$8.parseVar = function(node, isFor, kind) {13963node.declarations = [];13964node.kind = kind;13965for (;;) {13966var decl = this.startNode();13967this.parseVarId(decl, kind);13968if (this.eat(types$1.eq)) {13969decl.init = this.parseMaybeAssign(isFor);13970} else if (kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {13971this.unexpected();13972} else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {13973this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");13974} else {13975decl.init = null;13976}13977node.declarations.push(this.finishNode(decl, "VariableDeclarator"));13978if (!this.eat(types$1.comma)) { break }13979}13980return node13981};1398213983pp$8.parseVarId = function(decl, kind) {13984decl.id = this.parseBindingAtom();13985this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);13986};1398713988var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;1398913990// Parse a function declaration or literal (depending on the13991// `statement & FUNC_STATEMENT`).1399213993// Remove `allowExpressionBody` for 7.0.0, as it is only called with false13994pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {13995this.initFunction(node);13996if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {13997if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT))13998{ this.unexpected(); }13999node.generator = this.eat(types$1.star);14000}14001if (this.options.ecmaVersion >= 8)14002{ node.async = !!isAsync; }1400314004if (statement & FUNC_STATEMENT) {14005node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent();14006if (node.id && !(statement & FUNC_HANGING_STATEMENT))14007// If it is a regular function declaration in sloppy mode, then it is14008// subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding14009// mode depends on properties of the current scope (see14010// treatFunctionsAsVar).14011{ this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }14012}1401314014var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;14015this.yieldPos = 0;14016this.awaitPos = 0;14017this.awaitIdentPos = 0;14018this.enterScope(functionFlags(node.async, node.generator));1401914020if (!(statement & FUNC_STATEMENT))14021{ node.id = this.type === types$1.name ? this.parseIdent() : null; }1402214023this.parseFunctionParams(node);14024this.parseFunctionBody(node, allowExpressionBody, false, forInit);1402514026this.yieldPos = oldYieldPos;14027this.awaitPos = oldAwaitPos;14028this.awaitIdentPos = oldAwaitIdentPos;14029return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")14030};1403114032pp$8.parseFunctionParams = function(node) {14033this.expect(types$1.parenL);14034node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);14035this.checkYieldAwaitInDefaultParams();14036};1403714038// Parse a class declaration or literal (depending on the14039// `isStatement` parameter).1404014041pp$8.parseClass = function(node, isStatement) {14042this.next();1404314044// ecma-262 14.6 Class Definitions14045// A class definition is always strict mode code.14046var oldStrict = this.strict;14047this.strict = true;1404814049this.parseClassId(node, isStatement);14050this.parseClassSuper(node);14051var privateNameMap = this.enterClassBody();14052var classBody = this.startNode();14053var hadConstructor = false;14054classBody.body = [];14055this.expect(types$1.braceL);14056while (this.type !== types$1.braceR) {14057var element = this.parseClassElement(node.superClass !== null);14058if (element) {14059classBody.body.push(element);14060if (element.type === "MethodDefinition" && element.kind === "constructor") {14061if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }14062hadConstructor = true;14063} else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {14064this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));14065}14066}14067}14068this.strict = oldStrict;14069this.next();14070node.body = this.finishNode(classBody, "ClassBody");14071this.exitClassBody();14072return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")14073};1407414075pp$8.parseClassElement = function(constructorAllowsSuper) {14076if (this.eat(types$1.semi)) { return null }1407714078var ecmaVersion = this.options.ecmaVersion;14079var node = this.startNode();14080var keyName = "";14081var isGenerator = false;14082var isAsync = false;14083var kind = "method";14084var isStatic = false;1408514086if (this.eatContextual("static")) {14087// Parse static init block14088if (ecmaVersion >= 13 && this.eat(types$1.braceL)) {14089this.parseClassStaticBlock(node);14090return node14091}14092if (this.isClassElementNameStart() || this.type === types$1.star) {14093isStatic = true;14094} else {14095keyName = "static";14096}14097}14098node.static = isStatic;14099if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {14100if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {14101isAsync = true;14102} else {14103keyName = "async";14104}14105}14106if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) {14107isGenerator = true;14108}14109if (!keyName && !isAsync && !isGenerator) {14110var lastValue = this.value;14111if (this.eatContextual("get") || this.eatContextual("set")) {14112if (this.isClassElementNameStart()) {14113kind = lastValue;14114} else {14115keyName = lastValue;14116}14117}14118}1411914120// Parse element name14121if (keyName) {14122// 'async', 'get', 'set', or 'static' were not a keyword contextually.14123// The last token is any of those. Make it the element name.14124node.computed = false;14125node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);14126node.key.name = keyName;14127this.finishNode(node.key, "Identifier");14128} else {14129this.parseClassElementName(node);14130}1413114132// Parse element value14133if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) {14134var isConstructor = !node.static && checkKeyName(node, "constructor");14135var allowsDirectSuper = isConstructor && constructorAllowsSuper;14136// Couldn't move this check into the 'parseClassMethod' method for backward compatibility.14137if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }14138node.kind = isConstructor ? "constructor" : kind;14139this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);14140} else {14141this.parseClassField(node);14142}1414314144return node14145};1414614147pp$8.isClassElementNameStart = function() {14148return (14149this.type === types$1.name ||14150this.type === types$1.privateId ||14151this.type === types$1.num ||14152this.type === types$1.string ||14153this.type === types$1.bracketL ||14154this.type.keyword14155)14156};1415714158pp$8.parseClassElementName = function(element) {14159if (this.type === types$1.privateId) {14160if (this.value === "constructor") {14161this.raise(this.start, "Classes can't have an element named '#constructor'");14162}14163element.computed = false;14164element.key = this.parsePrivateIdent();14165} else {14166this.parsePropertyName(element);14167}14168};1416914170pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {14171// Check key and flags14172var key = method.key;14173if (method.kind === "constructor") {14174if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }14175if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }14176} else if (method.static && checkKeyName(method, "prototype")) {14177this.raise(key.start, "Classes may not have a static property named prototype");14178}1417914180// Parse value14181var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);1418214183// Check value14184if (method.kind === "get" && value.params.length !== 0)14185{ this.raiseRecoverable(value.start, "getter should have no params"); }14186if (method.kind === "set" && value.params.length !== 1)14187{ this.raiseRecoverable(value.start, "setter should have exactly one param"); }14188if (method.kind === "set" && value.params[0].type === "RestElement")14189{ this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }1419014191return this.finishNode(method, "MethodDefinition")14192};1419314194pp$8.parseClassField = function(field) {14195if (checkKeyName(field, "constructor")) {14196this.raise(field.key.start, "Classes can't have a field named 'constructor'");14197} else if (field.static && checkKeyName(field, "prototype")) {14198this.raise(field.key.start, "Classes can't have a static field named 'prototype'");14199}1420014201if (this.eat(types$1.eq)) {14202// To raise SyntaxError if 'arguments' exists in the initializer.14203var scope = this.currentThisScope();14204var inClassFieldInit = scope.inClassFieldInit;14205scope.inClassFieldInit = true;14206field.value = this.parseMaybeAssign();14207scope.inClassFieldInit = inClassFieldInit;14208} else {14209field.value = null;14210}14211this.semicolon();1421214213return this.finishNode(field, "PropertyDefinition")14214};1421514216pp$8.parseClassStaticBlock = function(node) {14217node.body = [];1421814219var oldLabels = this.labels;14220this.labels = [];14221this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);14222while (this.type !== types$1.braceR) {14223var stmt = this.parseStatement(null);14224node.body.push(stmt);14225}14226this.next();14227this.exitScope();14228this.labels = oldLabels;1422914230return this.finishNode(node, "StaticBlock")14231};1423214233pp$8.parseClassId = function(node, isStatement) {14234if (this.type === types$1.name) {14235node.id = this.parseIdent();14236if (isStatement)14237{ this.checkLValSimple(node.id, BIND_LEXICAL, false); }14238} else {14239if (isStatement === true)14240{ this.unexpected(); }14241node.id = null;14242}14243};1424414245pp$8.parseClassSuper = function(node) {14246node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(false) : null;14247};1424814249pp$8.enterClassBody = function() {14250var element = {declared: Object.create(null), used: []};14251this.privateNameStack.push(element);14252return element.declared14253};1425414255pp$8.exitClassBody = function() {14256var ref = this.privateNameStack.pop();14257var declared = ref.declared;14258var used = ref.used;14259var len = this.privateNameStack.length;14260var parent = len === 0 ? null : this.privateNameStack[len - 1];14261for (var i = 0; i < used.length; ++i) {14262var id = used[i];14263if (!hasOwn(declared, id.name)) {14264if (parent) {14265parent.used.push(id);14266} else {14267this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));14268}14269}14270}14271};1427214273function isPrivateNameConflicted(privateNameMap, element) {14274var name = element.key.name;14275var curr = privateNameMap[name];1427614277var next = "true";14278if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {14279next = (element.static ? "s" : "i") + element.kind;14280}1428114282// `class { get #a(){}; static set #a(_){} }` is also conflict.14283if (14284curr === "iget" && next === "iset" ||14285curr === "iset" && next === "iget" ||14286curr === "sget" && next === "sset" ||14287curr === "sset" && next === "sget"14288) {14289privateNameMap[name] = "true";14290return false14291} else if (!curr) {14292privateNameMap[name] = next;14293return false14294} else {14295return true14296}14297}1429814299function checkKeyName(node, name) {14300var computed = node.computed;14301var key = node.key;14302return !computed && (14303key.type === "Identifier" && key.name === name ||14304key.type === "Literal" && key.value === name14305)14306}1430714308// Parses module export declaration.1430914310pp$8.parseExport = function(node, exports) {14311this.next();14312// export * from '...'14313if (this.eat(types$1.star)) {14314if (this.options.ecmaVersion >= 11) {14315if (this.eatContextual("as")) {14316node.exported = this.parseModuleExportName();14317this.checkExport(exports, node.exported, this.lastTokStart);14318} else {14319node.exported = null;14320}14321}14322this.expectContextual("from");14323if (this.type !== types$1.string) { this.unexpected(); }14324node.source = this.parseExprAtom();14325this.semicolon();14326return this.finishNode(node, "ExportAllDeclaration")14327}14328if (this.eat(types$1._default)) { // export default ...14329this.checkExport(exports, "default", this.lastTokStart);14330var isAsync;14331if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {14332var fNode = this.startNode();14333this.next();14334if (isAsync) { this.next(); }14335node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);14336} else if (this.type === types$1._class) {14337var cNode = this.startNode();14338node.declaration = this.parseClass(cNode, "nullableID");14339} else {14340node.declaration = this.parseMaybeAssign();14341this.semicolon();14342}14343return this.finishNode(node, "ExportDefaultDeclaration")14344}14345// export var|const|let|function|class ...14346if (this.shouldParseExportStatement()) {14347node.declaration = this.parseStatement(null);14348if (node.declaration.type === "VariableDeclaration")14349{ this.checkVariableExport(exports, node.declaration.declarations); }14350else14351{ this.checkExport(exports, node.declaration.id, node.declaration.id.start); }14352node.specifiers = [];14353node.source = null;14354} else { // export { x, y as z } [from '...']14355node.declaration = null;14356node.specifiers = this.parseExportSpecifiers(exports);14357if (this.eatContextual("from")) {14358if (this.type !== types$1.string) { this.unexpected(); }14359node.source = this.parseExprAtom();14360} else {14361for (var i = 0, list = node.specifiers; i < list.length; i += 1) {14362// check for keywords used as local names14363var spec = list[i];1436414365this.checkUnreserved(spec.local);14366// check if export is defined14367this.checkLocalExport(spec.local);1436814369if (spec.local.type === "Literal") {14370this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");14371}14372}1437314374node.source = null;14375}14376this.semicolon();14377}14378return this.finishNode(node, "ExportNamedDeclaration")14379};1438014381pp$8.checkExport = function(exports, name, pos) {14382if (!exports) { return }14383if (typeof name !== "string")14384{ name = name.type === "Identifier" ? name.name : name.value; }14385if (hasOwn(exports, name))14386{ this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }14387exports[name] = true;14388};1438914390pp$8.checkPatternExport = function(exports, pat) {14391var type = pat.type;14392if (type === "Identifier")14393{ this.checkExport(exports, pat, pat.start); }14394else if (type === "ObjectPattern")14395{ for (var i = 0, list = pat.properties; i < list.length; i += 1)14396{14397var prop = list[i];1439814399this.checkPatternExport(exports, prop);14400} }14401else if (type === "ArrayPattern")14402{ for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {14403var elt = list$1[i$1];1440414405if (elt) { this.checkPatternExport(exports, elt); }14406} }14407else if (type === "Property")14408{ this.checkPatternExport(exports, pat.value); }14409else if (type === "AssignmentPattern")14410{ this.checkPatternExport(exports, pat.left); }14411else if (type === "RestElement")14412{ this.checkPatternExport(exports, pat.argument); }14413else if (type === "ParenthesizedExpression")14414{ this.checkPatternExport(exports, pat.expression); }14415};1441614417pp$8.checkVariableExport = function(exports, decls) {14418if (!exports) { return }14419for (var i = 0, list = decls; i < list.length; i += 1)14420{14421var decl = list[i];1442214423this.checkPatternExport(exports, decl.id);14424}14425};1442614427pp$8.shouldParseExportStatement = function() {14428return this.type.keyword === "var" ||14429this.type.keyword === "const" ||14430this.type.keyword === "class" ||14431this.type.keyword === "function" ||14432this.isLet() ||14433this.isAsyncFunction()14434};1443514436// Parses a comma-separated list of module exports.1443714438pp$8.parseExportSpecifiers = function(exports) {14439var nodes = [], first = true;14440// export { x, y as z } [from '...']14441this.expect(types$1.braceL);14442while (!this.eat(types$1.braceR)) {14443if (!first) {14444this.expect(types$1.comma);14445if (this.afterTrailingComma(types$1.braceR)) { break }14446} else { first = false; }1444714448var node = this.startNode();14449node.local = this.parseModuleExportName();14450node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;14451this.checkExport(14452exports,14453node.exported,14454node.exported.start14455);14456nodes.push(this.finishNode(node, "ExportSpecifier"));14457}14458return nodes14459};1446014461// Parses import declaration.1446214463pp$8.parseImport = function(node) {14464this.next();14465// import '...'14466if (this.type === types$1.string) {14467node.specifiers = empty$1;14468node.source = this.parseExprAtom();14469} else {14470node.specifiers = this.parseImportSpecifiers();14471this.expectContextual("from");14472node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();14473}14474this.semicolon();14475return this.finishNode(node, "ImportDeclaration")14476};1447714478// Parses a comma-separated list of module imports.1447914480pp$8.parseImportSpecifiers = function() {14481var nodes = [], first = true;14482if (this.type === types$1.name) {14483// import defaultObj, { x, y as z } from '...'14484var node = this.startNode();14485node.local = this.parseIdent();14486this.checkLValSimple(node.local, BIND_LEXICAL);14487nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));14488if (!this.eat(types$1.comma)) { return nodes }14489}14490if (this.type === types$1.star) {14491var node$1 = this.startNode();14492this.next();14493this.expectContextual("as");14494node$1.local = this.parseIdent();14495this.checkLValSimple(node$1.local, BIND_LEXICAL);14496nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));14497return nodes14498}14499this.expect(types$1.braceL);14500while (!this.eat(types$1.braceR)) {14501if (!first) {14502this.expect(types$1.comma);14503if (this.afterTrailingComma(types$1.braceR)) { break }14504} else { first = false; }1450514506var node$2 = this.startNode();14507node$2.imported = this.parseModuleExportName();14508if (this.eatContextual("as")) {14509node$2.local = this.parseIdent();14510} else {14511this.checkUnreserved(node$2.imported);14512node$2.local = node$2.imported;14513}14514this.checkLValSimple(node$2.local, BIND_LEXICAL);14515nodes.push(this.finishNode(node$2, "ImportSpecifier"));14516}14517return nodes14518};1451914520pp$8.parseModuleExportName = function() {14521if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {14522var stringLiteral = this.parseLiteral(this.value);14523if (loneSurrogate.test(stringLiteral.value)) {14524this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");14525}14526return stringLiteral14527}14528return this.parseIdent(true)14529};1453014531// Set `ExpressionStatement#directive` property for directive prologues.14532pp$8.adaptDirectivePrologue = function(statements) {14533for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {14534statements[i].directive = statements[i].expression.raw.slice(1, -1);14535}14536};14537pp$8.isDirectiveCandidate = function(statement) {14538return (14539this.options.ecmaVersion >= 5 &&14540statement.type === "ExpressionStatement" &&14541statement.expression.type === "Literal" &&14542typeof statement.expression.value === "string" &&14543// Reject parenthesized strings.14544(this.input[statement.start] === "\"" || this.input[statement.start] === "'")14545)14546};1454714548var pp$7 = Parser.prototype;1454914550// Convert existing expression atom to assignable pattern14551// if possible.1455214553pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {14554if (this.options.ecmaVersion >= 6 && node) {14555switch (node.type) {14556case "Identifier":14557if (this.inAsync && node.name === "await")14558{ this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }14559break1456014561case "ObjectPattern":14562case "ArrayPattern":14563case "AssignmentPattern":14564case "RestElement":14565break1456614567case "ObjectExpression":14568node.type = "ObjectPattern";14569if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }14570for (var i = 0, list = node.properties; i < list.length; i += 1) {14571var prop = list[i];1457214573this.toAssignable(prop, isBinding);14574// Early error:14575// AssignmentRestProperty[Yield, Await] :14576// `...` DestructuringAssignmentTarget[Yield, Await]14577//14578// It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.14579if (14580prop.type === "RestElement" &&14581(prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")14582) {14583this.raise(prop.argument.start, "Unexpected token");14584}14585}14586break1458714588case "Property":14589// AssignmentProperty has type === "Property"14590if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }14591this.toAssignable(node.value, isBinding);14592break1459314594case "ArrayExpression":14595node.type = "ArrayPattern";14596if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }14597this.toAssignableList(node.elements, isBinding);14598break1459914600case "SpreadElement":14601node.type = "RestElement";14602this.toAssignable(node.argument, isBinding);14603if (node.argument.type === "AssignmentPattern")14604{ this.raise(node.argument.start, "Rest elements cannot have a default value"); }14605break1460614607case "AssignmentExpression":14608if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }14609node.type = "AssignmentPattern";14610delete node.operator;14611this.toAssignable(node.left, isBinding);14612break1461314614case "ParenthesizedExpression":14615this.toAssignable(node.expression, isBinding, refDestructuringErrors);14616break1461714618case "ChainExpression":14619this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");14620break1462114622case "MemberExpression":14623if (!isBinding) { break }1462414625default:14626this.raise(node.start, "Assigning to rvalue");14627}14628} else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }14629return node14630};1463114632// Convert list of expression atoms to binding list.1463314634pp$7.toAssignableList = function(exprList, isBinding) {14635var end = exprList.length;14636for (var i = 0; i < end; i++) {14637var elt = exprList[i];14638if (elt) { this.toAssignable(elt, isBinding); }14639}14640if (end) {14641var last = exprList[end - 1];14642if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")14643{ this.unexpected(last.argument.start); }14644}14645return exprList14646};1464714648// Parses spread element.1464914650pp$7.parseSpread = function(refDestructuringErrors) {14651var node = this.startNode();14652this.next();14653node.argument = this.parseMaybeAssign(false, refDestructuringErrors);14654return this.finishNode(node, "SpreadElement")14655};1465614657pp$7.parseRestBinding = function() {14658var node = this.startNode();14659this.next();1466014661// RestElement inside of a function parameter must be an identifier14662if (this.options.ecmaVersion === 6 && this.type !== types$1.name)14663{ this.unexpected(); }1466414665node.argument = this.parseBindingAtom();1466614667return this.finishNode(node, "RestElement")14668};1466914670// Parses lvalue (assignable) atom.1467114672pp$7.parseBindingAtom = function() {14673if (this.options.ecmaVersion >= 6) {14674switch (this.type) {14675case types$1.bracketL:14676var node = this.startNode();14677this.next();14678node.elements = this.parseBindingList(types$1.bracketR, true, true);14679return this.finishNode(node, "ArrayPattern")1468014681case types$1.braceL:14682return this.parseObj(true)14683}14684}14685return this.parseIdent()14686};1468714688pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma) {14689var elts = [], first = true;14690while (!this.eat(close)) {14691if (first) { first = false; }14692else { this.expect(types$1.comma); }14693if (allowEmpty && this.type === types$1.comma) {14694elts.push(null);14695} else if (allowTrailingComma && this.afterTrailingComma(close)) {14696break14697} else if (this.type === types$1.ellipsis) {14698var rest = this.parseRestBinding();14699this.parseBindingListItem(rest);14700elts.push(rest);14701if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }14702this.expect(close);14703break14704} else {14705var elem = this.parseMaybeDefault(this.start, this.startLoc);14706this.parseBindingListItem(elem);14707elts.push(elem);14708}14709}14710return elts14711};1471214713pp$7.parseBindingListItem = function(param) {14714return param14715};1471614717// Parses assignment pattern around given atom if possible.1471814719pp$7.parseMaybeDefault = function(startPos, startLoc, left) {14720left = left || this.parseBindingAtom();14721if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left }14722var node = this.startNodeAt(startPos, startLoc);14723node.left = left;14724node.right = this.parseMaybeAssign();14725return this.finishNode(node, "AssignmentPattern")14726};1472714728// The following three functions all verify that a node is an lvalue —14729// something that can be bound, or assigned to. In order to do so, they perform14730// a variety of checks:14731//14732// - Check that none of the bound/assigned-to identifiers are reserved words.14733// - Record name declarations for bindings in the appropriate scope.14734// - Check duplicate argument names, if checkClashes is set.14735//14736// If a complex binding pattern is encountered (e.g., object and array14737// destructuring), the entire pattern is recursively checked.14738//14739// There are three versions of checkLVal*() appropriate for different14740// circumstances:14741//14742// - checkLValSimple() shall be used if the syntactic construct supports14743// nothing other than identifiers and member expressions. Parenthesized14744// expressions are also correctly handled. This is generally appropriate for14745// constructs for which the spec says14746//14747// > It is a Syntax Error if AssignmentTargetType of [the production] is not14748// > simple.14749//14750// It is also appropriate for checking if an identifier is valid and not14751// defined elsewhere, like import declarations or function/class identifiers.14752//14753// Examples where this is used include:14754// a += …;14755// import a from '…';14756// where a is the node to be checked.14757//14758// - checkLValPattern() shall be used if the syntactic construct supports14759// anything checkLValSimple() supports, as well as object and array14760// destructuring patterns. This is generally appropriate for constructs for14761// which the spec says14762//14763// > It is a Syntax Error if [the production] is neither an ObjectLiteral nor14764// > an ArrayLiteral and AssignmentTargetType of [the production] is not14765// > simple.14766//14767// Examples where this is used include:14768// (a = …);14769// const a = …;14770// try { … } catch (a) { … }14771// where a is the node to be checked.14772//14773// - checkLValInnerPattern() shall be used if the syntactic construct supports14774// anything checkLValPattern() supports, as well as default assignment14775// patterns, rest elements, and other constructs that may appear within an14776// object or array destructuring pattern.14777//14778// As a special case, function parameters also use checkLValInnerPattern(),14779// as they also support defaults and rest constructs.14780//14781// These functions deliberately support both assignment and binding constructs,14782// as the logic for both is exceedingly similar. If the node is the target of14783// an assignment, then bindingType should be set to BIND_NONE. Otherwise, it14784// should be set to the appropriate BIND_* constant, like BIND_VAR or14785// BIND_LEXICAL.14786//14787// If the function is called with a non-BIND_NONE bindingType, then14788// additionally a checkClashes object may be specified to allow checking for14789// duplicate argument names. checkClashes is ignored if the provided construct14790// is an assignment (i.e., bindingType is BIND_NONE).1479114792pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {14793if ( bindingType === void 0 ) bindingType = BIND_NONE;1479414795var isBind = bindingType !== BIND_NONE;1479614797switch (expr.type) {14798case "Identifier":14799if (this.strict && this.reservedWordsStrictBind.test(expr.name))14800{ this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }14801if (isBind) {14802if (bindingType === BIND_LEXICAL && expr.name === "let")14803{ this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }14804if (checkClashes) {14805if (hasOwn(checkClashes, expr.name))14806{ this.raiseRecoverable(expr.start, "Argument name clash"); }14807checkClashes[expr.name] = true;14808}14809if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }14810}14811break1481214813case "ChainExpression":14814this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");14815break1481614817case "MemberExpression":14818if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }14819break1482014821case "ParenthesizedExpression":14822if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }14823return this.checkLValSimple(expr.expression, bindingType, checkClashes)1482414825default:14826this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");14827}14828};1482914830pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {14831if ( bindingType === void 0 ) bindingType = BIND_NONE;1483214833switch (expr.type) {14834case "ObjectPattern":14835for (var i = 0, list = expr.properties; i < list.length; i += 1) {14836var prop = list[i];1483714838this.checkLValInnerPattern(prop, bindingType, checkClashes);14839}14840break1484114842case "ArrayPattern":14843for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {14844var elem = list$1[i$1];1484514846if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }14847}14848break1484914850default:14851this.checkLValSimple(expr, bindingType, checkClashes);14852}14853};1485414855pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {14856if ( bindingType === void 0 ) bindingType = BIND_NONE;1485714858switch (expr.type) {14859case "Property":14860// AssignmentProperty has type === "Property"14861this.checkLValInnerPattern(expr.value, bindingType, checkClashes);14862break1486314864case "AssignmentPattern":14865this.checkLValPattern(expr.left, bindingType, checkClashes);14866break1486714868case "RestElement":14869this.checkLValPattern(expr.argument, bindingType, checkClashes);14870break1487114872default:14873this.checkLValPattern(expr, bindingType, checkClashes);14874}14875};1487614877// The algorithm used to determine whether a regexp can appear at a1487814879var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {14880this.token = token;14881this.isExpr = !!isExpr;14882this.preserveSpace = !!preserveSpace;14883this.override = override;14884this.generator = !!generator;14885};1488614887var types = {14888b_stat: new TokContext("{", false),14889b_expr: new TokContext("{", true),14890b_tmpl: new TokContext("${", false),14891p_stat: new TokContext("(", false),14892p_expr: new TokContext("(", true),14893q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),14894f_stat: new TokContext("function", false),14895f_expr: new TokContext("function", true),14896f_expr_gen: new TokContext("function", true, false, null, true),14897f_gen: new TokContext("function", false, false, null, true)14898};1489914900var pp$6 = Parser.prototype;1490114902pp$6.initialContext = function() {14903return [types.b_stat]14904};1490514906pp$6.curContext = function() {14907return this.context[this.context.length - 1]14908};1490914910pp$6.braceIsBlock = function(prevType) {14911var parent = this.curContext();14912if (parent === types.f_expr || parent === types.f_stat)14913{ return true }14914if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr))14915{ return !parent.isExpr }1491614917// The check for `tt.name && exprAllowed` detects whether we are14918// after a `yield` or `of` construct. See the `updateContext` for14919// `tt.name`.14920if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed)14921{ return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }14922if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow)14923{ return true }14924if (prevType === types$1.braceL)14925{ return parent === types.b_stat }14926if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name)14927{ return false }14928return !this.exprAllowed14929};1493014931pp$6.inGeneratorContext = function() {14932for (var i = this.context.length - 1; i >= 1; i--) {14933var context = this.context[i];14934if (context.token === "function")14935{ return context.generator }14936}14937return false14938};1493914940pp$6.updateContext = function(prevType) {14941var update, type = this.type;14942if (type.keyword && prevType === types$1.dot)14943{ this.exprAllowed = false; }14944else if (update = type.updateContext)14945{ update.call(this, prevType); }14946else14947{ this.exprAllowed = type.beforeExpr; }14948};1494914950// Used to handle egde cases when token context could not be inferred correctly during tokenization phase1495114952pp$6.overrideContext = function(tokenCtx) {14953if (this.curContext() !== tokenCtx) {14954this.context[this.context.length - 1] = tokenCtx;14955}14956};1495714958// Token-specific context update code1495914960types$1.parenR.updateContext = types$1.braceR.updateContext = function() {14961if (this.context.length === 1) {14962this.exprAllowed = true;14963return14964}14965var out = this.context.pop();14966if (out === types.b_stat && this.curContext().token === "function") {14967out = this.context.pop();14968}14969this.exprAllowed = !out.isExpr;14970};1497114972types$1.braceL.updateContext = function(prevType) {14973this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);14974this.exprAllowed = true;14975};1497614977types$1.dollarBraceL.updateContext = function() {14978this.context.push(types.b_tmpl);14979this.exprAllowed = true;14980};1498114982types$1.parenL.updateContext = function(prevType) {14983var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;14984this.context.push(statementParens ? types.p_stat : types.p_expr);14985this.exprAllowed = true;14986};1498714988types$1.incDec.updateContext = function() {14989// tokExprAllowed stays unchanged14990};1499114992types$1._function.updateContext = types$1._class.updateContext = function(prevType) {14993if (prevType.beforeExpr && prevType !== types$1._else &&14994!(prevType === types$1.semi && this.curContext() !== types.p_stat) &&14995!(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&14996!((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat))14997{ this.context.push(types.f_expr); }14998else14999{ this.context.push(types.f_stat); }15000this.exprAllowed = false;15001};1500215003types$1.backQuote.updateContext = function() {15004if (this.curContext() === types.q_tmpl)15005{ this.context.pop(); }15006else15007{ this.context.push(types.q_tmpl); }15008this.exprAllowed = false;15009};1501015011types$1.star.updateContext = function(prevType) {15012if (prevType === types$1._function) {15013var index = this.context.length - 1;15014if (this.context[index] === types.f_expr)15015{ this.context[index] = types.f_expr_gen; }15016else15017{ this.context[index] = types.f_gen; }15018}15019this.exprAllowed = true;15020};1502115022types$1.name.updateContext = function(prevType) {15023var allowed = false;15024if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {15025if (this.value === "of" && !this.exprAllowed ||15026this.value === "yield" && this.inGeneratorContext())15027{ allowed = true; }15028}15029this.exprAllowed = allowed;15030};1503115032// A recursive descent parser operates by defining functions for all1503315034var pp$5 = Parser.prototype;1503515036// Check if property name clashes with already added.15037// Object/class getters and setters are not allowed to clash —15038// either with each other or with an init property — and in15039// strict mode, init properties are also not allowed to be repeated.1504015041pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {15042if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")15043{ return }15044if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))15045{ return }15046var key = prop.key;15047var name;15048switch (key.type) {15049case "Identifier": name = key.name; break15050case "Literal": name = String(key.value); break15051default: return15052}15053var kind = prop.kind;15054if (this.options.ecmaVersion >= 6) {15055if (name === "__proto__" && kind === "init") {15056if (propHash.proto) {15057if (refDestructuringErrors) {15058if (refDestructuringErrors.doubleProto < 0) {15059refDestructuringErrors.doubleProto = key.start;15060}15061} else {15062this.raiseRecoverable(key.start, "Redefinition of __proto__ property");15063}15064}15065propHash.proto = true;15066}15067return15068}15069name = "$" + name;15070var other = propHash[name];15071if (other) {15072var redefinition;15073if (kind === "init") {15074redefinition = this.strict && other.init || other.get || other.set;15075} else {15076redefinition = other.init || other[kind];15077}15078if (redefinition)15079{ this.raiseRecoverable(key.start, "Redefinition of property"); }15080} else {15081other = propHash[name] = {15082init: false,15083get: false,15084set: false15085};15086}15087other[kind] = true;15088};1508915090// ### Expression parsing1509115092// These nest, from the most general expression type at the top to15093// 'atomic', nondivisible expression types at the bottom. Most of15094// the functions will simply let the function(s) below them parse,15095// and, *if* the syntactic construct they handle is present, wrap15096// the AST node that the inner parser gave them in another node.1509715098// Parse a full expression. The optional arguments are used to15099// forbid the `in` operator (in for loops initalization expressions)15100// and provide reference for storing '=' operator inside shorthand15101// property assignment in contexts where both object expression15102// and object pattern might appear (so it's possible to raise15103// delayed syntax error at correct position).1510415105pp$5.parseExpression = function(forInit, refDestructuringErrors) {15106var startPos = this.start, startLoc = this.startLoc;15107var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);15108if (this.type === types$1.comma) {15109var node = this.startNodeAt(startPos, startLoc);15110node.expressions = [expr];15111while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }15112return this.finishNode(node, "SequenceExpression")15113}15114return expr15115};1511615117// Parse an assignment expression. This includes applications of15118// operators like `+=`.1511915120pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {15121if (this.isContextual("yield")) {15122if (this.inGenerator) { return this.parseYield(forInit) }15123// The tokenizer will assume an expression is allowed after15124// `yield`, but this isn't that kind of yield15125else { this.exprAllowed = false; }15126}1512715128var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;15129if (refDestructuringErrors) {15130oldParenAssign = refDestructuringErrors.parenthesizedAssign;15131oldTrailingComma = refDestructuringErrors.trailingComma;15132oldDoubleProto = refDestructuringErrors.doubleProto;15133refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;15134} else {15135refDestructuringErrors = new DestructuringErrors;15136ownDestructuringErrors = true;15137}1513815139var startPos = this.start, startLoc = this.startLoc;15140if (this.type === types$1.parenL || this.type === types$1.name) {15141this.potentialArrowAt = this.start;15142this.potentialArrowInForAwait = forInit === "await";15143}15144var left = this.parseMaybeConditional(forInit, refDestructuringErrors);15145if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }15146if (this.type.isAssign) {15147var node = this.startNodeAt(startPos, startLoc);15148node.operator = this.value;15149if (this.type === types$1.eq)15150{ left = this.toAssignable(left, false, refDestructuringErrors); }15151if (!ownDestructuringErrors) {15152refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;15153}15154if (refDestructuringErrors.shorthandAssign >= left.start)15155{ refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly15156if (this.type === types$1.eq)15157{ this.checkLValPattern(left); }15158else15159{ this.checkLValSimple(left); }15160node.left = left;15161this.next();15162node.right = this.parseMaybeAssign(forInit);15163if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; }15164return this.finishNode(node, "AssignmentExpression")15165} else {15166if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }15167}15168if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }15169if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }15170return left15171};1517215173// Parse a ternary conditional (`?:`) operator.1517415175pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {15176var startPos = this.start, startLoc = this.startLoc;15177var expr = this.parseExprOps(forInit, refDestructuringErrors);15178if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }15179if (this.eat(types$1.question)) {15180var node = this.startNodeAt(startPos, startLoc);15181node.test = expr;15182node.consequent = this.parseMaybeAssign();15183this.expect(types$1.colon);15184node.alternate = this.parseMaybeAssign(forInit);15185return this.finishNode(node, "ConditionalExpression")15186}15187return expr15188};1518915190// Start the precedence parser.1519115192pp$5.parseExprOps = function(forInit, refDestructuringErrors) {15193var startPos = this.start, startLoc = this.startLoc;15194var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);15195if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }15196return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)15197};1519815199// Parse binary operators with the operator precedence parsing15200// algorithm. `left` is the left-hand side of the operator.15201// `minPrec` provides context that allows the function to stop and15202// defer further parser to one of its callers when it encounters an15203// operator that has a lower precedence than the set it is parsing.1520415205pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {15206var prec = this.type.binop;15207if (prec != null && (!forInit || this.type !== types$1._in)) {15208if (prec > minPrec) {15209var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;15210var coalesce = this.type === types$1.coalesce;15211if (coalesce) {15212// Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.15213// In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.15214prec = types$1.logicalAND.binop;15215}15216var op = this.value;15217this.next();15218var startPos = this.start, startLoc = this.startLoc;15219var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);15220var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);15221if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) {15222this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");15223}15224return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)15225}15226}15227return left15228};1522915230pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {15231if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); }15232var node = this.startNodeAt(startPos, startLoc);15233node.left = left;15234node.operator = op;15235node.right = right;15236return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")15237};1523815239// Parse unary operators, both prefix and postfix.1524015241pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {15242var startPos = this.start, startLoc = this.startLoc, expr;15243if (this.isContextual("await") && this.canAwait) {15244expr = this.parseAwait(forInit);15245sawUnary = true;15246} else if (this.type.prefix) {15247var node = this.startNode(), update = this.type === types$1.incDec;15248node.operator = this.value;15249node.prefix = true;15250this.next();15251node.argument = this.parseMaybeUnary(null, true, update, forInit);15252this.checkExpressionErrors(refDestructuringErrors, true);15253if (update) { this.checkLValSimple(node.argument); }15254else if (this.strict && node.operator === "delete" &&15255node.argument.type === "Identifier")15256{ this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }15257else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))15258{ this.raiseRecoverable(node.start, "Private fields can not be deleted"); }15259else { sawUnary = true; }15260expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");15261} else if (!sawUnary && this.type === types$1.privateId) {15262if (forInit || this.privateNameStack.length === 0) { this.unexpected(); }15263expr = this.parsePrivateIdent();15264// only could be private fields in 'in', such as #x in obj15265if (this.type !== types$1._in) { this.unexpected(); }15266} else {15267expr = this.parseExprSubscripts(refDestructuringErrors, forInit);15268if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }15269while (this.type.postfix && !this.canInsertSemicolon()) {15270var node$1 = this.startNodeAt(startPos, startLoc);15271node$1.operator = this.value;15272node$1.prefix = false;15273node$1.argument = expr;15274this.checkLValSimple(expr);15275this.next();15276expr = this.finishNode(node$1, "UpdateExpression");15277}15278}1527915280if (!incDec && this.eat(types$1.starstar)) {15281if (sawUnary)15282{ this.unexpected(this.lastTokStart); }15283else15284{ return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) }15285} else {15286return expr15287}15288};1528915290function isPrivateFieldAccess(node) {15291return (15292node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||15293node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)15294)15295}1529615297// Parse call, dot, and `[]`-subscript expressions.1529815299pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {15300var startPos = this.start, startLoc = this.startLoc;15301var expr = this.parseExprAtom(refDestructuringErrors, forInit);15302if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")15303{ return expr }15304var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);15305if (refDestructuringErrors && result.type === "MemberExpression") {15306if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }15307if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }15308if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }15309}15310return result15311};1531215313pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {15314var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&15315this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&15316this.potentialArrowAt === base.start;15317var optionalChained = false;1531815319while (true) {15320var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);1532115322if (element.optional) { optionalChained = true; }15323if (element === base || element.type === "ArrowFunctionExpression") {15324if (optionalChained) {15325var chainNode = this.startNodeAt(startPos, startLoc);15326chainNode.expression = element;15327element = this.finishNode(chainNode, "ChainExpression");15328}15329return element15330}1533115332base = element;15333}15334};1533515336pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {15337var optionalSupported = this.options.ecmaVersion >= 11;15338var optional = optionalSupported && this.eat(types$1.questionDot);15339if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }1534015341var computed = this.eat(types$1.bracketL);15342if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) {15343var node = this.startNodeAt(startPos, startLoc);15344node.object = base;15345if (computed) {15346node.property = this.parseExpression();15347this.expect(types$1.bracketR);15348} else if (this.type === types$1.privateId && base.type !== "Super") {15349node.property = this.parsePrivateIdent();15350} else {15351node.property = this.parseIdent(this.options.allowReserved !== "never");15352}15353node.computed = !!computed;15354if (optionalSupported) {15355node.optional = optional;15356}15357base = this.finishNode(node, "MemberExpression");15358} else if (!noCalls && this.eat(types$1.parenL)) {15359var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;15360this.yieldPos = 0;15361this.awaitPos = 0;15362this.awaitIdentPos = 0;15363var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);15364if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {15365this.checkPatternErrors(refDestructuringErrors, false);15366this.checkYieldAwaitInDefaultParams();15367if (this.awaitIdentPos > 0)15368{ this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }15369this.yieldPos = oldYieldPos;15370this.awaitPos = oldAwaitPos;15371this.awaitIdentPos = oldAwaitIdentPos;15372return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)15373}15374this.checkExpressionErrors(refDestructuringErrors, true);15375this.yieldPos = oldYieldPos || this.yieldPos;15376this.awaitPos = oldAwaitPos || this.awaitPos;15377this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;15378var node$1 = this.startNodeAt(startPos, startLoc);15379node$1.callee = base;15380node$1.arguments = exprList;15381if (optionalSupported) {15382node$1.optional = optional;15383}15384base = this.finishNode(node$1, "CallExpression");15385} else if (this.type === types$1.backQuote) {15386if (optional || optionalChained) {15387this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");15388}15389var node$2 = this.startNodeAt(startPos, startLoc);15390node$2.tag = base;15391node$2.quasi = this.parseTemplate({isTagged: true});15392base = this.finishNode(node$2, "TaggedTemplateExpression");15393}15394return base15395};1539615397// Parse an atomic expression — either a single token that is an15398// expression, an expression started by a keyword like `function` or15399// `new`, or an expression wrapped in punctuation like `()`, `[]`,15400// or `{}`.1540115402pp$5.parseExprAtom = function(refDestructuringErrors, forInit) {15403// If a division operator appears in an expression position, the15404// tokenizer got confused, and we force it to read a regexp instead.15405if (this.type === types$1.slash) { this.readRegexp(); }1540615407var node, canBeArrow = this.potentialArrowAt === this.start;15408switch (this.type) {15409case types$1._super:15410if (!this.allowSuper)15411{ this.raise(this.start, "'super' keyword outside a method"); }15412node = this.startNode();15413this.next();15414if (this.type === types$1.parenL && !this.allowDirectSuper)15415{ this.raise(node.start, "super() call outside constructor of a subclass"); }15416// The `super` keyword can appear at below:15417// SuperProperty:15418// super [ Expression ]15419// super . IdentifierName15420// SuperCall:15421// super ( Arguments )15422if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL)15423{ this.unexpected(); }15424return this.finishNode(node, "Super")1542515426case types$1._this:15427node = this.startNode();15428this.next();15429return this.finishNode(node, "ThisExpression")1543015431case types$1.name:15432var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;15433var id = this.parseIdent(false);15434if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {15435this.overrideContext(types.f_expr);15436return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)15437}15438if (canBeArrow && !this.canInsertSemicolon()) {15439if (this.eat(types$1.arrow))15440{ return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) }15441if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc &&15442(!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {15443id = this.parseIdent(false);15444if (this.canInsertSemicolon() || !this.eat(types$1.arrow))15445{ this.unexpected(); }15446return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)15447}15448}15449return id1545015451case types$1.regexp:15452var value = this.value;15453node = this.parseLiteral(value.value);15454node.regex = {pattern: value.pattern, flags: value.flags};15455return node1545615457case types$1.num: case types$1.string:15458return this.parseLiteral(this.value)1545915460case types$1._null: case types$1._true: case types$1._false:15461node = this.startNode();15462node.value = this.type === types$1._null ? null : this.type === types$1._true;15463node.raw = this.type.keyword;15464this.next();15465return this.finishNode(node, "Literal")1546615467case types$1.parenL:15468var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);15469if (refDestructuringErrors) {15470if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))15471{ refDestructuringErrors.parenthesizedAssign = start; }15472if (refDestructuringErrors.parenthesizedBind < 0)15473{ refDestructuringErrors.parenthesizedBind = start; }15474}15475return expr1547615477case types$1.bracketL:15478node = this.startNode();15479this.next();15480node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);15481return this.finishNode(node, "ArrayExpression")1548215483case types$1.braceL:15484this.overrideContext(types.b_expr);15485return this.parseObj(false, refDestructuringErrors)1548615487case types$1._function:15488node = this.startNode();15489this.next();15490return this.parseFunction(node, 0)1549115492case types$1._class:15493return this.parseClass(this.startNode(), false)1549415495case types$1._new:15496return this.parseNew()1549715498case types$1.backQuote:15499return this.parseTemplate()1550015501case types$1._import:15502if (this.options.ecmaVersion >= 11) {15503return this.parseExprImport()15504} else {15505return this.unexpected()15506}1550715508default:15509this.unexpected();15510}15511};1551215513pp$5.parseExprImport = function() {15514var node = this.startNode();1551515516// Consume `import` as an identifier for `import.meta`.15517// Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.15518if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }15519var meta = this.parseIdent(true);1552015521switch (this.type) {15522case types$1.parenL:15523return this.parseDynamicImport(node)15524case types$1.dot:15525node.meta = meta;15526return this.parseImportMeta(node)15527default:15528this.unexpected();15529}15530};1553115532pp$5.parseDynamicImport = function(node) {15533this.next(); // skip `(`1553415535// Parse node.source.15536node.source = this.parseMaybeAssign();1553715538// Verify ending.15539if (!this.eat(types$1.parenR)) {15540var errorPos = this.start;15541if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {15542this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");15543} else {15544this.unexpected(errorPos);15545}15546}1554715548return this.finishNode(node, "ImportExpression")15549};1555015551pp$5.parseImportMeta = function(node) {15552this.next(); // skip `.`1555315554var containsEsc = this.containsEsc;15555node.property = this.parseIdent(true);1555615557if (node.property.name !== "meta")15558{ this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }15559if (containsEsc)15560{ this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }15561if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)15562{ this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }1556315564return this.finishNode(node, "MetaProperty")15565};1556615567pp$5.parseLiteral = function(value) {15568var node = this.startNode();15569node.value = value;15570node.raw = this.input.slice(this.start, this.end);15571if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }15572this.next();15573return this.finishNode(node, "Literal")15574};1557515576pp$5.parseParenExpression = function() {15577this.expect(types$1.parenL);15578var val = this.parseExpression();15579this.expect(types$1.parenR);15580return val15581};1558215583pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {15584var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;15585if (this.options.ecmaVersion >= 6) {15586this.next();1558715588var innerStartPos = this.start, innerStartLoc = this.startLoc;15589var exprList = [], first = true, lastIsComma = false;15590var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;15591this.yieldPos = 0;15592this.awaitPos = 0;15593// Do not save awaitIdentPos to allow checking awaits nested in parameters15594while (this.type !== types$1.parenR) {15595first ? first = false : this.expect(types$1.comma);15596if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {15597lastIsComma = true;15598break15599} else if (this.type === types$1.ellipsis) {15600spreadStart = this.start;15601exprList.push(this.parseParenItem(this.parseRestBinding()));15602if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }15603break15604} else {15605exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));15606}15607}15608var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;15609this.expect(types$1.parenR);1561015611if (canBeArrow && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {15612this.checkPatternErrors(refDestructuringErrors, false);15613this.checkYieldAwaitInDefaultParams();15614this.yieldPos = oldYieldPos;15615this.awaitPos = oldAwaitPos;15616return this.parseParenArrowList(startPos, startLoc, exprList, forInit)15617}1561815619if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }15620if (spreadStart) { this.unexpected(spreadStart); }15621this.checkExpressionErrors(refDestructuringErrors, true);15622this.yieldPos = oldYieldPos || this.yieldPos;15623this.awaitPos = oldAwaitPos || this.awaitPos;1562415625if (exprList.length > 1) {15626val = this.startNodeAt(innerStartPos, innerStartLoc);15627val.expressions = exprList;15628this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);15629} else {15630val = exprList[0];15631}15632} else {15633val = this.parseParenExpression();15634}1563515636if (this.options.preserveParens) {15637var par = this.startNodeAt(startPos, startLoc);15638par.expression = val;15639return this.finishNode(par, "ParenthesizedExpression")15640} else {15641return val15642}15643};1564415645pp$5.parseParenItem = function(item) {15646return item15647};1564815649pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {15650return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit)15651};1565215653// New's precedence is slightly tricky. It must allow its argument to15654// be a `[]` or dot subscript expression, but not a call — at least,15655// not without wrapping it in parentheses. Thus, it uses the noCalls15656// argument to parseSubscripts to prevent it from consuming the15657// argument list.1565815659var empty = [];1566015661pp$5.parseNew = function() {15662if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }15663var node = this.startNode();15664var meta = this.parseIdent(true);15665if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) {15666node.meta = meta;15667var containsEsc = this.containsEsc;15668node.property = this.parseIdent(true);15669if (node.property.name !== "target")15670{ this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }15671if (containsEsc)15672{ this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }15673if (!this.allowNewDotTarget)15674{ this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); }15675return this.finishNode(node, "MetaProperty")15676}15677var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types$1._import;15678node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false);15679if (isImport && node.callee.type === "ImportExpression") {15680this.raise(startPos, "Cannot use new with import()");15681}15682if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); }15683else { node.arguments = empty; }15684return this.finishNode(node, "NewExpression")15685};1568615687// Parse template expression.1568815689pp$5.parseTemplateElement = function(ref) {15690var isTagged = ref.isTagged;1569115692var elem = this.startNode();15693if (this.type === types$1.invalidTemplate) {15694if (!isTagged) {15695this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");15696}15697elem.value = {15698raw: this.value,15699cooked: null15700};15701} else {15702elem.value = {15703raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),15704cooked: this.value15705};15706}15707this.next();15708elem.tail = this.type === types$1.backQuote;15709return this.finishNode(elem, "TemplateElement")15710};1571115712pp$5.parseTemplate = function(ref) {15713if ( ref === void 0 ) ref = {};15714var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;1571515716var node = this.startNode();15717this.next();15718node.expressions = [];15719var curElt = this.parseTemplateElement({isTagged: isTagged});15720node.quasis = [curElt];15721while (!curElt.tail) {15722if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); }15723this.expect(types$1.dollarBraceL);15724node.expressions.push(this.parseExpression());15725this.expect(types$1.braceR);15726node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));15727}15728this.next();15729return this.finishNode(node, "TemplateLiteral")15730};1573115732pp$5.isAsyncProp = function(prop) {15733return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&15734(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)) &&15735!lineBreak.test(this.input.slice(this.lastTokEnd, this.start))15736};1573715738// Parse an object literal or binding pattern.1573915740pp$5.parseObj = function(isPattern, refDestructuringErrors) {15741var node = this.startNode(), first = true, propHash = {};15742node.properties = [];15743this.next();15744while (!this.eat(types$1.braceR)) {15745if (!first) {15746this.expect(types$1.comma);15747if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break }15748} else { first = false; }1574915750var prop = this.parseProperty(isPattern, refDestructuringErrors);15751if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }15752node.properties.push(prop);15753}15754return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")15755};1575615757pp$5.parseProperty = function(isPattern, refDestructuringErrors) {15758var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;15759if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {15760if (isPattern) {15761prop.argument = this.parseIdent(false);15762if (this.type === types$1.comma) {15763this.raise(this.start, "Comma is not permitted after the rest element");15764}15765return this.finishNode(prop, "RestElement")15766}15767// Parse argument.15768prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);15769// To disallow trailing comma via `this.toAssignable()`.15770if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {15771refDestructuringErrors.trailingComma = this.start;15772}15773// Finish15774return this.finishNode(prop, "SpreadElement")15775}15776if (this.options.ecmaVersion >= 6) {15777prop.method = false;15778prop.shorthand = false;15779if (isPattern || refDestructuringErrors) {15780startPos = this.start;15781startLoc = this.startLoc;15782}15783if (!isPattern)15784{ isGenerator = this.eat(types$1.star); }15785}15786var containsEsc = this.containsEsc;15787this.parsePropertyName(prop);15788if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {15789isAsync = true;15790isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);15791this.parsePropertyName(prop, refDestructuringErrors);15792} else {15793isAsync = false;15794}15795this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);15796return this.finishNode(prop, "Property")15797};1579815799pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {15800if ((isGenerator || isAsync) && this.type === types$1.colon)15801{ this.unexpected(); }1580215803if (this.eat(types$1.colon)) {15804prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);15805prop.kind = "init";15806} else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {15807if (isPattern) { this.unexpected(); }15808prop.kind = "init";15809prop.method = true;15810prop.value = this.parseMethod(isGenerator, isAsync);15811} else if (!isPattern && !containsEsc &&15812this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&15813(prop.key.name === "get" || prop.key.name === "set") &&15814(this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {15815if (isGenerator || isAsync) { this.unexpected(); }15816prop.kind = prop.key.name;15817this.parsePropertyName(prop);15818prop.value = this.parseMethod(false);15819var paramCount = prop.kind === "get" ? 0 : 1;15820if (prop.value.params.length !== paramCount) {15821var start = prop.value.start;15822if (prop.kind === "get")15823{ this.raiseRecoverable(start, "getter should have no params"); }15824else15825{ this.raiseRecoverable(start, "setter should have exactly one param"); }15826} else {15827if (prop.kind === "set" && prop.value.params[0].type === "RestElement")15828{ this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }15829}15830} else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {15831if (isGenerator || isAsync) { this.unexpected(); }15832this.checkUnreserved(prop.key);15833if (prop.key.name === "await" && !this.awaitIdentPos)15834{ this.awaitIdentPos = startPos; }15835prop.kind = "init";15836if (isPattern) {15837prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));15838} else if (this.type === types$1.eq && refDestructuringErrors) {15839if (refDestructuringErrors.shorthandAssign < 0)15840{ refDestructuringErrors.shorthandAssign = this.start; }15841prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));15842} else {15843prop.value = this.copyNode(prop.key);15844}15845prop.shorthand = true;15846} else { this.unexpected(); }15847};1584815849pp$5.parsePropertyName = function(prop) {15850if (this.options.ecmaVersion >= 6) {15851if (this.eat(types$1.bracketL)) {15852prop.computed = true;15853prop.key = this.parseMaybeAssign();15854this.expect(types$1.bracketR);15855return prop.key15856} else {15857prop.computed = false;15858}15859}15860return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")15861};1586215863// Initialize empty function node.1586415865pp$5.initFunction = function(node) {15866node.id = null;15867if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }15868if (this.options.ecmaVersion >= 8) { node.async = false; }15869};1587015871// Parse object or class method.1587215873pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {15874var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;1587515876this.initFunction(node);15877if (this.options.ecmaVersion >= 6)15878{ node.generator = isGenerator; }15879if (this.options.ecmaVersion >= 8)15880{ node.async = !!isAsync; }1588115882this.yieldPos = 0;15883this.awaitPos = 0;15884this.awaitIdentPos = 0;15885this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));1588615887this.expect(types$1.parenL);15888node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);15889this.checkYieldAwaitInDefaultParams();15890this.parseFunctionBody(node, false, true, false);1589115892this.yieldPos = oldYieldPos;15893this.awaitPos = oldAwaitPos;15894this.awaitIdentPos = oldAwaitIdentPos;15895return this.finishNode(node, "FunctionExpression")15896};1589715898// Parse arrow function expression with given parameters.1589915900pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {15901var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;1590215903this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);15904this.initFunction(node);15905if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }1590615907this.yieldPos = 0;15908this.awaitPos = 0;15909this.awaitIdentPos = 0;1591015911node.params = this.toAssignableList(params, true);15912this.parseFunctionBody(node, true, false, forInit);1591315914this.yieldPos = oldYieldPos;15915this.awaitPos = oldAwaitPos;15916this.awaitIdentPos = oldAwaitIdentPos;15917return this.finishNode(node, "ArrowFunctionExpression")15918};1591915920// Parse function body and check parameters.1592115922pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {15923var isExpression = isArrowFunction && this.type !== types$1.braceL;15924var oldStrict = this.strict, useStrict = false;1592515926if (isExpression) {15927node.body = this.parseMaybeAssign(forInit);15928node.expression = true;15929this.checkParams(node, false);15930} else {15931var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);15932if (!oldStrict || nonSimple) {15933useStrict = this.strictDirective(this.end);15934// If this is a strict mode function, verify that argument names15935// are not repeated, and it does not try to bind the words `eval`15936// or `arguments`.15937if (useStrict && nonSimple)15938{ this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }15939}15940// Start a new scope with regard to labels and the `inFunction`15941// flag (restore them to their old value afterwards).15942var oldLabels = this.labels;15943this.labels = [];15944if (useStrict) { this.strict = true; }1594515946// Add the params to varDeclaredNames to ensure that an error is thrown15947// if a let/const declaration in the function clashes with one of the params.15948this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));15949// Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'15950if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }15951node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);15952node.expression = false;15953this.adaptDirectivePrologue(node.body.body);15954this.labels = oldLabels;15955}15956this.exitScope();15957};1595815959pp$5.isSimpleParamList = function(params) {15960for (var i = 0, list = params; i < list.length; i += 1)15961{15962var param = list[i];1596315964if (param.type !== "Identifier") { return false15965} }15966return true15967};1596815969// Checks function params for various disallowed patterns such as using "eval"15970// or "arguments" and duplicate parameters.1597115972pp$5.checkParams = function(node, allowDuplicates) {15973var nameHash = Object.create(null);15974for (var i = 0, list = node.params; i < list.length; i += 1)15975{15976var param = list[i];1597715978this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);15979}15980};1598115982// Parses a comma-separated list of expressions, and returns them as15983// an array. `close` is the token type that ends the list, and15984// `allowEmpty` can be turned on to allow subsequent commas with15985// nothing in between them to be parsed as `null` (which is needed15986// for array literals).1598715988pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {15989var elts = [], first = true;15990while (!this.eat(close)) {15991if (!first) {15992this.expect(types$1.comma);15993if (allowTrailingComma && this.afterTrailingComma(close)) { break }15994} else { first = false; }1599515996var elt = (void 0);15997if (allowEmpty && this.type === types$1.comma)15998{ elt = null; }15999else if (this.type === types$1.ellipsis) {16000elt = this.parseSpread(refDestructuringErrors);16001if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0)16002{ refDestructuringErrors.trailingComma = this.start; }16003} else {16004elt = this.parseMaybeAssign(false, refDestructuringErrors);16005}16006elts.push(elt);16007}16008return elts16009};1601016011pp$5.checkUnreserved = function(ref) {16012var start = ref.start;16013var end = ref.end;16014var name = ref.name;1601516016if (this.inGenerator && name === "yield")16017{ this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }16018if (this.inAsync && name === "await")16019{ this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }16020if (this.currentThisScope().inClassFieldInit && name === "arguments")16021{ this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }16022if (this.inClassStaticBlock && (name === "arguments" || name === "await"))16023{ this.raise(start, ("Cannot use " + name + " in class static initialization block")); }16024if (this.keywords.test(name))16025{ this.raise(start, ("Unexpected keyword '" + name + "'")); }16026if (this.options.ecmaVersion < 6 &&16027this.input.slice(start, end).indexOf("\\") !== -1) { return }16028var re = this.strict ? this.reservedWordsStrict : this.reservedWords;16029if (re.test(name)) {16030if (!this.inAsync && name === "await")16031{ this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }16032this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));16033}16034};1603516036// Parse the next token as an identifier. If `liberal` is true (used16037// when parsing properties), it will also convert keywords into16038// identifiers.1603916040pp$5.parseIdent = function(liberal, isBinding) {16041var node = this.startNode();16042if (this.type === types$1.name) {16043node.name = this.value;16044} else if (this.type.keyword) {16045node.name = this.type.keyword;1604616047// To fix https://github.com/acornjs/acorn/issues/57516048// `class` and `function` keywords push new context into this.context.16049// But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.16050// If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword16051if ((node.name === "class" || node.name === "function") &&16052(this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {16053this.context.pop();16054}16055} else {16056this.unexpected();16057}16058this.next(!!liberal);16059this.finishNode(node, "Identifier");16060if (!liberal) {16061this.checkUnreserved(node);16062if (node.name === "await" && !this.awaitIdentPos)16063{ this.awaitIdentPos = node.start; }16064}16065return node16066};1606716068pp$5.parsePrivateIdent = function() {16069var node = this.startNode();16070if (this.type === types$1.privateId) {16071node.name = this.value;16072} else {16073this.unexpected();16074}16075this.next();16076this.finishNode(node, "PrivateIdentifier");1607716078// For validating existence16079if (this.privateNameStack.length === 0) {16080this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));16081} else {16082this.privateNameStack[this.privateNameStack.length - 1].used.push(node);16083}1608416085return node16086};1608716088// Parses yield expression inside generator.1608916090pp$5.parseYield = function(forInit) {16091if (!this.yieldPos) { this.yieldPos = this.start; }1609216093var node = this.startNode();16094this.next();16095if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) {16096node.delegate = false;16097node.argument = null;16098} else {16099node.delegate = this.eat(types$1.star);16100node.argument = this.parseMaybeAssign(forInit);16101}16102return this.finishNode(node, "YieldExpression")16103};1610416105pp$5.parseAwait = function(forInit) {16106if (!this.awaitPos) { this.awaitPos = this.start; }1610716108var node = this.startNode();16109this.next();16110node.argument = this.parseMaybeUnary(null, true, false, forInit);16111return this.finishNode(node, "AwaitExpression")16112};1611316114var pp$4 = Parser.prototype;1611516116// This function is used to raise exceptions on parse errors. It16117// takes an offset integer (into the current `input`) to indicate16118// the location of the error, attaches the position to the end16119// of the error message, and then raises a `SyntaxError` with that16120// message.1612116122pp$4.raise = function(pos, message) {16123var loc = getLineInfo(this.input, pos);16124message += " (" + loc.line + ":" + loc.column + ")";16125var err = new SyntaxError(message);16126err.pos = pos; err.loc = loc; err.raisedAt = this.pos;16127throw err16128};1612916130pp$4.raiseRecoverable = pp$4.raise;1613116132pp$4.curPosition = function() {16133if (this.options.locations) {16134return new Position(this.curLine, this.pos - this.lineStart)16135}16136};1613716138var pp$3 = Parser.prototype;1613916140var Scope = function Scope(flags) {16141this.flags = flags;16142// A list of var-declared names in the current lexical scope16143this.var = [];16144// A list of lexically-declared names in the current lexical scope16145this.lexical = [];16146// A list of lexically-declared FunctionDeclaration names in the current lexical scope16147this.functions = [];16148// A switch to disallow the identifier reference 'arguments'16149this.inClassFieldInit = false;16150};1615116152// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.1615316154pp$3.enterScope = function(flags) {16155this.scopeStack.push(new Scope(flags));16156};1615716158pp$3.exitScope = function() {16159this.scopeStack.pop();16160};1616116162// The spec says:16163// > At the top level of a function, or script, function declarations are16164// > treated like var declarations rather than like lexical declarations.16165pp$3.treatFunctionsAsVarInScope = function(scope) {16166return (scope.flags & SCOPE_FUNCTION$1) || !this.inModule && (scope.flags & SCOPE_TOP)16167};1616816169pp$3.declareName = function(name, bindingType, pos) {16170var redeclared = false;16171if (bindingType === BIND_LEXICAL) {16172var scope = this.currentScope();16173redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;16174scope.lexical.push(name);16175if (this.inModule && (scope.flags & SCOPE_TOP))16176{ delete this.undefinedExports[name]; }16177} else if (bindingType === BIND_SIMPLE_CATCH) {16178var scope$1 = this.currentScope();16179scope$1.lexical.push(name);16180} else if (bindingType === BIND_FUNCTION) {16181var scope$2 = this.currentScope();16182if (this.treatFunctionsAsVar)16183{ redeclared = scope$2.lexical.indexOf(name) > -1; }16184else16185{ redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }16186scope$2.functions.push(name);16187} else {16188for (var i = this.scopeStack.length - 1; i >= 0; --i) {16189var scope$3 = this.scopeStack[i];16190if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||16191!this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {16192redeclared = true;16193break16194}16195scope$3.var.push(name);16196if (this.inModule && (scope$3.flags & SCOPE_TOP))16197{ delete this.undefinedExports[name]; }16198if (scope$3.flags & SCOPE_VAR) { break }16199}16200}16201if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }16202};1620316204pp$3.checkLocalExport = function(id) {16205// scope.functions must be empty as Module code is always strict.16206if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&16207this.scopeStack[0].var.indexOf(id.name) === -1) {16208this.undefinedExports[id.name] = id;16209}16210};1621116212pp$3.currentScope = function() {16213return this.scopeStack[this.scopeStack.length - 1]16214};1621516216pp$3.currentVarScope = function() {16217for (var i = this.scopeStack.length - 1;; i--) {16218var scope = this.scopeStack[i];16219if (scope.flags & SCOPE_VAR) { return scope }16220}16221};1622216223// Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.16224pp$3.currentThisScope = function() {16225for (var i = this.scopeStack.length - 1;; i--) {16226var scope = this.scopeStack[i];16227if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }16228}16229};1623016231var Node$1 = function Node(parser, pos, loc) {16232this.type = "";16233this.start = pos;16234this.end = 0;16235if (parser.options.locations)16236{ this.loc = new SourceLocation(parser, loc); }16237if (parser.options.directSourceFile)16238{ this.sourceFile = parser.options.directSourceFile; }16239if (parser.options.ranges)16240{ this.range = [pos, 0]; }16241};1624216243// Start an AST node, attaching a start offset.1624416245var pp$2 = Parser.prototype;1624616247pp$2.startNode = function() {16248return new Node$1(this, this.start, this.startLoc)16249};1625016251pp$2.startNodeAt = function(pos, loc) {16252return new Node$1(this, pos, loc)16253};1625416255// Finish an AST node, adding `type` and `end` properties.1625616257function finishNodeAt(node, type, pos, loc) {16258node.type = type;16259node.end = pos;16260if (this.options.locations)16261{ node.loc.end = loc; }16262if (this.options.ranges)16263{ node.range[1] = pos; }16264return node16265}1626616267pp$2.finishNode = function(node, type) {16268return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)16269};1627016271// Finish node at given position1627216273pp$2.finishNodeAt = function(node, type, pos, loc) {16274return finishNodeAt.call(this, node, type, pos, loc)16275};1627616277pp$2.copyNode = function(node) {16278var newNode = new Node$1(this, node.start, this.startLoc);16279for (var prop in node) { newNode[prop] = node[prop]; }16280return newNode16281};1628216283// This file contains Unicode properties extracted from the ECMAScript16284// specification. The lists are extracted like so:16285// $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)1628616287// #table-binary-unicode-properties16288var 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";16289var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";16290var ecma11BinaryProperties = ecma10BinaryProperties;16291var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";16292var ecma13BinaryProperties = ecma12BinaryProperties;16293var unicodeBinaryProperties = {162949: ecma9BinaryProperties,1629510: ecma10BinaryProperties,1629611: ecma11BinaryProperties,1629712: ecma12BinaryProperties,1629813: ecma13BinaryProperties16299};1630016301// #table-unicode-general-category-values16302var 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";1630316304// #table-unicode-script-values16305var 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";16306var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";16307var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";16308var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";16309var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";16310var unicodeScriptValues = {163119: ecma9ScriptValues,1631210: ecma10ScriptValues,1631311: ecma11ScriptValues,1631412: ecma12ScriptValues,1631513: ecma13ScriptValues16316};1631716318var data = {};16319function buildUnicodeData(ecmaVersion) {16320var d = data[ecmaVersion] = {16321binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),16322nonBinary: {16323General_Category: wordsRegexp(unicodeGeneralCategoryValues),16324Script: wordsRegexp(unicodeScriptValues[ecmaVersion])16325}16326};16327d.nonBinary.Script_Extensions = d.nonBinary.Script;1632816329d.nonBinary.gc = d.nonBinary.General_Category;16330d.nonBinary.sc = d.nonBinary.Script;16331d.nonBinary.scx = d.nonBinary.Script_Extensions;16332}1633316334for (var i = 0, list = [9, 10, 11, 12, 13]; i < list.length; i += 1) {16335var ecmaVersion = list[i];1633616337buildUnicodeData(ecmaVersion);16338}1633916340var pp$1 = Parser.prototype;1634116342var RegExpValidationState = function RegExpValidationState(parser) {16343this.parser = parser;16344this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "");16345this.unicodeProperties = data[parser.options.ecmaVersion >= 13 ? 13 : parser.options.ecmaVersion];16346this.source = "";16347this.flags = "";16348this.start = 0;16349this.switchU = false;16350this.switchN = false;16351this.pos = 0;16352this.lastIntValue = 0;16353this.lastStringValue = "";16354this.lastAssertionIsQuantifiable = false;16355this.numCapturingParens = 0;16356this.maxBackReference = 0;16357this.groupNames = [];16358this.backReferenceNames = [];16359};1636016361RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {16362var unicode = flags.indexOf("u") !== -1;16363this.start = start | 0;16364this.source = pattern + "";16365this.flags = flags;16366this.switchU = unicode && this.parser.options.ecmaVersion >= 6;16367this.switchN = unicode && this.parser.options.ecmaVersion >= 9;16368};1636916370RegExpValidationState.prototype.raise = function raise (message) {16371this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));16372};1637316374// If u flag is given, this returns the code point at the index (it combines a surrogate pair).16375// Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).16376RegExpValidationState.prototype.at = function at (i, forceU) {16377if ( forceU === void 0 ) forceU = false;1637816379var s = this.source;16380var l = s.length;16381if (i >= l) {16382return -116383}16384var c = s.charCodeAt(i);16385if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {16386return c16387}16388var next = s.charCodeAt(i + 1);16389return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c16390};1639116392RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {16393if ( forceU === void 0 ) forceU = false;1639416395var s = this.source;16396var l = s.length;16397if (i >= l) {16398return l16399}16400var c = s.charCodeAt(i), next;16401if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||16402(next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {16403return i + 116404}16405return i + 216406};1640716408RegExpValidationState.prototype.current = function current (forceU) {16409if ( forceU === void 0 ) forceU = false;1641016411return this.at(this.pos, forceU)16412};1641316414RegExpValidationState.prototype.lookahead = function lookahead (forceU) {16415if ( forceU === void 0 ) forceU = false;1641616417return this.at(this.nextIndex(this.pos, forceU), forceU)16418};1641916420RegExpValidationState.prototype.advance = function advance (forceU) {16421if ( forceU === void 0 ) forceU = false;1642216423this.pos = this.nextIndex(this.pos, forceU);16424};1642516426RegExpValidationState.prototype.eat = function eat (ch, forceU) {16427if ( forceU === void 0 ) forceU = false;1642816429if (this.current(forceU) === ch) {16430this.advance(forceU);16431return true16432}16433return false16434};1643516436/**16437* Validate the flags part of a given RegExpLiteral.16438*16439* @param {RegExpValidationState} state The state to validate RegExp.16440* @returns {void}16441*/16442pp$1.validateRegExpFlags = function(state) {16443var validFlags = state.validFlags;16444var flags = state.flags;1644516446for (var i = 0; i < flags.length; i++) {16447var flag = flags.charAt(i);16448if (validFlags.indexOf(flag) === -1) {16449this.raise(state.start, "Invalid regular expression flag");16450}16451if (flags.indexOf(flag, i + 1) > -1) {16452this.raise(state.start, "Duplicate regular expression flag");16453}16454}16455};1645616457/**16458* Validate the pattern part of a given RegExpLiteral.16459*16460* @param {RegExpValidationState} state The state to validate RegExp.16461* @returns {void}16462*/16463pp$1.validateRegExpPattern = function(state) {16464this.regexp_pattern(state);1646516466// The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of16467// parsing contains a |GroupName|, reparse with the goal symbol16468// |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*16469// exception if _P_ did not conform to the grammar, if any elements of _P_16470// were not matched by the parse, or if any Early Error conditions exist.16471if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {16472state.switchN = true;16473this.regexp_pattern(state);16474}16475};1647616477// https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern16478pp$1.regexp_pattern = function(state) {16479state.pos = 0;16480state.lastIntValue = 0;16481state.lastStringValue = "";16482state.lastAssertionIsQuantifiable = false;16483state.numCapturingParens = 0;16484state.maxBackReference = 0;16485state.groupNames.length = 0;16486state.backReferenceNames.length = 0;1648716488this.regexp_disjunction(state);1648916490if (state.pos !== state.source.length) {16491// Make the same messages as V8.16492if (state.eat(0x29 /* ) */)) {16493state.raise("Unmatched ')'");16494}16495if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {16496state.raise("Lone quantifier brackets");16497}16498}16499if (state.maxBackReference > state.numCapturingParens) {16500state.raise("Invalid escape");16501}16502for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {16503var name = list[i];1650416505if (state.groupNames.indexOf(name) === -1) {16506state.raise("Invalid named capture referenced");16507}16508}16509};1651016511// https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction16512pp$1.regexp_disjunction = function(state) {16513this.regexp_alternative(state);16514while (state.eat(0x7C /* | */)) {16515this.regexp_alternative(state);16516}1651716518// Make the same message as V8.16519if (this.regexp_eatQuantifier(state, true)) {16520state.raise("Nothing to repeat");16521}16522if (state.eat(0x7B /* { */)) {16523state.raise("Lone quantifier brackets");16524}16525};1652616527// https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative16528pp$1.regexp_alternative = function(state) {16529while (state.pos < state.source.length && this.regexp_eatTerm(state))16530{ }16531};1653216533// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term16534pp$1.regexp_eatTerm = function(state) {16535if (this.regexp_eatAssertion(state)) {16536// Handle `QuantifiableAssertion Quantifier` alternative.16537// `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion16538// is a QuantifiableAssertion.16539if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {16540// Make the same message as V8.16541if (state.switchU) {16542state.raise("Invalid quantifier");16543}16544}16545return true16546}1654716548if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {16549this.regexp_eatQuantifier(state);16550return true16551}1655216553return false16554};1655516556// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion16557pp$1.regexp_eatAssertion = function(state) {16558var start = state.pos;16559state.lastAssertionIsQuantifiable = false;1656016561// ^, $16562if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {16563return true16564}1656516566// \b \B16567if (state.eat(0x5C /* \ */)) {16568if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {16569return true16570}16571state.pos = start;16572}1657316574// Lookahead / Lookbehind16575if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {16576var lookbehind = false;16577if (this.options.ecmaVersion >= 9) {16578lookbehind = state.eat(0x3C /* < */);16579}16580if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {16581this.regexp_disjunction(state);16582if (!state.eat(0x29 /* ) */)) {16583state.raise("Unterminated group");16584}16585state.lastAssertionIsQuantifiable = !lookbehind;16586return true16587}16588}1658916590state.pos = start;16591return false16592};1659316594// https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier16595pp$1.regexp_eatQuantifier = function(state, noError) {16596if ( noError === void 0 ) noError = false;1659716598if (this.regexp_eatQuantifierPrefix(state, noError)) {16599state.eat(0x3F /* ? */);16600return true16601}16602return false16603};1660416605// https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix16606pp$1.regexp_eatQuantifierPrefix = function(state, noError) {16607return (16608state.eat(0x2A /* * */) ||16609state.eat(0x2B /* + */) ||16610state.eat(0x3F /* ? */) ||16611this.regexp_eatBracedQuantifier(state, noError)16612)16613};16614pp$1.regexp_eatBracedQuantifier = function(state, noError) {16615var start = state.pos;16616if (state.eat(0x7B /* { */)) {16617var min = 0, max = -1;16618if (this.regexp_eatDecimalDigits(state)) {16619min = state.lastIntValue;16620if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {16621max = state.lastIntValue;16622}16623if (state.eat(0x7D /* } */)) {16624// SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term16625if (max !== -1 && max < min && !noError) {16626state.raise("numbers out of order in {} quantifier");16627}16628return true16629}16630}16631if (state.switchU && !noError) {16632state.raise("Incomplete quantifier");16633}16634state.pos = start;16635}16636return false16637};1663816639// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom16640pp$1.regexp_eatAtom = function(state) {16641return (16642this.regexp_eatPatternCharacters(state) ||16643state.eat(0x2E /* . */) ||16644this.regexp_eatReverseSolidusAtomEscape(state) ||16645this.regexp_eatCharacterClass(state) ||16646this.regexp_eatUncapturingGroup(state) ||16647this.regexp_eatCapturingGroup(state)16648)16649};16650pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {16651var start = state.pos;16652if (state.eat(0x5C /* \ */)) {16653if (this.regexp_eatAtomEscape(state)) {16654return true16655}16656state.pos = start;16657}16658return false16659};16660pp$1.regexp_eatUncapturingGroup = function(state) {16661var start = state.pos;16662if (state.eat(0x28 /* ( */)) {16663if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {16664this.regexp_disjunction(state);16665if (state.eat(0x29 /* ) */)) {16666return true16667}16668state.raise("Unterminated group");16669}16670state.pos = start;16671}16672return false16673};16674pp$1.regexp_eatCapturingGroup = function(state) {16675if (state.eat(0x28 /* ( */)) {16676if (this.options.ecmaVersion >= 9) {16677this.regexp_groupSpecifier(state);16678} else if (state.current() === 0x3F /* ? */) {16679state.raise("Invalid group");16680}16681this.regexp_disjunction(state);16682if (state.eat(0x29 /* ) */)) {16683state.numCapturingParens += 1;16684return true16685}16686state.raise("Unterminated group");16687}16688return false16689};1669016691// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom16692pp$1.regexp_eatExtendedAtom = function(state) {16693return (16694state.eat(0x2E /* . */) ||16695this.regexp_eatReverseSolidusAtomEscape(state) ||16696this.regexp_eatCharacterClass(state) ||16697this.regexp_eatUncapturingGroup(state) ||16698this.regexp_eatCapturingGroup(state) ||16699this.regexp_eatInvalidBracedQuantifier(state) ||16700this.regexp_eatExtendedPatternCharacter(state)16701)16702};1670316704// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier16705pp$1.regexp_eatInvalidBracedQuantifier = function(state) {16706if (this.regexp_eatBracedQuantifier(state, true)) {16707state.raise("Nothing to repeat");16708}16709return false16710};1671116712// https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter16713pp$1.regexp_eatSyntaxCharacter = function(state) {16714var ch = state.current();16715if (isSyntaxCharacter(ch)) {16716state.lastIntValue = ch;16717state.advance();16718return true16719}16720return false16721};16722function isSyntaxCharacter(ch) {16723return (16724ch === 0x24 /* $ */ ||16725ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||16726ch === 0x2E /* . */ ||16727ch === 0x3F /* ? */ ||16728ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||16729ch >= 0x7B /* { */ && ch <= 0x7D /* } */16730)16731}1673216733// https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter16734// But eat eager.16735pp$1.regexp_eatPatternCharacters = function(state) {16736var start = state.pos;16737var ch = 0;16738while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {16739state.advance();16740}16741return state.pos !== start16742};1674316744// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter16745pp$1.regexp_eatExtendedPatternCharacter = function(state) {16746var ch = state.current();16747if (16748ch !== -1 &&16749ch !== 0x24 /* $ */ &&16750!(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&16751ch !== 0x2E /* . */ &&16752ch !== 0x3F /* ? */ &&16753ch !== 0x5B /* [ */ &&16754ch !== 0x5E /* ^ */ &&16755ch !== 0x7C /* | */16756) {16757state.advance();16758return true16759}16760return false16761};1676216763// GroupSpecifier ::16764// [empty]16765// `?` GroupName16766pp$1.regexp_groupSpecifier = function(state) {16767if (state.eat(0x3F /* ? */)) {16768if (this.regexp_eatGroupName(state)) {16769if (state.groupNames.indexOf(state.lastStringValue) !== -1) {16770state.raise("Duplicate capture group name");16771}16772state.groupNames.push(state.lastStringValue);16773return16774}16775state.raise("Invalid group");16776}16777};1677816779// GroupName ::16780// `<` RegExpIdentifierName `>`16781// Note: this updates `state.lastStringValue` property with the eaten name.16782pp$1.regexp_eatGroupName = function(state) {16783state.lastStringValue = "";16784if (state.eat(0x3C /* < */)) {16785if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {16786return true16787}16788state.raise("Invalid capture group name");16789}16790return false16791};1679216793// RegExpIdentifierName ::16794// RegExpIdentifierStart16795// RegExpIdentifierName RegExpIdentifierPart16796// Note: this updates `state.lastStringValue` property with the eaten name.16797pp$1.regexp_eatRegExpIdentifierName = function(state) {16798state.lastStringValue = "";16799if (this.regexp_eatRegExpIdentifierStart(state)) {16800state.lastStringValue += codePointToString(state.lastIntValue);16801while (this.regexp_eatRegExpIdentifierPart(state)) {16802state.lastStringValue += codePointToString(state.lastIntValue);16803}16804return true16805}16806return false16807};1680816809// RegExpIdentifierStart ::16810// UnicodeIDStart16811// `$`16812// `_`16813// `\` RegExpUnicodeEscapeSequence[+U]16814pp$1.regexp_eatRegExpIdentifierStart = function(state) {16815var start = state.pos;16816var forceU = this.options.ecmaVersion >= 11;16817var ch = state.current(forceU);16818state.advance(forceU);1681916820if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {16821ch = state.lastIntValue;16822}16823if (isRegExpIdentifierStart(ch)) {16824state.lastIntValue = ch;16825return true16826}1682716828state.pos = start;16829return false16830};16831function isRegExpIdentifierStart(ch) {16832return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */16833}1683416835// RegExpIdentifierPart ::16836// UnicodeIDContinue16837// `$`16838// `_`16839// `\` RegExpUnicodeEscapeSequence[+U]16840// <ZWNJ>16841// <ZWJ>16842pp$1.regexp_eatRegExpIdentifierPart = function(state) {16843var start = state.pos;16844var forceU = this.options.ecmaVersion >= 11;16845var ch = state.current(forceU);16846state.advance(forceU);1684716848if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {16849ch = state.lastIntValue;16850}16851if (isRegExpIdentifierPart(ch)) {16852state.lastIntValue = ch;16853return true16854}1685516856state.pos = start;16857return false16858};16859function isRegExpIdentifierPart(ch) {16860return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */16861}1686216863// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape16864pp$1.regexp_eatAtomEscape = function(state) {16865if (16866this.regexp_eatBackReference(state) ||16867this.regexp_eatCharacterClassEscape(state) ||16868this.regexp_eatCharacterEscape(state) ||16869(state.switchN && this.regexp_eatKGroupName(state))16870) {16871return true16872}16873if (state.switchU) {16874// Make the same message as V8.16875if (state.current() === 0x63 /* c */) {16876state.raise("Invalid unicode escape");16877}16878state.raise("Invalid escape");16879}16880return false16881};16882pp$1.regexp_eatBackReference = function(state) {16883var start = state.pos;16884if (this.regexp_eatDecimalEscape(state)) {16885var n = state.lastIntValue;16886if (state.switchU) {16887// For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape16888if (n > state.maxBackReference) {16889state.maxBackReference = n;16890}16891return true16892}16893if (n <= state.numCapturingParens) {16894return true16895}16896state.pos = start;16897}16898return false16899};16900pp$1.regexp_eatKGroupName = function(state) {16901if (state.eat(0x6B /* k */)) {16902if (this.regexp_eatGroupName(state)) {16903state.backReferenceNames.push(state.lastStringValue);16904return true16905}16906state.raise("Invalid named reference");16907}16908return false16909};1691016911// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape16912pp$1.regexp_eatCharacterEscape = function(state) {16913return (16914this.regexp_eatControlEscape(state) ||16915this.regexp_eatCControlLetter(state) ||16916this.regexp_eatZero(state) ||16917this.regexp_eatHexEscapeSequence(state) ||16918this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||16919(!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||16920this.regexp_eatIdentityEscape(state)16921)16922};16923pp$1.regexp_eatCControlLetter = function(state) {16924var start = state.pos;16925if (state.eat(0x63 /* c */)) {16926if (this.regexp_eatControlLetter(state)) {16927return true16928}16929state.pos = start;16930}16931return false16932};16933pp$1.regexp_eatZero = function(state) {16934if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {16935state.lastIntValue = 0;16936state.advance();16937return true16938}16939return false16940};1694116942// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape16943pp$1.regexp_eatControlEscape = function(state) {16944var ch = state.current();16945if (ch === 0x74 /* t */) {16946state.lastIntValue = 0x09; /* \t */16947state.advance();16948return true16949}16950if (ch === 0x6E /* n */) {16951state.lastIntValue = 0x0A; /* \n */16952state.advance();16953return true16954}16955if (ch === 0x76 /* v */) {16956state.lastIntValue = 0x0B; /* \v */16957state.advance();16958return true16959}16960if (ch === 0x66 /* f */) {16961state.lastIntValue = 0x0C; /* \f */16962state.advance();16963return true16964}16965if (ch === 0x72 /* r */) {16966state.lastIntValue = 0x0D; /* \r */16967state.advance();16968return true16969}16970return false16971};1697216973// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter16974pp$1.regexp_eatControlLetter = function(state) {16975var ch = state.current();16976if (isControlLetter(ch)) {16977state.lastIntValue = ch % 0x20;16978state.advance();16979return true16980}16981return false16982};16983function isControlLetter(ch) {16984return (16985(ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||16986(ch >= 0x61 /* a */ && ch <= 0x7A /* z */)16987)16988}1698916990// https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence16991pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {16992if ( forceU === void 0 ) forceU = false;1699316994var start = state.pos;16995var switchU = forceU || state.switchU;1699616997if (state.eat(0x75 /* u */)) {16998if (this.regexp_eatFixedHexDigits(state, 4)) {16999var lead = state.lastIntValue;17000if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {17001var leadSurrogateEnd = state.pos;17002if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {17003var trail = state.lastIntValue;17004if (trail >= 0xDC00 && trail <= 0xDFFF) {17005state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;17006return true17007}17008}17009state.pos = leadSurrogateEnd;17010state.lastIntValue = lead;17011}17012return true17013}17014if (17015switchU &&17016state.eat(0x7B /* { */) &&17017this.regexp_eatHexDigits(state) &&17018state.eat(0x7D /* } */) &&17019isValidUnicode(state.lastIntValue)17020) {17021return true17022}17023if (switchU) {17024state.raise("Invalid unicode escape");17025}17026state.pos = start;17027}1702817029return false17030};17031function isValidUnicode(ch) {17032return ch >= 0 && ch <= 0x10FFFF17033}1703417035// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape17036pp$1.regexp_eatIdentityEscape = function(state) {17037if (state.switchU) {17038if (this.regexp_eatSyntaxCharacter(state)) {17039return true17040}17041if (state.eat(0x2F /* / */)) {17042state.lastIntValue = 0x2F; /* / */17043return true17044}17045return false17046}1704717048var ch = state.current();17049if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {17050state.lastIntValue = ch;17051state.advance();17052return true17053}1705417055return false17056};1705717058// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape17059pp$1.regexp_eatDecimalEscape = function(state) {17060state.lastIntValue = 0;17061var ch = state.current();17062if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {17063do {17064state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);17065state.advance();17066} while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)17067return true17068}17069return false17070};1707117072// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape17073pp$1.regexp_eatCharacterClassEscape = function(state) {17074var ch = state.current();1707517076if (isCharacterClassEscape(ch)) {17077state.lastIntValue = -1;17078state.advance();17079return true17080}1708117082if (17083state.switchU &&17084this.options.ecmaVersion >= 9 &&17085(ch === 0x50 /* P */ || ch === 0x70 /* p */)17086) {17087state.lastIntValue = -1;17088state.advance();17089if (17090state.eat(0x7B /* { */) &&17091this.regexp_eatUnicodePropertyValueExpression(state) &&17092state.eat(0x7D /* } */)17093) {17094return true17095}17096state.raise("Invalid property name");17097}1709817099return false17100};17101function isCharacterClassEscape(ch) {17102return (17103ch === 0x64 /* d */ ||17104ch === 0x44 /* D */ ||17105ch === 0x73 /* s */ ||17106ch === 0x53 /* S */ ||17107ch === 0x77 /* w */ ||17108ch === 0x57 /* W */17109)17110}1711117112// UnicodePropertyValueExpression ::17113// UnicodePropertyName `=` UnicodePropertyValue17114// LoneUnicodePropertyNameOrValue17115pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {17116var start = state.pos;1711717118// UnicodePropertyName `=` UnicodePropertyValue17119if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {17120var name = state.lastStringValue;17121if (this.regexp_eatUnicodePropertyValue(state)) {17122var value = state.lastStringValue;17123this.regexp_validateUnicodePropertyNameAndValue(state, name, value);17124return true17125}17126}17127state.pos = start;1712817129// LoneUnicodePropertyNameOrValue17130if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {17131var nameOrValue = state.lastStringValue;17132this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);17133return true17134}17135return false17136};17137pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {17138if (!hasOwn(state.unicodeProperties.nonBinary, name))17139{ state.raise("Invalid property name"); }17140if (!state.unicodeProperties.nonBinary[name].test(value))17141{ state.raise("Invalid property value"); }17142};17143pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {17144if (!state.unicodeProperties.binary.test(nameOrValue))17145{ state.raise("Invalid property name"); }17146};1714717148// UnicodePropertyName ::17149// UnicodePropertyNameCharacters17150pp$1.regexp_eatUnicodePropertyName = function(state) {17151var ch = 0;17152state.lastStringValue = "";17153while (isUnicodePropertyNameCharacter(ch = state.current())) {17154state.lastStringValue += codePointToString(ch);17155state.advance();17156}17157return state.lastStringValue !== ""17158};17159function isUnicodePropertyNameCharacter(ch) {17160return isControlLetter(ch) || ch === 0x5F /* _ */17161}1716217163// UnicodePropertyValue ::17164// UnicodePropertyValueCharacters17165pp$1.regexp_eatUnicodePropertyValue = function(state) {17166var ch = 0;17167state.lastStringValue = "";17168while (isUnicodePropertyValueCharacter(ch = state.current())) {17169state.lastStringValue += codePointToString(ch);17170state.advance();17171}17172return state.lastStringValue !== ""17173};17174function isUnicodePropertyValueCharacter(ch) {17175return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)17176}1717717178// LoneUnicodePropertyNameOrValue ::17179// UnicodePropertyValueCharacters17180pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {17181return this.regexp_eatUnicodePropertyValue(state)17182};1718317184// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass17185pp$1.regexp_eatCharacterClass = function(state) {17186if (state.eat(0x5B /* [ */)) {17187state.eat(0x5E /* ^ */);17188this.regexp_classRanges(state);17189if (state.eat(0x5D /* ] */)) {17190return true17191}17192// Unreachable since it threw "unterminated regular expression" error before.17193state.raise("Unterminated character class");17194}17195return false17196};1719717198// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges17199// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges17200// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash17201pp$1.regexp_classRanges = function(state) {17202while (this.regexp_eatClassAtom(state)) {17203var left = state.lastIntValue;17204if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {17205var right = state.lastIntValue;17206if (state.switchU && (left === -1 || right === -1)) {17207state.raise("Invalid character class");17208}17209if (left !== -1 && right !== -1 && left > right) {17210state.raise("Range out of order in character class");17211}17212}17213}17214};1721517216// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom17217// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash17218pp$1.regexp_eatClassAtom = function(state) {17219var start = state.pos;1722017221if (state.eat(0x5C /* \ */)) {17222if (this.regexp_eatClassEscape(state)) {17223return true17224}17225if (state.switchU) {17226// Make the same message as V8.17227var ch$1 = state.current();17228if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {17229state.raise("Invalid class escape");17230}17231state.raise("Invalid escape");17232}17233state.pos = start;17234}1723517236var ch = state.current();17237if (ch !== 0x5D /* ] */) {17238state.lastIntValue = ch;17239state.advance();17240return true17241}1724217243return false17244};1724517246// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape17247pp$1.regexp_eatClassEscape = function(state) {17248var start = state.pos;1724917250if (state.eat(0x62 /* b */)) {17251state.lastIntValue = 0x08; /* <BS> */17252return true17253}1725417255if (state.switchU && state.eat(0x2D /* - */)) {17256state.lastIntValue = 0x2D; /* - */17257return true17258}1725917260if (!state.switchU && state.eat(0x63 /* c */)) {17261if (this.regexp_eatClassControlLetter(state)) {17262return true17263}17264state.pos = start;17265}1726617267return (17268this.regexp_eatCharacterClassEscape(state) ||17269this.regexp_eatCharacterEscape(state)17270)17271};1727217273// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter17274pp$1.regexp_eatClassControlLetter = function(state) {17275var ch = state.current();17276if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {17277state.lastIntValue = ch % 0x20;17278state.advance();17279return true17280}17281return false17282};1728317284// https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence17285pp$1.regexp_eatHexEscapeSequence = function(state) {17286var start = state.pos;17287if (state.eat(0x78 /* x */)) {17288if (this.regexp_eatFixedHexDigits(state, 2)) {17289return true17290}17291if (state.switchU) {17292state.raise("Invalid escape");17293}17294state.pos = start;17295}17296return false17297};1729817299// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits17300pp$1.regexp_eatDecimalDigits = function(state) {17301var start = state.pos;17302var ch = 0;17303state.lastIntValue = 0;17304while (isDecimalDigit(ch = state.current())) {17305state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);17306state.advance();17307}17308return state.pos !== start17309};17310function isDecimalDigit(ch) {17311return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */17312}1731317314// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits17315pp$1.regexp_eatHexDigits = function(state) {17316var start = state.pos;17317var ch = 0;17318state.lastIntValue = 0;17319while (isHexDigit(ch = state.current())) {17320state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);17321state.advance();17322}17323return state.pos !== start17324};17325function isHexDigit(ch) {17326return (17327(ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||17328(ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||17329(ch >= 0x61 /* a */ && ch <= 0x66 /* f */)17330)17331}17332function hexToInt(ch) {17333if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {17334return 10 + (ch - 0x41 /* A */)17335}17336if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {17337return 10 + (ch - 0x61 /* a */)17338}17339return ch - 0x30 /* 0 */17340}1734117342// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence17343// Allows only 0-377(octal) i.e. 0-255(decimal).17344pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {17345if (this.regexp_eatOctalDigit(state)) {17346var n1 = state.lastIntValue;17347if (this.regexp_eatOctalDigit(state)) {17348var n2 = state.lastIntValue;17349if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {17350state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;17351} else {17352state.lastIntValue = n1 * 8 + n2;17353}17354} else {17355state.lastIntValue = n1;17356}17357return true17358}17359return false17360};1736117362// https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit17363pp$1.regexp_eatOctalDigit = function(state) {17364var ch = state.current();17365if (isOctalDigit(ch)) {17366state.lastIntValue = ch - 0x30; /* 0 */17367state.advance();17368return true17369}17370state.lastIntValue = 0;17371return false17372};17373function isOctalDigit(ch) {17374return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */17375}1737617377// https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits17378// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit17379// And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence17380pp$1.regexp_eatFixedHexDigits = function(state, length) {17381var start = state.pos;17382state.lastIntValue = 0;17383for (var i = 0; i < length; ++i) {17384var ch = state.current();17385if (!isHexDigit(ch)) {17386state.pos = start;17387return false17388}17389state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);17390state.advance();17391}17392return true17393};1739417395// Object type used to represent tokens. Note that normally, tokens17396// simply exist as properties on the parser object. This is only17397// used for the onToken callback and the external tokenizer.1739817399var Token = function Token(p) {17400this.type = p.type;17401this.value = p.value;17402this.start = p.start;17403this.end = p.end;17404if (p.options.locations)17405{ this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }17406if (p.options.ranges)17407{ this.range = [p.start, p.end]; }17408};1740917410// ## Tokenizer1741117412var pp = Parser.prototype;1741317414// Move to the next token1741517416pp.next = function(ignoreEscapeSequenceInKeyword) {17417if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)17418{ this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }17419if (this.options.onToken)17420{ this.options.onToken(new Token(this)); }1742117422this.lastTokEnd = this.end;17423this.lastTokStart = this.start;17424this.lastTokEndLoc = this.endLoc;17425this.lastTokStartLoc = this.startLoc;17426this.nextToken();17427};1742817429pp.getToken = function() {17430this.next();17431return new Token(this)17432};1743317434// If we're in an ES6 environment, make parsers iterable17435if (typeof Symbol !== "undefined")17436{ pp[Symbol.iterator] = function() {17437var this$1$1 = this;1743817439return {17440next: function () {17441var token = this$1$1.getToken();17442return {17443done: token.type === types$1.eof,17444value: token17445}17446}17447}17448}; }1744917450// Toggle strict mode. Re-reads the next number or string to please17451// pedantic tests (`"use strict"; 010;` should fail).1745217453// Read a single token, updating the parser object's token-related17454// properties.1745517456pp.nextToken = function() {17457var curContext = this.curContext();17458if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }1745917460this.start = this.pos;17461if (this.options.locations) { this.startLoc = this.curPosition(); }17462if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) }1746317464if (curContext.override) { return curContext.override(this) }17465else { this.readToken(this.fullCharCodeAtPos()); }17466};1746717468pp.readToken = function(code) {17469// Identifier or keyword. '\uXXXX' sequences are allowed in17470// identifiers, so '\' also dispatches to that.17471if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)17472{ return this.readWord() }1747317474return this.getTokenFromCode(code)17475};1747617477pp.fullCharCodeAtPos = function() {17478var code = this.input.charCodeAt(this.pos);17479if (code <= 0xd7ff || code >= 0xdc00) { return code }17480var next = this.input.charCodeAt(this.pos + 1);17481return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc0017482};1748317484pp.skipBlockComment = function() {17485var startLoc = this.options.onComment && this.curPosition();17486var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);17487if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }17488this.pos = end + 2;17489if (this.options.locations) {17490for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) {17491++this.curLine;17492pos = this.lineStart = nextBreak;17493}17494}17495if (this.options.onComment)17496{ this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,17497startLoc, this.curPosition()); }17498};1749917500pp.skipLineComment = function(startSkip) {17501var start = this.pos;17502var startLoc = this.options.onComment && this.curPosition();17503var ch = this.input.charCodeAt(this.pos += startSkip);17504while (this.pos < this.input.length && !isNewLine(ch)) {17505ch = this.input.charCodeAt(++this.pos);17506}17507if (this.options.onComment)17508{ this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,17509startLoc, this.curPosition()); }17510};1751117512// Called at the start of the parse and after every token. Skips17513// whitespace and comments, and.1751417515pp.skipSpace = function() {17516loop: while (this.pos < this.input.length) {17517var ch = this.input.charCodeAt(this.pos);17518switch (ch) {17519case 32: case 160: // ' '17520++this.pos;17521break17522case 13:17523if (this.input.charCodeAt(this.pos + 1) === 10) {17524++this.pos;17525}17526case 10: case 8232: case 8233:17527++this.pos;17528if (this.options.locations) {17529++this.curLine;17530this.lineStart = this.pos;17531}17532break17533case 47: // '/'17534switch (this.input.charCodeAt(this.pos + 1)) {17535case 42: // '*'17536this.skipBlockComment();17537break17538case 47:17539this.skipLineComment(2);17540break17541default:17542break loop17543}17544break17545default:17546if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {17547++this.pos;17548} else {17549break loop17550}17551}17552}17553};1755417555// Called at the end of every token. Sets `end`, `val`, and17556// maintains `context` and `exprAllowed`, and skips the space after17557// the token, so that the next one's `start` will point at the17558// right position.1755917560pp.finishToken = function(type, val) {17561this.end = this.pos;17562if (this.options.locations) { this.endLoc = this.curPosition(); }17563var prevType = this.type;17564this.type = type;17565this.value = val;1756617567this.updateContext(prevType);17568};1756917570// ### Token reading1757117572// This is the function that is called to fetch the next token. It17573// is somewhat obscure, because it works in character codes rather17574// than characters, and because operator parsing has been inlined17575// into it.17576//17577// All in the name of speed.17578//17579pp.readToken_dot = function() {17580var next = this.input.charCodeAt(this.pos + 1);17581if (next >= 48 && next <= 57) { return this.readNumber(true) }17582var next2 = this.input.charCodeAt(this.pos + 2);17583if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'17584this.pos += 3;17585return this.finishToken(types$1.ellipsis)17586} else {17587++this.pos;17588return this.finishToken(types$1.dot)17589}17590};1759117592pp.readToken_slash = function() { // '/'17593var next = this.input.charCodeAt(this.pos + 1);17594if (this.exprAllowed) { ++this.pos; return this.readRegexp() }17595if (next === 61) { return this.finishOp(types$1.assign, 2) }17596return this.finishOp(types$1.slash, 1)17597};1759817599pp.readToken_mult_modulo_exp = function(code) { // '%*'17600var next = this.input.charCodeAt(this.pos + 1);17601var size = 1;17602var tokentype = code === 42 ? types$1.star : types$1.modulo;1760317604// exponentiation operator ** and **=17605if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {17606++size;17607tokentype = types$1.starstar;17608next = this.input.charCodeAt(this.pos + 2);17609}1761017611if (next === 61) { return this.finishOp(types$1.assign, size + 1) }17612return this.finishOp(tokentype, size)17613};1761417615pp.readToken_pipe_amp = function(code) { // '|&'17616var next = this.input.charCodeAt(this.pos + 1);17617if (next === code) {17618if (this.options.ecmaVersion >= 12) {17619var next2 = this.input.charCodeAt(this.pos + 2);17620if (next2 === 61) { return this.finishOp(types$1.assign, 3) }17621}17622return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2)17623}17624if (next === 61) { return this.finishOp(types$1.assign, 2) }17625return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1)17626};1762717628pp.readToken_caret = function() { // '^'17629var next = this.input.charCodeAt(this.pos + 1);17630if (next === 61) { return this.finishOp(types$1.assign, 2) }17631return this.finishOp(types$1.bitwiseXOR, 1)17632};1763317634pp.readToken_plus_min = function(code) { // '+-'17635var next = this.input.charCodeAt(this.pos + 1);17636if (next === code) {17637if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&17638(this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {17639// A `-->` line comment17640this.skipLineComment(3);17641this.skipSpace();17642return this.nextToken()17643}17644return this.finishOp(types$1.incDec, 2)17645}17646if (next === 61) { return this.finishOp(types$1.assign, 2) }17647return this.finishOp(types$1.plusMin, 1)17648};1764917650pp.readToken_lt_gt = function(code) { // '<>'17651var next = this.input.charCodeAt(this.pos + 1);17652var size = 1;17653if (next === code) {17654size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;17655if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) }17656return this.finishOp(types$1.bitShift, size)17657}17658if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&17659this.input.charCodeAt(this.pos + 3) === 45) {17660// `<!--`, an XML-style comment that should be interpreted as a line comment17661this.skipLineComment(4);17662this.skipSpace();17663return this.nextToken()17664}17665if (next === 61) { size = 2; }17666return this.finishOp(types$1.relational, size)17667};1766817669pp.readToken_eq_excl = function(code) { // '=!'17670var next = this.input.charCodeAt(this.pos + 1);17671if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }17672if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'17673this.pos += 2;17674return this.finishToken(types$1.arrow)17675}17676return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1)17677};1767817679pp.readToken_question = function() { // '?'17680var ecmaVersion = this.options.ecmaVersion;17681if (ecmaVersion >= 11) {17682var next = this.input.charCodeAt(this.pos + 1);17683if (next === 46) {17684var next2 = this.input.charCodeAt(this.pos + 2);17685if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) }17686}17687if (next === 63) {17688if (ecmaVersion >= 12) {17689var next2$1 = this.input.charCodeAt(this.pos + 2);17690if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) }17691}17692return this.finishOp(types$1.coalesce, 2)17693}17694}17695return this.finishOp(types$1.question, 1)17696};1769717698pp.readToken_numberSign = function() { // '#'17699var ecmaVersion = this.options.ecmaVersion;17700var code = 35; // '#'17701if (ecmaVersion >= 13) {17702++this.pos;17703code = this.fullCharCodeAtPos();17704if (isIdentifierStart(code, true) || code === 92 /* '\' */) {17705return this.finishToken(types$1.privateId, this.readWord1())17706}17707}1770817709this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");17710};1771117712pp.getTokenFromCode = function(code) {17713switch (code) {17714// The interpretation of a dot depends on whether it is followed17715// by a digit or another two dots.17716case 46: // '.'17717return this.readToken_dot()1771817719// Punctuation tokens.17720case 40: ++this.pos; return this.finishToken(types$1.parenL)17721case 41: ++this.pos; return this.finishToken(types$1.parenR)17722case 59: ++this.pos; return this.finishToken(types$1.semi)17723case 44: ++this.pos; return this.finishToken(types$1.comma)17724case 91: ++this.pos; return this.finishToken(types$1.bracketL)17725case 93: ++this.pos; return this.finishToken(types$1.bracketR)17726case 123: ++this.pos; return this.finishToken(types$1.braceL)17727case 125: ++this.pos; return this.finishToken(types$1.braceR)17728case 58: ++this.pos; return this.finishToken(types$1.colon)1772917730case 96: // '`'17731if (this.options.ecmaVersion < 6) { break }17732++this.pos;17733return this.finishToken(types$1.backQuote)1773417735case 48: // '0'17736var next = this.input.charCodeAt(this.pos + 1);17737if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number17738if (this.options.ecmaVersion >= 6) {17739if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number17740if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number17741}1774217743// Anything else beginning with a digit is an integer, octal17744// number, or float.17745case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-917746return this.readNumber(false)1774717748// Quotes produce strings.17749case 34: case 39: // '"', "'"17750return this.readString(code)1775117752// Operators are parsed inline in tiny state machines. '=' (61) is17753// often referred to. `finishOp` simply skips the amount of17754// characters it is given as second argument, and returns a token17755// of the type given by its first argument.17756case 47: // '/'17757return this.readToken_slash()1775817759case 37: case 42: // '%*'17760return this.readToken_mult_modulo_exp(code)1776117762case 124: case 38: // '|&'17763return this.readToken_pipe_amp(code)1776417765case 94: // '^'17766return this.readToken_caret()1776717768case 43: case 45: // '+-'17769return this.readToken_plus_min(code)1777017771case 60: case 62: // '<>'17772return this.readToken_lt_gt(code)1777317774case 61: case 33: // '=!'17775return this.readToken_eq_excl(code)1777617777case 63: // '?'17778return this.readToken_question()1777917780case 126: // '~'17781return this.finishOp(types$1.prefix, 1)1778217783case 35: // '#'17784return this.readToken_numberSign()17785}1778617787this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");17788};1778917790pp.finishOp = function(type, size) {17791var str = this.input.slice(this.pos, this.pos + size);17792this.pos += size;17793return this.finishToken(type, str)17794};1779517796pp.readRegexp = function() {17797var escaped, inClass, start = this.pos;17798for (;;) {17799if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }17800var ch = this.input.charAt(this.pos);17801if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }17802if (!escaped) {17803if (ch === "[") { inClass = true; }17804else if (ch === "]" && inClass) { inClass = false; }17805else if (ch === "/" && !inClass) { break }17806escaped = ch === "\\";17807} else { escaped = false; }17808++this.pos;17809}17810var pattern = this.input.slice(start, this.pos);17811++this.pos;17812var flagsStart = this.pos;17813var flags = this.readWord1();17814if (this.containsEsc) { this.unexpected(flagsStart); }1781517816// Validate pattern17817var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));17818state.reset(start, pattern, flags);17819this.validateRegExpFlags(state);17820this.validateRegExpPattern(state);1782117822// Create Literal#value property value.17823var value = null;17824try {17825value = new RegExp(pattern, flags);17826} catch (e) {17827// ESTree requires null if it failed to instantiate RegExp object.17828// https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral17829}1783017831return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value})17832};1783317834// Read an integer in the given radix. Return null if zero digits17835// were read, the integer value otherwise. When `len` is given, this17836// will return `null` unless the integer has exactly `len` digits.1783717838pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {17839// `len` is used for character escape sequences. In that case, disallow separators.17840var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;1784117842// `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)17843// and isn't fraction part nor exponent part. In that case, if the first digit17844// is zero then disallow separators.17845var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;1784617847var start = this.pos, total = 0, lastCode = 0;17848for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {17849var code = this.input.charCodeAt(this.pos), val = (void 0);1785017851if (allowSeparators && code === 95) {17852if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }17853if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }17854if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }17855lastCode = code;17856continue17857}1785817859if (code >= 97) { val = code - 97 + 10; } // a17860else if (code >= 65) { val = code - 65 + 10; } // A17861else if (code >= 48 && code <= 57) { val = code - 48; } // 0-917862else { val = Infinity; }17863if (val >= radix) { break }17864lastCode = code;17865total = total * radix + val;17866}1786717868if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }17869if (this.pos === start || len != null && this.pos - start !== len) { return null }1787017871return total17872};1787317874function stringToNumber(str, isLegacyOctalNumericLiteral) {17875if (isLegacyOctalNumericLiteral) {17876return parseInt(str, 8)17877}1787817879// `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.17880return parseFloat(str.replace(/_/g, ""))17881}1788217883function stringToBigInt(str) {17884if (typeof BigInt !== "function") {17885return null17886}1788717888// `BigInt(value)` throws syntax error if the string contains numeric separators.17889return BigInt(str.replace(/_/g, ""))17890}1789117892pp.readRadixNumber = function(radix) {17893var start = this.pos;17894this.pos += 2; // 0x17895var val = this.readInt(radix);17896if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }17897if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {17898val = stringToBigInt(this.input.slice(start, this.pos));17899++this.pos;17900} else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }17901return this.finishToken(types$1.num, val)17902};1790317904// Read an integer, octal integer, or floating-point number.1790517906pp.readNumber = function(startsWithDot) {17907var start = this.pos;17908if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }17909var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;17910if (octal && this.strict) { this.raise(start, "Invalid number"); }17911var next = this.input.charCodeAt(this.pos);17912if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {17913var val$1 = stringToBigInt(this.input.slice(start, this.pos));17914++this.pos;17915if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }17916return this.finishToken(types$1.num, val$1)17917}17918if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }17919if (next === 46 && !octal) { // '.'17920++this.pos;17921this.readInt(10);17922next = this.input.charCodeAt(this.pos);17923}17924if ((next === 69 || next === 101) && !octal) { // 'eE'17925next = this.input.charCodeAt(++this.pos);17926if (next === 43 || next === 45) { ++this.pos; } // '+-'17927if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }17928}17929if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }1793017931var val = stringToNumber(this.input.slice(start, this.pos), octal);17932return this.finishToken(types$1.num, val)17933};1793417935// Read a string value, interpreting backslash-escapes.1793617937pp.readCodePoint = function() {17938var ch = this.input.charCodeAt(this.pos), code;1793917940if (ch === 123) { // '{'17941if (this.options.ecmaVersion < 6) { this.unexpected(); }17942var codePos = ++this.pos;17943code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);17944++this.pos;17945if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }17946} else {17947code = this.readHexChar(4);17948}17949return code17950};1795117952pp.readString = function(quote) {17953var out = "", chunkStart = ++this.pos;17954for (;;) {17955if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }17956var ch = this.input.charCodeAt(this.pos);17957if (ch === quote) { break }17958if (ch === 92) { // '\'17959out += this.input.slice(chunkStart, this.pos);17960out += this.readEscapedChar(false);17961chunkStart = this.pos;17962} else if (ch === 0x2028 || ch === 0x2029) {17963if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); }17964++this.pos;17965if (this.options.locations) {17966this.curLine++;17967this.lineStart = this.pos;17968}17969} else {17970if (isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); }17971++this.pos;17972}17973}17974out += this.input.slice(chunkStart, this.pos++);17975return this.finishToken(types$1.string, out)17976};1797717978// Reads template string tokens.1797917980var INVALID_TEMPLATE_ESCAPE_ERROR = {};1798117982pp.tryReadTemplateToken = function() {17983this.inTemplateElement = true;17984try {17985this.readTmplToken();17986} catch (err) {17987if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {17988this.readInvalidTemplateToken();17989} else {17990throw err17991}17992}1799317994this.inTemplateElement = false;17995};1799617997pp.invalidStringToken = function(position, message) {17998if (this.inTemplateElement && this.options.ecmaVersion >= 9) {17999throw INVALID_TEMPLATE_ESCAPE_ERROR18000} else {18001this.raise(position, message);18002}18003};1800418005pp.readTmplToken = function() {18006var out = "", chunkStart = this.pos;18007for (;;) {18008if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }18009var ch = this.input.charCodeAt(this.pos);18010if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'18011if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {18012if (ch === 36) {18013this.pos += 2;18014return this.finishToken(types$1.dollarBraceL)18015} else {18016++this.pos;18017return this.finishToken(types$1.backQuote)18018}18019}18020out += this.input.slice(chunkStart, this.pos);18021return this.finishToken(types$1.template, out)18022}18023if (ch === 92) { // '\'18024out += this.input.slice(chunkStart, this.pos);18025out += this.readEscapedChar(true);18026chunkStart = this.pos;18027} else if (isNewLine(ch)) {18028out += this.input.slice(chunkStart, this.pos);18029++this.pos;18030switch (ch) {18031case 13:18032if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }18033case 10:18034out += "\n";18035break18036default:18037out += String.fromCharCode(ch);18038break18039}18040if (this.options.locations) {18041++this.curLine;18042this.lineStart = this.pos;18043}18044chunkStart = this.pos;18045} else {18046++this.pos;18047}18048}18049};1805018051// Reads a template token to search for the end, without validating any escape sequences18052pp.readInvalidTemplateToken = function() {18053for (; this.pos < this.input.length; this.pos++) {18054switch (this.input[this.pos]) {18055case "\\":18056++this.pos;18057break1805818059case "$":18060if (this.input[this.pos + 1] !== "{") {18061break18062}1806318064// falls through18065case "`":18066return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos))1806718068// no default18069}18070}18071this.raise(this.start, "Unterminated template");18072};1807318074// Used to read escaped characters1807518076pp.readEscapedChar = function(inTemplate) {18077var ch = this.input.charCodeAt(++this.pos);18078++this.pos;18079switch (ch) {18080case 110: return "\n" // 'n' -> '\n'18081case 114: return "\r" // 'r' -> '\r'18082case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'18083case 117: return codePointToString(this.readCodePoint()) // 'u'18084case 116: return "\t" // 't' -> '\t'18085case 98: return "\b" // 'b' -> '\b'18086case 118: return "\u000b" // 'v' -> '\u000b'18087case 102: return "\f" // 'f' -> '\f'18088case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'18089case 10: // ' \n'18090if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }18091return ""18092case 56:18093case 57:18094if (this.strict) {18095this.invalidStringToken(18096this.pos - 1,18097"Invalid escape sequence"18098);18099}18100if (inTemplate) {18101var codePos = this.pos - 1;1810218103this.invalidStringToken(18104codePos,18105"Invalid escape sequence in template string"18106);1810718108return null18109}18110default:18111if (ch >= 48 && ch <= 55) {18112var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];18113var octal = parseInt(octalStr, 8);18114if (octal > 255) {18115octalStr = octalStr.slice(0, -1);18116octal = parseInt(octalStr, 8);18117}18118this.pos += octalStr.length - 1;18119ch = this.input.charCodeAt(this.pos);18120if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {18121this.invalidStringToken(18122this.pos - 1 - octalStr.length,18123inTemplate18124? "Octal literal in template string"18125: "Octal literal in strict mode"18126);18127}18128return String.fromCharCode(octal)18129}18130if (isNewLine(ch)) {18131// Unicode new line characters after \ get removed from output in both18132// template literals and strings18133return ""18134}18135return String.fromCharCode(ch)18136}18137};1813818139// Used to read character escape sequences ('\x', '\u', '\U').1814018141pp.readHexChar = function(len) {18142var codePos = this.pos;18143var n = this.readInt(16, len);18144if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }18145return n18146};1814718148// Read an identifier, and return it as a string. Sets `this.containsEsc`18149// to whether the word contained a '\u' escape.18150//18151// Incrementally adds only escaped chars, adding other chunks as-is18152// as a micro-optimization.1815318154pp.readWord1 = function() {18155this.containsEsc = false;18156var word = "", first = true, chunkStart = this.pos;18157var astral = this.options.ecmaVersion >= 6;18158while (this.pos < this.input.length) {18159var ch = this.fullCharCodeAtPos();18160if (isIdentifierChar(ch, astral)) {18161this.pos += ch <= 0xffff ? 1 : 2;18162} else if (ch === 92) { // "\"18163this.containsEsc = true;18164word += this.input.slice(chunkStart, this.pos);18165var escStart = this.pos;18166if (this.input.charCodeAt(++this.pos) !== 117) // "u"18167{ this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }18168++this.pos;18169var esc = this.readCodePoint();18170if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))18171{ this.invalidStringToken(escStart, "Invalid Unicode escape"); }18172word += codePointToString(esc);18173chunkStart = this.pos;18174} else {18175break18176}18177first = false;18178}18179return word + this.input.slice(chunkStart, this.pos)18180};1818118182// Read an identifier or keyword token. Will check for reserved18183// words when necessary.1818418185pp.readWord = function() {18186var word = this.readWord1();18187var type = types$1.name;18188if (this.keywords.test(word)) {18189type = keywords[word];18190}18191return this.finishToken(type, word)18192};1819318194// Acorn is a tiny, fast JavaScript parser written in JavaScript.1819518196var version = "8.8.1";1819718198Parser.acorn = {18199Parser: Parser,18200version: version,18201defaultOptions: defaultOptions,18202Position: Position,18203SourceLocation: SourceLocation,18204getLineInfo: getLineInfo,18205Node: Node$1,18206TokenType: TokenType,18207tokTypes: types$1,18208keywordTypes: keywords,18209TokContext: TokContext,18210tokContexts: types,18211isIdentifierChar: isIdentifierChar,18212isIdentifierStart: isIdentifierStart,18213Token: Token,18214isNewLine: isNewLine,18215lineBreak: lineBreak,18216lineBreakG: lineBreakG,18217nonASCIIwhitespace: nonASCIIwhitespace18218};1821918220var defaultGlobals = new Set([18221"Array",18222"ArrayBuffer",18223"atob",18224"AudioContext",18225"Blob",18226"Boolean",18227"BigInt",18228"btoa",18229"clearInterval",18230"clearTimeout",18231"console",18232"crypto",18233"CustomEvent",18234"DataView",18235"Date",18236"decodeURI",18237"decodeURIComponent",18238"devicePixelRatio",18239"document",18240"encodeURI",18241"encodeURIComponent",18242"Error",18243"escape",18244"eval",18245"fetch",18246"File",18247"FileList",18248"FileReader",18249"Float32Array",18250"Float64Array",18251"Function",18252"Headers",18253"Image",18254"ImageData",18255"Infinity",18256"Int16Array",18257"Int32Array",18258"Int8Array",18259"Intl",18260"isFinite",18261"isNaN",18262"JSON",18263"Map",18264"Math",18265"NaN",18266"Number",18267"navigator",18268"Object",18269"parseFloat",18270"parseInt",18271"performance",18272"Path2D",18273"Promise",18274"Proxy",18275"RangeError",18276"ReferenceError",18277"Reflect",18278"RegExp",18279"cancelAnimationFrame",18280"requestAnimationFrame",18281"Set",18282"setInterval",18283"setTimeout",18284"String",18285"Symbol",18286"SyntaxError",18287"TextDecoder",18288"TextEncoder",18289"this",18290"TypeError",18291"Uint16Array",18292"Uint32Array",18293"Uint8Array",18294"Uint8ClampedArray",18295"undefined",18296"unescape",18297"URIError",18298"URL",18299"WeakMap",18300"WeakSet",18301"WebSocket",18302"Worker",18303"window"18304]);1830518306// AST walker module for Mozilla Parser API compatible trees1830718308// A simple walk is one where you simply specify callbacks to be18309// called on specific nodes. The last two arguments are optional. A18310// simple use would be18311//18312// walk.simple(myTree, {18313// Expression: function(node) { ... }18314// });18315//18316// to do something with all expressions. All Parser API node types18317// can be used to identify node types, as well as Expression and18318// Statement, which denote categories of nodes.18319//18320// The base argument can be used to pass a custom (recursive)18321// walker, and state can be used to give this walked an initial18322// state.1832318324function simple(node, visitors, baseVisitor, state, override) {18325if (!baseVisitor) { baseVisitor = base$118326; }(function c(node, st, override) {18327var type = override || node.type, found = visitors[type];18328baseVisitor[type](node, st, c);18329if (found) { found(node, st); }18330})(node, state, override);18331}1833218333// An ancestor walk keeps an array of ancestor nodes (including the18334// current node) and passes them to the callback as third parameter18335// (and also as state parameter when no other state is present).18336function ancestor(node, visitors, baseVisitor, state, override) {18337var ancestors = [];18338if (!baseVisitor) { baseVisitor = base$118339; }(function c(node, st, override) {18340var type = override || node.type, found = visitors[type];18341var isNew = node !== ancestors[ancestors.length - 1];18342if (isNew) { ancestors.push(node); }18343baseVisitor[type](node, st, c);18344if (found) { found(node, st || ancestors, ancestors); }18345if (isNew) { ancestors.pop(); }18346})(node, state, override);18347}1834818349// Used to create a custom walker. Will fill in all missing node18350// type properties with the defaults.18351function make(funcs, baseVisitor) {18352var visitor = Object.create(baseVisitor || base$1);18353for (var type in funcs) { visitor[type] = funcs[type]; }18354return visitor18355}1835618357function skipThrough(node, st, c) { c(node, st); }18358function ignore(_node, _st, _c) {}1835918360// Node walkers.1836118362var base$1 = {};1836318364base$1.Program = base$1.BlockStatement = base$1.StaticBlock = function (node, st, c) {18365for (var i = 0, list = node.body; i < list.length; i += 1)18366{18367var stmt = list[i];1836818369c(stmt, st, "Statement");18370}18371};18372base$1.Statement = skipThrough;18373base$1.EmptyStatement = ignore;18374base$1.ExpressionStatement = base$1.ParenthesizedExpression = base$1.ChainExpression =18375function (node, st, c) { return c(node.expression, st, "Expression"); };18376base$1.IfStatement = function (node, st, c) {18377c(node.test, st, "Expression");18378c(node.consequent, st, "Statement");18379if (node.alternate) { c(node.alternate, st, "Statement"); }18380};18381base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };18382base$1.BreakStatement = base$1.ContinueStatement = ignore;18383base$1.WithStatement = function (node, st, c) {18384c(node.object, st, "Expression");18385c(node.body, st, "Statement");18386};18387base$1.SwitchStatement = function (node, st, c) {18388c(node.discriminant, st, "Expression");18389for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {18390var cs = list$1[i$1];1839118392if (cs.test) { c(cs.test, st, "Expression"); }18393for (var i = 0, list = cs.consequent; i < list.length; i += 1)18394{18395var cons = list[i];1839618397c(cons, st, "Statement");18398}18399}18400};18401base$1.SwitchCase = function (node, st, c) {18402if (node.test) { c(node.test, st, "Expression"); }18403for (var i = 0, list = node.consequent; i < list.length; i += 1)18404{18405var cons = list[i];1840618407c(cons, st, "Statement");18408}18409};18410base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {18411if (node.argument) { c(node.argument, st, "Expression"); }18412};18413base$1.ThrowStatement = base$1.SpreadElement =18414function (node, st, c) { return c(node.argument, st, "Expression"); };18415base$1.TryStatement = function (node, st, c) {18416c(node.block, st, "Statement");18417if (node.handler) { c(node.handler, st); }18418if (node.finalizer) { c(node.finalizer, st, "Statement"); }18419};18420base$1.CatchClause = function (node, st, c) {18421if (node.param) { c(node.param, st, "Pattern"); }18422c(node.body, st, "Statement");18423};18424base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {18425c(node.test, st, "Expression");18426c(node.body, st, "Statement");18427};18428base$1.ForStatement = function (node, st, c) {18429if (node.init) { c(node.init, st, "ForInit"); }18430if (node.test) { c(node.test, st, "Expression"); }18431if (node.update) { c(node.update, st, "Expression"); }18432c(node.body, st, "Statement");18433};18434base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {18435c(node.left, st, "ForInit");18436c(node.right, st, "Expression");18437c(node.body, st, "Statement");18438};18439base$1.ForInit = function (node, st, c) {18440if (node.type === "VariableDeclaration") { c(node, st); }18441else { c(node, st, "Expression"); }18442};18443base$1.DebuggerStatement = ignore;1844418445base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };18446base$1.VariableDeclaration = function (node, st, c) {18447for (var i = 0, list = node.declarations; i < list.length; i += 1)18448{18449var decl = list[i];1845018451c(decl, st);18452}18453};18454base$1.VariableDeclarator = function (node, st, c) {18455c(node.id, st, "Pattern");18456if (node.init) { c(node.init, st, "Expression"); }18457};1845818459base$1.Function = function (node, st, c) {18460if (node.id) { c(node.id, st, "Pattern"); }18461for (var i = 0, list = node.params; i < list.length; i += 1)18462{18463var param = list[i];1846418465c(param, st, "Pattern");18466}18467c(node.body, st, node.expression ? "Expression" : "Statement");18468};1846918470base$1.Pattern = function (node, st, c) {18471if (node.type === "Identifier")18472{ c(node, st, "VariablePattern"); }18473else if (node.type === "MemberExpression")18474{ c(node, st, "MemberPattern"); }18475else18476{ c(node, st); }18477};18478base$1.VariablePattern = ignore;18479base$1.MemberPattern = skipThrough;18480base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };18481base$1.ArrayPattern = function (node, st, c) {18482for (var i = 0, list = node.elements; i < list.length; i += 1) {18483var elt = list[i];1848418485if (elt) { c(elt, st, "Pattern"); }18486}18487};18488base$1.ObjectPattern = function (node, st, c) {18489for (var i = 0, list = node.properties; i < list.length; i += 1) {18490var prop = list[i];1849118492if (prop.type === "Property") {18493if (prop.computed) { c(prop.key, st, "Expression"); }18494c(prop.value, st, "Pattern");18495} else if (prop.type === "RestElement") {18496c(prop.argument, st, "Pattern");18497}18498}18499};1850018501base$1.Expression = skipThrough;18502base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;18503base$1.ArrayExpression = function (node, st, c) {18504for (var i = 0, list = node.elements; i < list.length; i += 1) {18505var elt = list[i];1850618507if (elt) { c(elt, st, "Expression"); }18508}18509};18510base$1.ObjectExpression = function (node, st, c) {18511for (var i = 0, list = node.properties; i < list.length; i += 1)18512{18513var prop = list[i];1851418515c(prop, st);18516}18517};18518base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;18519base$1.SequenceExpression = function (node, st, c) {18520for (var i = 0, list = node.expressions; i < list.length; i += 1)18521{18522var expr = list[i];1852318524c(expr, st, "Expression");18525}18526};18527base$1.TemplateLiteral = function (node, st, c) {18528for (var i = 0, list = node.quasis; i < list.length; i += 1)18529{18530var quasi = list[i];1853118532c(quasi, st);18533}1853418535for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)18536{18537var expr = list$1[i$1];1853818539c(expr, st, "Expression");18540}18541};18542base$1.TemplateElement = ignore;18543base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {18544c(node.argument, st, "Expression");18545};18546base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {18547c(node.left, st, "Expression");18548c(node.right, st, "Expression");18549};18550base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {18551c(node.left, st, "Pattern");18552c(node.right, st, "Expression");18553};18554base$1.ConditionalExpression = function (node, st, c) {18555c(node.test, st, "Expression");18556c(node.consequent, st, "Expression");18557c(node.alternate, st, "Expression");18558};18559base$1.NewExpression = base$1.CallExpression = function (node, st, c) {18560c(node.callee, st, "Expression");18561if (node.arguments)18562{ for (var i = 0, list = node.arguments; i < list.length; i += 1)18563{18564var arg = list[i];1856518566c(arg, st, "Expression");18567} }18568};18569base$1.MemberExpression = function (node, st, c) {18570c(node.object, st, "Expression");18571if (node.computed) { c(node.property, st, "Expression"); }18572};18573base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {18574if (node.declaration)18575{ c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }18576if (node.source) { c(node.source, st, "Expression"); }18577};18578base$1.ExportAllDeclaration = function (node, st, c) {18579if (node.exported)18580{ c(node.exported, st); }18581c(node.source, st, "Expression");18582};18583base$1.ImportDeclaration = function (node, st, c) {18584for (var i = 0, list = node.specifiers; i < list.length; i += 1)18585{18586var spec = list[i];1858718588c(spec, st);18589}18590c(node.source, st, "Expression");18591};18592base$1.ImportExpression = function (node, st, c) {18593c(node.source, st, "Expression");18594};18595base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.PrivateIdentifier = base$1.Literal = ignore;1859618597base$1.TaggedTemplateExpression = function (node, st, c) {18598c(node.tag, st, "Expression");18599c(node.quasi, st, "Expression");18600};18601base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };18602base$1.Class = function (node, st, c) {18603if (node.id) { c(node.id, st, "Pattern"); }18604if (node.superClass) { c(node.superClass, st, "Expression"); }18605c(node.body, st);18606};18607base$1.ClassBody = function (node, st, c) {18608for (var i = 0, list = node.body; i < list.length; i += 1)18609{18610var elt = list[i];1861118612c(elt, st);18613}18614};18615base$1.MethodDefinition = base$1.PropertyDefinition = base$1.Property = function (node, st, c) {18616if (node.computed) { c(node.key, st, "Expression"); }18617if (node.value) { c(node.value, st, "Expression"); }18618};1861918620var walk = make({18621Import() {},18622ViewExpression(node, st, c) {18623c(node.id, st, "Identifier");18624},18625MutableExpression(node, st, c) {18626c(node.id, st, "Identifier");18627}18628});1862918630// Based on https://github.com/ForbesLindesay/acorn-globals1863118632function isScope(node) {18633return node.type === "FunctionExpression"18634|| node.type === "FunctionDeclaration"18635|| node.type === "ArrowFunctionExpression"18636|| node.type === "Program";18637}1863818639function isBlockScope(node) {18640return node.type === "BlockStatement"18641|| node.type === "ForInStatement"18642|| node.type === "ForOfStatement"18643|| node.type === "ForStatement"18644|| isScope(node);18645}1864618647function declaresArguments(node) {18648return node.type === "FunctionExpression"18649|| node.type === "FunctionDeclaration";18650}1865118652function findReferences(cell, globals) {18653const ast = {type: "Program", body: [cell.body]};18654const locals = new Map;18655const globalSet = new Set(globals);18656const references = [];1865718658function hasLocal(node, name) {18659const l = locals.get(node);18660return l ? l.has(name) : false;18661}1866218663function declareLocal(node, id) {18664const l = locals.get(node);18665if (l) l.add(id.name);18666else locals.set(node, new Set([id.name]));18667}1866818669function declareClass(node) {18670if (node.id) declareLocal(node, node.id);18671}1867218673function declareFunction(node) {18674node.params.forEach(param => declarePattern(param, node));18675if (node.id) declareLocal(node, node.id);18676}1867718678function declareCatchClause(node) {18679if (node.param) declarePattern(node.param, node);18680}1868118682function declarePattern(node, parent) {18683switch (node.type) {18684case "Identifier":18685declareLocal(parent, node);18686break;18687case "ObjectPattern":18688node.properties.forEach(node => declarePattern(node, parent));18689break;18690case "ArrayPattern":18691node.elements.forEach(node => node && declarePattern(node, parent));18692break;18693case "Property":18694declarePattern(node.value, parent);18695break;18696case "RestElement":18697declarePattern(node.argument, parent);18698break;18699case "AssignmentPattern":18700declarePattern(node.left, parent);18701break;18702default:18703throw new Error("Unrecognized pattern type: " + node.type);18704}18705}1870618707function declareModuleSpecifier(node) {18708declareLocal(ast, node.local);18709}1871018711ancestor(18712ast,18713{18714VariableDeclaration: (node, parents) => {18715let parent = null;18716for (let i = parents.length - 1; i >= 0 && parent === null; --i) {18717if (node.kind === "var" ? isScope(parents[i]) : isBlockScope(parents[i])) {18718parent = parents[i];18719}18720}18721node.declarations.forEach(declaration => declarePattern(declaration.id, parent));18722},18723FunctionDeclaration: (node, parents) => {18724let parent = null;18725for (let i = parents.length - 2; i >= 0 && parent === null; --i) {18726if (isScope(parents[i])) {18727parent = parents[i];18728}18729}18730declareLocal(parent, node.id);18731declareFunction(node);18732},18733Function: declareFunction,18734ClassDeclaration: (node, parents) => {18735let parent = null;18736for (let i = parents.length - 2; i >= 0 && parent === null; i--) {18737if (isScope(parents[i])) {18738parent = parents[i];18739}18740}18741declareLocal(parent, node.id);18742},18743Class: declareClass,18744CatchClause: declareCatchClause,18745ImportDefaultSpecifier: declareModuleSpecifier,18746ImportSpecifier: declareModuleSpecifier,18747ImportNamespaceSpecifier: declareModuleSpecifier18748},18749walk18750);1875118752function identifier(node, parents) {18753let name = node.name;18754if (name === "undefined") return;18755for (let i = parents.length - 2; i >= 0; --i) {18756if (name === "arguments") {18757if (declaresArguments(parents[i])) {18758return;18759}18760}18761if (hasLocal(parents[i], name)) {18762return;18763}18764if (parents[i].type === "ViewExpression") {18765node = parents[i];18766name = `viewof ${node.id.name}`;18767}18768if (parents[i].type === "MutableExpression") {18769node = parents[i];18770name = `mutable ${node.id.name}`;18771}18772}18773if (!globalSet.has(name)) {18774if (name === "arguments") {18775throw Object.assign(new SyntaxError(`arguments is not allowed`), {node});18776}18777references.push(node);18778}18779}1878018781ancestor(18782ast,18783{18784VariablePattern: identifier,18785Identifier: identifier18786},18787walk18788);1878918790function checkConst(node, parents) {18791if (!node) return;18792switch (node.type) {18793case "Identifier":18794case "VariablePattern": {18795for (const parent of parents) {18796if (hasLocal(parent, node.name)) {18797return;18798}18799}18800if (parents[parents.length - 2].type === "MutableExpression") {18801return;18802}18803throw Object.assign(new SyntaxError(`Assignment to constant variable ${node.name}`), {node});18804}18805case "ArrayPattern": {18806for (const element of node.elements) {18807checkConst(element, parents);18808}18809return;18810}18811case "ObjectPattern": {18812for (const property of node.properties) {18813checkConst(property, parents);18814}18815return;18816}18817case "Property": {18818checkConst(node.value, parents);18819return;18820}18821case "RestElement": {18822checkConst(node.argument, parents);18823return;18824}18825}18826}1882718828function checkConstArgument(node, parents) {18829checkConst(node.argument, parents);18830}1883118832function checkConstLeft(node, parents) {18833checkConst(node.left, parents);18834}1883518836ancestor(18837ast,18838{18839AssignmentExpression: checkConstLeft,18840AssignmentPattern: checkConstLeft,18841UpdateExpression: checkConstArgument,18842ForOfStatement: checkConstLeft,18843ForInStatement: checkConstLeft18844},18845walk18846);1884718848return references;18849}1885018851function findFeatures(cell, featureName) {18852const ast = {type: "Program", body: [cell.body]};18853const features = new Map();18854const {references} = cell;1885518856simple(18857ast,18858{18859CallExpression: node => {18860const {callee, arguments: args} = node;1886118862// Ignore function calls that are not references to the feature.18863if (18864callee.type !== "Identifier" ||18865callee.name !== featureName ||18866references.indexOf(callee) < 018867) return;1886818869// Forbid dynamic calls.18870if (18871args.length !== 1 ||18872!((args[0].type === "Literal" && /^['"]/.test(args[0].raw)) ||18873(args[0].type === "TemplateLiteral" && args[0].expressions.length === 0))18874) {18875throw Object.assign(new SyntaxError(`${featureName} requires a single literal string argument`), {node});18876}1887718878const [arg] = args;18879const name = arg.type === "Literal" ? arg.value : arg.quasis[0].value.cooked;18880const location = {start: arg.start, end: arg.end};18881if (features.has(name)) features.get(name).push(location);18882else features.set(name, [location]);18883}18884},18885walk18886);1888718888return features;18889}1889018891const SCOPE_FUNCTION = 2;18892const SCOPE_ASYNC = 4;18893const SCOPE_GENERATOR = 8;1889418895class CellParser extends Parser {18896constructor(options, ...args) {18897super(Object.assign({ecmaVersion: 13}, options), ...args);18898}18899enterScope(flags) {18900if (flags & SCOPE_FUNCTION) ++this.O_function;18901return super.enterScope(flags);18902}18903exitScope() {18904if (this.currentScope().flags & SCOPE_FUNCTION) --this.O_function;18905return super.exitScope();18906}18907parseForIn(node, init) {18908if (this.O_function === 1 && node.await) this.O_async = true;18909return super.parseForIn(node, init);18910}18911parseAwait() {18912if (this.O_function === 1) this.O_async = true;18913return super.parseAwait();18914}18915parseYield(noIn) {18916if (this.O_function === 1) this.O_generator = true;18917return super.parseYield(noIn);18918}18919parseImport(node) {18920this.next();18921node.specifiers = this.parseImportSpecifiers();18922if (this.type === types$1._with) {18923this.next();18924node.injections = this.parseImportSpecifiers();18925}18926this.expectContextual("from");18927node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();18928return this.finishNode(node, "ImportDeclaration");18929}18930parseImportSpecifiers() {18931const nodes = [];18932const identifiers = new Set;18933let first = true;18934this.expect(types$1.braceL);18935while (!this.eat(types$1.braceR)) {18936if (first) {18937first = false;18938} else {18939this.expect(types$1.comma);18940if (this.afterTrailingComma(types$1.braceR)) break;18941}18942const node = this.startNode();18943node.view = this.eatContextual("viewof");18944node.mutable = node.view ? false : this.eatContextual("mutable");18945node.imported = this.parseIdent();18946this.checkUnreserved(node.imported);18947this.checkLocal(node.imported);18948if (this.eatContextual("as")) {18949node.local = this.parseIdent();18950this.checkUnreserved(node.local);18951this.checkLocal(node.local);18952} else {18953node.local = node.imported;18954}18955this.checkLValSimple(node.local, "let");18956if (identifiers.has(node.local.name)) {18957this.raise(node.local.start, `Identifier '${node.local.name}' has already been declared`);18958}18959identifiers.add(node.local.name);18960nodes.push(this.finishNode(node, "ImportSpecifier"));18961}18962return nodes;18963}18964parseExprAtom(refDestructuringErrors) {18965return (18966this.parseMaybeKeywordExpression("viewof", "ViewExpression") ||18967this.parseMaybeKeywordExpression("mutable", "MutableExpression") ||18968super.parseExprAtom(refDestructuringErrors)18969);18970}18971startCell() {18972this.O_function = 0;18973this.O_async = false;18974this.O_generator = false;18975this.strict = true;18976this.enterScope(SCOPE_FUNCTION | SCOPE_ASYNC | SCOPE_GENERATOR);18977}18978finishCell(node, body, id) {18979if (id) this.checkLocal(id);18980node.id = id;18981node.body = body;18982node.async = this.O_async;18983node.generator = this.O_generator;18984this.exitScope();18985return this.finishNode(node, "Cell");18986}18987parseCell(node, eof) {18988const lookahead = new CellParser({}, this.input, this.start);18989let token = lookahead.getToken();18990let body = null;18991let id = null;1899218993this.startCell();1899418995// An import?18996if (token.type === types$1._import && lookahead.getToken().type !== types$1.parenL) {18997body = this.parseImport(this.startNode());18998}1899919000// A non-empty cell?19001else if (token.type !== types$1.eof && token.type !== types$1.semi) {19002// A named cell?19003if (token.type === types$1.name) {19004if (token.value === "viewof" || token.value === "mutable") {19005token = lookahead.getToken();19006if (token.type !== types$1.name) {19007lookahead.unexpected();19008}19009}19010token = lookahead.getToken();19011if (token.type === types$1.eq) {19012id =19013this.parseMaybeKeywordExpression("viewof", "ViewExpression") ||19014this.parseMaybeKeywordExpression("mutable", "MutableExpression") ||19015this.parseIdent();19016token = lookahead.getToken();19017this.expect(types$1.eq);19018}19019}1902019021// A block?19022if (token.type === types$1.braceL) {19023body = this.parseBlock();19024}1902519026// An expression?19027// Possibly a function or class declaration?19028else {19029body = this.parseExpression();19030if (19031id === null &&19032(body.type === "FunctionExpression" ||19033body.type === "ClassExpression")19034) {19035id = body.id;19036}19037}19038}1903919040this.semicolon();19041if (eof) this.expect(types$1.eof); // TODO1904219043return this.finishCell(node, body, id);19044}19045parseTopLevel(node) {19046return this.parseCell(node, true);19047}19048toAssignable(node, isBinding, refDestructuringErrors) {19049return node.type === "MutableExpression"19050? node19051: super.toAssignable(node, isBinding, refDestructuringErrors);19052}19053checkLocal(id) {19054const node = id.id || id;19055if (defaultGlobals.has(node.name) || node.name === "arguments") {19056this.raise(node.start, `Identifier '${node.name}' is reserved`);19057}19058}19059checkUnreserved(node) {19060if (node.name === "viewof" || node.name === "mutable") {19061this.raise(node.start, `Unexpected keyword '${node.name}'`);19062}19063return super.checkUnreserved(node);19064}19065checkLValSimple(expr, bindingType, checkClashes) {19066return super.checkLValSimple(19067expr.type === "MutableExpression" ? expr.id : expr,19068bindingType,19069checkClashes19070);19071}19072unexpected(pos) {19073this.raise(19074pos != null ? pos : this.start,19075this.type === types$1.eof ? "Unexpected end of input" : "Unexpected token"19076);19077}19078parseMaybeKeywordExpression(keyword, type) {19079if (this.isContextual(keyword)) {19080const node = this.startNode();19081this.next();19082node.id = this.parseIdent();19083return this.finishNode(node, type);19084}19085}19086}1908719088// Based on acorn’s q_tmpl. We will use this to initialize the19089// parser context so our `readTemplateToken` override is called.19090// `readTemplateToken` is based on acorn's `readTmplToken` which19091// is used inside template literals. Our version allows backQuotes.19092new TokContext(19093"`", // token19094true, // isExpr19095true, // preserveSpace19096parser => readTemplateToken.call(parser) // override19097);1909819099// This is our custom override for parsing a template that allows backticks.19100// Based on acorn's readInvalidTemplateToken.19101function readTemplateToken() {19102out: for (; this.pos < this.input.length; this.pos++) {19103switch (this.input.charCodeAt(this.pos)) {19104case 92: { // slash19105if (this.pos < this.input.length - 1) ++this.pos; // not a terminal slash19106break;19107}19108case 36: { // dollar19109if (this.input.charCodeAt(this.pos + 1) === 123) { // dollar curly19110if (this.pos === this.start && this.type === types$1.invalidTemplate) {19111this.pos += 2;19112return this.finishToken(types$1.dollarBraceL);19113}19114break out;19115}19116break;19117}19118}19119}19120return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos));19121}1912219123// Find references.19124// Check for illegal references to arguments.19125// Check for illegal assignments to global references.19126function parseReferences(cell, input, globals = defaultGlobals) {19127if (!cell.body) {19128cell.references = [];19129} else if (cell.body.type === "ImportDeclaration") {19130cell.references = cell.body.injections19131? cell.body.injections.map(i => i.imported)19132: [];19133} else {19134try {19135cell.references = findReferences(cell, globals);19136} catch (error) {19137if (error.node) {19138const loc = getLineInfo(input, error.node.start);19139error.message += ` (${loc.line}:${loc.column})`;19140error.pos = error.node.start;19141error.loc = loc;19142delete error.node;19143}19144throw error;19145}19146}19147return cell;19148}1914919150// Find features: file attachments, secrets, database clients.19151// Check for illegal references to arguments.19152// Check for illegal assignments to global references.19153function parseFeatures(cell, input) {19154if (cell.body && cell.body.type !== "ImportDeclaration") {19155try {19156cell.fileAttachments = findFeatures(cell, "FileAttachment");19157cell.databaseClients = findFeatures(cell, "DatabaseClient");19158cell.secrets = findFeatures(cell, "Secret");19159cell.notificationClients = findFeatures(cell, "NotificationClient");19160} catch (error) {19161if (error.node) {19162const loc = getLineInfo(input, error.node.start);19163error.message += ` (${loc.line}:${loc.column})`;19164error.pos = error.node.start;19165error.loc = loc;19166delete error.node;19167}19168throw error;19169}19170} else {19171cell.fileAttachments = new Map();19172cell.databaseClients = new Map();19173cell.secrets = new Map();19174cell.notificationClients = new Map();19175}19176return cell;19177}1917819179/* Fork changes begin here */1918019181function parseModule(input, {globals} = {}) {19182const program = ModuleParser.parse(input);19183for (const cell of program.cells) {19184parseReferences(cell, input, globals);19185parseFeatures(cell, input);19186}19187return program;19188}1918919190class ModuleParser extends CellParser {19191parseTopLevel(node) {19192if (!node.cells) node.cells = [];19193while (this.type !== types$1.eof) {19194const cell = this.parseCell(this.startNode());19195cell.input = this.input;19196node.cells.push(cell);19197}19198this.next();19199return this.finishNode(node, "Program");19200}19201}1920219203/* Fork changes end here */1920419205// https://developer.mozilla.org/en-US/docs/Glossary/Base641920619207function base64ToBytes(base64) {19208const binString = atob(base64);19209return Uint8Array.from(binString, (m) => m.codePointAt(0));19210}1921119212function base64ToStr(base64) {19213return new TextDecoder().decode(base64ToBytes(base64));19214}1921519216/*global Shiny, $, DOMParser, MutationObserver, URL19217*19218* ojs-connector.js19219*19220* Copyright (C) 2022 RStudio, PBC19221*19222*/1922319224//////////////////////////////////////////////////////////////////////////////1922519226class EmptyInspector {19227pending() {19228}19229fulfilled(_value, _name) {19230}19231rejected(_error, _name) {19232// TODO we should probably communicate this upstream somehow.19233}19234}1923519236// here we need to convert from an ES6 module to an observable module19237// in, well, a best-effort kind of way.19238function es6ImportAsObservableModule(modulePromise, specs) {19239const promiseMap = {};19240const resolveMap = {};19241specs.forEach(spec => {19242promiseMap[spec] = new Promise((resolve, reject) => { resolveMap[spec] = { resolve, reject }; });19243});19244modulePromise.then(m => {19245specs.forEach(spec => {19246resolveMap[spec].resolve(m[spec]);19247});19248}).catch(error => {19249specs.forEach(spec => {19250resolveMap[spec].reject(error);19251});19252});19253return function (runtime, observer) {19254const main = runtime.module();1925519256specs.forEach(key => {19257main.variable(observer(key)).define(key, [], () => promiseMap[key]);19258});19259/*19260Object.keys(m).forEach((key) => {19261const v = m[key];1926219263main.variable(observer(key)).define(key, [], () => promiseMap[key]v);19264});19265*/19266return main;19267};19268}192691927019271// this is essentially the import resolution code from observable's19272// runtime. we change it to add a license check for permissive19273// open-source licenses before resolving the import19274async function defaultResolveImportPath(path) {19275const extractPath = (path) => {19276let source = path;19277let m;19278if ((m = /\.js(\?|$)/i.exec(source))) {19279source = source.slice(0, m.index);19280}19281if ((m = /^[0-9a-f]{16}$/i.test(source))) {19282source = `d/${source}`;19283}19284if ((m = /^https:\/\/(api\.|beta\.|)observablehq\.com\//i.exec(source))) {19285source = source.slice(m[0].length);19286}19287return source;19288};19289const source = extractPath(path);19290const moduleURL = `https://api.observablehq.com/${source}.js?v=3`;1929119292/* TODO This should be the implementation we use, once/if observable19293starts reporting notebook license on their metadata.1929419295const metadata = await fetch(metadataURL, { mode: 'no-cors' });19296const nbJson = metadata.json();19297if (["isc", "mit", "bsd-3-clause", "apache-2.0"].indexOf(nbJson.license) === -1) {19298throw new Error(`Notebook doesn't have a permissive open-source license`);19299} */1930019301const m = await import(moduleURL);19302return m.default;19303}1930419305/*19306importPathResolver encodes the rules for ojsconnector to resolve19307import statements.1930819309This code doesn't depend have any dependencies on quarto, but some19310of the decisions here are influence by the needs of the quarto19311system.1931219313We use the same name from observable's runtime so the intended19314functionality is clear. However, note that their name is slightly19315misleading. importPathResolver not only resolves import paths but19316performs module imports as well. This is useful for us because it19317allows us to extend the meaning of ojs's import statement, but it19318makes the name confusing.1931919320Here are the rules for our version of the import statement.1932119322The function returned by importPathResolver expects a "module specifier", and19323produces a module as defined by observable's runtime.1932419325## Local vs remote vs observable imports1932619327A module specifier is a string, interpreted differently depending on19328the following properties:1932919330- it starts with "." or "/", in which case we call it a "local module"1933119332- it is a well-defined absolute URL which does _not_ match the regexp:19333/^https:\/\/(api\.|beta\.|)observablehq\.com\//i19334in which case we call it a "remote import"1933519336- otherwise, it is an "observable import"1933719338If the string is an observable import, it behaves exactly like the import19339statement inside observable notebooks (we actually defer to their function19340call.) Otherwise, the import statement first retrieves the text content19341of the resource referenced by the path, and then interprets it.1934219343## where resources come from1934419345When operating in non-self-contained mode, local and remote import19346paths are then interpreted as relative URLs (RFC 1808) with base URL19347window.location (specifically as "relative path" and "absolute path"19348relative URLs).1934919350In self-contained mode, these paths are interpreted as paths in the19351quarto project, either as root-relative or relative paths. The19352contents of these files are converted to data URLs and stored in a19353local resolution map.1935419355## how are contents interpreted1935619357The contents of the resource are then interpreted differently19358depending on the file type of the requested resource.1935919360For non-self-contained imports, the file type is determined by the19361extension of the URL pathname. If the extension is "js", we take the19362specifier to mean an ES module; If the extension is "ojs", we take19363the specifier to mean an "ojs" module (a collection of observable19364statements packaged into a module, suitable for reuse). If the19365extension is "ts" or "tsx", then this is an import that was actually transpiled19366into js during quarto render, and we change the extension to .js and19367resolve that. Finally, if the extension is "qmd", we take the specifier19368to mean an "implicit ojs module", equivalent to extracting all19369the ojs statements from the .qmd file and producing an OJS module.1937019371For self-contained imports, the file type is determined by the MIME19372type of the data URL. "application/javascript" is interpreted to19373mean an ES module, and "application/ojs-javascript" is interpreted19374to mean an "ojs" module. (.qmd imports will have been19375translated to ojs modules by the compilation step.)1937619377The resources are finally retrieved, compiled into modules19378compatible with the observable runtime, and returned as19379the result of the import statement.1938019381*/1938219383function importPathResolver(paths, localResolverMap) {19384// NB: only resolve the field values in paths when calling rootPath19385// and relativePath. If we prematurely optimize this by moving the19386// const declarations outside, then we will capture the19387// uninitialized values.1938819389// fetch() and import() have different relative path semantics, so19390// we need different paths for each use case1939119392function importRootPath(path) {19393const { runtimeToRoot } = paths;19394if (!runtimeToRoot) {19395return path;19396} else {19397return `${runtimeToRoot}/${path}`;19398}19399}1940019401function importRelativePath(path) {19402const { runtimeToDoc } = paths;19403if (!runtimeToDoc) {19404return path;19405} else {19406return `${runtimeToDoc}/${path}`;19407}19408}1940919410// a fetch path of a root-relative path is resolved wrt to19411// the document root19412function fetchRootPath(path) {19413const { docToRoot } = paths;19414if (!docToRoot) {19415return path;19416} else {19417return `${docToRoot}/${path}`;19418}19419}1942019421// a fetch path of a relative path is resolved the naive way19422function fetchRelativePath(path) {19423return path;19424}1942519426return async (path, specs) => {19427const isLocalModule = path.startsWith("/") || path.startsWith(".");19428const isImportFromObservableWebsite = path.match(19429/^https:\/\/(api\.|beta\.|)observablehq\.com\//i,19430);1943119432if (!isLocalModule || isImportFromObservableWebsite) {19433return defaultResolveImportPath(path);19434}1943519436let importPath, fetchPath;19437let moduleType;19438if (window._ojs.selfContained) {19439if (path.endsWith(".ts")) {19440path = path.replace(/\.ts$/, ".js");19441} else if (path.endsWith(".tsx")) {19442path = path.replace(/\.tsx$/, ".js");19443}19444const resolved = localResolverMap.get(path);19445if (resolved === undefined) {19446throw new Error(`missing local file ${path} in self-contained mode`);19447}19448// self-contained resolves to data URLs, so they behave the same.19449importPath = resolved;19450fetchPath = resolved;1945119452// we have a data URL here.19453const mimeType = resolved.match(/data:(.*);base64/)[1];19454switch (mimeType) {19455case "application/javascript":19456moduleType = "js";19457break;19458case "application/ojs-javascript":19459moduleType = "ojs";19460break;19461default:19462throw new Error(`unrecognized MIME type ${mimeType}`);19463}19464} else {19465// we have a relative URL here19466const resourceURL = new URL(path, window.location);19467moduleType = resourceURL.pathname.match(/\.(ojs|js|ts|tsx|qmd)$/)[1];1946819469// resolve path according to quarto path resolution rules.19470if (path.startsWith("/")) {19471importPath = importRootPath(path);19472fetchPath = fetchRootPath(path);19473} else {19474importPath = importRelativePath(path);19475fetchPath = fetchRelativePath(path);19476}19477}1947819479if (moduleType === "ts" || moduleType === "tsx") {19480try {19481const modulePromise = import(window._ojs.selfContained ?19482importPath :19483importPath.replace(/\.ts$/, ".js").replace(/\.tsx$/, ".js"));19484return es6ImportAsObservableModule(modulePromise, specs);19485} catch (e) {19486// record the error on the browser console to make debugging19487// slightly more convenient.19488console.error(e);19489throw e;19490}19491} else if (moduleType === "js") {19492try {19493const modulePromise = import(importPath);19494return es6ImportAsObservableModule(modulePromise, specs);19495} catch (e) {19496// record the error on the browser console to make debugging19497// slightly more convenient.19498console.error(e);19499throw e;19500}19501} else if (moduleType === "ojs") {19502return importOjsFromURL(fetchPath);19503} else if (moduleType === "qmd") {19504const htmlPath = `${fetchPath.slice(0, -4)}.html`;19505const response = await fetch(htmlPath);19506const text = await response.text();19507return createOjsModuleFromHTMLSrc(text);19508} else {19509throw new Error(`internal error, unrecognized module type ${moduleType}`);19510}19511};19512}195131951419515function createOjsModuleFromHTMLSrc(text) {19516const parser = new DOMParser();19517const doc = parser.parseFromString(text, "text/html");19518const staticDefns = [];19519for (const el of doc.querySelectorAll('script[type="ojs-define"]')) {19520staticDefns.push(el.text);19521}19522const ojsSource = [];19523for (19524const content of doc.querySelectorAll('script[type="ojs-module-contents"]')19525) {19526for (const cell of JSON.parse(base64ToStr(content.text)).contents) {19527ojsSource.push(cell.source);19528}19529}19530return createOjsModuleFromSrc(ojsSource.join("\n"), staticDefns);19531}1953219533function createOjsModuleFromSrc(src, staticDefns = []) {19534return (runtime, _observer) => {19535const newModule = runtime.module();19536const interpreter = window._ojs.ojsConnector.interpreter;19537interpreter.module(19538src,19539newModule,19540(_name) => new EmptyInspector(),19541);19542for (const defn of staticDefns) {19543for (const { name, value } of JSON.parse(defn).contents) {19544window._ojs.ojsConnector.define(name, newModule)(value);19545}19546}19547return newModule;19548};19549}1955019551/*19552* Given a URL, fetches the text content and creates a new observable module19553* exporting all of the names as variables19554*/19555async function importOjsFromURL(path) {19556const r = await fetch(path);19557const src = await r.text();19558return createOjsModuleFromSrc(src);19559}1956019561class OJSConnector {19562constructor({ paths, inspectorClass, library, allowPendingGlobals = false }) {19563this.library = library || new Library();1956419565// this map contains a mapping from resource names to data URLs19566// that governs fileAttachment and import() resolutions in the19567// case of self-contained files.19568this.localResolverMap = new Map();19569// Keeps track of variables that have been requested by ojs code, but do19570// not exist (not in the module, not in the library, not on window).19571// The keys are variable names, the values are {promise, resolve, reject}.19572// This is intended to allow for a (hopefully brief) phase during startup19573// in which, if an ojs code chunk references a variable that is not defined,19574// instead of treating it as an "x is not defined" error we instead19575// take a wait-and-see approach, in case the variable dynamically becomes19576// defined later. When the phase ends, killPendingGlobals() must be called19577// so any variables that are still missing do cause "x is not defined"19578// errors.19579this.pendingGlobals = {};19580// When true, the mechanism described in the `this.pendingGlobals` comment19581// is used. When false, the result of accessing undefined variables is just19582// "x is not defined". This should be considered private, only settable via19583// constructor or `killPendingGlobals`.19584this.allowPendingGlobals = allowPendingGlobals;19585// NB it looks like Runtime makes a local copy of the library object,19586// such that mutating library after this is initializaed doesn't actually19587// work.19588this.runtime = new Runtime(this.library, (name) => this.global(name));19589this.mainModule = this.runtime.module();19590this.interpreter = new dist.exports.Interpreter({19591module: this.mainModule,19592resolveImportPath: importPathResolver(paths, this.localResolverMap),19593});19594this.inspectorClass = inspectorClass || Inspector;1959519596// state to handle flash of unevaluated js because of async module imports19597this.mainModuleHasImports = false;19598this.mainModuleOutstandingImportCount = 0;19599this.chunkPromises = [];19600}1960119602// Customizes the Runtime's behavior when an undefined variable is accessed.19603// This is needed for cases where the ojs graph is not all present at the19604// time of initialization; in particular, the case where a dependent cell19605// starts executing before one or more of its dependencies have been defined.19606// Without this customization, the user would see a flash of errors while the19607// graph is constructed; with this customization, the dependents stay blank19608// while they wait.19609global(name) {19610if (typeof window[name] !== "undefined") {19611return window[name];19612}19613if (!this.allowPendingGlobals) {19614return undefined;19615}1961619617// deno-lint-ignore no-prototype-builtins19618if (!this.pendingGlobals.hasOwnProperty(name)) {19619// This is a pending global we haven't seen before. Stash a new promise,19620// along with its resolve/reject callbacks, in an object and remember it19621// for later.19622const info = {};19623info.promise = new Promise((resolve, reject) => {19624info.resolve = resolve;19625info.reject = reject;19626});19627this.pendingGlobals[name] = info;19628}19629return this.pendingGlobals[name].promise;19630}1963119632// Signals the end of the "pending globals" phase. Any promises we've handed19633// out from the global() method now are rejected. (We never resolve these19634// promises to values; if these variables made an appearance, it would've19635// been as variables on modules.)19636killPendingGlobals() {19637this.allowPendingGlobals = false;19638for (const [name, { reject }] of Object.entries(this.pendingGlobals)) {19639reject(new RuntimeError(`${name} is not defined`));19640}19641}1964219643setLocalResolver(map) {19644for (const [key, value] of Object.entries(map)) {19645this.localResolverMap.set(key, value);19646}19647}1964819649define(name, module = undefined) {19650if (!module) {19651module = this.mainModule;19652}19653let change;19654const obs = this.library.Generators.observe((change_) => {19655change = change_;19656// TODO do something about destruction19657});19658module.variable().define(name, obs);19659return change;19660}1966119662watch(name, k, module = undefined) {19663if (!module) {19664module = this.mainModule;19665}19666module.variable({19667fulfilled: (x) => k(x, name),19668}).define([name], (val) => val);19669}1967019671async value(val, module = undefined) {19672if (!module) {19673module = this.mainModule;19674}19675const result = await module.value(val);19676return result;19677}1967819679finishInterpreting() {19680return Promise.all(this.chunkPromises);19681}1968219683interpretWithRunner(src, runner) {19684try {19685const parse = parseModule(src);19686const chunkPromise = Promise.all(parse.cells.map(runner));19687this.chunkPromises.push(chunkPromise);19688return chunkPromise;19689} catch (error) {19690return Promise.reject(error);19691}19692}1969319694waitOnImports(cell, promise) {19695if (cell.body.type !== "ImportDeclaration") {19696return promise;19697} else {19698this.mainModuleHasImports = true;19699this.mainModuleOutstandingImportCount++;19700return promise.then((result) => {19701this.mainModuleOutstandingImportCount--;19702if (this.mainModuleOutstandingImportCount === 0) {19703this.clearImportModuleWait();19704}19705return result;19706});19707}19708}1970919710interpretQuiet(src) {19711const runCell = (cell) => {19712const cellSrc = src.slice(cell.start, cell.end);19713const promise = this.interpreter.module(19714cellSrc,19715undefined,19716(_name) => new EmptyInspector(),19717);19718return this.waitOnImports(cell, promise);19719};19720return this.interpretWithRunner(src, runCell);19721}19722}1972319724/*!19725* escape-html19726* Copyright(c) 2012-2013 TJ Holowaychuk19727* Copyright(c) 2015 Andreas Lubbe19728* Copyright(c) 2015 Tiancheng "Timothy" Gu19729* Copyright(c) 2022 RStudio, PBC19730*19731* MIT Licensed19732*19733* Minimal changes to make ES619734*19735*/1973619737var matchHtmlRegExp = /["'&<>]/;1973819739/**19740* Escape special characters in the given string of text.19741*19742* @param {string} string The string to escape for inserting into HTML19743* @return {string}19744* @public19745*/1974619747function escapeHtml (string) {19748var str = '' + string;19749var match = matchHtmlRegExp.exec(str);1975019751if (!match) {19752return str19753}1975419755var escape;19756var html = '';19757var index = 0;19758var lastIndex = 0;1975919760for (index = match.index; index < str.length; index++) {19761switch (str.charCodeAt(index)) {19762case 34: // "19763escape = '"';19764break19765case 38: // &19766escape = '&';19767break19768case 39: // '19769escape = ''';19770break19771case 60: // <19772escape = '<';19773break19774case 62: // >19775escape = '>';19776break19777default:19778continue19779}1978019781if (lastIndex !== index) {19782html += str.substring(lastIndex, index);19783}1978419785lastIndex = index + 1;19786html += escape;19787}1978819789return lastIndex !== index19790? html + str.substring(lastIndex, index)19791: html19792}1979319794function createHtmlElement(tag, attrs, ...children) {19795const el = document.createElement(tag);19796for (const [key, val] of Object.entries(attrs || {})) {19797el.setAttribute(key, val);19798}19799while (children.length) {19800const child = children.shift();19801if (Array.isArray(child)) {19802children.unshift(...child);19803} else if (child instanceof HTMLElement) {19804el.appendChild(child);19805} else {19806el.appendChild(document.createTextNode(escapeHtml(child)));19807}19808}19809return el;19810}1981119812function createNamespacedElement(ns, tag, attrs, ...children) {19813const el = document.createElementNS(ns.namespace, tag);19814for (const [key, val] of Object.entries(attrs || {})) {19815el.setAttribute(key, val);19816}19817while (children.length) {19818const child = children.shift();19819if (Array.isArray(child)) {19820children.unshift(...child);19821} else if (child instanceof HTMLElement || child instanceof ns.class) {19822el.appendChild(child);19823} else {19824el.appendChild(document.createTextNode(escapeHtml(child)));19825}19826}19827return el;19828}1982919830const resolver = {19831a: "svg",19832animate: "svg",19833animateMotion: "svg",19834animateTransform: "svg",19835circle: "svg",19836clipPath: "svg",19837defs: "svg",19838desc: "svg",19839discard: "svg",19840ellipse: "svg",19841feBlend: "svg",19842feColorMatrix: "svg",19843feComponentTransfer: "svg",19844feComposite: "svg",19845feConvolveMatrix: "svg",19846feDiffuseLighting: "svg",19847feDisplacementMap: "svg",19848feDistantLight: "svg",19849feDropShadow: "svg",19850feFlood: "svg",19851feFuncA: "svg",19852feFuncB: "svg",19853feFuncG: "svg",19854feFuncR: "svg",19855feGaussianBlur: "svg",19856feImage: "svg",19857feMerge: "svg",19858feMergeNode: "svg",19859feMorphology: "svg",19860feOffset: "svg",19861fePointLight: "svg",19862feSpecularLighting: "svg",19863feSpotLight: "svg",19864feTile: "svg",19865feTurbulence: "svg",19866filter: "svg",19867foreignObject: "svg",19868g: "svg",19869image: "svg",19870line: "svg",19871linearGradient: "svg",19872marker: "svg",19873mask: "svg",19874metadata: "svg",19875mpath: "svg",19876path: "svg",19877pattern: "svg",19878polygon: "svg",19879polyline: "svg",19880radialGradient: "svg",19881rect: "svg",19882script: "svg",19883set: "svg",19884stop: "svg",19885style: "svg",19886svg: "svg",19887switch: "svg",19888symbol: "svg",19889text: "svg",19890textPath: "svg",19891title: "svg",19892tspan: "svg",19893use: "svg",19894view: "svg",19895};1989619897const nss = {19898"svg": { namespace: "http://www.w3.org/2000/svg", class: SVGElement }19899};1990019901function resolveCreator(tag) {19902const nsKey = resolver[tag];19903if (nsKey === undefined) {19904return createHtmlElement;19905}19906const namespace = nss[nsKey];1990719908return function(tag, attrs, ...children) {19909return createNamespacedElement(namespace, tag, attrs, ...children);19910}19911}1991219913function createQuartoJsxShim()19914{19915return {19916createElement(tag, attrs, ...children) {19917if (typeof tag === "function") {19918return tag({...attrs, children });19919}1992019921return resolveCreator(tag)(tag, attrs, ...children);19922}19923};19924}1992519926/*19927Copyright (C) 2012-2014 Yusuke Suzuki <[email protected]>19928Copyright (C) 2015 Ingvar Stepanyan <[email protected]>19929Copyright (C) 2014 Ivan Nikulin <[email protected]>19930Copyright (C) 2012-2013 Michael Ficarra <[email protected]>19931Copyright (C) 2012-2013 Mathias Bynens <[email protected]>19932Copyright (C) 2013 Irakli Gozalishvili <[email protected]>19933Copyright (C) 2012 Robert Gust-Bardon <[email protected]>19934Copyright (C) 2012 John Freeman <[email protected]>19935Copyright (C) 2011-2012 Ariya Hidayat <[email protected]>19936Copyright (C) 2012 Joost-Wim Boekesteijn <[email protected]>19937Copyright (C) 2012 Kris Kowal <[email protected]>19938Copyright (C) 2012 Arpad Borsos <[email protected]>19939Copyright (C) 2020 Apple Inc. All rights reserved.19940Copyright (C) 2023 Posit, PBC.1994119942This is a minimal modern single-file fork of escodegen, so that19943199441) we can use it in modern module-based JS environments199452) we can extend the CodeGenerator prototype for the ability to19946support custom code generation for new AST nodes.1994719948Redistribution and use in source and binary forms, with or without19949modification, are permitted provided that the following conditions are met:1995019951* Redistributions of source code must retain the above copyright19952notice, this list of conditions and the following disclaimer.19953* Redistributions in binary form must reproduce the above copyright19954notice, this list of conditions and the following disclaimer in the19955documentation and/or other materials provided with the distribution.1995619957THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"19958AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE19959IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE19960ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY19961DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES19962(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;19963LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND19964ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT19965(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF19966THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.19967*/1996819969let Precedence;1997019971var BinaryPrecedence,19972esutils,19973base,19974indent,19975json,19976renumber,19977hexadecimal,19978quotes,19979escapeless,19980newline,19981space,19982parentheses,19983semicolons,19984safeConcatenation,19985directive,19986extra,19987parse,19988sourceMap,19989sourceCode,19990preserveBlankLines;1999119992esutils = {19993code: {19994ES5Regex: {19995NonAsciiIdentifierStart: /[\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\u0561-\u0587\u05D0-\u05EA\u05F0-\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\u08A0-\u08B4\u08B6-\u08BD\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\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\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\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\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\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-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\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\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\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\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\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-\uAB65\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]/,19996NonAsciiIdentifierPart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\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\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\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\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/19997},19998ES6Regex: {19999NonAsciiIdentifierStart: /[\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\u0561-\u0587\u05D0-\u05EA\u05F0-\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\u08A0-\u08B4\u08B6-\u08BD\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\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\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\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\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\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-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\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-\u2C2E\u2C30-\u2C5E\u2C60-\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-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\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-\uAB65\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]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,20000NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\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\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\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\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/20001},20002isDecimalDigit: function(ch) {20003return 48 <= ch && ch <= 57;20004},20005isHexDigit: function(ch) {20006return 48 <= ch && ch <= 57 || 97 <= ch && ch <= 102 || 65 <= ch && ch <= 70;20007},20008isOctalDigit: function(ch) {20009return ch >= 48 && ch <= 55;20010},20011NON_ASCII_WHITESPACES: [200125760,200138192,200148193,200158194,200168195,200178196,200188197,200198198,200208199,200218200,200228201,200238202,200248239,200258287,2002612288,200276527920028],20029isWhiteSpace: function(ch) {20030return ch === 32 || ch === 9 || ch === 11 || ch === 12 || ch === 160 || ch >= 5760 && esutils.code.NON_ASCII_WHITESPACES.indexOf(ch) >= 0;20031},20032isLineTerminator: function(ch) {20033return ch === 10 || ch === 13 || ch === 8232 || ch === 8233;20034},20035fromCodePoint: function(cp) {20036if (cp <= 65535) {20037return String.fromCharCode(cp);20038}20039var cu1 = String.fromCharCode(Math.floor((cp - 65536) / 1024) + 55296);20040var cu2 = String.fromCharCode((cp - 65536) % 1024 + 56320);20041return cu1 + cu2;20042},20043IDENTIFIER_START: new Array(128),20044IDENTIFIER_PART: new Array(128),20045isIdentifierStartES5: function(ch) {20046return ch < 128 ? esutils.code.IDENTIFIER_START[ch] : esutils.code.ES5Regex.NonAsciiIdentifierStart.test(esutils.code.fromCodePoint(ch));20047},20048isIdentifierPartES5: function(ch) {20049return ch < 128 ? esutils.code.IDENTIFIER_PART[ch] : esutils.code.ES5Regex.NonAsciiIdentifierPart.test(esutils.code.fromCodePoint(ch));20050},20051isIdentifierStartES6: function(ch) {20052return ch < 128 ? esutils.code.IDENTIFIER_START[ch] : esutils.code.ES6Regex.NonAsciiIdentifierStart.test(esutils.code.fromCodePoint(ch));20053},20054isIdentifierPartES6: function(ch) {20055return ch < 128 ? esutils.code.IDENTIFIER_PART[ch] : esutils.code.ES6Regex.NonAsciiIdentifierPart.test(esutils.code.fromCodePoint(ch));20056}20057}20058};20059for (var ch = 0; ch < 128; ++ch) {20060esutils.code.IDENTIFIER_START[ch] = ch >= 97 && ch <= 122 || ch >= 65 && ch <= 90 || ch === 36 || ch === 95;20061}20062for (var ch = 0; ch < 128; ++ch) {20063esutils.code.IDENTIFIER_PART[ch] = ch >= 97 && ch <= 122 || ch >= 65 && ch <= 90 || ch >= 48 && ch <= 57 || ch === 36 || ch === 95;20064}2006520066// Generation is done by generateExpression.20067function isExpression(node) {20068return CodeGenerator.Expression.hasOwnProperty(node.type);20069}2007020071// Generation is done by generateStatement.20072function isStatement(node) {20073return CodeGenerator.Statement.hasOwnProperty(node.type);20074}2007520076Precedence = {20077Sequence: 0,20078Yield: 1,20079Assignment: 1,20080Conditional: 2,20081ArrowFunction: 2,20082Coalesce: 3,20083LogicalOR: 4,20084LogicalAND: 5,20085BitwiseOR: 6,20086BitwiseXOR: 7,20087BitwiseAND: 8,20088Equality: 9,20089Relational: 10,20090BitwiseSHIFT: 11,20091Additive: 12,20092Multiplicative: 13,20093Exponentiation: 14,20094Await: 15,20095Unary: 15,20096Postfix: 16,20097OptionalChaining: 17,20098Call: 18,20099New: 19,20100TaggedTemplate: 20,20101Member: 21,20102Primary: 2220103};2010420105BinaryPrecedence = {20106'??': Precedence.Coalesce,20107'||': Precedence.LogicalOR,20108'&&': Precedence.LogicalAND,20109'|': Precedence.BitwiseOR,20110'^': Precedence.BitwiseXOR,20111'&': Precedence.BitwiseAND,20112'==': Precedence.Equality,20113'!=': Precedence.Equality,20114'===': Precedence.Equality,20115'!==': Precedence.Equality,20116'is': Precedence.Equality,20117'isnt': Precedence.Equality,20118'<': Precedence.Relational,20119'>': Precedence.Relational,20120'<=': Precedence.Relational,20121'>=': Precedence.Relational,20122'in': Precedence.Relational,20123'instanceof': Precedence.Relational,20124'<<': Precedence.BitwiseSHIFT,20125'>>': Precedence.BitwiseSHIFT,20126'>>>': Precedence.BitwiseSHIFT,20127'+': Precedence.Additive,20128'-': Precedence.Additive,20129'*': Precedence.Multiplicative,20130'%': Precedence.Multiplicative,20131'/': Precedence.Multiplicative,20132'**': Precedence.Exponentiation20133};2013420135//Flags20136var F_ALLOW_IN = 1,20137F_ALLOW_CALL = 1 << 1,20138F_ALLOW_UNPARATH_NEW = 1 << 2,20139F_FUNC_BODY = 1 << 3,20140F_DIRECTIVE_CTX = 1 << 4,20141F_SEMICOLON_OPT = 1 << 5,20142F_FOUND_COALESCE = 1 << 6;2014320144//Expression flag sets20145//NOTE: Flag order:20146// F_ALLOW_IN20147// F_ALLOW_CALL20148// F_ALLOW_UNPARATH_NEW20149var E_FTT = F_ALLOW_CALL | F_ALLOW_UNPARATH_NEW,20150E_TTF = F_ALLOW_IN | F_ALLOW_CALL,20151E_TTT = F_ALLOW_IN | F_ALLOW_CALL | F_ALLOW_UNPARATH_NEW,20152E_TFF = F_ALLOW_IN,20153E_FFT = F_ALLOW_UNPARATH_NEW,20154E_TFT = F_ALLOW_IN | F_ALLOW_UNPARATH_NEW;2015520156//Statement flag sets20157//NOTE: Flag order:20158// F_ALLOW_IN20159// F_FUNC_BODY20160// F_DIRECTIVE_CTX20161// F_SEMICOLON_OPT20162var S_TFFF = F_ALLOW_IN,20163S_TFFT = F_ALLOW_IN | F_SEMICOLON_OPT,20164S_FFFF = 0x00,20165S_TFTF = F_ALLOW_IN | F_DIRECTIVE_CTX,20166S_TTFF = F_ALLOW_IN | F_FUNC_BODY;2016720168function getDefaultOptions() {20169// default options20170return {20171indent: null,20172base: null,20173parse: null,20174comment: false,20175format: {20176indent: {20177style: ' ',20178base: 0,20179adjustMultilineComment: false20180},20181newline: '\n',20182space: ' ',20183json: false,20184renumber: false,20185hexadecimal: false,20186quotes: 'single',20187escapeless: false,20188compact: false,20189parentheses: true,20190semicolons: true,20191safeConcatenation: false,20192preserveBlankLines: false20193},20194moz: {20195comprehensionExpressionStartsWithAssignment: false,20196starlessGenerator: false20197},20198sourceMap: null,20199sourceMapRoot: null,20200sourceMapWithCode: false,20201directive: false,20202raw: true,20203verbatim: null,20204sourceCode: null20205};20206}2020720208function stringRepeat(str, num) {20209var result = '';2021020211for (num |= 0; num > 0; num >>>= 1, str += str) {20212if (num & 1) {20213result += str;20214}20215}2021620217return result;20218}2021920220function hasLineTerminator(str) {20221return (/[\r\n]/g).test(str);20222}2022320224function endsWithLineTerminator(str) {20225var len = str.length;20226return len && esutils.code.isLineTerminator(str.charCodeAt(len - 1));20227}2022820229function merge(target, override) {20230var key;20231for (key in override) {20232if (override.hasOwnProperty(key)) {20233target[key] = override[key];20234}20235}20236return target;20237}2023820239function updateDeeply(target, override) {20240var key, val;2024120242function isHashObject(target) {20243return typeof target === 'object' && target instanceof Object && !(target instanceof RegExp);20244}2024520246for (key in override) {20247if (override.hasOwnProperty(key)) {20248val = override[key];20249if (isHashObject(val)) {20250if (isHashObject(target[key])) {20251updateDeeply(target[key], val);20252} else {20253target[key] = updateDeeply({}, val);20254}20255} else {20256target[key] = val;20257}20258}20259}20260return target;20261}2026220263function generateNumber(value) {20264var result, point, temp, exponent, pos;2026520266if (value !== value) {20267throw new Error('Numeric literal whose value is NaN');20268}20269if (value < 0 || (value === 0 && 1 / value < 0)) {20270throw new Error('Numeric literal whose value is negative');20271}2027220273if (value === 1 / 0) {20274return json ? 'null' : renumber ? '1e400' : '1e+400';20275}2027620277result = '' + value;20278if (!renumber || result.length < 3) {20279return result;20280}2028120282point = result.indexOf('.');20283if (!json && result.charCodeAt(0) === 0x30 /* 0 */ && point === 1) {20284point = 0;20285result = result.slice(1);20286}20287temp = result;20288result = result.replace('e+', 'e');20289exponent = 0;20290if ((pos = temp.indexOf('e')) > 0) {20291exponent = +temp.slice(pos + 1);20292temp = temp.slice(0, pos);20293}20294if (point >= 0) {20295exponent -= temp.length - point - 1;20296temp = +(temp.slice(0, point) + temp.slice(point + 1)) + '';20297}20298pos = 0;20299while (temp.charCodeAt(temp.length + pos - 1) === 0x30 /* 0 */) {20300--pos;20301}20302if (pos !== 0) {20303exponent -= pos;20304temp = temp.slice(0, pos);20305}20306if (exponent !== 0) {20307temp += 'e' + exponent;20308}20309if ((temp.length < result.length ||20310(hexadecimal && value > 1e12 && Math.floor(value) === value && (temp = '0x' + value.toString(16)).length < result.length)) &&20311+temp === value) {20312result = temp;20313}2031420315return result;20316}2031720318// Generate valid RegExp expression.20319// This function is based on https://github.com/Constellation/iv Engine2032020321function escapeRegExpCharacter(ch, previousIsBackslash) {20322// not handling '\' and handling \u2028 or \u2029 to unicode escape sequence20323if ((ch & ~1) === 0x2028) {20324return (previousIsBackslash ? 'u' : '\\u') + ((ch === 0x2028) ? '2028' : '2029');20325} else if (ch === 10 || ch === 13) { // \n, \r20326return (previousIsBackslash ? '' : '\\') + ((ch === 10) ? 'n' : 'r');20327}20328return String.fromCharCode(ch);20329}2033020331function generateRegExp(reg) {20332var match, result, flags, i, iz, ch, characterInBrack, previousIsBackslash;2033320334result = reg.toString();2033520336if (reg.source) {20337// extract flag from toString result20338match = result.match(/\/([^/]*)$/);20339if (!match) {20340return result;20341}2034220343flags = match[1];20344result = '';2034520346characterInBrack = false;20347previousIsBackslash = false;20348for (i = 0, iz = reg.source.length; i < iz; ++i) {20349ch = reg.source.charCodeAt(i);2035020351if (!previousIsBackslash) {20352if (characterInBrack) {20353if (ch === 93) { // ]20354characterInBrack = false;20355}20356} else {20357if (ch === 47) { // /20358result += '\\';20359} else if (ch === 91) { // [20360characterInBrack = true;20361}20362}20363result += escapeRegExpCharacter(ch, previousIsBackslash);20364previousIsBackslash = ch === 92; // \20365} else {20366// if new RegExp("\\\n') is provided, create /\n/20367result += escapeRegExpCharacter(ch, previousIsBackslash);20368// prevent like /\\[/]/20369previousIsBackslash = false;20370}20371}2037220373return '/' + result + '/' + flags;20374}2037520376return result;20377}2037820379function escapeAllowedCharacter(code, next) {20380var hex;2038120382if (code === 0x08 /* \b */) {20383return '\\b';20384}2038520386if (code === 0x0C /* \f */) {20387return '\\f';20388}2038920390if (code === 0x09 /* \t */) {20391return '\\t';20392}2039320394hex = code.toString(16).toUpperCase();20395if (json || code > 0xFF) {20396return '\\u' + '0000'.slice(hex.length) + hex;20397} else if (code === 0x0000 && !esutils.code.isDecimalDigit(next)) {20398return '\\0';20399} else if (code === 0x000B /* \v */) { // '\v'20400return '\\x0B';20401} else {20402return '\\x' + '00'.slice(hex.length) + hex;20403}20404}2040520406function escapeDisallowedCharacter(code) {20407if (code === 0x5C /* \ */) {20408return '\\\\';20409}2041020411if (code === 0x0A /* \n */) {20412return '\\n';20413}2041420415if (code === 0x0D /* \r */) {20416return '\\r';20417}2041820419if (code === 0x2028) {20420return '\\u2028';20421}2042220423if (code === 0x2029) {20424return '\\u2029';20425}2042620427throw new Error('Incorrectly classified character');20428}2042920430function escapeDirective(str) {20431var i, iz, code, quote;2043220433quote = quotes === 'double' ? '"' : '\'';20434for (i = 0, iz = str.length; i < iz; ++i) {20435code = str.charCodeAt(i);20436if (code === 0x27 /* ' */) {20437quote = '"';20438break;20439} else if (code === 0x22 /* " */) {20440quote = '\'';20441break;20442} else if (code === 0x5C /* \ */) {20443++i;20444}20445}2044620447return quote + str + quote;20448}2044920450function escapeString(str) {20451var result = '', i, len, code, singleQuotes = 0, doubleQuotes = 0, single, quote;2045220453for (i = 0, len = str.length; i < len; ++i) {20454code = str.charCodeAt(i);20455if (code === 0x27 /* ' */) {20456++singleQuotes;20457} else if (code === 0x22 /* " */) {20458++doubleQuotes;20459} else if (code === 0x2F /* / */ && json) {20460result += '\\';20461} else if (esutils.code.isLineTerminator(code) || code === 0x5C /* \ */) {20462result += escapeDisallowedCharacter(code);20463continue;20464} else if (!esutils.code.isIdentifierPartES5(code) && (json && code < 0x20 /* SP */ || !json && !escapeless && (code < 0x20 /* SP */ || code > 0x7E /* ~ */))) {20465result += escapeAllowedCharacter(code, str.charCodeAt(i + 1));20466continue;20467}20468result += String.fromCharCode(code);20469}2047020471single = !(quotes === 'double' || (quotes === 'auto' && doubleQuotes < singleQuotes));20472quote = single ? '\'' : '"';2047320474if (!(single ? singleQuotes : doubleQuotes)) {20475return quote + result + quote;20476}2047720478str = result;20479result = quote;2048020481for (i = 0, len = str.length; i < len; ++i) {20482code = str.charCodeAt(i);20483if ((code === 0x27 /* ' */ && single) || (code === 0x22 /* " */ && !single)) {20484result += '\\';20485}20486result += String.fromCharCode(code);20487}2048820489return result + quote;20490}2049120492/**20493* flatten an array to a string, where the array can contain20494* either strings or nested arrays20495*/20496function flattenToString(arr) {20497var i, iz, elem, result = '';20498for (i = 0, iz = arr.length; i < iz; ++i) {20499elem = arr[i];20500result += Array.isArray(elem) ? flattenToString(elem) : elem;20501}20502return result;20503}2050420505function toSourceNodeWhenNeeded(generated) {20506// with no source maps, generated is either an20507// array or a string. if an array, flatten it.20508// if a string, just return it20509if (Array.isArray(generated)) {20510return flattenToString(generated);20511} else {20512return generated;20513}20514}2051520516function noEmptySpace() {20517return (space) ? space : ' ';20518}2051920520function join(left, right) {20521var leftSource,20522rightSource,20523leftCharCode,20524rightCharCode;2052520526leftSource = toSourceNodeWhenNeeded(left).toString();20527if (leftSource.length === 0) {20528return [right];20529}2053020531rightSource = toSourceNodeWhenNeeded(right).toString();20532if (rightSource.length === 0) {20533return [left];20534}2053520536leftCharCode = leftSource.charCodeAt(leftSource.length - 1);20537rightCharCode = rightSource.charCodeAt(0);2053820539if ((leftCharCode === 0x2B /* + */ || leftCharCode === 0x2D /* - */) && leftCharCode === rightCharCode ||20540esutils.code.isIdentifierPartES5(leftCharCode) && esutils.code.isIdentifierPartES5(rightCharCode) ||20541leftCharCode === 0x2F /* / */ && rightCharCode === 0x69 /* i */) { // infix word operators all start with `i`20542return [left, noEmptySpace(), right];20543} else if (esutils.code.isWhiteSpace(leftCharCode) || esutils.code.isLineTerminator(leftCharCode) ||20544esutils.code.isWhiteSpace(rightCharCode) || esutils.code.isLineTerminator(rightCharCode)) {20545return [left, right];20546}20547return [left, space, right];20548}2054920550function addIndent(stmt) {20551return [base, stmt];20552}2055320554function withIndent(fn) {20555var previousBase;20556previousBase = base;20557base += indent;20558fn(base);20559base = previousBase;20560}2056120562function calculateSpaces(str) {20563var i;20564for (i = str.length - 1; i >= 0; --i) {20565if (esutils.code.isLineTerminator(str.charCodeAt(i))) {20566break;20567}20568}20569return (str.length - 1) - i;20570}2057120572function adjustMultilineComment(value, specialBase) {20573var array, i, len, line, j, spaces, previousBase, sn;2057420575array = value.split(/\r\n|[\r\n]/);20576spaces = Number.MAX_VALUE;2057720578// first line doesn't have indentation20579for (i = 1, len = array.length; i < len; ++i) {20580line = array[i];20581j = 0;20582while (j < line.length && esutils.code.isWhiteSpace(line.charCodeAt(j))) {20583++j;20584}20585if (spaces > j) {20586spaces = j;20587}20588}2058920590if (typeof specialBase !== 'undefined') {20591// pattern like20592// {20593// var t = 20; /*20594// * this is comment20595// */20596// }20597previousBase = base;20598if (array[1][spaces] === '*') {20599specialBase += ' ';20600}20601base = specialBase;20602} else {20603if (spaces & 1) {20604// /*20605// *20606// */20607// If spaces are odd number, above pattern is considered.20608// We waste 1 space.20609--spaces;20610}20611previousBase = base;20612}2061320614for (i = 1, len = array.length; i < len; ++i) {20615sn = toSourceNodeWhenNeeded(addIndent(array[i].slice(spaces)));20616array[i] = sourceMap ? sn.join('') : sn;20617}2061820619base = previousBase;2062020621return array.join('\n');20622}2062320624function generateComment(comment, specialBase) {20625if (comment.type === 'Line') {20626if (endsWithLineTerminator(comment.value)) {20627return '//' + comment.value;20628} else {20629// Always use LineTerminator20630var result = '//' + comment.value;20631if (!preserveBlankLines) {20632result += '\n';20633}20634return result;20635}20636}20637if (extra.format.indent.adjustMultilineComment && /[\n\r]/.test(comment.value)) {20638return adjustMultilineComment('/*' + comment.value + '*/', specialBase);20639}20640return '/*' + comment.value + '*/';20641}2064220643function addComments(stmt, result) {20644var i, len, comment, save, tailingToStatement, specialBase, fragment,20645extRange, range, prevRange, prefix, infix, suffix, count;2064620647if (stmt.leadingComments && stmt.leadingComments.length > 0) {20648save = result;2064920650if (preserveBlankLines) {20651comment = stmt.leadingComments[0];20652result = [];2065320654extRange = comment.extendedRange;20655range = comment.range;2065620657prefix = sourceCode.substring(extRange[0], range[0]);20658count = (prefix.match(/\n/g) || []).length;20659if (count > 0) {20660result.push(stringRepeat('\n', count));20661result.push(addIndent(generateComment(comment)));20662} else {20663result.push(prefix);20664result.push(generateComment(comment));20665}2066620667prevRange = range;2066820669for (i = 1, len = stmt.leadingComments.length; i < len; i++) {20670comment = stmt.leadingComments[i];20671range = comment.range;2067220673infix = sourceCode.substring(prevRange[1], range[0]);20674count = (infix.match(/\n/g) || []).length;20675result.push(stringRepeat('\n', count));20676result.push(addIndent(generateComment(comment)));2067720678prevRange = range;20679}2068020681suffix = sourceCode.substring(range[1], extRange[1]);20682count = (suffix.match(/\n/g) || []).length;20683result.push(stringRepeat('\n', count));20684} else {20685comment = stmt.leadingComments[0];20686result = [];20687if (safeConcatenation && stmt.type === "Program" && stmt.body.length === 0) {20688result.push('\n');20689}20690result.push(generateComment(comment));20691if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {20692result.push('\n');20693}2069420695for (i = 1, len = stmt.leadingComments.length; i < len; ++i) {20696comment = stmt.leadingComments[i];20697fragment = [generateComment(comment)];20698if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {20699fragment.push('\n');20700}20701result.push(addIndent(fragment));20702}20703}2070420705result.push(addIndent(save));20706}2070720708if (stmt.trailingComments) {2070920710if (preserveBlankLines) {20711comment = stmt.trailingComments[0];20712extRange = comment.extendedRange;20713range = comment.range;2071420715prefix = sourceCode.substring(extRange[0], range[0]);20716count = (prefix.match(/\n/g) || []).length;2071720718if (count > 0) {20719result.push(stringRepeat('\n', count));20720result.push(addIndent(generateComment(comment)));20721} else {20722result.push(prefix);20723result.push(generateComment(comment));20724}20725} else {20726tailingToStatement = !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString());20727specialBase = stringRepeat(' ', calculateSpaces(toSourceNodeWhenNeeded([base, result, indent]).toString()));20728for (i = 0, len = stmt.trailingComments.length; i < len; ++i) {20729comment = stmt.trailingComments[i];20730if (tailingToStatement) {20731// We assume target like following script20732//20733// var t = 20; /**20734// * This is comment of t20735// */20736if (i === 0) {20737// first case20738result = [result, indent];20739} else {20740result = [result, specialBase];20741}20742result.push(generateComment(comment, specialBase));20743} else {20744result = [result, addIndent(generateComment(comment))];20745}20746if (i !== len - 1 && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {20747result = [result, '\n'];20748}20749}20750}20751}2075220753return result;20754}2075520756function generateBlankLines(start, end, result) {20757var j, newlineCount = 0;2075820759for (j = start; j < end; j++) {20760if (sourceCode[j] === '\n') {20761newlineCount++;20762}20763}2076420765for (j = 1; j < newlineCount; j++) {20766result.push(newline);20767}20768}2076920770function parenthesize(text, current, should) {20771if (current < should) {20772return ['(', text, ')'];20773}20774return text;20775}2077620777function generateVerbatimString(string) {20778var i, iz, result;20779result = string.split(/\r\n|\n/);20780for (i = 1, iz = result.length; i < iz; i++) {20781result[i] = newline + base + result[i];20782}20783return result;20784}2078520786function generateVerbatim(expr, precedence) {20787var verbatim, result, prec;20788verbatim = expr[extra.verbatim];2078920790if (typeof verbatim === 'string') {20791result = parenthesize(generateVerbatimString(verbatim), Precedence.Sequence, precedence);20792} else {20793// verbatim is object20794result = generateVerbatimString(verbatim.content);20795prec = (verbatim.precedence != null) ? verbatim.precedence : Precedence.Sequence;20796result = parenthesize(result, prec, precedence);20797}2079820799return toSourceNodeWhenNeeded(result);20800}2080120802function CodeGenerator() {20803}2080420805// Helpers.2080620807CodeGenerator.prototype.maybeBlock = function(stmt, flags) {20808var result, noLeadingComment, that = this;2080920810noLeadingComment = !extra.comment || !stmt.leadingComments;2081120812if (stmt.type === "BlockStatement" && noLeadingComment) {20813return [space, this.generateStatement(stmt, flags)];20814}2081520816if (stmt.type === "EmptyStatement" && noLeadingComment) {20817return ';';20818}2081920820withIndent(function () {20821result = [20822newline,20823addIndent(that.generateStatement(stmt, flags))20824];20825});2082620827return result;20828};2082920830CodeGenerator.prototype.maybeBlockSuffix = function (stmt, result) {20831var ends = endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString());20832if (stmt.type === "BlockStatement" && (!extra.comment || !stmt.leadingComments) && !ends) {20833return [result, space];20834}20835if (ends) {20836return [result, base];20837}20838return [result, newline, base];20839};2084020841function generateIdentifier(node) {20842return toSourceNodeWhenNeeded(node.name);20843}2084420845function generateAsyncPrefix(node, spaceRequired) {20846return node.async ? 'async' + (spaceRequired ? noEmptySpace() : space) : '';20847}2084820849function generateStarSuffix(node) {20850var isGenerator = node.generator && !extra.moz.starlessGenerator;20851return isGenerator ? '*' + space : '';20852}2085320854function generateMethodPrefix(prop) {20855var func = prop.value, prefix = '';20856if (func.async) {20857prefix += generateAsyncPrefix(func, !prop.computed);20858}20859if (func.generator) {20860// avoid space before method name20861prefix += generateStarSuffix(func) ? '*' : '';20862}20863return prefix;20864}2086520866CodeGenerator.prototype.generatePattern = function (node, precedence, flags) {20867if (node.type === "Identifier") {20868return generateIdentifier(node);20869}20870return this.generateExpression(node, precedence, flags);20871};2087220873CodeGenerator.prototype.generateFunctionParams = function (node) {20874var i, iz, result, hasDefault;2087520876hasDefault = false;2087720878if (node.type === "ArrowFunctionExpression" &&20879!node.rest && (!node.defaults || node.defaults.length === 0) &&20880node.params.length === 1 && node.params[0].type === "Identifier") {20881// arg => { } case20882result = [generateAsyncPrefix(node, true), generateIdentifier(node.params[0])];20883} else {20884result = node.type === "ArrowFunctionExpression"? [generateAsyncPrefix(node, false)] : [];20885result.push('(');20886if (node.defaults) {20887hasDefault = true;20888}20889for (i = 0, iz = node.params.length; i < iz; ++i) {20890if (hasDefault && node.defaults[i]) {20891// Handle default values.20892result.push(this.generateAssignment(node.params[i], node.defaults[i], '=', Precedence.Assignment, E_TTT));20893} else {20894result.push(this.generatePattern(node.params[i], Precedence.Assignment, E_TTT));20895}20896if (i + 1 < iz) {20897result.push(',' + space);20898}20899}2090020901if (node.rest) {20902if (node.params.length) {20903result.push(',' + space);20904}20905result.push('...');20906result.push(generateIdentifier(node.rest));20907}2090820909result.push(')');20910}2091120912return result;20913};2091420915CodeGenerator.prototype.generateFunctionBody = function (node) {20916var result, expr;2091720918result = this.generateFunctionParams(node);2091920920if (node.type === "ArrowFunctionExpression") {20921result.push(space);20922result.push('=>');20923}2092420925if (node.expression) {20926result.push(space);20927expr = this.generateExpression(node.body, Precedence.Assignment, E_TTT);20928if (expr.toString().charAt(0) === '{') {20929expr = ['(', expr, ')'];20930}20931result.push(expr);20932} else {20933result.push(this.maybeBlock(node.body, S_TTFF));20934}2093520936return result;20937};2093820939CodeGenerator.prototype.generateIterationForStatement = function (operator, stmt, flags) {20940var result = ['for' + (stmt.await ? noEmptySpace() + 'await' : '') + space + '('], that = this;20941withIndent(function () {20942if (stmt.left.type === "VariableDeclaration") {20943withIndent(function () {20944result.push(stmt.left.kind + noEmptySpace());20945result.push(that.generateStatement(stmt.left.declarations[0], S_FFFF));20946});20947} else {20948result.push(that.generateExpression(stmt.left, Precedence.Call, E_TTT));20949}2095020951result = join(result, operator);20952result = [join(20953result,20954that.generateExpression(stmt.right, Precedence.Assignment, E_TTT)20955), ')'];20956});20957result.push(this.maybeBlock(stmt.body, flags));20958return result;20959};2096020961CodeGenerator.prototype.generatePropertyKey = function (expr, computed) {20962var result = [];2096320964if (computed) {20965result.push('[');20966}2096720968result.push(this.generateExpression(expr, Precedence.Assignment, E_TTT));2096920970if (computed) {20971result.push(']');20972}2097320974return result;20975};2097620977CodeGenerator.prototype.generateAssignment = function (left, right, operator, precedence, flags) {20978if (Precedence.Assignment < precedence) {20979flags |= F_ALLOW_IN;20980}2098120982return parenthesize(20983[20984this.generateExpression(left, Precedence.Call, flags),20985space + operator + space,20986this.generateExpression(right, Precedence.Assignment, flags)20987],20988Precedence.Assignment,20989precedence20990);20991};2099220993CodeGenerator.prototype.semicolon = function (flags) {20994if (!semicolons && flags & F_SEMICOLON_OPT) {20995return '';20996}20997return ';';20998};2099921000// Statements.2100121002CodeGenerator.Statement = {2100321004BlockStatement: function (stmt, flags) {21005var range, content, result = ['{', newline], that = this;2100621007withIndent(function () {21008// handle functions without any code21009if (stmt.body.length === 0 && preserveBlankLines) {21010range = stmt.range;21011if (range[1] - range[0] > 2) {21012content = sourceCode.substring(range[0] + 1, range[1] - 1);21013if (content[0] === '\n') {21014result = ['{'];21015}21016result.push(content);21017}21018}2101921020var i, iz, fragment, bodyFlags;21021bodyFlags = S_TFFF;21022if (flags & F_FUNC_BODY) {21023bodyFlags |= F_DIRECTIVE_CTX;21024}2102521026for (i = 0, iz = stmt.body.length; i < iz; ++i) {21027if (preserveBlankLines) {21028// handle spaces before the first line21029if (i === 0) {21030if (stmt.body[0].leadingComments) {21031range = stmt.body[0].leadingComments[0].extendedRange;21032content = sourceCode.substring(range[0], range[1]);21033if (content[0] === '\n') {21034result = ['{'];21035}21036}21037if (!stmt.body[0].leadingComments) {21038generateBlankLines(stmt.range[0], stmt.body[0].range[0], result);21039}21040}2104121042// handle spaces between lines21043if (i > 0) {21044if (!stmt.body[i - 1].trailingComments && !stmt.body[i].leadingComments) {21045generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result);21046}21047}21048}2104921050if (i === iz - 1) {21051bodyFlags |= F_SEMICOLON_OPT;21052}2105321054if (stmt.body[i].leadingComments && preserveBlankLines) {21055fragment = that.generateStatement(stmt.body[i], bodyFlags);21056} else {21057fragment = addIndent(that.generateStatement(stmt.body[i], bodyFlags));21058}2105921060result.push(fragment);21061if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {21062if (preserveBlankLines && i < iz - 1) {21063// don't add a new line if there are leading coments21064// in the next statement21065if (!stmt.body[i + 1].leadingComments) {21066result.push(newline);21067}21068} else {21069result.push(newline);21070}21071}2107221073if (preserveBlankLines) {21074// handle spaces after the last line21075if (i === iz - 1) {21076if (!stmt.body[i].trailingComments) {21077generateBlankLines(stmt.body[i].range[1], stmt.range[1], result);21078}21079}21080}21081}21082});2108321084result.push(addIndent('}'));21085return result;21086},2108721088BreakStatement: function (stmt, flags) {21089if (stmt.label) {21090return 'break ' + stmt.label.name + this.semicolon(flags);21091}21092return 'break' + this.semicolon(flags);21093},2109421095ContinueStatement: function (stmt, flags) {21096if (stmt.label) {21097return 'continue ' + stmt.label.name + this.semicolon(flags);21098}21099return 'continue' + this.semicolon(flags);21100},2110121102ClassBody: function (stmt, flags) {21103var result = [ '{', newline], that = this;2110421105withIndent(function (indent) {21106var i, iz;2110721108for (i = 0, iz = stmt.body.length; i < iz; ++i) {21109result.push(indent);21110result.push(that.generateExpression(stmt.body[i], Precedence.Sequence, E_TTT));21111if (i + 1 < iz) {21112result.push(newline);21113}21114}21115});2111621117if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {21118result.push(newline);21119}21120result.push(base);21121result.push('}');21122return result;21123},2112421125ClassDeclaration: function (stmt, flags) {21126var result, fragment;21127result = ['class'];21128if (stmt.id) {21129result = join(result, this.generateExpression(stmt.id, Precedence.Sequence, E_TTT));21130}21131if (stmt.superClass) {21132fragment = join('extends', this.generateExpression(stmt.superClass, Precedence.Unary, E_TTT));21133result = join(result, fragment);21134}21135result.push(space);21136result.push(this.generateStatement(stmt.body, S_TFFT));21137return result;21138},2113921140DirectiveStatement: function (stmt, flags) {21141if (extra.raw && stmt.raw) {21142return stmt.raw + this.semicolon(flags);21143}21144return escapeDirective(stmt.directive) + this.semicolon(flags);21145},2114621147DoWhileStatement: function (stmt, flags) {21148// Because `do 42 while (cond)` is Syntax Error. We need semicolon.21149var result = join('do', this.maybeBlock(stmt.body, S_TFFF));21150result = this.maybeBlockSuffix(stmt.body, result);21151return join(result, [21152'while' + space + '(',21153this.generateExpression(stmt.test, Precedence.Sequence, E_TTT),21154')' + this.semicolon(flags)21155]);21156},2115721158CatchClause: function (stmt, flags) {21159var result, that = this;21160withIndent(function () {21161var guard;2116221163if (stmt.param) {21164result = [21165'catch' + space + '(',21166that.generateExpression(stmt.param, Precedence.Sequence, E_TTT),21167')'21168];2116921170if (stmt.guard) {21171guard = that.generateExpression(stmt.guard, Precedence.Sequence, E_TTT);21172result.splice(2, 0, ' if ', guard);21173}21174} else {21175result = ['catch'];21176}21177});21178result.push(this.maybeBlock(stmt.body, S_TFFF));21179return result;21180},2118121182DebuggerStatement: function (stmt, flags) {21183return 'debugger' + this.semicolon(flags);21184},2118521186EmptyStatement: function (stmt, flags) {21187return ';';21188},2118921190ExportDefaultDeclaration: function (stmt, flags) {21191var result = [ 'export' ], bodyFlags;2119221193bodyFlags = (flags & F_SEMICOLON_OPT) ? S_TFFT : S_TFFF;2119421195// export default HoistableDeclaration[Default]21196// export default AssignmentExpression[In] ;21197result = join(result, 'default');21198if (isStatement(stmt.declaration)) {21199result = join(result, this.generateStatement(stmt.declaration, bodyFlags));21200} else {21201result = join(result, this.generateExpression(stmt.declaration, Precedence.Assignment, E_TTT) + this.semicolon(flags));21202}21203return result;21204},2120521206ExportNamedDeclaration: function (stmt, flags) {21207var result = [ 'export' ], bodyFlags, that = this;2120821209bodyFlags = (flags & F_SEMICOLON_OPT) ? S_TFFT : S_TFFF;2121021211// export VariableStatement21212// export Declaration[Default]21213if (stmt.declaration) {21214return join(result, this.generateStatement(stmt.declaration, bodyFlags));21215}2121621217// export ExportClause[NoReference] FromClause ;21218// export ExportClause ;21219if (stmt.specifiers) {21220if (stmt.specifiers.length === 0) {21221result = join(result, '{' + space + '}');21222} else if (stmt.specifiers[0].type === "ExportBatchSpecifier") {21223result = join(result, this.generateExpression(stmt.specifiers[0], Precedence.Sequence, E_TTT));21224} else {21225result = join(result, '{');21226withIndent(function (indent) {21227var i, iz;21228result.push(newline);21229for (i = 0, iz = stmt.specifiers.length; i < iz; ++i) {21230result.push(indent);21231result.push(that.generateExpression(stmt.specifiers[i], Precedence.Sequence, E_TTT));21232if (i + 1 < iz) {21233result.push(',' + newline);21234}21235}21236});21237if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {21238result.push(newline);21239}21240result.push(base + '}');21241}2124221243if (stmt.source) {21244result = join(result, [21245'from' + space,21246// ModuleSpecifier21247this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),21248this.semicolon(flags)21249]);21250} else {21251result.push(this.semicolon(flags));21252}21253}21254return result;21255},2125621257ExportAllDeclaration: function (stmt, flags) {21258// export * FromClause ;21259return [21260'export' + space,21261'*' + space,21262'from' + space,21263// ModuleSpecifier21264this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),21265this.semicolon(flags)21266];21267},2126821269ExpressionStatement: function (stmt, flags) {21270var result, fragment;2127121272function isClassPrefixed(fragment) {21273var code;21274if (fragment.slice(0, 5) !== 'class') {21275return false;21276}21277code = fragment.charCodeAt(5);21278return code === 0x7B /* '{' */ || esutils.code.isWhiteSpace(code) || esutils.code.isLineTerminator(code);21279}2128021281function isFunctionPrefixed(fragment) {21282var code;21283if (fragment.slice(0, 8) !== 'function') {21284return false;21285}21286code = fragment.charCodeAt(8);21287return code === 0x28 /* '(' */ || esutils.code.isWhiteSpace(code) || code === 0x2A /* '*' */ || esutils.code.isLineTerminator(code);21288}2128921290function isAsyncPrefixed(fragment) {21291var code, i, iz;21292if (fragment.slice(0, 5) !== 'async') {21293return false;21294}21295if (!esutils.code.isWhiteSpace(fragment.charCodeAt(5))) {21296return false;21297}21298for (i = 6, iz = fragment.length; i < iz; ++i) {21299if (!esutils.code.isWhiteSpace(fragment.charCodeAt(i))) {21300break;21301}21302}21303if (i === iz) {21304return false;21305}21306if (fragment.slice(i, i + 8) !== 'function') {21307return false;21308}21309code = fragment.charCodeAt(i + 8);21310return code === 0x28 /* '(' */ || esutils.code.isWhiteSpace(code) || code === 0x2A /* '*' */ || esutils.code.isLineTerminator(code);21311}2131221313result = [this.generateExpression(stmt.expression, Precedence.Sequence, E_TTT)];21314// 12.4 '{', 'function', 'class' is not allowed in this position.21315// wrap expression with parentheses21316fragment = toSourceNodeWhenNeeded(result).toString();21317if (fragment.charCodeAt(0) === 0x7B /* '{' */ || // ObjectExpression21318isClassPrefixed(fragment) ||21319isFunctionPrefixed(fragment) ||21320isAsyncPrefixed(fragment) ||21321(directive && (flags & F_DIRECTIVE_CTX) && stmt.expression.type === "Literal" && typeof stmt.expression.value === 'string')) {21322result = ['(', result, ')' + this.semicolon(flags)];21323} else {21324result.push(this.semicolon(flags));21325}21326return result;21327},2132821329ImportDeclaration: function (stmt, flags) {21330// ES6: 15.2.1 valid import declarations:21331// - import ImportClause FromClause ;21332// - import ModuleSpecifier ;21333var result, cursor, that = this;2133421335// If no ImportClause is present,21336// this should be `import ModuleSpecifier` so skip `from`21337// ModuleSpecifier is StringLiteral.21338if (stmt.specifiers.length === 0) {21339// import ModuleSpecifier ;21340return [21341'import',21342space,21343// ModuleSpecifier21344this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),21345this.semicolon(flags)21346];21347}2134821349// import ImportClause FromClause ;21350result = [21351'import'21352];21353cursor = 0;2135421355// ImportedBinding21356if (stmt.specifiers[cursor].type === "ImportDefaultSpecifier") {21357result = join(result, [21358this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT)21359]);21360++cursor;21361}2136221363if (stmt.specifiers[cursor]) {21364if (cursor !== 0) {21365result.push(',');21366}2136721368if (stmt.specifiers[cursor].type === "ImportNamespaceSpecifier") {21369// NameSpaceImport21370result = join(result, [21371space,21372this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT)21373]);21374} else {21375// NamedImports21376result.push(space + '{');2137721378if ((stmt.specifiers.length - cursor) === 1) {21379// import { ... } from "...";21380result.push(space);21381result.push(this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT));21382result.push(space + '}' + space);21383} else {21384// import {21385// ...,21386// ...,21387// } from "...";21388withIndent(function (indent) {21389var i, iz;21390result.push(newline);21391for (i = cursor, iz = stmt.specifiers.length; i < iz; ++i) {21392result.push(indent);21393result.push(that.generateExpression(stmt.specifiers[i], Precedence.Sequence, E_TTT));21394if (i + 1 < iz) {21395result.push(',' + newline);21396}21397}21398});21399if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {21400result.push(newline);21401}21402result.push(base + '}' + space);21403}21404}21405}2140621407result = join(result, [21408'from' + space,21409// ModuleSpecifier21410this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),21411this.semicolon(flags)21412]);21413return result;21414},2141521416VariableDeclarator: function (stmt, flags) {21417var itemFlags = (flags & F_ALLOW_IN) ? E_TTT : E_FTT;21418if (stmt.init) {21419return [21420this.generateExpression(stmt.id, Precedence.Assignment, itemFlags),21421space,21422'=',21423space,21424this.generateExpression(stmt.init, Precedence.Assignment, itemFlags)21425];21426}21427return this.generatePattern(stmt.id, Precedence.Assignment, itemFlags);21428},2142921430VariableDeclaration: function (stmt, flags) {21431// VariableDeclarator is typed as Statement,21432// but joined with comma (not LineTerminator).21433// So if comment is attached to target node, we should specialize.21434var result, i, iz, node, bodyFlags, that = this;2143521436result = [ stmt.kind ];2143721438bodyFlags = (flags & F_ALLOW_IN) ? S_TFFF : S_FFFF;2143921440function block() {21441node = stmt.declarations[0];21442if (extra.comment && node.leadingComments) {21443result.push('\n');21444result.push(addIndent(that.generateStatement(node, bodyFlags)));21445} else {21446result.push(noEmptySpace());21447result.push(that.generateStatement(node, bodyFlags));21448}2144921450for (i = 1, iz = stmt.declarations.length; i < iz; ++i) {21451node = stmt.declarations[i];21452if (extra.comment && node.leadingComments) {21453result.push(',' + newline);21454result.push(addIndent(that.generateStatement(node, bodyFlags)));21455} else {21456result.push(',' + space);21457result.push(that.generateStatement(node, bodyFlags));21458}21459}21460}2146121462if (stmt.declarations.length > 1) {21463withIndent(block);21464} else {21465block();21466}2146721468result.push(this.semicolon(flags));2146921470return result;21471},2147221473ThrowStatement: function (stmt, flags) {21474return [join(21475'throw',21476this.generateExpression(stmt.argument, Precedence.Sequence, E_TTT)21477), this.semicolon(flags)];21478},2147921480TryStatement: function (stmt, flags) {21481var result, i, iz, guardedHandlers;2148221483result = ['try', this.maybeBlock(stmt.block, S_TFFF)];21484result = this.maybeBlockSuffix(stmt.block, result);2148521486if (stmt.handlers) {21487// old interface21488for (i = 0, iz = stmt.handlers.length; i < iz; ++i) {21489result = join(result, this.generateStatement(stmt.handlers[i], S_TFFF));21490if (stmt.finalizer || i + 1 !== iz) {21491result = this.maybeBlockSuffix(stmt.handlers[i].body, result);21492}21493}21494} else {21495guardedHandlers = stmt.guardedHandlers || [];2149621497for (i = 0, iz = guardedHandlers.length; i < iz; ++i) {21498result = join(result, this.generateStatement(guardedHandlers[i], S_TFFF));21499if (stmt.finalizer || i + 1 !== iz) {21500result = this.maybeBlockSuffix(guardedHandlers[i].body, result);21501}21502}2150321504// new interface21505if (stmt.handler) {21506if (Array.isArray(stmt.handler)) {21507for (i = 0, iz = stmt.handler.length; i < iz; ++i) {21508result = join(result, this.generateStatement(stmt.handler[i], S_TFFF));21509if (stmt.finalizer || i + 1 !== iz) {21510result = this.maybeBlockSuffix(stmt.handler[i].body, result);21511}21512}21513} else {21514result = join(result, this.generateStatement(stmt.handler, S_TFFF));21515if (stmt.finalizer) {21516result = this.maybeBlockSuffix(stmt.handler.body, result);21517}21518}21519}21520}21521if (stmt.finalizer) {21522result = join(result, ['finally', this.maybeBlock(stmt.finalizer, S_TFFF)]);21523}21524return result;21525},2152621527SwitchStatement: function (stmt, flags) {21528var result, fragment, i, iz, bodyFlags, that = this;21529withIndent(function () {21530result = [21531'switch' + space + '(',21532that.generateExpression(stmt.discriminant, Precedence.Sequence, E_TTT),21533')' + space + '{' + newline21534];21535});21536if (stmt.cases) {21537bodyFlags = S_TFFF;21538for (i = 0, iz = stmt.cases.length; i < iz; ++i) {21539if (i === iz - 1) {21540bodyFlags |= F_SEMICOLON_OPT;21541}21542fragment = addIndent(this.generateStatement(stmt.cases[i], bodyFlags));21543result.push(fragment);21544if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {21545result.push(newline);21546}21547}21548}21549result.push(addIndent('}'));21550return result;21551},2155221553SwitchCase: function (stmt, flags) {21554var result, fragment, i, iz, bodyFlags, that = this;21555withIndent(function () {21556if (stmt.test) {21557result = [21558join('case', that.generateExpression(stmt.test, Precedence.Sequence, E_TTT)),21559':'21560];21561} else {21562result = ['default:'];21563}2156421565i = 0;21566iz = stmt.consequent.length;21567if (iz && stmt.consequent[0].type === "BlockStatement") {21568fragment = that.maybeBlock(stmt.consequent[0], S_TFFF);21569result.push(fragment);21570i = 1;21571}2157221573if (i !== iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {21574result.push(newline);21575}2157621577bodyFlags = S_TFFF;21578for (; i < iz; ++i) {21579if (i === iz - 1 && flags & F_SEMICOLON_OPT) {21580bodyFlags |= F_SEMICOLON_OPT;21581}21582fragment = addIndent(that.generateStatement(stmt.consequent[i], bodyFlags));21583result.push(fragment);21584if (i + 1 !== iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {21585result.push(newline);21586}21587}21588});21589return result;21590},2159121592IfStatement: function (stmt, flags) {21593var result, bodyFlags, semicolonOptional, that = this;21594withIndent(function () {21595result = [21596'if' + space + '(',21597that.generateExpression(stmt.test, Precedence.Sequence, E_TTT),21598')'21599];21600});21601semicolonOptional = flags & F_SEMICOLON_OPT;21602bodyFlags = S_TFFF;21603if (semicolonOptional) {21604bodyFlags |= F_SEMICOLON_OPT;21605}21606if (stmt.alternate) {21607result.push(this.maybeBlock(stmt.consequent, S_TFFF));21608result = this.maybeBlockSuffix(stmt.consequent, result);21609if (stmt.alternate.type === "IfStatement") {21610result = join(result, ['else ', this.generateStatement(stmt.alternate, bodyFlags)]);21611} else {21612result = join(result, join('else', this.maybeBlock(stmt.alternate, bodyFlags)));21613}21614} else {21615result.push(this.maybeBlock(stmt.consequent, bodyFlags));21616}21617return result;21618},2161921620ForStatement: function (stmt, flags) {21621var result, that = this;21622withIndent(function () {21623result = ['for' + space + '('];21624if (stmt.init) {21625if (stmt.init.type === "VariableDeclaration") {21626result.push(that.generateStatement(stmt.init, S_FFFF));21627} else {21628// F_ALLOW_IN becomes false.21629result.push(that.generateExpression(stmt.init, Precedence.Sequence, E_FTT));21630result.push(';');21631}21632} else {21633result.push(';');21634}2163521636if (stmt.test) {21637result.push(space);21638result.push(that.generateExpression(stmt.test, Precedence.Sequence, E_TTT));21639result.push(';');21640} else {21641result.push(';');21642}2164321644if (stmt.update) {21645result.push(space);21646result.push(that.generateExpression(stmt.update, Precedence.Sequence, E_TTT));21647result.push(')');21648} else {21649result.push(')');21650}21651});2165221653result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));21654return result;21655},2165621657ForInStatement: function (stmt, flags) {21658return this.generateIterationForStatement('in', stmt, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF);21659},2166021661ForOfStatement: function (stmt, flags) {21662return this.generateIterationForStatement('of', stmt, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF);21663},2166421665LabeledStatement: function (stmt, flags) {21666return [stmt.label.name + ':', this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF)];21667},2166821669Program: function (stmt, flags) {21670var result, fragment, i, iz, bodyFlags;21671iz = stmt.body.length;21672result = [safeConcatenation && iz > 0 ? '\n' : ''];21673bodyFlags = S_TFTF;21674for (i = 0; i < iz; ++i) {21675if (!safeConcatenation && i === iz - 1) {21676bodyFlags |= F_SEMICOLON_OPT;21677}2167821679if (preserveBlankLines) {21680// handle spaces before the first line21681if (i === 0) {21682if (!stmt.body[0].leadingComments) {21683generateBlankLines(stmt.range[0], stmt.body[i].range[0], result);21684}21685}2168621687// handle spaces between lines21688if (i > 0) {21689if (!stmt.body[i - 1].trailingComments && !stmt.body[i].leadingComments) {21690generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result);21691}21692}21693}2169421695fragment = addIndent(this.generateStatement(stmt.body[i], bodyFlags));21696result.push(fragment);21697if (i + 1 < iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {21698if (preserveBlankLines) {21699if (!stmt.body[i + 1].leadingComments) {21700result.push(newline);21701}21702} else {21703result.push(newline);21704}21705}2170621707if (preserveBlankLines) {21708// handle spaces after the last line21709if (i === iz - 1) {21710if (!stmt.body[i].trailingComments) {21711generateBlankLines(stmt.body[i].range[1], stmt.range[1], result);21712}21713}21714}21715}21716return result;21717},2171821719FunctionDeclaration: function (stmt, flags) {21720return [21721generateAsyncPrefix(stmt, true),21722'function',21723generateStarSuffix(stmt) || noEmptySpace(),21724stmt.id ? generateIdentifier(stmt.id) : '',21725this.generateFunctionBody(stmt)21726];21727},2172821729ReturnStatement: function (stmt, flags) {21730if (stmt.argument) {21731return [join(21732'return',21733this.generateExpression(stmt.argument, Precedence.Sequence, E_TTT)21734), this.semicolon(flags)];21735}21736return ['return' + this.semicolon(flags)];21737},2173821739WhileStatement: function (stmt, flags) {21740var result, that = this;21741withIndent(function () {21742result = [21743'while' + space + '(',21744that.generateExpression(stmt.test, Precedence.Sequence, E_TTT),21745')'21746];21747});21748result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));21749return result;21750},2175121752WithStatement: function (stmt, flags) {21753var result, that = this;21754withIndent(function () {21755result = [21756'with' + space + '(',21757that.generateExpression(stmt.object, Precedence.Sequence, E_TTT),21758')'21759];21760});21761result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));21762return result;21763}2176421765};2176621767merge(CodeGenerator.prototype, CodeGenerator.Statement);2176821769// Expressions.2177021771CodeGenerator.Expression = {2177221773/* OJS expressions begin */2177421775MutableExpression: function(expr, precedence, flags) {21776return `mutable ${expr.id.name}`;21777},2177821779ViewExpression: function(expr, precedence, flags) {21780return `viewof ${expr.id.name}`;21781},2178221783/* OJS expressions end */2178421785SequenceExpression: function (expr, precedence, flags) {21786var result, i, iz;21787if (Precedence.Sequence < precedence) {21788flags |= F_ALLOW_IN;21789}21790result = [];21791for (i = 0, iz = expr.expressions.length; i < iz; ++i) {21792result.push(this.generateExpression(expr.expressions[i], Precedence.Assignment, flags));21793if (i + 1 < iz) {21794result.push(',' + space);21795}21796}21797return parenthesize(result, Precedence.Sequence, precedence);21798},2179921800AssignmentExpression: function (expr, precedence, flags) {21801return this.generateAssignment(expr.left, expr.right, expr.operator, precedence, flags);21802},2180321804ArrowFunctionExpression: function (expr, precedence, flags) {21805return parenthesize(this.generateFunctionBody(expr), Precedence.ArrowFunction, precedence);21806},2180721808ConditionalExpression: function (expr, precedence, flags) {21809if (Precedence.Conditional < precedence) {21810flags |= F_ALLOW_IN;21811}21812return parenthesize(21813[21814this.generateExpression(expr.test, Precedence.Coalesce, flags),21815space + '?' + space,21816this.generateExpression(expr.consequent, Precedence.Assignment, flags),21817space + ':' + space,21818this.generateExpression(expr.alternate, Precedence.Assignment, flags)21819],21820Precedence.Conditional,21821precedence21822);21823},2182421825LogicalExpression: function (expr, precedence, flags) {21826if (expr.operator === '??') {21827flags |= F_FOUND_COALESCE;21828}21829return this.BinaryExpression(expr, precedence, flags);21830},2183121832BinaryExpression: function (expr, precedence, flags) {21833var result, leftPrecedence, rightPrecedence, currentPrecedence, fragment, leftSource;21834currentPrecedence = BinaryPrecedence[expr.operator];21835leftPrecedence = expr.operator === '**' ? Precedence.Postfix : currentPrecedence;21836rightPrecedence = expr.operator === '**' ? currentPrecedence : currentPrecedence + 1;2183721838if (currentPrecedence < precedence) {21839flags |= F_ALLOW_IN;21840}2184121842fragment = this.generateExpression(expr.left, leftPrecedence, flags);2184321844leftSource = fragment.toString();2184521846if (leftSource.charCodeAt(leftSource.length - 1) === 0x2F /* / */ && esutils.code.isIdentifierPartES5(expr.operator.charCodeAt(0))) {21847result = [fragment, noEmptySpace(), expr.operator];21848} else {21849result = join(fragment, expr.operator);21850}2185121852fragment = this.generateExpression(expr.right, rightPrecedence, flags);2185321854if (expr.operator === '/' && fragment.toString().charAt(0) === '/' ||21855expr.operator.slice(-1) === '<' && fragment.toString().slice(0, 3) === '!--') {21856// If '/' concats with '/' or `<` concats with `!--`, it is interpreted as comment start21857result.push(noEmptySpace());21858result.push(fragment);21859} else {21860result = join(result, fragment);21861}2186221863if (expr.operator === 'in' && !(flags & F_ALLOW_IN)) {21864return ['(', result, ')'];21865}21866if ((expr.operator === '||' || expr.operator === '&&') && (flags & F_FOUND_COALESCE)) {21867return ['(', result, ')'];21868}21869return parenthesize(result, currentPrecedence, precedence);21870},2187121872CallExpression: function (expr, precedence, flags) {21873var result, i, iz;2187421875// F_ALLOW_UNPARATH_NEW becomes false.21876result = [this.generateExpression(expr.callee, Precedence.Call, E_TTF)];2187721878if (expr.optional) {21879result.push('?.');21880}2188121882result.push('(');21883for (i = 0, iz = expr['arguments'].length; i < iz; ++i) {21884result.push(this.generateExpression(expr['arguments'][i], Precedence.Assignment, E_TTT));21885if (i + 1 < iz) {21886result.push(',' + space);21887}21888}21889result.push(')');2189021891if (!(flags & F_ALLOW_CALL)) {21892return ['(', result, ')'];21893}2189421895return parenthesize(result, Precedence.Call, precedence);21896},2189721898ChainExpression: function (expr, precedence, flags) {21899if (Precedence.OptionalChaining < precedence) {21900flags |= F_ALLOW_CALL;21901}2190221903var result = this.generateExpression(expr.expression, Precedence.OptionalChaining, flags);2190421905return parenthesize(result, Precedence.OptionalChaining, precedence);21906},2190721908NewExpression: function (expr, precedence, flags) {21909var result, length, i, iz, itemFlags;21910length = expr['arguments'].length;2191121912// F_ALLOW_CALL becomes false.21913// F_ALLOW_UNPARATH_NEW may become false.21914itemFlags = (flags & F_ALLOW_UNPARATH_NEW && !parentheses && length === 0) ? E_TFT : E_TFF;2191521916result = join(21917'new',21918this.generateExpression(expr.callee, Precedence.New, itemFlags)21919);2192021921if (!(flags & F_ALLOW_UNPARATH_NEW) || parentheses || length > 0) {21922result.push('(');21923for (i = 0, iz = length; i < iz; ++i) {21924result.push(this.generateExpression(expr['arguments'][i], Precedence.Assignment, E_TTT));21925if (i + 1 < iz) {21926result.push(',' + space);21927}21928}21929result.push(')');21930}2193121932return parenthesize(result, Precedence.New, precedence);21933},2193421935MemberExpression: function (expr, precedence, flags) {21936var result, fragment;2193721938// F_ALLOW_UNPARATH_NEW becomes false.21939result = [this.generateExpression(expr.object, Precedence.Call, (flags & F_ALLOW_CALL) ? E_TTF : E_TFF)];2194021941if (expr.computed) {21942if (expr.optional) {21943result.push('?.');21944}2194521946result.push('[');21947result.push(this.generateExpression(expr.property, Precedence.Sequence, flags & F_ALLOW_CALL ? E_TTT : E_TFT));21948result.push(']');21949} else {21950if (!expr.optional && expr.object.type === "Literal" && typeof expr.object.value === 'number') {21951fragment = toSourceNodeWhenNeeded(result).toString();21952// When the following conditions are all true,21953// 1. No floating point21954// 2. Don't have exponents21955// 3. The last character is a decimal digit21956// 4. Not hexadecimal OR octal number literal21957// we should add a floating point.21958if (21959fragment.indexOf('.') < 0 &&21960!/[eExX]/.test(fragment) &&21961esutils.code.isDecimalDigit(fragment.charCodeAt(fragment.length - 1)) &&21962!(fragment.length >= 2 && fragment.charCodeAt(0) === 48) // '0'21963) {21964result.push(' ');21965}21966}21967result.push(expr.optional ? '?.' : '.');21968result.push(generateIdentifier(expr.property));21969}2197021971return parenthesize(result, Precedence.Member, precedence);21972},2197321974MetaProperty: function (expr, precedence, flags) {21975var result;21976result = [];21977result.push(typeof expr.meta === "string" ? expr.meta : generateIdentifier(expr.meta));21978result.push('.');21979result.push(typeof expr.property === "string" ? expr.property : generateIdentifier(expr.property));21980return parenthesize(result, Precedence.Member, precedence);21981},2198221983UnaryExpression: function (expr, precedence, flags) {21984var result, fragment, rightCharCode, leftSource, leftCharCode;21985fragment = this.generateExpression(expr.argument, Precedence.Unary, E_TTT);2198621987if (space === '') {21988result = join(expr.operator, fragment);21989} else {21990result = [expr.operator];21991if (expr.operator.length > 2) {21992// delete, void, typeof21993// get `typeof []`, not `typeof[]`21994result = join(result, fragment);21995} else {21996// Prevent inserting spaces between operator and argument if it is unnecessary21997// like, `!cond`21998leftSource = toSourceNodeWhenNeeded(result).toString();21999leftCharCode = leftSource.charCodeAt(leftSource.length - 1);22000rightCharCode = fragment.toString().charCodeAt(0);2200122002if (((leftCharCode === 0x2B /* + */ || leftCharCode === 0x2D /* - */) && leftCharCode === rightCharCode) ||22003(esutils.code.isIdentifierPartES5(leftCharCode) && esutils.code.isIdentifierPartES5(rightCharCode))) {22004result.push(noEmptySpace());22005result.push(fragment);22006} else {22007result.push(fragment);22008}22009}22010}22011return parenthesize(result, Precedence.Unary, precedence);22012},2201322014YieldExpression: function (expr, precedence, flags) {22015var result;22016if (expr.delegate) {22017result = 'yield*';22018} else {22019result = 'yield';22020}22021if (expr.argument) {22022result = join(22023result,22024this.generateExpression(expr.argument, Precedence.Yield, E_TTT)22025);22026}22027return parenthesize(result, Precedence.Yield, precedence);22028},2202922030AwaitExpression: function (expr, precedence, flags) {22031var result = join(22032expr.all ? 'await*' : 'await',22033this.generateExpression(expr.argument, Precedence.Await, E_TTT)22034);22035return parenthesize(result, Precedence.Await, precedence);22036},2203722038UpdateExpression: function (expr, precedence, flags) {22039if (expr.prefix) {22040return parenthesize(22041[22042expr.operator,22043this.generateExpression(expr.argument, Precedence.Unary, E_TTT)22044],22045Precedence.Unary,22046precedence22047);22048}22049return parenthesize(22050[22051this.generateExpression(expr.argument, Precedence.Postfix, E_TTT),22052expr.operator22053],22054Precedence.Postfix,22055precedence22056);22057},2205822059FunctionExpression: function (expr, precedence, flags) {22060var result = [22061generateAsyncPrefix(expr, true),22062'function'22063];22064if (expr.id) {22065result.push(generateStarSuffix(expr) || noEmptySpace());22066result.push(generateIdentifier(expr.id));22067} else {22068result.push(generateStarSuffix(expr) || space);22069}22070result.push(this.generateFunctionBody(expr));22071return result;22072},2207322074ArrayPattern: function (expr, precedence, flags) {22075return this.ArrayExpression(expr, precedence, flags, true);22076},2207722078ArrayExpression: function (expr, precedence, flags, isPattern) {22079var result, multiline, that = this;22080if (!expr.elements.length) {22081return '[]';22082}22083multiline = isPattern ? false : expr.elements.length > 1;22084result = ['[', multiline ? newline : ''];22085withIndent(function (indent) {22086var i, iz;22087for (i = 0, iz = expr.elements.length; i < iz; ++i) {22088if (!expr.elements[i]) {22089if (multiline) {22090result.push(indent);22091}22092if (i + 1 === iz) {22093result.push(',');22094}22095} else {22096result.push(multiline ? indent : '');22097result.push(that.generateExpression(expr.elements[i], Precedence.Assignment, E_TTT));22098}22099if (i + 1 < iz) {22100result.push(',' + (multiline ? newline : space));22101}22102}22103});22104if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {22105result.push(newline);22106}22107result.push(multiline ? base : '');22108result.push(']');22109return result;22110},2211122112RestElement: function(expr, precedence, flags) {22113return '...' + this.generatePattern(expr.argument);22114},2211522116ClassExpression: function (expr, precedence, flags) {22117var result, fragment;22118result = ['class'];22119if (expr.id) {22120result = join(result, this.generateExpression(expr.id, Precedence.Sequence, E_TTT));22121}22122if (expr.superClass) {22123fragment = join('extends', this.generateExpression(expr.superClass, Precedence.Unary, E_TTT));22124result = join(result, fragment);22125}22126result.push(space);22127result.push(this.generateStatement(expr.body, S_TFFT));22128return result;22129},2213022131MethodDefinition: function (expr, precedence, flags) {22132var result, fragment;22133if (expr['static']) {22134result = ['static' + space];22135} else {22136result = [];22137}22138if (expr.kind === 'get' || expr.kind === 'set') {22139fragment = [22140join(expr.kind, this.generatePropertyKey(expr.key, expr.computed)),22141this.generateFunctionBody(expr.value)22142];22143} else {22144fragment = [22145generateMethodPrefix(expr),22146this.generatePropertyKey(expr.key, expr.computed),22147this.generateFunctionBody(expr.value)22148];22149}22150return join(result, fragment);22151},2215222153Property: function (expr, precedence, flags) {22154if (expr.kind === 'get' || expr.kind === 'set') {22155return [22156expr.kind, noEmptySpace(),22157this.generatePropertyKey(expr.key, expr.computed),22158this.generateFunctionBody(expr.value)22159];22160}2216122162if (expr.shorthand) {22163if (expr.value.type === "AssignmentPattern") {22164return this.AssignmentPattern(expr.value, Precedence.Sequence, E_TTT);22165}22166return this.generatePropertyKey(expr.key, expr.computed);22167}2216822169if (expr.method) {22170return [22171generateMethodPrefix(expr),22172this.generatePropertyKey(expr.key, expr.computed),22173this.generateFunctionBody(expr.value)22174];22175}2217622177return [22178this.generatePropertyKey(expr.key, expr.computed),22179':' + space,22180this.generateExpression(expr.value, Precedence.Assignment, E_TTT)22181];22182},2218322184ObjectExpression: function (expr, precedence, flags) {22185var multiline, result, fragment, that = this;2218622187if (!expr.properties.length) {22188return '{}';22189}22190multiline = expr.properties.length > 1;2219122192withIndent(function () {22193fragment = that.generateExpression(expr.properties[0], Precedence.Sequence, E_TTT);22194});2219522196if (!multiline) {22197// issues 422198// Do not transform from22199// dejavu.Class.declare({22200// method2: function () {}22201// });22202// to22203// dejavu.Class.declare({method2: function () {22204// }});22205if (!hasLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {22206return [ '{', space, fragment, space, '}' ];22207}22208}2220922210withIndent(function (indent) {22211var i, iz;22212result = [ '{', newline, indent, fragment ];2221322214if (multiline) {22215result.push(',' + newline);22216for (i = 1, iz = expr.properties.length; i < iz; ++i) {22217result.push(indent);22218result.push(that.generateExpression(expr.properties[i], Precedence.Sequence, E_TTT));22219if (i + 1 < iz) {22220result.push(',' + newline);22221}22222}22223}22224});2222522226if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {22227result.push(newline);22228}22229result.push(base);22230result.push('}');22231return result;22232},2223322234AssignmentPattern: function(expr, precedence, flags) {22235return this.generateAssignment(expr.left, expr.right, '=', precedence, flags);22236},2223722238ObjectPattern: function (expr, precedence, flags) {22239var result, i, iz, multiline, property, that = this;22240if (!expr.properties.length) {22241return '{}';22242}2224322244multiline = false;22245if (expr.properties.length === 1) {22246property = expr.properties[0];22247if (22248property.type === "Property"22249&& property.value.type !== "Identifier"22250) {22251multiline = true;22252}22253} else {22254for (i = 0, iz = expr.properties.length; i < iz; ++i) {22255property = expr.properties[i];22256if (22257property.type === "Property"22258&& !property.shorthand22259) {22260multiline = true;22261break;22262}22263}22264}22265result = ['{', multiline ? newline : '' ];2226622267withIndent(function (indent) {22268var i, iz;22269for (i = 0, iz = expr.properties.length; i < iz; ++i) {22270result.push(multiline ? indent : '');22271result.push(that.generateExpression(expr.properties[i], Precedence.Sequence, E_TTT));22272if (i + 1 < iz) {22273result.push(',' + (multiline ? newline : space));22274}22275}22276});2227722278if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {22279result.push(newline);22280}22281result.push(multiline ? base : '');22282result.push('}');22283return result;22284},2228522286ThisExpression: function (expr, precedence, flags) {22287return 'this';22288},2228922290Super: function (expr, precedence, flags) {22291return 'super';22292},2229322294Identifier: function (expr, precedence, flags) {22295return generateIdentifier(expr);22296},2229722298ImportDefaultSpecifier: function (expr, precedence, flags) {22299return generateIdentifier(expr.id || expr.local);22300},2230122302ImportNamespaceSpecifier: function (expr, precedence, flags) {22303var result = ['*'];22304var id = expr.id || expr.local;22305if (id) {22306result.push(space + 'as' + noEmptySpace() + generateIdentifier(id));22307}22308return result;22309},2231022311ImportSpecifier: function (expr, precedence, flags) {22312var imported = expr.imported;22313var result = [ imported.name ];22314var local = expr.local;22315if (local && local.name !== imported.name) {22316result.push(noEmptySpace() + 'as' + noEmptySpace() + generateIdentifier(local));22317}22318return result;22319},2232022321ExportSpecifier: function (expr, precedence, flags) {22322var local = expr.local;22323var result = [ local.name ];22324var exported = expr.exported;22325if (exported && exported.name !== local.name) {22326result.push(noEmptySpace() + 'as' + noEmptySpace() + generateIdentifier(exported));22327}22328return result;22329},2233022331Literal: function (expr, precedence, flags) {22332var raw;22333if (expr.hasOwnProperty('raw') && parse && extra.raw) {22334try {22335raw = parse(expr.raw).body[0].expression;22336if (raw.type === "Literal") {22337if (raw.value === expr.value) {22338return expr.raw;22339}22340}22341} catch (e) {22342// not use raw property22343}22344}2234522346if (expr.regex) {22347return '/' + expr.regex.pattern + '/' + expr.regex.flags;22348}2234922350if (typeof expr.value === 'bigint') {22351return expr.value.toString() + 'n';22352}2235322354// `expr.value` can be null if `expr.bigint` exists. We need to check22355// `expr.bigint` first.22356if (expr.bigint) {22357return expr.bigint + 'n';22358}2235922360if (expr.value === null) {22361return 'null';22362}2236322364if (typeof expr.value === 'string') {22365return escapeString(expr.value);22366}2236722368if (typeof expr.value === 'number') {22369return generateNumber(expr.value);22370}2237122372if (typeof expr.value === 'boolean') {22373return expr.value ? 'true' : 'false';22374}2237522376return generateRegExp(expr.value);22377},2237822379GeneratorExpression: function (expr, precedence, flags) {22380return this.ComprehensionExpression(expr, precedence, flags);22381},2238222383ComprehensionExpression: function (expr, precedence, flags) {22384// GeneratorExpression should be parenthesized with (...), ComprehensionExpression with [...]22385// Due to https://bugzilla.mozilla.org/show_bug.cgi?id=883468 position of expr.body can differ in Spidermonkey and ES62238622387var result, i, iz, fragment, that = this;22388result = (expr.type === "GeneratorExpression") ? ['('] : ['['];2238922390if (extra.moz.comprehensionExpressionStartsWithAssignment) {22391fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT);22392result.push(fragment);22393}2239422395if (expr.blocks) {22396withIndent(function () {22397for (i = 0, iz = expr.blocks.length; i < iz; ++i) {22398fragment = that.generateExpression(expr.blocks[i], Precedence.Sequence, E_TTT);22399if (i > 0 || extra.moz.comprehensionExpressionStartsWithAssignment) {22400result = join(result, fragment);22401} else {22402result.push(fragment);22403}22404}22405});22406}2240722408if (expr.filter) {22409result = join(result, 'if' + space);22410fragment = this.generateExpression(expr.filter, Precedence.Sequence, E_TTT);22411result = join(result, [ '(', fragment, ')' ]);22412}2241322414if (!extra.moz.comprehensionExpressionStartsWithAssignment) {22415fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT);2241622417result = join(result, fragment);22418}2241922420result.push((expr.type === "GeneratorExpression") ? ')' : ']');22421return result;22422},2242322424ComprehensionBlock: function (expr, precedence, flags) {22425var fragment;22426if (expr.left.type === "VariableDeclaration") {22427fragment = [22428expr.left.kind, noEmptySpace(),22429this.generateStatement(expr.left.declarations[0], S_FFFF)22430];22431} else {22432fragment = this.generateExpression(expr.left, Precedence.Call, E_TTT);22433}2243422435fragment = join(fragment, expr.of ? 'of' : 'in');22436fragment = join(fragment, this.generateExpression(expr.right, Precedence.Sequence, E_TTT));2243722438return [ 'for' + space + '(', fragment, ')' ];22439},2244022441SpreadElement: function (expr, precedence, flags) {22442return [22443'...',22444this.generateExpression(expr.argument, Precedence.Assignment, E_TTT)22445];22446},2244722448TaggedTemplateExpression: function (expr, precedence, flags) {22449var itemFlags = E_TTF;22450if (!(flags & F_ALLOW_CALL)) {22451itemFlags = E_TFF;22452}22453var result = [22454this.generateExpression(expr.tag, Precedence.Call, itemFlags),22455this.generateExpression(expr.quasi, Precedence.Primary, E_FFT)22456];22457return parenthesize(result, Precedence.TaggedTemplate, precedence);22458},2245922460TemplateElement: function (expr, precedence, flags) {22461// Don't use "cooked". Since tagged template can use raw template22462// representation. So if we do so, it breaks the script semantics.22463return expr.value.raw;22464},2246522466TemplateLiteral: function (expr, precedence, flags) {22467var result, i, iz;22468result = [ '`' ];22469for (i = 0, iz = expr.quasis.length; i < iz; ++i) {22470result.push(this.generateExpression(expr.quasis[i], Precedence.Primary, E_TTT));22471if (i + 1 < iz) {22472result.push('${' + space);22473result.push(this.generateExpression(expr.expressions[i], Precedence.Sequence, E_TTT));22474result.push(space + '}');22475}22476}22477result.push('`');22478return result;22479},2248022481ModuleSpecifier: function (expr, precedence, flags) {22482return this.Literal(expr, precedence, flags);22483},2248422485ImportExpression: function(expr, precedence, flag) {22486return parenthesize([22487'import(',22488this.generateExpression(expr.source, Precedence.Assignment, E_TTT),22489')'22490], Precedence.Call, precedence);22491}22492};2249322494merge(CodeGenerator.prototype, CodeGenerator.Expression);2249522496CodeGenerator.prototype.generateExpression = function (expr, precedence, flags) {22497var result, type;2249822499type = expr.type || "Property";2250022501if (extra.verbatim && expr.hasOwnProperty(extra.verbatim)) {22502return generateVerbatim(expr, precedence);22503}2250422505result = this[type](expr, precedence, flags);225062250722508if (extra.comment) {22509result = addComments(expr, result);22510}22511return toSourceNodeWhenNeeded(result);22512};2251322514CodeGenerator.prototype.generateStatement = function (stmt, flags) {22515var result,22516fragment;2251722518result = this[stmt.type](stmt, flags);2251922520// Attach comments2252122522if (extra.comment) {22523result = addComments(stmt, result);22524}2252522526fragment = toSourceNodeWhenNeeded(result).toString();22527if (stmt.type === "Program" && !safeConcatenation && newline === '' && fragment.charAt(fragment.length - 1) === '\n') {22528result = sourceMap ? toSourceNodeWhenNeeded(result).replaceRight(/\s+$/, '') : fragment.replace(/\s+$/, '');22529}2253022531return toSourceNodeWhenNeeded(result);22532};2253322534function generateInternal(node) {22535var codegen;2253622537codegen = new CodeGenerator();22538if (isStatement(node)) {22539return codegen.generateStatement(node, S_TFFF);22540}2254122542if (isExpression(node)) {22543return codegen.generateExpression(node, Precedence.Sequence, E_TTT);22544}2254522546throw new Error('Unknown node type: ' + node.type);22547}2254822549function generate(node, options) {22550var defaultOptions = getDefaultOptions();2255122552if (options != null) {22553// Obsolete options22554//22555// `options.indent`22556// `options.base`22557//22558// Instead of them, we can use `option.format.indent`.22559if (typeof options.indent === 'string') {22560defaultOptions.format.indent.style = options.indent;22561}22562if (typeof options.base === 'number') {22563defaultOptions.format.indent.base = options.base;22564}22565options = updateDeeply(defaultOptions, options);22566indent = options.format.indent.style;22567if (typeof options.base === 'string') {22568base = options.base;22569} else {22570base = stringRepeat(indent, options.format.indent.base);22571}22572} else {22573options = defaultOptions;22574indent = options.format.indent.style;22575base = stringRepeat(indent, options.format.indent.base);22576}22577json = options.format.json;22578renumber = options.format.renumber;22579hexadecimal = json ? false : options.format.hexadecimal;22580quotes = json ? 'double' : options.format.quotes;22581escapeless = options.format.escapeless;22582newline = options.format.newline;22583space = options.format.space;22584if (options.format.compact) {22585newline = space = indent = base = '';22586}22587parentheses = options.format.parentheses;22588semicolons = options.format.semicolons;22589safeConcatenation = options.format.safeConcatenation;22590directive = options.directive;22591parse = json ? null : options.parse;22592sourceMap = false;22593sourceCode = options.sourceCode;22594preserveBlankLines = options.format.preserveBlankLines && sourceCode !== null;22595extra = options;2259622597return generateInternal(node).toString();22598}2259922600getDefaultOptions().format;2260122602Precedence = updateDeeply({}, Precedence);2260322604/*22605* ojs-code-transform.ts22606*22607* Copyright (C) 2021-2023 Posit Software, PBC22608*/2260922610// we need to patch the base walker ourselves because OJS sometimes22611// emits Program nodes with "cells" rather than "body"22612const walkerBase = make({22613Import() {},22614// deno-lint-ignore no-explicit-any22615ViewExpression(node, st, c) {22616c(node.id, st, "Identifier");22617},22618// deno-lint-ignore no-explicit-any22619MutableExpression(node, st, c) {22620c(node.id, st, "Identifier");22621},22622// deno-lint-ignore no-explicit-any22623Cell(node, st, c) {22624c(node.body, st);22625},22626// deno-lint-ignore no-explicit-any22627Program(node, st, c) {22628if (node.body) {22629for (let i = 0, list = node.body; i < list.length; i += 1) {22630const stmt = list[i];22631c(stmt, st, "Statement");22632}22633} else if (node.cells) {22634for (let i = 0, list = node.cells; i < list.length; i += 1) {22635const stmt = list[i];22636c(stmt, st);22637}22638} else {22639throw new Error(22640`OJS traversal: I don't know how to walk this node: ${node}`,22641);22642}22643},22644});2264522646// deno-lint-ignore no-explicit-any22647function ojsSimpleWalker(parse, visitor) {22648simple(parse, visitor, walkerBase);22649}2265022651function isPlotPlotCall(node) {22652if (node.type !== "CallExpression") {22653return null;22654}22655const callee = node.callee;22656if (callee.type !== "MemberExpression") {22657return null;22658}22659if (callee.property.type !== "Identifier" ||22660callee.property.name !== "plot") {22661return null;22662}2266322664let result = node.arguments;2266522666node = callee.object;22667while (true) {22668if (node.type === "Identifier" &&22669node.name === "Plot") {22670return result;22671}22672if (node.type !== "CallExpression" ||22673node.callee.type !== "MemberExpression") {22674return null;22675}22676node = node.callee.object;22677}22678}226792268022681/*22682Rewrites Plot.(method(...).method(...).)plot({22683...22684})22685to22686Plot.(method(...).method(...).)plot({22687width: card[$CARD_IN_SCOPE].width,22688height: card[$CARD_IN_SCOPE].height,22689...22690}) */22691const multipleOutputCellMap = {};22692function rewritePlotPlotCall(exp, cellName) {22693// First, check if cellName exists. If it doesn't,22694// then that's likely because we're on a multiple-output cell.22695// attempt to find a cell with the name cellName-1, cellName-2, etc.22696const fixupCellName = () => {22697if (document.getElementById(cellName) === null) {22698let index = 1;22699let subcellName;22700do {22701subcellName = `${cellName}-${index}`;22702index += 1;22703if (document.getElementById(subcellName) !== null && multipleOutputCellMap[subcellName] === undefined) {22704multipleOutputCellMap[subcellName] = true;22705return subcellName;22706}22707} while (document.getElementById(subcellName) !== null);22708return undefined;22709} else {22710return cellName;22711}22712};2271322714const args = isPlotPlotCall(exp);22715if (args === null) {22716return false;22717}22718if (args.length > 1) {22719return false;22720}22721if (args.length === 0) {22722args.push({22723type: "ObjectExpression",22724properties: []22725});22726}22727if (args[0].type !== "ObjectExpression") {22728return false;22729}2273022731const props = args[0].properties;22732// this will need to be more robust in the future.22733// deno-lint-ignore no-explicit-any22734if (!props.every((a) => a.type === "Property")) {22735return false;22736}22737// insert22738// width: cards[cardIndex].width property22739// and height: cards[cardIndex].height property2274022741const cellNameToUse = fixupCellName();22742if (cellNameToUse === undefined) {22743return false;22744}22745const value = (field) => ({22746type: "MemberExpression",22747object: {22748type: "MemberExpression",22749computed: true,22750object: {22751type: "Identifier",22752name: "cards",22753},22754property: {22755type: "Literal",22756value: cellNameToUse,22757},22758},22759property: {22760type: "Identifier",22761name: field,22762},22763});22764const prop = (field) => ({22765type: "Property",22766key: {22767type: "Identifier",22768name: field,22769},22770value: value(field),22771});2277222773props.unshift(prop("width"));22774props.unshift(prop("height"));22775return true;22776}2277722778function autosizeOJSPlot(22779src,22780cellName,22781) {22782// deno-lint-ignore no-explicit-any22783let ast;22784try {22785ast = parseModule(src);22786} catch (e) {22787// if we fail to parse, don't do anything22788// FIXME warn?22789if (!(e instanceof SyntaxError)) throw e;22790return src;22791}22792ojsSimpleWalker(ast, {22793// deno-lint-ignore no-explicit-any22794CallExpression(exp) {22795if (rewritePlotPlotCall(exp, cellName)) {22796return;22797}22798}22799});2280022801const result = ast.cells.map((cell) => {22802const bodySrc = generate(cell.body);22803if (cell.id === null) {22804return bodySrc;22805} else if (cell.id.type === "Identifier") {22806return `${cell.id.name} = ${bodySrc}`;22807} else if (cell.id.type === "ViewExpression") {22808return `viewof ${cell.id.id.name} = ${bodySrc}`;22809} else if (cell.id.type === "MutableExpression") {22810return `mutable ${cell.id.id.name} = ${bodySrc}`;22811} else {22812throw new Error(`OJS: I don't know how to handle this cell id: ${cell.id.type}`);22813}22814}).join("\n");22815return result;22816}2281722818/**22819* @param typeMap [Object] Map of MIME type -> Array[extensions]22820* @param ...22821*/22822function Mime$1() {22823this._types = Object.create(null);22824this._extensions = Object.create(null);2282522826for (let i = 0; i < arguments.length; i++) {22827this.define(arguments[i]);22828}2282922830this.define = this.define.bind(this);22831this.getType = this.getType.bind(this);22832this.getExtension = this.getExtension.bind(this);22833}2283422835/**22836* Define mimetype -> extension mappings. Each key is a mime-type that maps22837* to an array of extensions associated with the type. The first extension is22838* used as the default extension for the type.22839*22840* e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});22841*22842* If a type declares an extension that has already been defined, an error will22843* be thrown. To suppress this error and force the extension to be associated22844* with the new type, pass `force`=true. Alternatively, you may prefix the22845* extension with "*" to map the type to extension, without mapping the22846* extension to the type.22847*22848* e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']});22849*22850*22851* @param map (Object) type definitions22852* @param force (Boolean) if true, force overriding of existing definitions22853*/22854Mime$1.prototype.define = function(typeMap, force) {22855for (let type in typeMap) {22856let extensions = typeMap[type].map(function(t) {22857return t.toLowerCase();22858});22859type = type.toLowerCase();2286022861for (let i = 0; i < extensions.length; i++) {22862const ext = extensions[i];2286322864// '*' prefix = not the preferred type for this extension. So fixup the22865// extension, and skip it.22866if (ext[0] === '*') {22867continue;22868}2286922870if (!force && (ext in this._types)) {22871throw new Error(22872'Attempt to change mapping for "' + ext +22873'" extension from "' + this._types[ext] + '" to "' + type +22874'". Pass `force=true` to allow this, otherwise remove "' + ext +22875'" from the list of extensions for "' + type + '".'22876);22877}2287822879this._types[ext] = type;22880}2288122882// Use first extension as default22883if (force || !this._extensions[type]) {22884const ext = extensions[0];22885this._extensions[type] = (ext[0] !== '*') ? ext : ext.substr(1);22886}22887}22888};2288922890/**22891* Lookup a mime type based on extension22892*/22893Mime$1.prototype.getType = function(path) {22894path = String(path);22895let last = path.replace(/^.*[/\\]/, '').toLowerCase();22896let ext = last.replace(/^.*\./, '').toLowerCase();2289722898let hasPath = last.length < path.length;22899let hasDot = ext.length < last.length - 1;2290022901return (hasDot || !hasPath) && this._types[ext] || null;22902};2290322904/**22905* Return file extension associated with a mime type22906*/22907Mime$1.prototype.getExtension = function(type) {22908type = /^\s*([^;\s]*)/.test(type) && RegExp.$1;22909return type && this._extensions[type.toLowerCase()] || null;22910};2291122912var Mime_1 = Mime$1;2291322914var standard = {"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["es","ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]};2291522916var other = {"application/prs.cww":["cww"],"application/vnd.1000minds.decision-model+xml":["1km"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.keynote":["key"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.numbers":["numbers"],"application/vnd.apple.pages":["pages"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.balsamiq.bmml+xml":["bmml"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.citationstyles.style+xml":["csl"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dbf":["dbf"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mapbox-vector-tile":["mvt"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["*stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.ac+xml":["*ac"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openblox.game+xml":["obgx"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openstreetmap.data+xml":["osm"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.rar":["rar"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.software602.filler.form+xml":["fo"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.syncml.dmddf+xml":["ddf"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":["*dmg"],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":["*bdoc"],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["*deb","udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["*iso"],"application/x-iwork-keynote-sffkey":["*key"],"application/x-iwork-numbers-sffnumbers":["*numbers"],"application/x-iwork-pages-sffpages":["*pages"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-keepass2":["kdbx"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":["*exe"],"application/x-msdownload":["*exe","*dll","com","bat","*msi"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["*wmf","*wmz","*emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":["*prc","*pdb"],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["*rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["*obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["*xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/x-aac":["aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":["*m4a"],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":["*ra"],"audio/x-wav":["*wav"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"image/prs.btif":["btif"],"image/prs.pti":["pti"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.airzip.accelerator.azv":["azv"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["*sub"],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.microsoft.icon":["ico"],"image/vnd.ms-dds":["dds"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.pco.b16":["b16"],"image/vnd.tencent.tap":["tap"],"image/vnd.valve.source.texture":["vtf"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/vnd.zbrush.pcx":["pcx"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["*ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":["*bmp"],"image/x-pcx":["*pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/vnd.wfa.wsc":["wsc"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.opengex":["ogex"],"model/vnd.parasolid.transmit.binary":["x_b"],"model/vnd.parasolid.transmit.text":["x_t"],"model/vnd.sap.vds":["vds"],"model/vnd.usdz+zip":["usdz"],"model/vnd.valve.source.compiled-map":["bsp"],"model/vnd.vtu":["vtu"],"text/prs.lines.tag":["dsc"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":["*org"],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]};2291722918let Mime = Mime_1;22919var mime = new Mime(standard, other);2292022921/*global Shiny, $, DOMParser, MutationObserver, URL22922*22923* quarto-ojs.js22924*22925* Copyright (C) 2021 RStudio, PBC22926*22927*/2292822929//////////////////////////////////////////////////////////////////////////////2293022931function displayOJSWarning(warning)22932{22933const cells = [];22934for (22935const content of document.querySelectorAll('script[type="ojs-module-contents"]')22936) {22937for (const cellJson of JSON.parse(base64ToStr(content.text)).contents) {22938let cell = document.getElementById(cellJson.cellName) || document.getElementById(`${cellJson.cellName}-1`);22939if (!cell) {22940// give up22941continue;22942}22943cells.push(cell);22944}22945}2294622947debugger;22948cells.forEach((cell) => {22949debugger;22950cell.innerHTML = "";2295122952const message = warning();2295322954cell.appendChild(22955calloutBlock({22956heading: "Error",22957type: "error",22958message22959})22960);22961});22962}2296322964function displayQtWebEngineError() {22965displayOJSWarning(() => {22966const message = document.createElement("div");22967message.appendChild(document.createTextNode("This document uses OJS, which requires JavaScript features not present in this version of QtWebEngine. If you're using RStudio IDE, please upgrade to a "));22968const link = document.createElement("a");22969link.appendChild(document.createTextNode("2022.12 build"));22970link.href = "https://dailies.rstudio.com/rstudio/elsbeth-geranium/";22971message.appendChild(link);22972message.appendChild(document.createTextNode("."));22973return message;22974});22975}2297622977function displayFileProtocolError() {22978displayOJSWarning(() => {22979const message = document.createElement("div");22980message.appendChild(document.createTextNode("This document uses OJS, which requires JavaScript features disabled when running in file://... URLs. In order for these features to work, run this document in a web server."));22981return message;22982});22983}229842298522986//////////////////////////////////////////////////////////////////////////////22987// Quarto-specific code starts here.2298822989// For RStudio IDE integration22990/** creates a click handler to point the IDE to a given line and column */22991const makeDevhostErrorClickHandler = (line, column) => {22992return function () {22993if (!window.quartoDevhost) {22994return false;22995}22996window.quartoDevhost.openInputFile(line, column, true);22997return false;22998};22999};2300023001// we cannot depend on Object.fromEntries because the IDE23002// doesn't support it. We minimally polyfill it23003if (Object.fromEntries === undefined) {23004Object.fromEntries = function (obj) {23005const result = {};23006for (const [key, value] of obj) {23007result[key] = value;23008}23009return result;23010};23011}2301223013/** create a callout block with the given opts, currently to be used23014to signal a runtime error in the observable runtime.23015*/23016function calloutBlock(opts) {23017const { type, heading, message, onclick } = opts;2301823019const outerBlock = document.createElement("div");23020outerBlock.classList.add(23021`callout-${type}`,23022"callout",23023"callout-style-default",23024"callout-captioned"23025);23026const header = document.createElement("div");23027header.classList.add("callout-header", "d-flex", "align-content-center");23028const iconContainer = document.createElement("div");23029iconContainer.classList.add("callout-icon-container");23030const icon = document.createElement("i");23031icon.classList.add("callout-icon");23032iconContainer.appendChild(icon);23033header.appendChild(iconContainer);2303423035const headingDiv = document.createElement("div");23036headingDiv.classList.add("callout-caption-container", "flex-fill");23037// we assume heading is either a string or a span23038if (typeof heading === "string") {23039headingDiv.innerText = heading;23040} else {23041headingDiv.appendChild(heading);23042}23043header.appendChild(headingDiv);23044outerBlock.appendChild(header);2304523046const container = document.createElement("div");23047container.classList.add("callout-body-container", "callout-body");23048if (typeof message === "string") {23049const p = document.createElement("p");23050p.innerText = message;23051container.appendChild(p);23052} else {23053container.append(message);23054}23055outerBlock.appendChild(container);2305623057if (onclick) {23058outerBlock.onclick = onclick;23059outerBlock.style.cursor = "pointer";23060}2306123062return outerBlock;23063}2306423065const kQuartoModuleWaitClass = "ojs-in-a-box-waiting-for-module-import";2306623067class QuartoOJSConnector extends OJSConnector {23068constructor(opts) {23069super(opts);23070}2307123072////////////////////////////////////////////////////////////////////////////23073// handle import module waits2307423075clearImportModuleWait() {23076const array = Array.from(23077document.querySelectorAll(`.${kQuartoModuleWaitClass}`)23078);23079for (const node of array) {23080node.classList.remove(kQuartoModuleWaitClass);23081}23082}2308323084finishInterpreting() {23085return super.finishInterpreting().then(() => {23086if (this.mainModuleHasImports) {23087this.clearImportModuleWait();23088}23089});23090}2309123092////////////////////////////////////////////////////////////////////////////23093// Error tracking/reporting2309423095locatePreDiv(cellDiv, ojsDiv) {23096// locate the correct pre div with the pandocDecorator23097// of all potential divs, we need to find the one that most23098// immediately precedes `ojsDiv` in the DOM.23099let preDiv;23100for (const candidate of cellDiv.querySelectorAll("pre.sourceCode")) {23101if (23102candidate.compareDocumentPosition(ojsDiv) &23103ojsDiv.DOCUMENT_POSITION_FOLLOWING23104) {23105preDiv = candidate;23106} else {23107break;23108}23109}23110return preDiv;23111}2311223113findCellOutputDisplay(ojsDiv) {23114while (ojsDiv && !ojsDiv.classList.contains("cell-output-display")) {23115ojsDiv = ojsDiv.parentElement;23116}23117if (!ojsDiv) {23118return null;23119}23120return ojsDiv;23121}2312223123setPreDivClasses(preDiv, hasErrors) {23124if (!hasErrors) {23125preDiv.classList.remove("numberSource");23126if (preDiv._hidden === true) {23127const parent = preDiv.parentElement;23128parent.classList.add("hidden");23129// when code-tools is active (that is, when pre is inside a details tag), we also need to hide the details tag.23130if (parent.parentElement.tagName === "DETAILS") {23131parent.parentElement.classList.add("hidden");23132}23133}23134} else {23135preDiv.classList.add("numberSource");23136const parent = preDiv.parentElement;23137if (parent.classList.contains("hidden")) {23138preDiv._hidden = true; // signal that we used to be hidden so that when errors go away, we're hidden again.23139parent.classList.remove("hidden");2314023141// when code-tools is active (that is, when pre is inside a details tag), we also need to unhide the details tag.23142if (parent.parentElement.tagName === "DETAILS") {23143parent.parentElement.classList.remove("hidden");23144// open the code-tools by default when error happens.23145parent.parentElement.setAttribute("open", "open");23146}23147}23148}23149}2315023151clearErrorPinpoints(cellDiv, ojsDiv) {23152const preDiv = this.locatePreDiv(cellDiv, ojsDiv);23153if (preDiv === undefined) {23154return;23155}23156this.setPreDivClasses(preDiv, false);23157let startingOffset = 0;23158if (preDiv.parentElement.dataset.sourceOffset) {23159startingOffset = -Number(preDiv.parentElement.dataset.sourceOffset);23160}23161for (const entryPoint of preDiv._decorator.spanSelection(23162startingOffset,23163Infinity23164)) {23165const { node } = entryPoint;23166node.classList.remove("quarto-ojs-error-pinpoint");23167node.onclick = null;23168}23169}2317023171decorateOjsDivWithErrorPinpoint(ojsDiv, start, end, line, column) {23172const cellOutputDisplay = this.findCellOutputDisplay(ojsDiv);23173// if ojs element is inline, there's no div.23174if (!cellOutputDisplay) {23175return;23176}23177if (cellOutputDisplay._errorSpans === undefined) {23178cellOutputDisplay._errorSpans = [];23179}23180cellOutputDisplay._errorSpans.push({23181start,23182end,23183line,23184column,23185});23186}2318723188decorateSource(cellDiv, ojsDiv) {23189if (!cellDiv) {23190// no div in inline spans23191return;23192}23193this.clearErrorPinpoints(cellDiv, ojsDiv);23194const preDiv = this.locatePreDiv(cellDiv, ojsDiv);23195// sometimes the source code is not echoed.23196// FIXME: should ojs source always be "hidden" so we can show it23197// in case of runtime errors?23198if (preDiv === undefined) {23199return;23200}23201// now find all ojsDivs that contain errors that need to be decorated23202// on preDiv23203let parent = preDiv.parentElement;23204if (parent.parentElement.tagName === "DETAILS") {23205// we're in a code-tools setting, need to go one further up23206parent = parent.parentElement;23207}23208let div = parent.nextElementSibling;23209let foundErrors = false;23210while (div !== null && div.classList.contains("cell-output-display")) {23211for (const errorSpan of div._errorSpans || []) {23212for (const entryPoint of preDiv._decorator.spanSelection(23213errorSpan.start,23214errorSpan.end23215)) {23216const { node } = entryPoint;23217node.classList.add("quarto-ojs-error-pinpoint");23218node.onclick = makeDevhostErrorClickHandler(23219errorSpan.line,23220errorSpan.column23221);23222}23223foundErrors = true;23224}23225div = div.nextElementSibling;23226}23227this.setPreDivClasses(preDiv, foundErrors);23228}2322923230clearError(ojsDiv) {23231const cellOutputDisplay = this.findCellOutputDisplay(ojsDiv);23232// if ojs element is inline, there's no div.23233if (cellOutputDisplay)23234cellOutputDisplay._errorSpans = [];23235}2323623237signalError(cellDiv, ojsDiv, ojsAst) {23238const buildCallout = (ojsDiv) => {23239let onclick;23240const inspectChild = ojsDiv.querySelector(".observablehq--inspect");23241let [heading, message] = inspectChild.textContent.split(": ");23242if (heading === "RuntimeError") {23243heading = "OJS Runtime Error";23244if (message.match(/^(.+) is not defined$/)) {23245const [varName, ...rest] = message.split(" ");23246const p = document.createElement("p");23247const tt = document.createElement("tt");23248tt.innerText = varName;23249p.appendChild(tt);23250p.appendChild(document.createTextNode(" " + rest.join(" ")));23251message = p;2325223253const preDiv = this.locatePreDiv(cellDiv, ojsDiv);23254// preDiv might not be exist in case source isn't echoed to HTML23255if (preDiv !== undefined) {23256// force line numbers to show23257preDiv.classList.add("numberSource");23258const missingRef = ojsAst.references.find(23259(n) => n.name === varName23260);23261// TODO when missingRef === undefined, it likely means an unresolved23262// import reference. For now we will leave things as is, but23263// this needs better handling.23264if (missingRef !== undefined) {23265const { line, column } = preDiv._decorator.offsetToLineColumn(23266missingRef.start23267);23268const headingSpan = document.createElement("span");23269const headingTextEl = document.createTextNode(23270`${heading} (line ${line}, column ${column}) `23271);23272headingSpan.appendChild(headingTextEl);23273if (window.quartoDevhost) {23274const clicker = document.createElement("a");23275clicker.href = "#"; // this forces the right CSS to apply23276clicker.innerText = "(source)";23277onclick = makeDevhostErrorClickHandler(line, column);23278headingSpan.appendChild(clicker);23279}23280heading = headingSpan;23281this.decorateOjsDivWithErrorPinpoint(23282ojsDiv,23283missingRef.start,23284missingRef.end,23285line,23286column23287);23288}23289}23290} else if (23291message.match(/^(.+) could not be resolved$/) ||23292message.match(/^(.+) is defined more than once$/)23293) {23294const [varName, ...rest] = message.split(" ");23295const p = document.createElement("p");23296const tt = document.createElement("tt");23297tt.innerText = varName;23298p.appendChild(tt);23299p.appendChild(document.createTextNode(" " + rest.join(" ")));23300message = p;23301} else {23302const p = document.createElement("p");23303p.appendChild(document.createTextNode(message));23304message = p;23305}23306} else {23307heading = "OJS Error";23308const p = document.createElement("p");23309p.appendChild(document.createTextNode(inspectChild.textContent));23310message = p;23311}23312const callout = calloutBlock({23313type: "important",23314heading,23315message,23316onclick,23317});23318ojsDiv.appendChild(callout);23319};2332023321buildCallout(ojsDiv);23322}2332323324interpret(src, elementGetter, elementCreator) {23325// deno-lint-ignore no-this-alias23326const that = this;23327const observer = (targetElement, ojsAst) => {23328return (name) => {23329const element =23330typeof elementCreator === "function"23331? elementCreator()23332: elementCreator;23333targetElement.appendChild(element);2333423335// TODO the unofficial interpreter always calls viewexpression observers23336// twice, one with the name, and the next with 'viewof $name'.23337// we check for 'viewof ' here and hide the element we're creating.23338// this behavior appears inconsistent with OHQ's interpreter, so we23339// shouldn't be surprised to see this fail in the future.23340if (23341ojsAst.id &&23342ojsAst.id.type === "ViewExpression" &&23343!name.startsWith("viewof ")23344) {23345element.classList.add("quarto-ojs-hide");23346}2334723348// handle output:all hiding23349//23350// if every output from a cell is is not displayed, then we23351// must also not display the cell output display element23352// itself.2335323354// collect the cell element as well as the cell output display23355// element23356let cellDiv = targetElement;23357let cellOutputDisplay;23358while (cellDiv !== null && !cellDiv.classList.contains("cell")) {23359cellDiv = cellDiv.parentElement;23360if (cellDiv && cellDiv.classList.contains("cell-output-display")) {23361cellOutputDisplay = cellDiv;23362}23363}23364const forceShowDeclarations = (!cellDiv) || (cellDiv.dataset.output === "all");2336523366const config = { childList: true };23367const callback = function (mutationsList) {23368// we may fail to find a cell in inline settings; but23369// inline cells won't have inspectors, so in that case23370// we never hide23371for (const mutation of mutationsList) {23372const ojsDiv = mutation.target;2337323374if (!forceShowDeclarations) {23375const childNodes = Array.from(mutation.target.childNodes);23376for (const n of childNodes) {23377// hide the inner inspect outputs that aren't errors or23378// declarations23379if (23380n.classList.contains("observablehq--inspect") &&23381!n.parentNode.classList.contains("observablehq--error") &&23382n.parentNode.parentNode.dataset.nodetype !== "expression"23383) {23384n.classList.add("quarto-ojs-hide");23385}23386// show the inspect outputs that aren't errors and are23387// expressions (they might have been hidden in the past,23388// since errors can clear)23389if (23390n.classList.contains("observablehq--inspect") &&23391!n.parentNode.classList.contains("observablehq--error") &&23392n.parentNode.parentNode.dataset.nodetype === "expression"23393) {23394n.classList.remove("quarto-ojs-hide");23395}23396}23397}2339823399// if the ojsDiv shows an error, display a callout block instead of it.23400if (ojsDiv.classList.contains("observablehq--error")) {23401// we don't use quarto-ojs-hide here because that would confuse23402// the code which depends on that class for its logic.23403ojsDiv.querySelector(".observablehq--inspect").style.display =23404"none";2340523406if (ojsDiv.querySelectorAll(".callout-important").length === 0) {23407that.signalError(cellDiv, ojsDiv, ojsAst);23408}23409} else {23410that.clearError(ojsDiv);23411if (23412ojsDiv.parentNode.dataset.nodetype !== "expression" &&23413!forceShowDeclarations &&23414Array.from(ojsDiv.childNodes).every((n) =>23415n.classList.contains("observablehq--inspect")23416)23417) {23418// if every child is an inspect output, hide the ojsDiv23419ojsDiv.classList.add("quarto-ojs-hide");23420}23421}2342223423that.decorateSource(cellDiv, ojsDiv);2342423425for (const added of mutation.addedNodes) {2342623427// https://github.com/quarto-dev/quarto-cli/issues/742623428// ObservableHQ.Plot fixup:23429// remove "background: white" from style declaration23430if (added.tagName === "svg" &&23431Array.from(added.classList)23432.some(x => x.match(/plot-[0-9a-f]+/))) {23433// this overrides the style CSS inside.23434added.style.background = "none";23435}2343623437if (23438added.tagName === "FORM" &&23439Array.from(added.classList).some(23440(x) => x.endsWith("table") && x.startsWith("oi-")23441)23442) {23443// add quarto-specific classes to OJS-generated tables23444added.classList.add("quarto-ojs-table-fixup");2344523446// in dashboard, change styles so that autosizing works23447if (window._ojs.isDashboard) {23448const table = added.querySelector("table");23449if (table) {23450table.style.width = "100%";23451}23452added.style.maxHeight = null;23453added.style.margin = "0 0 0 0";23454added.style.padding = "0 0 0 0";2345523456// find parentElement with class cell-output-display or cell23457let parent = added.parentElement;23458while (parent && !parent.classList.contains("cell-output-display") && !parent.classList.contains("cell")) {23459parent = parent.parentElement;23460}23461if (parent !== null && added.clientHeight > parent.clientHeight) {23462added.style.maxHeight = `${parent.clientHeight}px`;23463}23464}23465}2346623467// add quarto-specific classes to OJS-generated buttons23468const addedButtons = added.querySelectorAll("button");23469for (const button of Array.from(addedButtons)) {23470button.classList.add("btn");23471button.classList.add("btn-quarto");23472}2347323474// hide import statements even if output === "all"23475//// Hide imports that aren't javascript code23476//23477// We search here for code.javascript and node span.hljs-... because23478// at this point in the DOM, observable's runtime hasn't called23479// HLJS yet. if you inspect the DOM yourself, you're likely to see23480// HLJS, so this comment is here to prevent future confusion.23481const result = added.querySelectorAll("code.javascript");23482if (result.length !== 1) {23483continue;23484}23485if (result[0].textContent.trim().startsWith("import")) {23486ojsDiv.classList.add("quarto-ojs-hide");23487}23488}23489}2349023491// cellOutputDisplay doesn't exist in inline spans, so we must check it explicitly23492if (cellOutputDisplay) {23493const children = Array.from(23494cellOutputDisplay.querySelectorAll("div.observablehq")23495);23496// after all mutations are handled, we check the full cell for hiding23497if (23498children.every((n) => {23499return n.classList.contains("quarto-ojs-hide");23500})23501) {23502cellOutputDisplay.classList.add("quarto-ojs-hide");23503} else {23504cellOutputDisplay.classList.remove("quarto-ojs-hide");23505}23506}23507};23508new MutationObserver(callback).observe(element, config);23509// 'element' is the outer div given to observable's runtime to insert their output23510// every quarto cell will have either one or two such divs.23511// The parent of these divs should always be a div corresponding to an ojs "cell"23512// (with ids "ojs-cell-*")2351323514element.classList.add(kQuartoModuleWaitClass);2351523516return new this.inspectorClass(element, ojsAst);23517};23518};23519const runCell = (cell) => {23520const targetElement =23521typeof elementGetter === "function" ? elementGetter() : elementGetter;23522const cellSrc = src.slice(cell.start, cell.end);23523const promise = this.interpreter.module(23524cellSrc,23525undefined,23526observer(targetElement, cell)23527);23528return this.waitOnImports(cell, promise);23529};23530return this.interpretWithRunner(src, runCell);23531}23532}2353323534//////////////////////////////////////////////////////////////////////////////23535// previously quarto-observable-shiny.js2353623537function createRuntime() {23538const quartoOjsGlobal = window._ojs;23539const isShiny = window.Shiny !== undefined;2354023541// Are we QtWebEngine? bail23542if (window.navigator.userAgent.includes("QtWebEngine")) {23543displayQtWebEngineError();23544return;23545}2354623547// Are we file://? bail23548if (window.location.protocol === "file:") {23549displayFileProtocolError();23550return;23551}2355223553// Are we shiny?23554if (isShiny) {23555quartoOjsGlobal.hasShiny = true;23556initOjsShinyRuntime();2355723558const span = document.createElement("span");23559window._ojs.shinyElementRoot = span;23560document.body.appendChild(span);23561}2356223563// we use the trick described here to extend observable runtime's standard library23564// https://talk.observablehq.com/t/embedded-width/10632356523566// stdlib from our fork, which uses the safe d3-require23567const lib = new Library();23568if (isShiny) {23569extendObservableStdlib(lib);23570}2357123572function transpose(df) {23573const keys = Object.keys(df);23574return df[keys[0]]23575.map((v, i) =>23576Object.fromEntries(keys.map((key) => {23577const v = df[key][i];23578const result = v === null ? undefined : v;23579return [key, result];23580})))23581.filter((v) => !Object.values(v).every((e) => e === undefined));23582}23583lib.transpose = () => transpose;2358423585// TODO this should be user-configurable, so that we can actually23586// make it work in arbitrary layouts.23587// There's probably a slick reactive trick to make the element23588// user settable.23589//23590// Right now we support quarto's standard HTML formats2359123592const mainEl = (document.querySelector("main") // html23593|| document.querySelector("div.reveal") // reveal23594|| document.querySelector("body")); // fall-through2359523596function cards() {23597if (mainEl === null) {23598return lib.Generators.observe((change) => {23599change(undefined);23600});23601}23602return lib.Generators.observe(function(change) {23603let previous = undefined;23604function resized() {23605let changed = false;23606const result = {};23607let cellIndex = 0;23608const handle = (card) => {23609const cardInfo = {23610card,23611width: card.clientWidth,23612height: card.clientHeight,23613};23614result[cellIndex] = cardInfo;23615if (previous === undefined ||23616previous[cellIndex].width !== cardInfo.width ||23617previous[cellIndex].height !== cardInfo.height) {23618changed = true;23619}23620cellIndex++;2362123622// there can be an id in the card itself, allow that as a key23623if (card.id) {23624result[card.id] = cardInfo;23625}23626};23627for (const card of document.querySelectorAll("div.card")) {23628for (const cell of card.querySelectorAll("div.cell-output-display")) {23629handle(cell);23630}23631for (const cell of card.querySelectorAll("div.quarto-layout-cell")) {23632handle(cell);23633}23634}23635for (const card of document.querySelectorAll("div")) {23636if (!(card.id.startsWith("ojs-cell-"))) {23637continue;23638}23639let cardInfoCard;23640// many possible cases:2364123642if (card.parentElement.classList.contains("cell-output-display")) {23643// single cell: card parent is cell-output-display23644cardInfoCard = card.parentElement;23645} else if (card.parentElement.classList.contains("quarto-layout-cell")) {23646// subcell of layout23647cardInfoCard = card.parentElement;23648} else if (card.parentElement.parentElement.classList.contains("cell-output-display")) {23649// subcell of cell-output-display23650cardInfoCard = card.parentElement.parentElement;23651} else {23652continue;23653}23654const cardInfo = {23655card: cardInfoCard,23656width: card.clientWidth,23657height: card.clientHeight,23658};23659result[card.id] = cardInfo;23660if (previous === undefined ||23661previous[card.id].width !== cardInfo.width ||23662previous[card.id].height !== cardInfo.height) {23663changed = true;23664}23665if (card.parentElement.id !== "") {23666result[card.parentElement.id] = cardInfo;23667}23668}2366923670if (changed) {23671previous = result;23672change(result);23673}23674}23675resized();23676window.addEventListener("resize", resized);23677return function() {23678window.removeEventListener("resize", resized);23679}23680});23681}2368223683function width() {23684if (mainEl === null) {23685return lib.Generators.observe((change) => {23686change(undefined);23687});23688}23689return lib.Generators.observe(function (change) {23690var width = change(mainEl.clientWidth);23691function resized() {23692var w = mainEl.clientWidth;23693if (w !== width) change((width = w));23694}23695window.addEventListener("resize", resized);23696return function () {23697window.removeEventListener("resize", resized);23698};23699});23700}23701lib.width = width;23702lib.cards = cards;2370323704// hack for "echo: fenced": remove all "//| echo: fenced" lines the hard way, but keep23705// the right line numbers around.23706Array.from(document.querySelectorAll("span.co"))23707.filter((n) => n.textContent === "//| echo: fenced")23708.forEach((n) => {23709const lineSpan = n.parentElement;23710const lineBreak = lineSpan.nextSibling;23711if (lineBreak) {23712const nextLineSpan = lineBreak.nextSibling;23713if (nextLineSpan) {23714const lineNumber = Number(nextLineSpan.id.split("-")[1]);23715nextLineSpan.style = `counter-reset: source-line ${lineNumber - 1}`;23716}23717}2371823719// update the source offset variable with the new right amount23720const sourceDiv = lineSpan.parentElement.parentElement.parentElement;23721const oldOffset = Number(sourceDiv.dataset.sourceOffset);23722sourceDiv.dataset.sourceOffset = oldOffset - "//| echo: fenced\n".length;2372323724lineSpan.remove();23725lineBreak.remove();23726});2372723728// select all elements to track:23729// panel elements with ids, and divs with ids and .ojs-track-layout2373023731const layoutDivs = [...Array.from(23732document.querySelectorAll("div.quarto-layout-panel div[id]")23733),23734...Array.from(23735document.querySelectorAll('div.ojs-track-layout[id]')23736)];2373723738function layoutWidth() {23739return lib.Generators.observe(function (change) {23740const ourWidths = Object.fromEntries(23741layoutDivs.map((div) => [div.id, div.clientWidth])23742);23743change(ourWidths);23744function resized() {23745let changed = false;23746for (const div of layoutDivs) {23747const w = div.clientWidth;23748if (w !== ourWidths[div.id]) {23749ourWidths[div.id] = w;23750changed = true;23751}23752}23753if (changed) {23754change(ourWidths);23755}23756}23757window.addEventListener("resize", resized);23758return function () {23759window.removeEventListener("resize", resized);23760};23761});23762}23763lib.layoutWidth = layoutWidth;23764let localResolver = {};2376523766function fileAttachmentPathResolver(n) {23767if (localResolver[n]) {23768return localResolver[n];23769}2377023771let name;2377223773// we need to remove the hash from the current path23774// for this to work in revealjs23775const currentPath = window.location.href.split("#")[0].replace(/[^/]*$/, '');2377623777if (n.startsWith("/")) {23778// docToRoot can be empty, in which case naive concatenation creates23779// an absolute path.23780if (quartoOjsGlobal.paths.docToRoot === "") {23781name = `${currentPath}.${n}`;23782} else {23783name = `${currentPath}${quartoOjsGlobal.paths.docToRoot}${n}`;23784}23785} else if (n.startsWith("http")) {23786name = n;23787} else {23788name = `${currentPath}${n}`;23789}2379023791const mimeType = mime.getType(name);2379223793return {23794url: name,23795mimeType: mimeType,23796}2379723798}23799lib.FileAttachment = () => FileAttachments(fileAttachmentPathResolver);2380023801const ojsConnector = new QuartoOJSConnector({23802paths: quartoOjsGlobal.paths,23803inspectorClass: isShiny ? ShinyInspector : QuartoInspector,23804library: lib,23805allowPendingGlobals: isShiny,23806});23807quartoOjsGlobal.ojsConnector = ojsConnector;23808if (isShiny) {23809// When isShiny, OJSConnector is constructed with allowPendingGlobals:true.23810// Our guess is that most shiny-to-ojs exports will have been defined23811// by the time the server function finishes executing (i.e. session init23812// completion); so we call `killPendingGlobals()` to show errors for23813// variables that are still undefined.23814$(document).one("shiny:idle", () => {23815// "shiny:idle" is not late enough; it is raised before the resulting23816// outputs are received from the server.23817$(document).one("shiny:message", () => {23818// "shiny:message" is not late enough; it is raised after the message23819// is received, but before it is processed (i.e. variables are still23820// not actually defined).23821setTimeout(() => {23822ojsConnector.killPendingGlobals();23823}, 0);23824});23825});23826}2382723828const subfigIdMap = new Map();23829function getSubfigId(elementId) {23830if (!subfigIdMap.has(elementId)) {23831subfigIdMap.set(elementId, 0);23832}23833let nextIx = subfigIdMap.get(elementId);23834nextIx++;23835subfigIdMap.set(elementId, nextIx);23836return `${elementId}-${nextIx}`;23837}2383823839const sourceNodes = document.querySelectorAll(23840"pre.sourceCode code.sourceCode"23841);23842const decorators = Array.from(sourceNodes).map((n) => {23843n = n.parentElement;23844const decorator = new PandocCodeDecorator(n);23845n._decorator = decorator;23846return decorator;23847});23848// handle build-time syntax error23849decorators.forEach((n) => {23850if (n._node.parentElement.dataset.syntaxErrorPosition === undefined) {23851return;23852}23853const offset = Number(n._node.parentElement.dataset.syntaxErrorPosition);23854n.decorateSpan(offset, offset + 1, ["quarto-ojs-error-pinpoint"]);23855});2385623857const result = {23858setLocalResolver(obj) {23859localResolver = obj;23860ojsConnector.setLocalResolver(obj);23861},23862finishInterpreting() {23863return ojsConnector.finishInterpreting();23864},2386523866// return the latest value of the named reactive variable in the main module23867async value(name) {23868await this.finishInterpreting();23869const result = await ojsConnector.value(name);23870return result;23871},2387223873// fixme clarify what's the expected behavior of the 'error' option23874// when evaluation is at client-time23875interpretLenient(src, targetElementId, inline) {23876return result.interpret(src, targetElementId, inline).catch(() => {});23877},23878interpret(src, targetElementId, inline) {23879// we capture the result here so that the error handler doesn't23880// grab a new id accidentally.23881let targetElement;23882const getElement = () => {23883targetElement = document.getElementById(targetElementId);23884let subFigId;23885if (!targetElement) {23886// this is a subfigure23887subFigId = getSubfigId(targetElementId);23888targetElement = document.getElementById(subFigId);23889if (!targetElement) {23890// console.error("Ran out of subfigures for element", targetElementId);23891// console.error("This will fail.");23892throw new Error("Ran out of quarto subfigures.");23893}23894}23895return targetElement;23896};2389723898const makeElement = () => {23899return document.createElement(inline ? "span" : "div");23900};2390123902return ojsConnector.interpret(src, getElement, makeElement).catch((e) => {23903// to the best of our knowledge, we only get here23904// on import statement failures. So we report those23905// in a callout2390623907let cellDiv = targetElement;23908while (cellDiv !== null && !cellDiv.classList.contains("cell")) {23909cellDiv = cellDiv.parentElement;23910}2391123912const ojsDiv = targetElement.querySelector(".observablehq");23913if (!ojsDiv) {23914// we failed to find an observablehq div inside the targetElement.23915// This is an internal error and we have no way to report it23916// except throwing the original exception.23917throw e;23918}23919// because this is in an exception handler, we might need23920// to clear some of the garbage that other pieces of code23921// won't have the chance to23922//23923for (const div of ojsDiv.querySelectorAll(".callout")) {23924div.remove();23925}2392623927const messagePre = document.createElement("pre");23928messagePre.innerText = e.stack;2392923930const callout = calloutBlock({23931type: "important",23932heading: `${e.name}: ${e.message}`,23933message: messagePre,23934});23935ojsDiv.appendChild(callout);23936ojsConnector.clearError(ojsDiv);23937ojsConnector.clearErrorPinpoints(cellDiv, ojsDiv);2393823939return e;23940});23941},23942interpretQuiet(src) {23943return ojsConnector.interpretQuiet(src);23944},23945interpretFromScriptTags() {23946// source definitions23947for (const el of document.querySelectorAll(23948"script[type='ojs-module-contents']"23949)) {23950for (const call of JSON.parse(base64ToStr(el.text)).contents) {23951let source = window._ojs.isDashboard ? autosizeOJSPlot(call.source, call.cellName) : call.source;23952switch (call.methodName) {23953case "interpret":23954this.interpret(source, call.cellName, call.inline);23955break;23956case "interpretLenient":23957this.interpretLenient(source, call.cellName, call.inline);23958break;23959case "interpretQuiet":23960this.interpretQuiet(source);23961break;23962default:23963throw new Error(23964`Don't know how to call method ${call.methodName}`23965);23966}23967}23968}2396923970// static data definitions23971for (const el of document.querySelectorAll("script[type='ojs-define']")) {23972for (const { name, value } of JSON.parse(el.text).contents) {23973ojsConnector.define(name)(value);23974}23975}23976},23977};2397823979return result;23980}239812398223983function initializeRuntime()23984{23985// TODO "obs" or "ojs"? Inconsistent naming.23986window._ojs = {23987ojsConnector: undefined,2398823989paths: {}, // placeholder for per-quarto-file paths23990// necessary for module resolution2399123992hasShiny: false, // true if we have the quarto-ojs-shiny runtime2399323994isDashboard: document.body.classList.contains("quarto-dashboard"), // true if we are a dashboard format2399523996shinyElementRoot: undefined, // root element for the communication with shiny23997// via DOM23998};23999window._ojs.runtime = createRuntime();24000window._ojs.jsx = createQuartoJsxShim();24001}2400224003initializeRuntime();24004// export default init;240052400624007