'use strict';
/*!
 * Copyright (c) Anaconda, Inc., and Bokeh Contributors
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * 
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * 
 * Neither the name of Anaconda nor the names of any contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */
(function(root, factory) {
  const bokeh = factory();
  bokeh.__bokeh__ = true;
  if (typeof root.Bokeh === "undefined" || typeof root.Bokeh.__bokeh__ === "undefined") {
    root.Bokeh = bokeh;
  }
  const Bokeh = root.Bokeh;
  Bokeh[bokeh.version] = bokeh;
})(this, function() {
  let define;
  const parent_require = typeof require === "function" && require
  return (function(modules, entry, aliases, externals) {
  if (aliases === undefined) aliases = {};
  if (externals === undefined) externals = {};

  const cache = {};

  const normalize = function(name) {
    if (typeof name === "number")
      return name;

    if (name === "bokehjs")
      return entry;

    if (!externals[name]) {
      const prefix = "@bokehjs/"
      if (name.slice(0, prefix.length) === prefix)
        name = name.slice(prefix.length)
    }

    const alias = aliases[name]
    if (alias != null)
      return alias;

    const trailing = name.length > 0 && name[name.length-1] === "/";
    const index = aliases[name + (trailing ? "" : "/") + "index"];
    if (index != null)
      return index;

    return name;
  }

  const require = function(name) {
    let mod = cache[name];
    if (!mod) {
      const id = normalize(name);

      mod = cache[id];
      if (!mod) {
        if (!modules[id]) {
          if (externals[id] === false || (externals[id] == true && parent_require)) {
            try {
              mod = {exports: externals[id] ? parent_require(id) : {}};
              cache[id] = cache[name] = mod;
              return mod.exports;
            } catch (e) {}
          }

          const err = new Error("Cannot find module '" + name + "'");
          err.code = 'MODULE_NOT_FOUND';
          throw err;
        }

        mod = {exports: {}};
        cache[id] = cache[name] = mod;

        function __esModule() {
          Object.defineProperty(mod.exports, "__esModule", {value: true});
        }

        function __esExport(name, value) {
          Object.defineProperty(mod.exports, name, {
            enumerable: true, get: function () { return value; }
          });
        }

        modules[id].call(mod.exports, require, mod, mod.exports, __esModule, __esExport);
      } else {
        cache[name] = mod;
      }
    }

    return mod.exports;
  }
  require.resolve = function(name) {
    return ""
  }

  const main = require(entry);
  main.require = require;

  if (typeof Proxy !== "undefined") {
    // allow Bokeh.loader["@bokehjs/module/name"] syntax
    main.loader = new Proxy({}, {
      get: function(_obj, module) {
        return require(module);
      }
    });
  }

  main.register_plugin = function(plugin_modules, plugin_entry, plugin_aliases, plugin_externals) {
    if (plugin_aliases === undefined) plugin_aliases = {};
    if (plugin_externals === undefined) plugin_externals = {};

    for (let name in plugin_modules) {
      modules[name] = plugin_modules[name];
    }

    for (let name in plugin_aliases) {
      aliases[name] = plugin_aliases[name];
    }

    for (let name in plugin_externals) {
      externals[name] = plugin_externals[name];
    }

    const plugin = require(plugin_entry);

    for (let name in plugin) {
      main[name] = plugin[name];
    }

    return plugin;
  }

  return main;
})
([
/* main.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(2) /* ./index */, exports);
    // TODO: remove this when models are split up from core
    require(91) /* ./models/main */;
},
/* tslib/tslib.es6.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.__extends = __extends;
    exports.__rest = __rest;
    exports.__decorate = __decorate;
    exports.__param = __param;
    exports.__esDecorate = __esDecorate;
    exports.__runInitializers = __runInitializers;
    exports.__propKey = __propKey;
    exports.__setFunctionName = __setFunctionName;
    exports.__metadata = __metadata;
    exports.__awaiter = __awaiter;
    exports.__generator = __generator;
    exports.__exportStar = __exportStar;
    exports.__values = __values;
    exports.__read = __read;
    exports.__spread = __spread;
    exports.__spreadArrays = __spreadArrays;
    exports.__spreadArray = __spreadArray;
    exports.__await = __await;
    exports.__asyncGenerator = __asyncGenerator;
    exports.__asyncDelegator = __asyncDelegator;
    exports.__asyncValues = __asyncValues;
    exports.__makeTemplateObject = __makeTemplateObject;
    exports.__importStar = __importStar;
    exports.__importDefault = __importDefault;
    exports.__classPrivateFieldGet = __classPrivateFieldGet;
    exports.__classPrivateFieldSet = __classPrivateFieldSet;
    exports.__classPrivateFieldIn = __classPrivateFieldIn;
    exports.__addDisposableResource = __addDisposableResource;
    exports.__disposeResources = __disposeResources;
    exports.__rewriteRelativeImportExtension = __rewriteRelativeImportExtension;
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) {
                for (var p in b)
                    if (Object.prototype.hasOwnProperty.call(b, p))
                        d[p] = b[p];
            };
        return extendStatics(d, b);
    };
    function __extends(d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    }
    var __assign = function () {
        exports.__assign = Object.assign || function __assign(t) {
            for (var s, i = 1, n = arguments.length; i < n; i++) {
                s = arguments[i];
                for (var p in s)
                    if (Object.prototype.hasOwnProperty.call(s, p))
                        t[p] = s[p];
            }
            return t;
        };
        return exports.__assign.apply(this, arguments);
    };
    exports.__assign = __assign;
    function __rest(s, e) {
        var t = {};
        for (var p in s)
            if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
                t[p] = s[p];
        if (s != null && typeof Object.getOwnPropertySymbols === "function")
            for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
                if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                    t[p[i]] = s[p[i]];
            }
        return t;
    }
    function __decorate(decorators, target, key, desc) {
        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
        if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
            r = Reflect.decorate(decorators, target, key, desc);
        else
            for (var i = decorators.length - 1; i >= 0; i--)
                if (d = decorators[i])
                    r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
        return c > 3 && r && Object.defineProperty(target, key, r), r;
    }
    function __param(paramIndex, decorator) {
        return function (target, key) { decorator(target, key, paramIndex); };
    }
    function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
        function accept(f) {
            if (f !== void 0 && typeof f !== "function")
                throw new TypeError("Function expected");
            return f;
        }
        var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
        var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
        var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
        var _, done = false;
        for (var i = decorators.length - 1; i >= 0; i--) {
            var context = {};
            for (var p in contextIn)
                context[p] = p === "access" ? {} : contextIn[p];
            for (var p in contextIn.access)
                context.access[p] = contextIn.access[p];
            context.addInitializer = function (f) {
                if (done)
                    throw new TypeError("Cannot add initializers after decoration has completed");
                extraInitializers.push(accept(f || null));
            };
            var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
            if (kind === "accessor") {
                if (result === void 0)
                    continue;
                if (result === null || typeof result !== "object")
                    throw new TypeError("Object expected");
                if (_ = accept(result.get))
                    descriptor.get = _;
                if (_ = accept(result.set))
                    descriptor.set = _;
                if (_ = accept(result.init))
                    initializers.unshift(_);
            }
            else if (_ = accept(result)) {
                if (kind === "field")
                    initializers.unshift(_);
                else
                    descriptor[key] = _;
            }
        }
        if (target)
            Object.defineProperty(target, contextIn.name, descriptor);
        done = true;
    }
    ;
    function __runInitializers(thisArg, initializers, value) {
        var useValue = arguments.length > 2;
        for (var i = 0; i < initializers.length; i++) {
            value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
        }
        return useValue ? value : void 0;
    }
    ;
    function __propKey(x) {
        return typeof x === "symbol" ? x : "".concat(x);
    }
    ;
    function __setFunctionName(f, name, prefix) {
        if (typeof name === "symbol")
            name = name.description ? "[".concat(name.description, "]") : "";
        return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
    }
    ;
    function __metadata(metadataKey, metadataValue) {
        if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
            return Reflect.metadata(metadataKey, metadataValue);
    }
    function __awaiter(thisArg, _arguments, P, generator) {
        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
        return new (P || (P = Promise))(function (resolve, reject) {
            function fulfilled(value) {
                try {
                    step(generator.next(value));
                }
                catch (e) {
                    reject(e);
                }
            }
            function rejected(value) {
                try {
                    step(generator["throw"](value));
                }
                catch (e) {
                    reject(e);
                }
            }
            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
            step((generator = generator.apply(thisArg, _arguments || [])).next());
        });
    }
    function __generator(thisArg, body) {
        var _ = { label: 0, sent: function () {
                if (t[0] & 1)
                    throw t[1];
                return t[1];
            }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
        return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
        function verb(n) { return function (v) { return step([n, v]); }; }
        function step(op) {
            if (f)
                throw new TypeError("Generator is already executing.");
            while (g && (g = 0, op[0] && (_ = 0)), _)
                try {
                    if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
                        return t;
                    if (y = 0, t)
                        op = [op[0] & 2, t.value];
                    switch (op[0]) {
                        case 0:
                        case 1:
                            t = op;
                            break;
                        case 4:
                            _.label++;
                            return { value: op[1], done: false };
                        case 5:
                            _.label++;
                            y = op[1];
                            op = [0];
                            continue;
                        case 7:
                            op = _.ops.pop();
                            _.trys.pop();
                            continue;
                        default:
                            if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                                _ = 0;
                                continue;
                            }
                            if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
                                _.label = op[1];
                                break;
                            }
                            if (op[0] === 6 && _.label < t[1]) {
                                _.label = t[1];
                                t = op;
                                break;
                            }
                            if (t && _.label < t[2]) {
                                _.label = t[2];
                                _.ops.push(op);
                                break;
                            }
                            if (t[2])
                                _.ops.pop();
                            _.trys.pop();
                            continue;
                    }
                    op = body.call(thisArg, _);
                }
                catch (e) {
                    op = [6, e];
                    y = 0;
                }
                finally {
                    f = t = 0;
                }
            if (op[0] & 5)
                throw op[1];
            return { value: op[0] ? op[1] : void 0, done: true };
        }
    }
    exports.__createBinding = Object.create ? (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        var desc = Object.getOwnPropertyDescriptor(m, k);
        if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
            desc = { enumerable: true, get: function () { return m[k]; } };
        }
        Object.defineProperty(o, k2, desc);
    }) : (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        o[k2] = m[k];
    });
    function __exportStar(m, o) {
        for (var p in m)
            if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
                (0, exports.__createBinding)(o, m, p);
    }
    function __values(o) {
        var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
        if (m)
            return m.call(o);
        if (o && typeof o.length === "number")
            return {
                next: function () {
                    if (o && i >= o.length)
                        o = void 0;
                    return { value: o && o[i++], done: !o };
                }
            };
        throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
    }
    function __read(o, n) {
        var m = typeof Symbol === "function" && o[Symbol.iterator];
        if (!m)
            return o;
        var i = m.call(o), r, ar = [], e;
        try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
                ar.push(r.value);
        }
        catch (error) {
            e = { error: error };
        }
        finally {
            try {
                if (r && !r.done && (m = i["return"]))
                    m.call(i);
            }
            finally {
                if (e)
                    throw e.error;
            }
        }
        return ar;
    }
    /** @deprecated */
    function __spread() {
        for (var ar = [], i = 0; i < arguments.length; i++)
            ar = ar.concat(__read(arguments[i]));
        return ar;
    }
    /** @deprecated */
    function __spreadArrays() {
        for (var s = 0, i = 0, il = arguments.length; i < il; i++)
            s += arguments[i].length;
        for (var r = Array(s), k = 0, i = 0; i < il; i++)
            for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
                r[k] = a[j];
        return r;
    }
    function __spreadArray(to, from, pack) {
        if (pack || arguments.length === 2)
            for (var i = 0, l = from.length, ar; i < l; i++) {
                if (ar || !(i in from)) {
                    if (!ar)
                        ar = Array.prototype.slice.call(from, 0, i);
                    ar[i] = from[i];
                }
            }
        return to.concat(ar || Array.prototype.slice.call(from));
    }
    function __await(v) {
        return this instanceof __await ? (this.v = v, this) : new __await(v);
    }
    function __asyncGenerator(thisArg, _arguments, generator) {
        if (!Symbol.asyncIterator)
            throw new TypeError("Symbol.asyncIterator is not defined.");
        var g = generator.apply(thisArg, _arguments || []), i, q = [];
        return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
        function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
        function verb(n, f) {
            if (g[n]) {
                i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); };
                if (f)
                    i[n] = f(i[n]);
            }
        }
        function resume(n, v) {
            try {
                step(g[n](v));
            }
            catch (e) {
                settle(q[0][3], e);
            }
        }
        function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
        function fulfill(value) { resume("next", value); }
        function reject(value) { resume("throw", value); }
        function settle(f, v) {
            if (f(v), q.shift(), q.length)
                resume(q[0][0], q[0][1]);
        }
    }
    function __asyncDelegator(o) {
        var i, p;
        return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
        function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
    }
    function __asyncValues(o) {
        if (!Symbol.asyncIterator)
            throw new TypeError("Symbol.asyncIterator is not defined.");
        var m = o[Symbol.asyncIterator], i;
        return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
        function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
        function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
    }
    function __makeTemplateObject(cooked, raw) {
        if (Object.defineProperty) {
            Object.defineProperty(cooked, "raw", { value: raw });
        }
        else {
            cooked.raw = raw;
        }
        return cooked;
    }
    ;
    var __setModuleDefault = Object.create ? (function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function (o, v) {
        o["default"] = v;
    };
    var ownKeys = function (o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o)
                if (Object.prototype.hasOwnProperty.call(o, k))
                    ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    function __importStar(mod) {
        if (mod && mod.__esModule)
            return mod;
        var result = {};
        if (mod != null)
            for (var k = ownKeys(mod), i = 0; i < k.length; i++)
                if (k[i] !== "default")
                    (0, exports.__createBinding)(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    }
    function __importDefault(mod) {
        return (mod && mod.__esModule) ? mod : { default: mod };
    }
    function __classPrivateFieldGet(receiver, state, kind, f) {
        if (kind === "a" && !f)
            throw new TypeError("Private accessor was defined without a getter");
        if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
            throw new TypeError("Cannot read private member from an object whose class did not declare it");
        return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
    }
    function __classPrivateFieldSet(receiver, state, value, kind, f) {
        if (kind === "m")
            throw new TypeError("Private method is not writable");
        if (kind === "a" && !f)
            throw new TypeError("Private accessor was defined without a setter");
        if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
            throw new TypeError("Cannot write private member to an object whose class did not declare it");
        return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
    }
    function __classPrivateFieldIn(state, receiver) {
        if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function"))
            throw new TypeError("Cannot use 'in' operator on non-object");
        return typeof state === "function" ? receiver === state : state.has(receiver);
    }
    function __addDisposableResource(env, value, async) {
        if (value !== null && value !== void 0) {
            if (typeof value !== "object" && typeof value !== "function")
                throw new TypeError("Object expected.");
            var dispose, inner;
            if (async) {
                if (!Symbol.asyncDispose)
                    throw new TypeError("Symbol.asyncDispose is not defined.");
                dispose = value[Symbol.asyncDispose];
            }
            if (dispose === void 0) {
                if (!Symbol.dispose)
                    throw new TypeError("Symbol.dispose is not defined.");
                dispose = value[Symbol.dispose];
                if (async)
                    inner = dispose;
            }
            if (typeof dispose !== "function")
                throw new TypeError("Object not disposable.");
            if (inner)
                dispose = function () {
                    try {
                        inner.call(this);
                    }
                    catch (e) {
                        return Promise.reject(e);
                    }
                };
            env.stack.push({ value: value, dispose: dispose, async: async });
        }
        else if (async) {
            env.stack.push({ async: true });
        }
        return value;
    }
    var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
        var e = new Error(message);
        return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    };
    function __disposeResources(env) {
        function fail(e) {
            env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
            env.hasError = true;
        }
        var r, s = 0;
        function next() {
            while (r = env.stack.pop()) {
                try {
                    if (!r.async && s === 1)
                        return s = 0, env.stack.push(r), Promise.resolve().then(next);
                    if (r.dispose) {
                        var result = r.dispose.call(r.value);
                        if (r.async)
                            return s |= 2, Promise.resolve(result).then(next, function (e) { fail(e); return next(); });
                    }
                    else
                        s |= 1;
                }
                catch (e) {
                    fail(e);
                }
            }
            if (s === 1)
                return env.hasError ? Promise.reject(env.error) : Promise.resolve();
            if (env.hasError)
                throw env.error;
        }
        return next();
    }
    function __rewriteRelativeImportExtension(path, preserveJsx) {
        if (typeof path === "string" && /^\.\.?\//.test(path)) {
            return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
                return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
            });
        }
        return path;
    }
    exports.default = {
        __extends: __extends,
        __assign: exports.__assign,
        __rest: __rest,
        __decorate: __decorate,
        __param: __param,
        __esDecorate: __esDecorate,
        __runInitializers: __runInitializers,
        __propKey: __propKey,
        __setFunctionName: __setFunctionName,
        __metadata: __metadata,
        __awaiter: __awaiter,
        __generator: __generator,
        __createBinding: exports.__createBinding,
        __exportStar: __exportStar,
        __values: __values,
        __read: __read,
        __spread: __spread,
        __spreadArrays: __spreadArrays,
        __spreadArray: __spreadArray,
        __await: __await,
        __asyncGenerator: __asyncGenerator,
        __asyncDelegator: __asyncDelegator,
        __asyncValues: __asyncValues,
        __makeTemplateObject: __makeTemplateObject,
        __importStar: __importStar,
        __importDefault: __importDefault,
        __classPrivateFieldGet: __classPrivateFieldGet,
        __classPrivateFieldSet: __classPrivateFieldSet,
        __classPrivateFieldIn: __classPrivateFieldIn,
        __addDisposableResource: __addDisposableResource,
        __disposeResources: __disposeResources,
        __rewriteRelativeImportExtension: __rewriteRelativeImportExtension,
    };
},
/* index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    var version_1 = require(3) /* ./version */;
    __esExport("version", version_1.version);
    var embed_1 = require(4) /* ./embed */;
    __esExport("index", embed_1.index);
    exports.embed = tslib_1.__importStar(require(4) /* ./embed */);
    exports.protocol = tslib_1.__importStar(require(89) /* ./protocol */);
    var logging_1 = require(11) /* ./core/logging */;
    __esExport("logger", logging_1.logger);
    __esExport("set_log_level", logging_1.set_log_level);
    var settings_1 = require(30) /* ./core/settings */;
    __esExport("settings", settings_1.settings);
    var base_1 = require(7) /* ./base */;
    __esExport("Models", base_1.Models);
    var document_1 = require(5) /* ./document */;
    __esExport("documents", document_1.documents);
    var safely_1 = require(90) /* ./safely */;
    __esExport("safely", safely_1.safely);
},
/* version.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.version = "3.10.0";
},
/* embed/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.embed_item = embed_item;
    exports.embed_items = embed_items;
    const document_1 = require(5) /* ../document */;
    const settings_1 = require(30) /* ../core/settings */;
    const logging_1 = require(11) /* ../core/logging */;
    const string_1 = require(41) /* ../core/util/string */;
    const object_1 = require(9) /* ../core/util/object */;
    const types_1 = require(8) /* ../core/util/types */;
    const defer_1 = require(18) /* ../core/util/defer */;
    const standalone_1 = require(81) /* ./standalone */;
    const server_1 = require(82) /* ./server */;
    const dom_1 = require(87) /* ./dom */;
    var standalone_2 = require(81) /* ./standalone */;
    __esExport("add_document_standalone", standalone_2.add_document_standalone);
    __esExport("index", standalone_2.index);
    var server_2 = require(82) /* ./server */;
    __esExport("add_document_from_session", server_2.add_document_from_session);
    var notebook_1 = require(88) /* ./notebook */;
    __esExport("embed_items_notebook", notebook_1.embed_items_notebook);
    __esExport("kernels", notebook_1.kernels);
    async function embed_item(item, target) {
        const docs_json = {};
        const doc_id = (0, string_1.uuid4)();
        docs_json[doc_id] = item.doc;
        if (target == null) {
            target = item.target_id;
        }
        const roots = { [item.root_id]: target };
        const render_item = { roots, root_ids: [item.root_id], docid: doc_id };
        await (0, defer_1.defer)();
        const [views] = await _embed_items(docs_json, [render_item]);
        return views;
    }
    // TODO (bev) this is currently clunky. Standalone embeds only provide
    // the first two args, whereas server provide the app_app, and *may* prove and
    // absolute_url as well if non-relative links are needed for resources. This function
    // should probably be split in to two pieces to reflect the different usage patterns
    async function embed_items(docs_json, render_items, app_path, absolute_url) {
        await (0, defer_1.defer)();
        return _embed_items(docs_json, render_items, app_path, absolute_url);
    }
    async function _embed_items(docs_json, render_items, app_path, absolute_url) {
        if ((0, types_1.isString)(docs_json)) {
            docs_json = JSON.parse((0, string_1.unescape)(docs_json));
        }
        const docs = {};
        for (const [docid, doc_json] of (0, object_1.entries)(docs_json)) {
            docs[docid] = document_1.Document.from_json(doc_json);
        }
        const views = [];
        for (const item of render_items) {
            const element = (0, dom_1._resolve_element)(item);
            const roots = (0, dom_1._resolve_root_elements)(item);
            if (item.docid != null) {
                views.push(await (0, standalone_1.add_document_standalone)(docs[item.docid], element, roots, item.use_for_title));
            }
            else if (item.token != null) {
                const websocket_url = (0, server_1._get_ws_url)(app_path, absolute_url);
                logging_1.logger.debug(`embed: computed ws url: ${websocket_url}`);
                try {
                    views.push(await (0, server_1.add_document_from_session)(websocket_url, item.token, element, roots, item.use_for_title));
                    console.log("Bokeh items were rendered successfully");
                }
                catch (error) {
                    if (settings_1.settings.dev) {
                        throw error;
                    }
                    else {
                        console.error("Error rendering Bokeh items:", error);
                    }
                }
            }
            else {
                throw new Error("Error rendering Bokeh items: either 'docid' or 'token' was expected.");
            }
        }
        return views;
    }
},
/* document/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(6) /* ./document */, exports);
    tslib_1.__exportStar(require(42) /* ./events */, exports);
    const base_1 = require(7) /* ../base */;
    const ConfigModels = tslib_1.__importStar(require(53) /* ./config */);
    (0, base_1.register_models)(ConfigModels);
},
/* document/document.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const base_1 = require(7) /* ../base */;
    const version_1 = require(3) /* ../version */;
    const logging_1 = require(11) /* ../core/logging */;
    const has_props_1 = require(16) /* ../core/has_props */;
    const resolvers_1 = require(47) /* ../core/resolvers */;
    const serialization_1 = require(33) /* ../core/serialization */;
    const deserializer_1 = require(48) /* ../core/serialization/deserializer */;
    const version_2 = require(50) /* ../core/util/version */;
    const signaling_1 = require(17) /* ../core/signaling */;
    const types_1 = require(8) /* ../core/util/types */;
    const eq_1 = require(27) /* ../core/util/eq */;
    const array_1 = require(10) /* ../core/util/array */;
    const object_1 = require(9) /* ../core/util/object */;
    const sets = tslib_1.__importStar(require(45) /* ../core/util/set */);
    const callbacks_1 = require(51) /* ../core/util/callbacks */;
    const assert_1 = require(13) /* ../core/util/assert */;
    const model_1 = require(52) /* ../model */;
    const config_1 = require(53) /* ./config */;
    const defs_1 = require(79) /* ./defs */;
    const bokeh_events_1 = require(80) /* ../core/bokeh_events */;
    const bokeh_events_2 = require(80) /* ../core/bokeh_events */;
    const events_1 = require(42) /* ./events */;
    deserializer_1.Deserializer.register("model", defs_1.decode_def);
    // Dispatches events to the subscribed models
    class EventManager {
        document;
        subscribed_models = new Set();
        constructor(document) {
            this.document = document;
        }
        send_event(bokeh_event) {
            if (bokeh_event.publish) {
                const event = new events_1.MessageSentEvent(this.document, "bokeh_event", bokeh_event);
                this.document._trigger_on_change(event);
            }
            this.document._trigger_on_event(bokeh_event);
        }
        trigger(event) {
            for (const model of this.subscribed_models) {
                if (event.origin != null && event.origin != model) {
                    continue;
                }
                model._process_event(event);
            }
        }
    }
    exports.EventManager = EventManager;
    exports.documents = [];
    exports.DEFAULT_TITLE = "Bokeh Application";
    // This class should match the API of the Python Document class
    // as much as possible.
    class Document {
        /** @experimental */
        views_manager;
        event_manager;
        idle;
        resolver;
        _init_timestamp;
        _title;
        _roots;
        _all_models;
        _new_models;
        _all_models_freeze_count;
        _callbacks;
        _document_callbacks;
        _message_callbacks;
        _idle_roots;
        _interactive_timestamp;
        _interactive_plot;
        _interactive_finalize;
        _recompute_timeout;
        _config;
        get config() {
            (0, assert_1.assert)(this._config != null, "configuration is missing");
            return this._config;
        }
        set config(config) {
            this.freeze_all_models(() => this._config = config);
        }
        constructor(options = {}) {
            exports.documents.push(this);
            this._init_timestamp = Date.now();
            this.resolver = options.resolver ?? new resolvers_1.ModelResolver(base_1.default_resolver);
            this._title = exports.DEFAULT_TITLE;
            this._roots = [];
            this._all_models = new Map();
            this._new_models = new Set();
            this._all_models_freeze_count = 0;
            this._callbacks = new Map();
            this._document_callbacks = new Map();
            this._message_callbacks = new Map();
            this.event_manager = new EventManager(this);
            this.idle = new signaling_1.Signal0(this, "idle");
            this._idle_roots = new WeakSet();
            this._interactive_timestamp = null;
            this._interactive_plot = null;
            this._recompute_timeout = options.recompute_timeout ?? 30000; /* 30s */
            if (options.roots != null) {
                this._add_roots(...options.roots);
            }
            this.on_message("bokeh_event", (event) => {
                (0, assert_1.assert)(event instanceof bokeh_events_1.ModelEvent);
                this.event_manager.trigger(event);
            });
            this.config = new config_1.DocumentConfig();
        }
        [eq_1.equals](that, _cmp) {
            return this == that;
        }
        get all_models() {
            return new Set(this._all_models.values());
        }
        get is_idle() {
            // TODO: models without views, e.g. data models
            for (const root of this.roots()) {
                if (!this._idle_roots.has(root)) {
                    return false;
                }
            }
            return true;
        }
        _notified_idle = false;
        notify_idle(model) {
            if (this._notified_idle || !this.roots().includes(model)) {
                return;
            }
            this._idle_roots.add(model);
            if (this.is_idle) {
                logging_1.logger.info(`document idle at ${Date.now() - this._init_timestamp} ms`);
                this.event_manager.send_event(new bokeh_events_2.DocumentReady());
                this.idle.emit();
                this._notified_idle = true;
            }
        }
        clear({ sync } = {}) {
            this._push_all_models_freeze();
            try {
                while (this._roots.length > 0) {
                    this.remove_root(this._roots[0], { sync });
                }
                this._config = undefined;
            }
            finally {
                this._pop_all_models_freeze();
            }
        }
        interactive_start(plot, finalize = null) {
            if (this._interactive_plot == null) {
                this._interactive_plot = plot;
                this._interactive_plot.trigger_event(new bokeh_events_2.LODStart());
            }
            this._interactive_finalize = finalize;
            this._interactive_timestamp = Date.now();
        }
        interactive_stop() {
            if (this._interactive_plot != null) {
                this._interactive_plot.trigger_event(new bokeh_events_2.LODEnd());
                if (this._interactive_finalize != null) {
                    this._interactive_finalize();
                }
            }
            this._interactive_plot = null;
            this._interactive_timestamp = null;
            this._interactive_finalize = null;
        }
        interactive_duration() {
            if (this._interactive_timestamp == null) {
                return -1;
            }
            else {
                return Date.now() - this._interactive_timestamp;
            }
        }
        destructively_move(dest_doc) {
            if (dest_doc === this) {
                throw new Error("Attempted to overwrite a document with itself");
            }
            // Don't synchronize root removal with the server, because we are rebuilding from
            // scratch and server has the complete state. However, events will be distributed
            // internally within bokehjs, because UI refresh depends on this (in standalone
            // embedding and its derivatives).
            dest_doc.clear({ sync: false });
            // we have to remove ALL roots before adding any
            // to the new doc or else models referenced from multiple
            // roots could be in both docs at once, which isn't allowed.
            const { config } = this;
            const roots = (0, array_1.copy)(this._roots);
            this.clear({ sync: false });
            for (const root of [...roots, config]) {
                if (root.document != null) {
                    throw new Error(`Somehow we didn't detach ${root}`);
                }
            }
            if (this._all_models.size != 0) {
                throw new Error(`this._all_models still had stuff in it: ${this._all_models}`);
            }
            dest_doc.config = config;
            for (const root of roots) {
                dest_doc.add_root(root);
            }
            dest_doc.set_title(this._title);
        }
        _hold_models_freeze = false;
        freeze_all_models(fn) {
            this._push_all_models_freeze();
            try {
                fn();
            }
            finally {
                this._pop_all_models_freeze();
            }
        }
        _push_all_models_freeze() {
            if (this._hold_models_freeze) {
                return;
            }
            this._all_models_freeze_count += 1;
        }
        _pop_all_models_freeze() {
            if (this._hold_models_freeze) {
                return;
            }
            this._all_models_freeze_count -= 1;
            if (this._all_models_freeze_count === 0) {
                this._recompute_all_models();
            }
        }
        _recompute_timer = null;
        _cancel_recompute_all_models() {
            if (this._recompute_timer != null) {
                clearTimeout(this._recompute_timer);
                this._recompute_timer = null;
            }
        }
        _schedule_recompute_all_models() {
            const timeout = this._recompute_timeout;
            if (isNaN(timeout) || timeout <= 0) {
                this._recompute_all_models();
            }
            else if (isFinite(timeout) && this._recompute_timer == null) {
                // Throttle, don't debounce: an already pending recomputation is left
                // alone, so that `timeout` bounds how long unreachable models can linger
                // in `_all_models`. Restarting the timer on every update would defer the
                // recomputation indefinitely in a document that is updated more often
                // than `timeout`, e.g. any server application with a periodic callback.
                this._recompute_timer = setTimeout(() => {
                    this._recompute_all_models();
                }, timeout);
            }
        }
        _recompute_all_models() {
            this._cancel_recompute_all_models();
            let new_all_models_set = new Set();
            for (const r of this.all_roots) {
                new_all_models_set = sets.union(new_all_models_set, r.references());
            }
            const old_all_models_set = new Set(this._all_models.values());
            const to_detach = sets.difference(old_all_models_set, new_all_models_set);
            const to_attach = sets.difference(new_all_models_set, old_all_models_set);
            const recomputed = new Map();
            for (const model of new_all_models_set) {
                recomputed.set(model.id, model);
            }
            for (const d of to_detach) {
                d.detach_document();
            }
            for (const model of to_attach) {
                model.attach_document(this);
                this._new_models.add(model);
            }
            this._all_models = recomputed;
        }
        partially_update_all_models(value) {
            const refs = new Set();
            has_props_1.HasProps._value_record_references(value, refs, { recursive: false });
            for (const ref of refs) {
                if (!this._all_models.has(ref.id)) {
                    ref.attach_document(this);
                    this._new_models.add(ref);
                    this._all_models.set(ref.id, ref);
                }
            }
            this._schedule_recompute_all_models();
        }
        get all_roots() {
            const all_roots = [...this._roots];
            if (this._config != null) {
                all_roots.push(this._config);
            }
            return all_roots;
        }
        roots() {
            return this._roots;
        }
        _add_roots(...models) {
            models = models.filter((model) => !this._roots.includes(model));
            if (models.length == 0) {
                return false;
            }
            this._push_all_models_freeze();
            try {
                this._roots.push(...models);
            }
            finally {
                this._pop_all_models_freeze();
            }
            return true;
        }
        _remove_root(model) {
            const i = this._roots.indexOf(model);
            if (i < 0) {
                return false;
            }
            this._push_all_models_freeze();
            try {
                this._roots.splice(i, 1);
            }
            finally {
                this._pop_all_models_freeze();
            }
            return true;
        }
        _set_title(title) {
            const new_title = title != this._title;
            if (new_title) {
                this._title = title;
            }
            return new_title;
        }
        add_root(model, { sync } = {}) {
            if (this._add_roots(model)) {
                const event = new events_1.RootAddedEvent(this, model);
                event.sync = sync ?? true;
                this._trigger_on_change(event);
            }
        }
        remove_root(model, { sync } = {}) {
            if (this._remove_root(model)) {
                const event = new events_1.RootRemovedEvent(this, model);
                event.sync = sync ?? true;
                this._trigger_on_change(event);
            }
        }
        set_title(title, { sync } = {}) {
            if (this._set_title(title)) {
                const event = new events_1.TitleChangedEvent(this, title);
                event.sync = sync ?? true;
                this._trigger_on_change(event);
            }
        }
        title() {
            return this._title;
        }
        get_model_by_id(model_id) {
            return this._all_models.get(model_id) ?? null;
        }
        get_model_by_name(name) {
            const found = [];
            for (const model of this._all_models.values()) {
                if (model instanceof model_1.Model && model.name == name) {
                    found.push(model);
                }
            }
            switch (found.length) {
                case 0:
                    return null;
                case 1:
                    return found[0];
                default:
                    throw new Error(`Multiple models are named '${name}'`);
            }
        }
        on_message(msg_type, callback) {
            const message_callbacks = this._message_callbacks.get(msg_type);
            if (message_callbacks == null) {
                this._message_callbacks.set(msg_type, new Set([callback]));
            }
            else {
                message_callbacks.add(callback);
            }
        }
        remove_on_message(msg_type, callback) {
            this._message_callbacks.get(msg_type)?.delete(callback);
        }
        _trigger_on_message(msg_type, msg_data) {
            const message_callbacks = this._message_callbacks.get(msg_type);
            if (message_callbacks != null) {
                for (const cb of message_callbacks) {
                    cb(msg_data);
                }
            }
        }
        on_change(callback, allow_batches = false) {
            if (!this._callbacks.has(callback)) {
                this._callbacks.set(callback, allow_batches);
            }
        }
        remove_on_change(callback) {
            this._callbacks.delete(callback);
        }
        _trigger_on_change(event) {
            for (const [callback, allow_batches] of this._callbacks) {
                if (!allow_batches && event instanceof events_1.DocumentEventBatch) {
                    for (const ev of event.events) {
                        callback(ev);
                    }
                }
                else {
                    callback(event); // TODO
                }
            }
        }
        _trigger_on_event(event) {
            const callbacks = this._document_callbacks.get(event.event_name);
            if (callbacks != null) {
                for (const callback of callbacks) {
                    void (0, callbacks_1.execute)(callback, this, event);
                }
            }
        }
        on_event(event, ...callbacks) {
            const name = (0, types_1.isString)(event) ? event : event.prototype.event_name;
            const existing = this._document_callbacks.get(name) ?? [];
            const added = callbacks;
            this._document_callbacks.set(name, [...existing, ...added]);
        }
        to_json_string(include_defaults = true) {
            return JSON.stringify(this.to_json(include_defaults));
        }
        to_json(include_defaults = true) {
            const serializer = new serialization_1.Serializer({ include_defaults });
            const config = serializer.encode(this.config);
            const roots = serializer.encode(this._roots);
            return {
                version: version_1.version,
                title: this._title,
                config,
                roots,
            };
        }
        static from_json_string(s, events) {
            const json = JSON.parse(s);
            return Document.from_json(json, events);
        }
        static _handle_version(json) {
            if (json.version == null) {
                logging_1.logger.warn("'version' field is missing");
            }
            const py_version = json.version ?? "0.0.0";
            const py_ver = version_2.Version.from(py_version);
            const js_ver = version_2.Version.from(version_1.version);
            const message = `new document using Bokeh ${py_version} and BokehJS ${version_1.version}`;
            if ((0, eq_1.is_equal)(py_ver, js_ver)) {
                logging_1.logger.debug(message);
            }
            else {
                logging_1.logger.warn(`Bokeh/BokehJS version mismatch: ${message}`);
            }
        }
        static from_json(doc_json, events, buffers = new Map()) {
            logging_1.logger.debug("Creating Document from JSON");
            Document._handle_version(doc_json);
            const resolver = new resolvers_1.ModelResolver(base_1.default_resolver);
            if (doc_json.defs != null) {
                const deserializer = new deserializer_1.Deserializer(resolver);
                deserializer.decode(doc_json.defs, buffers);
            }
            const doc = new Document({ resolver });
            doc._push_all_models_freeze();
            const listener = (event) => events?.push(event);
            doc.on_change(listener, true);
            const deserializer = new deserializer_1.Deserializer(resolver, doc._all_models, (obj) => obj.attach_document(doc));
            const config = deserializer.decode(doc_json.config, buffers);
            (0, assert_1.assert)(config instanceof config_1.DocumentConfig || config == null);
            if (config != null) {
                doc.config = config;
            }
            const roots = deserializer.decode(doc_json.roots, buffers);
            const callbacks = (() => {
                if (doc_json.callbacks != null) {
                    return deserializer.decode(doc_json.callbacks, buffers);
                }
                else {
                    return {};
                }
            })();
            doc.remove_on_change(listener);
            for (const [event, event_callbacks] of (0, object_1.entries)(callbacks)) {
                doc.on_event(event, ...event_callbacks);
            }
            for (const root of roots) {
                doc.add_root(root);
            }
            if (doc_json.title != null) {
                doc.set_title(doc_json.title);
            }
            doc._pop_all_models_freeze();
            return doc;
        }
        replace_with_json(json, buffers = new Map()) {
            const replacement = Document.from_json(json, undefined, buffers);
            replacement.destructively_move(this);
        }
        create_json_patch(events) {
            for (const event of events) {
                if (event.document != this) {
                    throw new Error("Cannot create a patch using events from a different document");
                }
            }
            const references = new Map();
            for (const model of this._all_models.values()) {
                if (!this._new_models.has(model)) {
                    references.set(model, model.ref());
                }
            }
            const serializer = new serialization_1.Serializer({ references, binary: true });
            const patch = { events: serializer.encode(events) };
            this._new_models.clear();
            return patch;
        }
        apply_json_patch(patch, buffers = new Map()) {
            const { _hold_models_freeze } = this;
            this._hold_models_freeze = true;
            try {
                this._apply_json_patch(patch, buffers);
            }
            finally {
                this._hold_models_freeze = _hold_models_freeze;
            }
            this._schedule_recompute_all_models();
        }
        _apply_json_patch(patch, buffers = new Map()) {
            const finalize = (obj) => {
                obj.attach_document(this);
                this._new_models.add(obj);
                this._all_models.set(obj.id, obj);
            };
            const deserializer = new deserializer_1.Deserializer(this.resolver, this._all_models, finalize);
            const events = deserializer.decode(patch.events, buffers);
            for (const event of events) {
                switch (event.kind) {
                    case "MessageSent": {
                        const { msg_type, msg_data } = event;
                        this._trigger_on_message(msg_type, msg_data);
                        break;
                    }
                    case "ModelChanged": {
                        const { model, attr, new: value } = event;
                        model.setv({ [attr]: value }, { sync: false });
                        break;
                    }
                    case "ColumnDataChanged": {
                        const { model, attr, data, cols } = event;
                        if (cols != null) {
                            const new_data = (0, object_1.dict)(data);
                            const current_data = (0, object_1.dict)(model.property(attr).get_value());
                            for (const [name, column] of current_data) {
                                if (!new_data.has(name)) {
                                    new_data.set(name, column);
                                }
                            }
                        }
                        model.setv({ data }, { sync: false, check_eq: false });
                        break;
                    }
                    case "ColumnsStreamed": {
                        const { model, attr, data, rollover } = event;
                        const prop = model.property(attr);
                        model.stream_to(prop, data, rollover, { sync: false });
                        break;
                    }
                    case "ColumnsPatched": {
                        const { model, attr, patches } = event;
                        const prop = model.property(attr);
                        model.patch_to(prop, patches, { sync: false });
                        break;
                    }
                    case "RootAdded": {
                        this.add_root(event.model, { sync: false });
                        break;
                    }
                    case "RootRemoved": {
                        this.remove_root(event.model, { sync: false });
                        break;
                    }
                    case "TitleChanged": {
                        this.set_title(event.title, { sync: false });
                        break;
                    }
                    default: {
                        throw new Error(`unknown patch event type '${event.kind}'`); // XXX
                    }
                }
            }
        }
    }
    exports.Document = Document;
},
/* base.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.register_models = register_models;
    const types_1 = require(8) /* ./core/util/types */;
    const object_1 = require(9) /* ./core/util/object */;
    const types_2 = require(8) /* ./core/util/types */;
    const has_props_1 = require(16) /* ./core/has_props */;
    const resolvers_1 = require(47) /* ./core/resolvers */;
    exports.default_resolver = new resolvers_1.ModelResolver(null);
    exports.Models = new Proxy(exports.default_resolver, {
        get(target, name, receiver) {
            if ((0, types_2.isString)(name)) {
                const model = target.get(name);
                if (model != null) {
                    return model;
                }
            }
            return Reflect.get(target, name, receiver);
        },
        has(target, name) {
            if ((0, types_2.isString)(name)) {
                const model = target.get(name);
                if (model != null) {
                    return true;
                }
            }
            return Reflect.has(target, name);
        },
        ownKeys(target) {
            return target.names;
        },
        getOwnPropertyDescriptor(target, name) {
            if ((0, types_2.isString)(name)) {
                const model = target.get(name);
                if (model != null) {
                    return { configurable: true, enumerable: true, writable: false, value: model };
                }
            }
            return Reflect.getOwnPropertyDescriptor(target, name);
        },
    });
    function is_HasProps(obj) {
        return (0, types_1.isObject)(obj) && obj.prototype instanceof has_props_1.HasProps;
    }
    function register_models(models, force = false) {
        for (const model of (0, types_1.isArray)(models) ? models : (0, object_1.values)(models)) {
            if (is_HasProps(model)) {
                exports.default_resolver.register(model, force);
            }
        }
    }
},
/* core/util/types.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.is_undefined = is_undefined;
    exports.is_defined = is_defined;
    exports.is_nullish = is_nullish;
    exports.isBoolean = isBoolean;
    exports.isNumber = isNumber;
    exports.isInteger = isInteger;
    exports.isString = isString;
    exports.isSymbol = isSymbol;
    exports.isPrimitive = isPrimitive;
    exports.isFunction = isFunction;
    exports.isArray = isArray;
    exports.isArrayOf = isArrayOf;
    exports.isArrayableOf = isArrayableOf;
    exports.isTypedArray = isTypedArray;
    exports.isObject = isObject;
    exports.isBasicObject = isBasicObject;
    exports.isPlainObject = isPlainObject;
    exports.isDict = isDict;
    exports.isIterable = isIterable;
    exports.isArrayable = isArrayable;
    exports.is_ArrayBufferLike = is_ArrayBufferLike;
    //     Underscore.js 1.8.3
    //     http://underscorejs.org
    //     (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
    //     Underscore may be freely distributed under the MIT license.
    function is_undefined(obj) {
        return typeof obj === "undefined";
    }
    function is_defined(obj) {
        return typeof obj !== "undefined";
    }
    // XXX: use only to work around strict conditional expressions
    function is_nullish(obj) {
        return obj == null;
    }
    function isBoolean(obj) {
        return obj === true || obj === false || typeof obj === "boolean" || obj instanceof Boolean;
    }
    function isNumber(obj) {
        return typeof obj === "number" || obj instanceof Number;
    }
    function isInteger(obj) {
        return isNumber(obj) && Number.isInteger(obj);
    }
    function isString(obj) {
        return typeof obj === "string" || obj instanceof String;
    }
    function isSymbol(obj) {
        return typeof obj === "symbol";
    }
    function isPrimitive(obj) {
        return obj === null || isBoolean(obj) || isNumber(obj) || isString(obj) || isSymbol(obj);
    }
    function isFunction(obj) {
        return typeof obj == "function" || obj instanceof Function;
    }
    function isArray(obj) {
        return Array.isArray(obj);
    }
    function isArrayOf(array, predicate) {
        if (!isArray(array)) {
            return false;
        }
        for (const item of array) {
            if (!predicate(item)) {
                return false;
            }
        }
        return true;
    }
    function isArrayableOf(array, predicate) {
        if (!isArrayable(array)) {
            return false;
        }
        for (const item of array) {
            if (!predicate(item)) {
                return false;
            }
        }
        return true;
    }
    function isTypedArray(obj) {
        return ArrayBuffer.isView(obj) && !(obj instanceof DataView);
    }
    function isObject(obj) {
        const tp = typeof obj;
        return tp === "function" || tp === "object" && !!obj;
    }
    function isBasicObject(obj) {
        return isObject(obj) && is_nullish(obj.constructor);
    }
    function isPlainObject(obj) {
        return isObject(obj) && (is_nullish(obj.constructor) || obj.constructor === Object);
    }
    function isDict(obj) {
        return obj instanceof Map || isPlainObject(obj);
    }
    function isIterable(obj) {
        return isObject(obj) && Symbol.iterator in obj;
    }
    function isArrayable(obj) {
        return isIterable(obj) && "length" in obj;
    }
    function is_ArrayBufferLike(obj) {
        // SharedArrayBuffer is only available in cross origin isolated environments, otherwise it's undefined
        return obj instanceof ArrayBuffer || (typeof SharedArrayBuffer !== "undefined" && obj instanceof SharedArrayBuffer);
    }
},
/* core/util/object.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.to_object = to_object;
    exports.keys = keys;
    exports.values = values;
    exports.entries = entries;
    exports.clone = clone;
    exports.merge = merge;
    exports.size = size;
    exports.is_empty = is_empty;
    exports.dict = dict;
    const types_1 = require(8) /* ./types */;
    const array_1 = require(10) /* ./array */;
    exports.assign = Object.assign;
    exports.extend = exports.assign;
    function to_object(obj) {
        return (0, types_1.isPlainObject)(obj) ? obj : Object.fromEntries(obj);
    }
    function keys(obj) {
        return obj instanceof Map ? [...obj.keys()] : Object.keys(obj);
    }
    function values(obj) {
        return obj instanceof Map ? [...obj.values()] : Object.values(obj);
    }
    function entries(obj) {
        return obj instanceof Map ? [...obj.entries()] : Object.entries(obj);
    }
    exports.typed_keys = Object.keys;
    exports.typed_values = Object.values;
    exports.typed_entries = Object.entries;
    function clone(obj) {
        return obj instanceof Map ? new Map(obj) : { ...obj };
    }
    function merge(obj0, obj1) {
        /*
        * Returns an object with the array values for obj1 and obj2 unioned by key.
        */
        const result = new Map();
        const keys = [...obj0.keys(), ...obj1.keys()];
        for (const key of keys) {
            const v0 = obj0.get(key);
            const v1 = obj1.get(key);
            const arr0 = v0 === undefined ? [] : v0;
            const arr1 = v1 === undefined ? [] : v1;
            result.set(key, (0, array_1.union)(arr0, arr1));
        }
        return result;
    }
    function size(obj) {
        return obj instanceof Map ? obj.size : Object.keys(obj).length;
    }
    function is_empty(obj) {
        return size(obj) == 0;
    }
    const { hasOwnProperty } = Object.prototype;
    class PlainObjectProxy {
        obj;
        constructor(obj) {
            this.obj = obj;
        }
        [Symbol.toStringTag] = "PlainObjectProxy";
        clear() {
            for (const key of this.keys()) {
                delete this.obj[key];
            }
        }
        delete(key) {
            const exists = this.has(key);
            if (exists) {
                delete this.obj[key];
            }
            return exists;
        }
        has(key) {
            return hasOwnProperty.call(this.obj, key);
        }
        get(key) {
            return this.has(key) ? this.obj[key] : undefined;
        }
        set(key, value) {
            this.obj[key] = value;
            return this;
        }
        get size() {
            return size(this.obj);
        }
        [Symbol.iterator]() {
            return this.entries();
        }
        *keys() {
            yield* keys(this.obj);
        }
        *values() {
            yield* values(this.obj);
        }
        *entries() {
            yield* entries(this.obj);
        }
        forEach(callback, that) {
            for (const [key, value] of this.entries()) {
                callback.call(that, value, key, this);
            }
        }
    }
    exports.PlainObjectProxy = PlainObjectProxy;
    function dict(obj) {
        return (0, types_1.isPlainObject)(obj) ? new PlainObjectProxy(obj) : obj;
    }
},
/* core/util/array.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.head = head;
    exports.last = last;
    exports.copy = copy;
    exports.concat = concat;
    exports.nth = nth;
    exports.zip = zip;
    exports.unzip = unzip;
    exports.range = range;
    exports.linspace = linspace;
    exports.logspace = logspace;
    exports.transpose = transpose;
    exports.argmin = argmin;
    exports.argmax = argmax;
    exports.argsort = argsort;
    exports.uniq = uniq;
    exports.uniq_by = uniq_by;
    exports._union = _union;
    exports.union = union;
    exports.intersection = intersection;
    exports.difference = difference;
    exports.symmetric_difference = symmetric_difference;
    exports.remove_at = remove_at;
    exports.remove = remove;
    exports.remove_by = remove_by;
    exports.clear = clear;
    exports.split = split;
    exports.shuffle = shuffle;
    exports.pairwise = pairwise;
    exports.elementwise = elementwise;
    exports.reversed = reversed;
    exports.repeat = repeat;
    exports.resize = resize;
    exports.interleave = interleave;
    const tslib_1 = require(1) /* tslib */;
    //     Underscore.js 1.8.3
    //     http://underscorejs.org
    //     (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
    //     Underscore may be freely distributed under the MIT license.
    const logging_1 = require(11) /* ../logging */;
    const math_1 = require(12) /* ./math */;
    const assert_1 = require(13) /* ./assert */;
    const types_1 = require(8) /* ./types */;
    const arrayable_1 = require(14) /* ./arrayable */;
    const iter = tslib_1.__importStar(require(15) /* ./iterator */);
    var arrayable_2 = require(14) /* ./arrayable */;
    __esExport("map", arrayable_2.map);
    __esExport("reduce", arrayable_2.reduce);
    __esExport("min", arrayable_2.min);
    __esExport("min_by", arrayable_2.min_by);
    __esExport("max", arrayable_2.max);
    __esExport("max_by", arrayable_2.max_by);
    __esExport("sum", arrayable_2.sum);
    __esExport("cumsum", arrayable_2.cumsum);
    __esExport("every", arrayable_2.every);
    __esExport("some", arrayable_2.some);
    __esExport("find", arrayable_2.find);
    __esExport("find_last", arrayable_2.find_last);
    __esExport("find_index", arrayable_2.find_index);
    __esExport("find_last_index", arrayable_2.find_last_index);
    __esExport("sorted_index", arrayable_2.sorted_index);
    __esExport("is_empty", arrayable_2.is_empty);
    __esExport("includes", arrayable_2.includes);
    __esExport("contains", arrayable_2.contains);
    __esExport("sort_by", arrayable_2.sort_by);
    __esExport("subselect", arrayable_2.subselect);
    const { slice } = Array.prototype;
    function head(array) {
        if (array.length != 0) {
            return array[0];
        }
        else {
            throw new Error("out of bounds access");
        }
    }
    function last(array) {
        if (array.length != 0) {
            return array[array.length - 1];
        }
        else {
            throw new Error("out of bounds access");
        }
    }
    function copy(array) {
        return slice.call(array);
    }
    function concat(arrays) {
        return [].concat(...arrays);
    }
    function nth(array, index) {
        return array[index >= 0 ? index : array.length + index];
    }
    function zip(...arrays) {
        if (arrays.length == 0) {
            return [];
        }
        const n = (0, arrayable_1.min)(arrays.map((a) => a.length));
        const k = arrays.length;
        const result = new Array(n);
        for (let i = 0; i < n; i++) {
            result[i] = new Array(k);
            for (let j = 0; j < k; j++) {
                result[i][j] = arrays[j][i];
            }
        }
        return result;
    }
    function unzip(array) {
        const n = array.length;
        if (n == 0) {
            return [];
        }
        const k = (0, arrayable_1.min)(array.map((a) => a.length));
        const results = Array(k);
        for (let j = 0; j < k; j++) {
            results[j] = new Array(n);
        }
        for (let i = 0; i < n; i++) {
            for (let j = 0; j < k; j++) {
                results[j][i] = array[i][j];
            }
        }
        return results;
    }
    function range(start, stop, step = 1) {
        (0, assert_1.assert)(step > 0, "'step' must be a positive number");
        if (stop == null) {
            stop = start;
            start = 0;
        }
        const { max, ceil, abs } = Math;
        const delta = start <= stop ? step : -step;
        const length = max(ceil(abs(stop - start) / step), 0);
        try {
            // Creating an array too large for V8's allowed array lengths raises an error
            const range = new Array(length);
            for (let i = 0; i < length; i++, start += delta) {
                range[i] = start;
            }
            return range;
        }
        catch (error) {
            if (error instanceof RangeError) {
                logging_1.logger.error("Caught a structural array size limit error, not an JS engine-wide out-of-memory error:", error.message);
            }
            throw (error);
        }
    }
    function linspace(start, stop, num = 100) {
        const step = num == 1 ? 0 : (stop - start) / (num - 1);
        const array = new Array(num);
        for (let i = 0; i < num; i++) {
            array[i] = start + i * step;
        }
        return array;
    }
    function logspace(start, stop, num = 100, base = 10) {
        const step = num == 1 ? 0 : (stop - start) / (num - 1);
        const array = new Array(num);
        for (let i = 0; i < num; i++) {
            array[i] = base ** (start + i * step);
        }
        return array;
    }
    function transpose(array) {
        const rows = array.length;
        const cols = array[0].length;
        const transposed = [];
        for (let j = 0; j < cols; j++) {
            transposed[j] = [];
            for (let i = 0; i < rows; i++) {
                transposed[j][i] = array[i][j];
            }
        }
        return transposed;
    }
    function argmin(array) {
        return (0, arrayable_1.min_by)(range(array.length), (i) => array[i]);
    }
    function argmax(array) {
        return (0, arrayable_1.max_by)(range(array.length), (i) => array[i]);
    }
    /**
     * Return the permutation indices for sorting an array.
     */
    function argsort(array) {
        const indices = Array.from(array.keys());
        indices.sort((a, b) => array[a] - array[b]);
        return indices;
    }
    function uniq(array) {
        const result = new Set();
        for (const value of array) {
            result.add(value);
        }
        return [...result];
    }
    function uniq_by(array, key) {
        const result = [];
        const seen = [];
        for (const value of array) {
            const computed = key(value);
            if (!(0, arrayable_1.includes)(seen, computed)) {
                seen.push(computed);
                result.push(value);
            }
        }
        return result;
    }
    function _union(arrays) {
        const result = new Set();
        for (const array of arrays) {
            for (const value of array) {
                result.add(value);
            }
        }
        return result;
    }
    function union(...arrays) {
        return [..._union(arrays)];
    }
    function intersection(array, ...arrays) {
        const result = [];
        top: for (const item of array) {
            if ((0, arrayable_1.includes)(result, item)) {
                continue;
            }
            for (const other of arrays) {
                if (!(0, arrayable_1.includes)(other, item)) {
                    continue top;
                }
            }
            result.push(item);
        }
        return result;
    }
    function difference(array, ...arrays) {
        const rest = _union(arrays);
        return (0, arrayable_1.filter)(array, (value) => !rest.has(value));
    }
    function symmetric_difference(array0, array1) {
        const set0 = new Set(array0);
        const set1 = new Set(array1);
        const result = [];
        for (const val of set0) {
            if (!set1.has(val)) {
                result.push(val);
            }
        }
        for (const val of set1) {
            if (!set0.has(val)) {
                result.push(val);
            }
        }
        return result;
    }
    function remove_at(array, i) {
        (0, assert_1.assert)((0, types_1.isInteger)(i) && i >= 0);
        const result = copy(array);
        result.splice(i, 1);
        return result;
    }
    function remove(array, item) {
        remove_by(array, (value) => value == item);
    }
    function remove_by(array, key) {
        for (let i = 0; i < array.length;) {
            if (key(array[i])) {
                array.splice(i, 1);
            }
            else {
                i++;
            }
        }
    }
    function clear(array) {
        array.splice(0, array.length);
    }
    function split(array, separator) {
        const chunks = [];
        const n = array.length;
        let i = 0;
        let j = 0;
        while (j < n) {
            if (array[j] === separator) {
                chunks.push(array.slice(i, j));
                i = ++j;
            }
            else {
                ++j;
            }
        }
        chunks.push(array.slice(i));
        return chunks;
    }
    // Shuffle a collection, using the modern version of the
    // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
    function shuffle(array) {
        const length = array.length;
        const shuffled = new Array(length);
        for (let i = 0; i < length; i++) {
            const rand = (0, math_1.randomIn)(0, i);
            if (rand !== i) {
                shuffled[i] = shuffled[rand];
            }
            shuffled[rand] = array[i];
        }
        return shuffled;
    }
    function pairwise(array, fn) {
        const n = array.length;
        const result = new Array(n - 1);
        for (let i = 0; i < n - 1; i++) {
            result[i] = fn(array[i], array[i + 1]);
        }
        return result;
    }
    function elementwise(array0, array1, fn) {
        const n = Math.min(array0.length, array1.length);
        const result = Array(n);
        for (let i = 0; i < n; i++) {
            result[i] = fn(array0[i], array1[i]);
        }
        return result;
    }
    function reversed(array) {
        const n = array.length;
        const result = new Array(n);
        for (let i = 0; i < n; i++) {
            result[n - i - 1] = array[i];
        }
        return result;
    }
    function repeat(value, n) {
        const result = new Array(n).fill(value);
        return result;
    }
    function resize(array, new_length, fill_value) {
        if (array.length >= new_length) {
            return array.slice(0, new_length);
        }
        else {
            const suffix = new Array(new_length - array.length);
            if (fill_value !== undefined) {
                suffix.fill(fill_value);
            }
            return array.concat(suffix);
        }
    }
    function interleave(seq, separator) {
        return [...iter.interleave(seq, separator)];
    }
},
/* core/logging.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.set_log_level = set_log_level;
    exports.with_log_level = with_log_level;
    // This is based on https://github.com/pimterry/loglevel
    const types_1 = require(8) /* ./util/types */;
    const version_1 = require(3) /* ../version */;
    const _loggers = {};
    class LogLevel {
        name;
        level;
        method;
        constructor(name, level, method) {
            this.name = name;
            this.level = level;
            this.method = method;
        }
    }
    exports.LogLevel = LogLevel;
    class Logger {
        static TRACE = new LogLevel("trace", 0, "trace");
        static DEBUG = new LogLevel("debug", 1, "debug");
        static INFO = new LogLevel("info", 2, "info");
        static WARN = new LogLevel("warn", 6, "warn");
        static ERROR = new LogLevel("error", 7, "error");
        static FATAL = new LogLevel("fatal", 8, "error");
        static OFF = new LogLevel("off", 9, "log");
        static log_levels = {
            trace: Logger.TRACE,
            debug: Logger.DEBUG,
            info: Logger.INFO,
            warn: Logger.WARN,
            error: Logger.ERROR,
            fatal: Logger.FATAL,
            off: Logger.OFF,
        };
        static get levels() {
            return Object.keys(Logger.log_levels);
        }
        static get(name, level = Logger.INFO) {
            if (name.length > 0) {
                if (name in _loggers) {
                    return _loggers[name];
                }
                else {
                    return _loggers[name] = new Logger(name, level);
                }
            }
            else {
                throw new TypeError("Logger.get() expects a non-empty string name and an optional log-level");
            }
        }
        _name;
        _log_level = Logger.DEBUG;
        constructor(name, level = Logger.INFO) {
            this._name = name;
            this.set_level(level);
        }
        get level() {
            return this.get_level();
        }
        get_level() {
            return this._log_level;
        }
        set_level(log_level) {
            if (log_level instanceof LogLevel) {
                this._log_level = log_level;
            }
            else if (Logger.log_levels.hasOwnProperty(log_level)) {
                this._log_level = Logger.log_levels[log_level];
            }
            else {
                throw new Error("Logger.set_level() expects a log-level object or a string name of a log-level");
            }
            const prefix = `[${this._name}]`;
            for (const { level, method } of Object.values(Logger.log_levels)) {
                if (level < this._log_level.level || this._log_level.level === Logger.OFF.level) {
                    this[method] = function () { };
                }
                else {
                    this[method] = _method_factory(method, prefix);
                }
            }
            this.log = _method_factory("log", prefix);
        }
        log(..._args) { }
        trace(..._args) { }
        debug(..._args) { }
        info(..._args) { }
        warn(..._args) { }
        error(..._args) { }
    }
    exports.Logger = Logger;
    function _method_factory(method_name, prefix) {
        const method = console[method_name];
        const fn = typeof method != "undefined" ? method : console.log;
        return fn.bind(console, prefix);
    }
    exports.logger = Logger.get(`bokeh ${version_1.version}`);
    function set_log_level(level) {
        const previous_level = exports.logger.level;
        if ((0, types_1.isString)(level) && !(level in Logger.log_levels)) {
            exports.logger.log(`unrecognized logging level '${level}' passed to Bokeh.set_log_level(), ignoring`);
            exports.logger.log(`valid log levels are: ${Logger.levels.join(", ")}`);
        }
        else {
            exports.logger.log(`setting log level to: '${(0, types_1.isString)(level) ? level : level.level}'`);
            exports.logger.set_level(level);
        }
        return previous_level;
    }
    function with_log_level(level, fn) {
        const original = set_log_level(level);
        try {
            fn();
        }
        finally {
            set_log_level(original);
        }
    }
},
/* core/util/math.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.angle_norm = angle_norm;
    exports.angle_dist = angle_dist;
    exports.angle_between = angle_between;
    exports.randomIn = randomIn;
    exports.atan2 = atan2;
    exports.radians = radians;
    exports.degrees = degrees;
    exports.compute_angle = compute_angle;
    exports.invert_angle = invert_angle;
    exports.to_radians_coeff = to_radians_coeff;
    exports.minmax = minmax;
    exports.clamp = clamp;
    exports.cycle = cycle;
    exports.log = log;
    exports.gcd = gcd;
    exports.lcm = lcm;
    exports.is_Floating = is_Floating;
    exports.factorial = factorial;
    exports.hermite = hermite;
    exports.eval_poly = eval_poly;
    const types_1 = require(8) /* ./types */;
    const assert_1 = require(13) /* ./assert */;
    const { PI, abs, sign, sqrt } = Math;
    exports.PI = PI;
    exports.abs = abs;
    exports.sqrt = sqrt;
    function angle_norm(angle) {
        if (angle == 0) {
            return 0;
        }
        while (angle <= 0) {
            angle += 2 * PI;
        }
        while (angle > 2 * PI) {
            angle -= 2 * PI;
        }
        return angle;
    }
    function angle_dist(lhs, rhs) {
        return angle_norm(lhs - rhs);
    }
    function angle_between(mid, lhs, rhs, anticlock = false) {
        const d = angle_dist(lhs, rhs);
        if (d == 0) {
            return false;
        }
        if (d == 2 * PI) {
            return true;
        }
        const norm_mid = angle_norm(mid);
        const cond = angle_dist(lhs, norm_mid) <= d && angle_dist(norm_mid, rhs) <= d;
        return !anticlock ? cond : !cond;
    }
    function randomIn(min, max) {
        if (max == null) {
            max = min;
            min = 0;
        }
        return min + Math.floor(Math.random() * (max - min + 1));
    }
    function atan2(start, end) {
        /*
         * Calculate the angle between a line containing start and end points (composed
         * of [x, y] arrays) and the positive x-axis.
         */
        return Math.atan2(end[1] - start[1], end[0] - start[0]);
    }
    function radians(degrees) {
        return degrees * (PI / 180);
    }
    function degrees(radians) {
        return radians / (PI / 180);
    }
    function compute_angle(angle, units, dir = "anticlock") {
        /**
         * Convert math CCW(default)/CW angle with units to CW radians (canvas).
         */
        const sign = dir == "anticlock" ? 1 : -1;
        return -sign * angle * to_radians_coeff(units);
    }
    exports.resolve_angle = compute_angle;
    function invert_angle(angle, units, dir = "anticlock") {
        /**
         * Convert CW radians (canvas) to math CCW(default)/CW angle with units.
         */
        const sign = dir == "anticlock" ? 1 : -1;
        return -sign * angle / to_radians_coeff(units);
    }
    function to_radians_coeff(units) {
        switch (units) {
            case "deg": return PI / 180;
            case "rad": return 1;
            case "grad": return PI / 200;
            case "turn": return 2 * PI;
        }
    }
    function minmax(v0, v1) {
        return v0 <= v1 ? [v0, v1] : [v1, v0];
    }
    function clamp(val, min, max) {
        return val < min ? min : (val > max ? max : val);
    }
    function cycle(val, min, max) {
        if (val > max) {
            return min;
        }
        if (val < min) {
            return max;
        }
        return val;
    }
    function log(x, base = Math.E) {
        return Math.log(x) / Math.log(base);
    }
    function gcd(a, b) {
        a = Math.abs(a);
        b = Math.abs(b);
        while (b != 0) {
            [a, b] = [b, a % b];
        }
        return a;
    }
    function lcm(a, ...rest) {
        for (const b of rest) {
            a = Math.floor((a * b) / gcd(a, b));
        }
        return a;
    }
    exports.float = Symbol("float");
    function is_Floating(obj) {
        return (0, types_1.isObject)(obj) && exports.float in obj;
    }
    class Fraction {
        numer;
        denom;
        constructor(numer, denom) {
            (0, assert_1.assert)(denom != 0, "Zero divisor");
            const div = gcd(numer, denom);
            const sgn = sign(numer) * sign(denom);
            this.numer = sgn * abs(numer) / div;
            this.denom = abs(denom) / div;
        }
        [exports.float]() {
            return this.numer / this.denom;
        }
        toString() {
            return `${this.numer}/${this.denom}`;
        }
    }
    exports.Fraction = Fraction;
    exports.float32_epsilon = 1.1920928955078125e-7; // IEEE-754
    function factorial(x) {
        let y = 1;
        for (let i = 2; i <= x; i++) {
            y *= i;
        }
        return y;
    }
    function hermite(n) {
        const poly = new Array(n + 1);
        poly.fill(0);
        const fn = factorial(n);
        for (let k = 0; k <= Math.floor(n / 2); k++) {
            const c = (-1) ** k * fn / (factorial(k) * factorial(n - 2 * k)) * 2 ** (n - 2 * k);
            poly[2 * k] = c;
        }
        return poly;
    }
    function eval_poly(poly, x) {
        const n = poly.length - 1;
        let y = 0;
        let x_n = 1;
        for (let i = n; i >= 0; i--) {
            y += x_n * poly[i];
            x_n *= x;
        }
        return y;
    }
},
/* core/util/assert.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.assert = assert;
    exports.assert_debug = assert_debug;
    exports.unreachable = unreachable;
    class AssertionError extends Error {
    }
    exports.AssertionError = AssertionError;
    class UnreachableError extends Error {
    }
    exports.UnreachableError = UnreachableError;
    function assert(condition, message) {
        if (condition === true || (condition !== false && condition())) {
            return;
        }
        throw new AssertionError(message ?? "Assertion failed");
    }
    function assert_debug(condition, message) {
        if (typeof DEBUG !== "undefined" && DEBUG) {
            assert(condition, message);
        }
    }
    function unreachable(msg) {
        const suffix = msg != null ? `: ${msg}` : "";
        throw new UnreachableError(`unreachable code${suffix}`);
    }
},
/* core/util/arrayable.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.minmax = minmax;
    exports.min = min;
    exports.max = max;
    exports.is_empty = is_empty;
    exports.is_sorted = is_sorted;
    exports.copy = copy;
    exports.splice = splice;
    exports.head = head;
    exports.insert = insert;
    exports.append = append;
    exports.prepend = prepend;
    exports.index_of = index_of;
    exports.includes = includes;
    exports.subselect = subselect;
    exports.mul = mul;
    exports.map = map;
    exports.inplace_map = inplace_map;
    exports.filter = filter;
    exports.reduce = reduce;
    exports.sort_by = sort_by;
    exports.minmax2 = minmax2;
    exports.min_by = min_by;
    exports.max_by = max_by;
    exports.sum = sum;
    exports.cumsum = cumsum;
    exports.every = every;
    exports.some = some;
    exports.find = find;
    exports.find_last = find_last;
    exports.bisect_left_by = bisect_left_by;
    exports.bisect_right_by = bisect_right_by;
    exports.bisect_left = bisect_left;
    exports.bisect_right = bisect_right;
    exports.binary_search = binary_search;
    exports.bin_counts = bin_counts;
    exports.interpolate = interpolate;
    exports.left_edge_index = left_edge_index;
    exports.norm = norm;
    const math_1 = require(12) /* ./math */;
    const assert_1 = require(13) /* ./assert */;
    const { floor } = Math;
    function minmax(array) {
        let min = +Infinity;
        let max = -Infinity;
        const { length } = array;
        for (let i = 0; i < length; i++) {
            const value = array[i];
            if (value < min) {
                min = value;
            }
            if (value > max) {
                max = value;
            }
        }
        return [min, max];
    }
    function min(array) {
        const [min] = minmax(array);
        return min;
    }
    function max(array) {
        const [, max] = minmax(array);
        return max;
    }
    function is_empty(array) {
        return array.length == 0;
    }
    function is_sorted(array) {
        const n = array.length;
        if (n == 0) {
            return true;
        }
        let prev = array[0];
        for (let i = 1; i < n; i++) {
            const curr = array[i];
            if (prev <= curr) {
                prev = curr;
            }
            else {
                return false;
            }
        }
        return true;
    }
    function copy(array) {
        if (Array.isArray(array)) {
            return array.slice();
        }
        else {
            return new array.constructor(array);
        }
    }
    function splice(array, start, k, ...items) {
        if (Array.isArray(array)) {
            const result = copy(array);
            if (k === undefined) {
                result.splice(start);
            }
            else {
                result.splice(start, k, ...items);
            }
            return result;
        }
        const len = array.length;
        if (start < 0) {
            start += len;
        }
        if (start < 0) {
            start = 0;
        }
        else if (start > len) {
            start = len;
        }
        if (k == null || k > len - start) {
            k = len - start;
        }
        else if (k < 0) {
            k = 0;
        }
        const n = len - k + items.length;
        const result = new array.constructor(n);
        let i = 0;
        for (; i < start; i++) {
            result[i] = array[i];
        }
        for (const item of items) {
            result[i++] = item;
        }
        for (let j = start + k; j < len; j++) {
            result[i++] = array[j];
        }
        return result;
    }
    function head(array, n) {
        return splice(array, n, array.length - n);
    }
    function insert(array, item, i) {
        return splice(array, i, 0, item);
    }
    function append(array, item) {
        return splice(array, array.length, 0, item);
    }
    function prepend(array, item) {
        return splice(array, 0, 0, item);
    }
    function index_of(array, item) {
        return array.indexOf(item);
    }
    function includes(array, value) {
        return array.indexOf(value) !== -1;
    }
    exports.contains = includes;
    function subselect(array, indices) {
        const n = indices.length;
        const result = new array.constructor(n);
        for (let i = 0; i < n; i++) {
            result[i] = array[indices[i]];
        }
        return result;
    }
    function mul(array, coeff, output) {
        const n = array.length;
        const result = output ?? new array.constructor(n);
        for (let i = 0; i < n; i++) {
            result[i] = array[i] * coeff;
        }
        return result;
    }
    function map(array, fn) {
        const n = array.length;
        const result = new array.constructor(n);
        for (let i = 0; i < n; i++) {
            result[i] = fn(array[i], i, array);
        }
        return result;
    }
    function inplace_map(array, fn, output) {
        const n = array.length;
        const result = output ?? array;
        for (let i = 0; i < n; i++) {
            result[i] = fn(array[i], i);
        }
    }
    function filter(array, pred) {
        const n = array.length;
        const result = new array.constructor(n);
        let k = 0;
        for (let i = 0; i < n; i++) {
            const value = array[i];
            if (pred(value, i, array)) {
                result[k++] = value;
            }
        }
        return head(result, k);
    }
    function reduce(array, fn, initial) {
        const n = array.length;
        if (initial === undefined && n == 0) {
            throw new Error("can't reduce an empty array without an initial value");
        }
        let value;
        let i;
        if (initial === undefined) {
            value = array[0];
            i = 1;
        }
        else {
            value = initial;
            i = 0;
        }
        for (; i < n; i++) {
            value = fn(value, array[i], i, array);
        }
        return value;
    }
    function sort_by(array, key) {
        const tmp = Array.from(array, (value, index) => {
            return { index, key: key(value) };
        });
        tmp.sort((left, right) => {
            const a = left.key;
            const b = right.key;
            if (a !== b) {
                if (a > b) {
                    return 1;
                }
                if (a < b) {
                    return -1;
                }
            }
            return left.index - right.index;
        });
        return map(array, (_, i) => array[tmp[i].index]);
    }
    function minmax2(arr, brr) {
        let a;
        let b;
        let a_min = +Infinity;
        let a_max = -Infinity;
        let b_min = +Infinity;
        let b_max = -Infinity;
        const n = Math.min(arr.length, brr.length);
        for (let i = 0; i < n; i++) {
            a = arr[i];
            b = brr[i];
            if (!isNaN(a) && !isNaN(b)) {
                if (a < a_min) {
                    a_min = a;
                }
                if (a > a_max) {
                    a_max = a;
                }
                if (b < b_min) {
                    b_min = b;
                }
                if (b > b_max) {
                    b_max = b;
                }
            }
        }
        return [a_min, a_max, b_min, b_max];
    }
    function min_by(array, key) {
        if (array.length == 0) {
            throw new Error("min_by() called with an empty array");
        }
        let result = array[0];
        let result_computed = key(result, 0);
        for (let i = 1, length = array.length; i < length; i++) {
            const value = array[i];
            const computed = key(value, i);
            if (computed < result_computed) {
                result = value;
                result_computed = computed;
            }
        }
        return result;
    }
    function max_by(array, key) {
        if (array.length == 0) {
            throw new Error("max_by() called with an empty array");
        }
        let result = array[0];
        let result_computed = key(result, 0);
        for (let i = 1, length = array.length; i < length; i++) {
            const value = array[i];
            const computed = key(value, i);
            if (computed > result_computed) {
                result = value;
                result_computed = computed;
            }
        }
        return result;
    }
    function sum(array) {
        let result = 0;
        for (let i = 0, n = array.length; i < n; i++) {
            result += array[i];
        }
        return result;
    }
    function cumsum(array) {
        const result = new array.constructor(array.length);
        reduce(array, (a, b, i) => result[i] = a + b, 0);
        return result;
    }
    function every(iter, predicate) {
        for (const item of iter) {
            if (!predicate(item)) {
                return false;
            }
        }
        return true;
    }
    function some(iter, predicate) {
        for (const item of iter) {
            if (predicate(item)) {
                return true;
            }
        }
        return false;
    }
    function _find_index(dir) {
        return function (array, predicate) {
            const length = array.length;
            let index = dir > 0 ? 0 : length - 1;
            for (; index >= 0 && index < length; index += dir) {
                if (predicate(array[index])) {
                    return index;
                }
            }
            return -1;
        };
    }
    exports.find_index = _find_index(1);
    exports.find_last_index = _find_index(-1);
    function find(array, predicate) {
        const index = (0, exports.find_index)(array, predicate);
        return index == -1 ? undefined : array[index];
    }
    function find_last(array, predicate) {
        const index = (0, exports.find_last_index)(array, predicate);
        return index == -1 ? undefined : array[index];
    }
    function bisect_left_by(array, value, fn, low = 0, high = array.length) {
        (0, assert_1.assert_debug)(() => is_sorted(array));
        (0, assert_1.assert)(0 <= low && high <= array.length);
        while (low < high) {
            const mid = floor((low + high) / 2);
            if (fn(array[mid]) < value) {
                low = mid + 1;
            }
            else {
                high = mid;
            }
        }
        return low;
    }
    function bisect_right_by(array, value, fn, low = 0, high = array.length) {
        (0, assert_1.assert_debug)(() => is_sorted(array));
        (0, assert_1.assert)(0 <= low && high <= array.length);
        while (low < high) {
            const mid = floor((low + high) / 2);
            if (fn(array[mid]) <= value) {
                low = mid + 1;
            }
            else {
                high = mid;
            }
        }
        return low;
    }
    function bisect_left(array, value, low = 0, high) {
        return bisect_left_by(array, value, (item) => item, low, high);
    }
    function bisect_right(array, value, low = 0, high) {
        return bisect_right_by(array, value, (item) => item, low, high);
    }
    function binary_search(array, value) {
        const i = bisect_left(array, value);
        return i != array.length && array[i] == value ? i : null;
    }
    exports.sorted_index = bisect_left;
    function bin_counts(data, bin_edges) {
        const nbins = bin_edges.length - 1;
        const counts = Array(nbins).fill(0);
        for (let i = 0; i < data.length; i++) {
            const sample = data[i];
            const index = (0, exports.sorted_index)(bin_edges, sample);
            const bin = (0, math_1.clamp)(index - 1, 0, nbins - 1);
            counts[bin] += 1;
        }
        return counts;
    }
    function interpolate(points, x_values, y_values) {
        // Implementation ported from np.interp
        const n = points.length;
        const results = new Array(n);
        for (let i = 0; i < n; i++) {
            const point = points[i];
            if (isNaN(point) || x_values.length == 0) {
                results[i] = NaN;
                continue;
            }
            const index = left_edge_index(point, x_values);
            if (index == -1) {
                results[i] = y_values[0];
            }
            else if (index == x_values.length) {
                results[i] = y_values[y_values.length - 1];
            }
            else if (index == x_values.length - 1 || x_values[index] == point) {
                results[i] = y_values[index];
            }
            else {
                const x0 = x_values[index];
                const y0 = y_values[index];
                const x1 = x_values[index + 1];
                const y1 = y_values[index + 1];
                results[i] = lerp(point, x0, y0, x1, y1);
            }
        }
        return results;
    }
    function lerp(x, x0, y0, x1, y1) {
        const slope = (y1 - y0) / (x1 - x0);
        let res = slope * (x - x0) + y0;
        if (!isFinite(res)) {
            res = slope * (x - x1) + y1;
            if (!isFinite(res) && (y0 == y1)) {
                res = y0;
            }
        }
        return res;
    }
    function left_edge_index(point, intervals) {
        if (point < intervals[0]) {
            return -1;
        }
        if (point > intervals[intervals.length - 1]) {
            return intervals.length;
        }
        if (intervals.length == 1) {
            // Implies point == intervals[0]
            return 0;
        }
        let leftEdgeIndex = 0;
        let rightEdgeIndex = intervals.length - 1;
        while (rightEdgeIndex - leftEdgeIndex != 1) {
            const indexOfNumberToCompare = leftEdgeIndex + Math.floor((rightEdgeIndex - leftEdgeIndex) / 2);
            if (point >= intervals[indexOfNumberToCompare]) {
                leftEdgeIndex = indexOfNumberToCompare;
            }
            else {
                rightEdgeIndex = indexOfNumberToCompare;
            }
        }
        return leftEdgeIndex;
    }
    function norm(array, start, end) {
        const span = end - start;
        return map(array, (x) => (x - start) / span);
    }
},
/* core/util/iterator.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.iter = iter;
    exports.range = range;
    exports.reverse = reverse;
    exports.enumerate = enumerate;
    exports.take = take;
    exports.skip = skip;
    exports.tail = tail;
    exports.join = join;
    exports.zip = zip;
    exports.interleave = interleave;
    exports.map = map;
    exports.flat_map = flat_map;
    exports.filter = filter;
    exports.no_repeated = no_repeated;
    exports.every = every;
    exports.some = some;
    exports.combinations = combinations;
    exports.subsets = subsets;
    exports.minmax = minmax;
    exports.min = min;
    exports.max = max;
    const assert_1 = require(13) /* ./assert */;
    const types_1 = require(8) /* ./types */;
    function* iter(obj) {
        if ((0, types_1.isIterable)(obj)) {
            yield* obj;
        }
        else {
            yield obj;
        }
    }
    function* range(start, stop, step = 1) {
        (0, assert_1.assert)(step > 0);
        const { abs, ceil, max } = Math;
        if (stop == null) {
            stop = start;
            start = 0;
        }
        const delta = start <= stop ? step : -step;
        const length = max(ceil(abs(stop - start) / abs(step)), 0);
        for (let i = 0; i < length; i++, start += delta) {
            yield start;
        }
    }
    function* reverse(array) {
        const n = array.length;
        for (let i = 0; i < n; i++) {
            yield array[n - i - 1];
        }
    }
    function* enumerate(seq) {
        let i = 0;
        for (const item of seq) {
            yield [item, i++];
        }
    }
    function* take(seq, n) {
        (0, assert_1.assert)(n >= 0);
        let i = 0;
        for (const item of seq) {
            if (i++ < n) {
                yield item;
            }
            else {
                break;
            }
        }
    }
    function* skip(seq, n) {
        (0, assert_1.assert)(n >= 0);
        for (const value of seq) {
            if (n == 0) {
                yield value;
            }
            else {
                n -= 1;
            }
        }
    }
    function* tail(seq) {
        yield* skip(seq, 1);
    }
    function* join(seq, separator) {
        let first = true;
        for (const entry of seq) {
            if (first) {
                first = false;
            }
            else if (separator != null) {
                yield separator();
            }
            yield* entry;
        }
    }
    function* zip(iterable0, iterable1) {
        const it0 = iterable0[Symbol.iterator]();
        const it1 = iterable1[Symbol.iterator]();
        do {
            const r0 = it0.next();
            const r1 = it1.next();
            if (r0.done === true || r1.done === true) {
                break;
            }
            else {
                yield [r0.value, r1.value];
            }
        } while (true);
    }
    function* interleave(seq, separator) {
        let first = true;
        for (const entry of seq) {
            if (first) {
                first = false;
            }
            else {
                yield separator();
            }
            yield entry;
        }
    }
    function* map(iterable, fn) {
        let i = 0;
        for (const item of iterable) {
            yield fn(item, i++);
        }
    }
    function* flat_map(iterable, fn) {
        let i = 0;
        for (const item of iterable) {
            yield* fn(item, i++);
        }
    }
    function* filter(iterable, fn) {
        let i = 0;
        for (const item of iterable) {
            if (fn(item, i++)) {
                yield item;
            }
        }
    }
    const nothing = Symbol("nothing");
    function* no_repeated(iterable) {
        let last = nothing;
        for (const item of iterable) {
            if (item !== last) {
                yield item;
            }
            last = item;
        }
    }
    function every(iterable, predicate) {
        for (const item of iterable) {
            if (!predicate(item)) {
                return false;
            }
        }
        return true;
    }
    function some(iterable, predicate) {
        for (const item of iterable) {
            if (predicate(item)) {
                return true;
            }
        }
        return false;
    }
    // https://docs.python.org/3.8/library/itertools.html#itertools.combinations
    function* combinations(seq, r) {
        const n = seq.length;
        if (r > n) {
            return;
        }
        const indices = [...range(r)];
        yield indices.map((i) => seq[i]);
        while (true) {
            let k;
            for (const i of range(r - 1, -1)) {
                if (indices[i] != i + n - r) {
                    k = i;
                    break;
                }
            }
            if (k == null) {
                return;
            }
            indices[k] += 1;
            for (const j of range(k + 1, r)) {
                indices[j] = indices[j - 1] + 1;
            }
            yield indices.map((i) => seq[i]);
        }
    }
    function* subsets(seq) {
        for (const k of range(seq.length + 1)) {
            yield* combinations(seq, k);
        }
    }
    function minmax(iterable) {
        let min = +Infinity;
        let max = -Infinity;
        for (const value of iterable) {
            if (value < min) {
                min = value;
            }
            if (value > max) {
                max = value;
            }
        }
        return [min, max];
    }
    function min(iterable) {
        const [min] = minmax(iterable);
        return min;
    }
    function max(iterable) {
        const [, max] = minmax(iterable);
        return max;
    }
},
/* core/has_props.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const signaling_1 = require(17) /* ./signaling */;
    const refs_1 = require(19) /* ./util/refs */;
    const p = tslib_1.__importStar(require(20) /* ./properties */);
    const k = tslib_1.__importStar(require(22) /* ./kinds */);
    const assert_1 = require(13) /* ./util/assert */;
    const string_1 = require(41) /* ./util/string */;
    const object_1 = require(9) /* ./util/object */;
    const types_1 = require(8) /* ./util/types */;
    const serialization_1 = require(33) /* ./serialization */;
    const events_1 = require(42) /* ../document/events */;
    const eq_1 = require(27) /* ./util/eq */;
    const pretty_1 = require(43) /* ./util/pretty */;
    const cloneable_1 = require(32) /* ./util/cloneable */;
    const kinds = tslib_1.__importStar(require(22) /* ./kinds */);
    const vectorization_1 = require(29) /* ./vectorization */;
    const patching_1 = require(44) /* ./patching */;
    const _qualified_names = new WeakMap();
    class HasProps extends (0, signaling_1.Signalable)() {
        id;
        get is_syncable() {
            return true;
        }
        get type() {
            return this.constructor.__qualified__;
        }
        get is_root() {
            return this.document?.roots().includes(this) ?? false;
        }
        static __module__;
        static get __qualified__() {
            let qualified = _qualified_names.get(this);
            if (qualified == null) {
                const { __module__, name } = this;
                qualified = __module__ != null ? `${__module__}.${name}` : name;
                _qualified_names.set(this, qualified);
            }
            return qualified;
        }
        static set __qualified__(qualified) {
            _qualified_names.set(this, qualified);
        }
        get [Symbol.toStringTag]() {
            return this.constructor.__qualified__;
        }
        static {
            this.prototype._props = {};
            this.prototype._mixins = [];
        }
        static _fix_default(default_value, _attr) {
            if (default_value === undefined || default_value === p.unset) {
                return () => p.unset;
            }
            else if ((0, types_1.isFunction)(default_value)) {
                return default_value;
            }
            else if ((0, types_1.isPrimitive)(default_value)) {
                return () => default_value;
            }
            else {
                const cloner = new cloneable_1.Cloner();
                return () => cloner.clone(default_value);
            }
        }
        // TODO: don't use Partial<>, but exclude inherited properties
        static define(obj) {
            for (const [name, prop] of (0, object_1.entries)((0, types_1.isFunction)(obj) ? obj(kinds) : obj)) {
                if (name in this.prototype._props) {
                    throw new Error(`attempted to redefine property '${this.prototype.type}.${name}'`);
                }
                if (name in this.prototype) {
                    throw new Error(`attempted to redefine attribute '${this.prototype.type}.${name}'`);
                }
                Object.defineProperty(this.prototype, name, {
                    // XXX: don't use tail calls in getters/setters due to https://bugs.webkit.org/show_bug.cgi?id=164306
                    get() {
                        const value = this.properties[name].get_value();
                        return value;
                    },
                    set(value) {
                        this.setv({ [name]: value });
                        return this;
                    },
                    configurable: false,
                    enumerable: true,
                });
                const [type, default_value, options = {}] = prop;
                const refined_prop = {
                    type,
                    default_value: this._fix_default(default_value, name),
                    options,
                };
                this.prototype._props = {
                    ...this.prototype._props,
                    [name]: refined_prop,
                };
            }
        }
        static internal(obj) {
            const _object = {};
            for (const [name, prop] of (0, object_1.entries)((0, types_1.isFunction)(obj) ? obj(kinds) : obj)) {
                const [type, default_value, options = {}] = prop;
                _object[name] = [type, default_value, { ...options, internal: true }];
            }
            this.define(_object);
        }
        static mixins(defs) {
            function rename(prefix, mixin) {
                const result = {};
                for (const [name, prop] of (0, object_1.entries)(mixin)) {
                    result[prefix + name] = prop;
                }
                return result;
            }
            const mixin_defs = {};
            const mixins = [];
            for (const def of (0, types_1.isArray)(defs) ? defs : [defs]) {
                if ((0, types_1.isArray)(def)) {
                    const [prefix, mixin] = def;
                    (0, object_1.extend)(mixin_defs, rename(prefix, mixin));
                    mixins.push([prefix, mixin]);
                }
                else {
                    const mixin = def;
                    (0, object_1.extend)(mixin_defs, mixin);
                    mixins.push(["", mixin]);
                }
            }
            this.define(mixin_defs);
            this.prototype._mixins = [...this.prototype._mixins, ...mixins];
        }
        static override(obj) {
            for (const [name, prop] of (0, object_1.entries)(obj)) {
                const default_value = this._fix_default(prop, name);
                if (!(name in this.prototype._props)) {
                    throw new Error(`attempted to override nonexistent '${this.prototype.type}.${name}'`);
                }
                const value = this.prototype._props[name];
                const props = { ...this.prototype._props };
                props[name] = { ...value, default_value };
                this.prototype._props = props;
            }
        }
        static override_options(obj) {
            for (const [name, options] of (0, object_1.entries)(obj)) {
                if (!(name in this.prototype._props)) {
                    throw new Error(`attempted to override nonexistent '${this.prototype.type}.${name}'`);
                }
                const current = this.prototype._props[name];
                const props = {
                    ...this.prototype._props,
                    [name]: { ...current, options: { ...current.options, ...options } },
                };
                this.prototype._props = props;
            }
        }
        static toString() {
            return this.__qualified__;
        }
        toString() {
            return `${this.type}(${this.id})`;
        }
        document = null;
        destroyed = new signaling_1.Signal0(this, "destroyed");
        change = new signaling_1.Signal0(this, "change");
        transformchange = new signaling_1.Signal0(this, "transformchange");
        exprchange = new signaling_1.Signal0(this, "exprchange");
        streaming = new signaling_1.Signal0(this, "streaming");
        patching = new signaling_1.Signal(this, "patching");
        properties = {};
        property(name) {
            if (name in this.properties) {
                return this.properties[name];
            }
            else {
                throw new Error(`unknown property ${this.type}.${name}`);
            }
        }
        /**
         * Gets values of all set properties.
         */
        get attributes() {
            const attrs = {};
            for (const prop of this) {
                if (!prop.is_unset) {
                    attrs[prop.attr] = prop.get_value();
                }
            }
            return attrs;
        }
        /**
         * Gets values of all set and dirty (modified) properties.
         */
        get dirty_attributes() {
            const attrs = {};
            for (const prop of this) {
                if (!prop.is_unset && prop.dirty) {
                    attrs[prop.attr] = prop.get_value();
                }
            }
            return attrs;
        }
        [cloneable_1.clone](cloner) {
            const attrs = new Map();
            for (const prop of this) {
                if (prop.dirty) {
                    attrs.set(prop.attr, cloner.clone(prop.get_value()));
                }
            }
            return new this.constructor(attrs);
        }
        [eq_1.equals](that, cmp) {
            for (const p0 of this) {
                const p1 = that.property(p0.attr);
                if (!cmp.eq(p0.get_value(), p1.get_value())) {
                    return false;
                }
            }
            return true;
        }
        [pretty_1.pretty](printer) {
            const T = printer.token;
            const items = [];
            for (const prop of this) {
                if (prop.dirty) {
                    const value = prop.get_value();
                    items.push(`${prop.attr}${T(":")} ${printer.to_string(value)}`);
                }
            }
            const cls = this.constructor.__qualified__;
            return `${cls}${T("(")}${T("{")}${items.join(`${T(",")} `)}${T("}")}${T(")")}`;
        }
        [serialization_1.serialize](serializer) {
            const ref = this.ref();
            serializer.add_ref(this, ref);
            const attributes = {};
            for (const prop of this) {
                if (prop.syncable && (serializer.include_defaults || prop.dirty) && !(prop.readonly && prop.is_unset)) {
                    const value = prop.get_value();
                    attributes[prop.attr] = serializer.encode(value);
                }
            }
            const { type: name, id } = this;
            const rep = { type: "object", name, id };
            return (0, object_1.is_empty)(attributes) ? rep : { ...rep, attributes };
        }
        constructor(attrs = {}) {
            super();
            const deferred = (0, types_1.isPlainObject)(attrs) && "id" in attrs;
            this.id = deferred ? attrs.id : (0, string_1.unique_id)();
            for (const [name, { type, default_value, options }] of (0, object_1.entries)(this._props)) {
                let property;
                if (type instanceof p.PropertyAlias) {
                    const property = this.properties[type.attr];
                    if (typeof property === "undefined") {
                        throw new Error(`can't resolve ${type.attr} before ${name} to create an alias`);
                    }
                    Object.defineProperty(this.properties, name, {
                        get: () => property,
                        configurable: false,
                        enumerable: false,
                    });
                }
                else {
                    if (type instanceof k.Kind) {
                        property = new p.PrimitiveProperty(this, name, type, default_value, options);
                    }
                    else {
                        property = new type(this, name, k.Any, default_value, options);
                    }
                    this.properties[name] = property;
                }
            }
            // allowing us to defer initialization when loading many models
            // when loading a bunch of models, we want to do initialization as a second pass
            // because other objects that this one depends on might not be loaded yet
            if (deferred) {
                (0, assert_1.assert)((0, object_1.keys)(attrs).length == 1, "'id' cannot be used together with property initializers");
            }
            else {
                this.initialize_props(attrs);
                this.finalize();
                this.connect_signals();
            }
        }
        initialize_props(vals) {
            const vals_proxy = (0, object_1.dict)(vals);
            const visited = new Set();
            for (const prop of this) {
                const val = vals_proxy.get(prop.attr);
                prop.initialize(val);
                visited.add(prop.attr);
            }
            for (const [attr, val] of vals_proxy) {
                if (!visited.has(attr)) {
                    // either throws for unknown properties or updates aliased properties
                    this.property(attr).set_value(val);
                }
            }
        }
        finalize() {
            this.initialize();
        }
        initialize() { }
        assert_initialized() {
            for (const prop of this) {
                if (prop.syncable && !prop.readonly) {
                    prop.get_value();
                }
            }
        }
        connect_signals() {
            for (const prop of this) {
                if (!(prop instanceof p.VectorSpec || prop instanceof p.ScalarSpec)) {
                    continue;
                }
                if (prop.is_unset) {
                    continue;
                }
                const value = prop.get_value();
                if (value.transform != null) {
                    this.connect(value.transform.change, () => this.transformchange.emit());
                }
                if ((0, vectorization_1.isExpr)(value)) {
                    this.connect(value.expr.change, () => this.exprchange.emit());
                }
            }
        }
        disconnect_signals() {
            signaling_1.Signal.disconnect_receiver(this);
        }
        destroy() {
            this.disconnect_signals();
            this.destroyed.emit();
        }
        // Create a new model with exact attribute values to this one, but new identity.
        clone(attrs) {
            const cloner = new cloneable_1.Cloner();
            const that = cloner.clone(this);
            if (attrs != null) {
                that.setv(attrs);
            }
            return that;
        }
        _watchers = new WeakMap();
        _clear_watchers() {
            this._watchers = new WeakMap();
        }
        changed_for(obj) {
            const changed = this._watchers.get(obj);
            this._watchers.set(obj, false);
            return changed ?? true;
        }
        _pending = false;
        _changing = false;
        // Set a hash of model attributes on the object, firing `"change"`. This is
        // the core primitive operation of a model, updating the data and notifying
        // anyone who needs to know about the change in state. The heart of the beast.
        _setv(changes, options) {
            // Extract attributes and options.
            const check_eq = options.check_eq;
            const changed = new Set();
            const changing = this._changing;
            this._changing = true;
            const cmp = new eq_1.Comparator({ no_fail: true });
            for (const [prop, value] of changes) {
                if (check_eq === false || prop.is_unset || !cmp.eq(prop.get_value(), value)) {
                    prop.set_value(value);
                    changed.add(prop);
                }
            }
            // Trigger all relevant attribute changes.
            if (changed.size > 0) {
                this._clear_watchers();
                this._pending = true;
            }
            for (const prop of changed) {
                prop.change.emit();
            }
            // You might be wondering why there's a `while` loop here. Changes can
            // be recursively nested within `"change"` events.
            if (!changing) {
                if (!(options.no_change ?? false)) {
                    while (this._pending) {
                        this._pending = false;
                        this.change.emit();
                    }
                }
                this._pending = false;
                this._changing = false;
            }
            return changed;
        }
        setv(changed_attrs, options = {}) {
            const changes = (0, object_1.entries)(changed_attrs);
            if (changes.length == 0) {
                return;
            }
            if (options.silent ?? false) {
                this._clear_watchers();
                for (const [attr, value] of changes) {
                    this.properties[attr].set_value(value);
                }
                return;
            }
            const changed = new Map();
            const previous = new Map();
            for (const [attr, value] of changes) {
                const prop = this.properties[attr];
                changed.set(prop, value);
                previous.set(prop, prop.is_unset ? undefined : prop.get_value());
            }
            const updated = this._setv(changed, options);
            const { document } = this;
            if (document != null) {
                const changed = [];
                for (const [prop, value] of previous) {
                    if (updated.has(prop)) {
                        changed.push([prop, value, prop.get_value()]);
                    }
                }
                for (const [prop, _, new_value] of changed) {
                    if (prop.may_have_refs) {
                        document.partially_update_all_models(new_value);
                        break;
                    }
                }
                const sync = options.sync ?? true;
                this._push_changes(changed, sync);
            }
        }
        ref() {
            return { id: this.id };
        }
        *[Symbol.iterator]() {
            yield* (0, object_1.values)(this.properties);
        }
        *syncable_properties() {
            for (const prop of this) {
                if (prop.syncable) {
                    yield prop;
                }
            }
        }
        *own_properties() {
            const self = Object.getPrototypeOf(this);
            const base = Object.getPrototypeOf(self);
            const exclude = new Set((0, object_1.keys)(base._props));
            for (const prop of this) {
                if (!exclude.has(prop.attr)) {
                    yield prop;
                }
            }
        }
        // add all references from 'v' to 'result', if recurse
        // is true then descend into refs, if false only
        // descend into non-refs
        static _value_record_references(value, refs, options) {
            if (!(0, types_1.isObject)(value) || !(0, refs_1.may_have_refs)(value)) {
                return;
            }
            const { recursive } = options;
            if (value instanceof HasProps) {
                if (!refs.has(value)) {
                    refs.add(value);
                    if (recursive) {
                        for (const prop of value.syncable_properties()) {
                            if (!prop.is_unset && prop.may_have_refs) {
                                const value = prop.get_value();
                                HasProps._value_record_references(value, refs, { recursive });
                            }
                        }
                    }
                }
            }
            else if ((0, types_1.isIterable)(value)) {
                for (const elem of value) {
                    HasProps._value_record_references(elem, refs, { recursive });
                }
            }
            else if ((0, types_1.isPlainObject)(value)) {
                for (const elem of (0, object_1.values)(value)) {
                    HasProps._value_record_references(elem, refs, { recursive });
                }
            }
        }
        static references(value, options) {
            const refs = new Set();
            HasProps._value_record_references(value, refs, options);
            return refs;
        }
        references() {
            return HasProps.references(this, { recursive: true });
        }
        _doc_attached() { }
        _doc_detached() { }
        attach_document(doc) {
            // This should only be called by the Document implementation to set the document field
            if (this.document != null) {
                if (this.document == doc) {
                    return;
                }
                else {
                    throw new Error("models must be owned by only a single document");
                }
            }
            this.document = doc;
            this._doc_attached();
        }
        detach_document() {
            // This should only be called by the Document implementation to unset the document field
            if (this.document != null) {
                this._doc_detached();
                this.document = null;
            }
        }
        _push_changes(changes, sync) {
            if (!this.is_syncable) {
                return;
            }
            const { document } = this;
            if (document == null) {
                return;
            }
            const events = [];
            for (const [prop, , new_value] of changes) {
                if (prop.syncable) {
                    const event = new events_1.ModelChangedEvent(document, this, prop.attr, new_value);
                    event.sync = sync;
                    events.push(event);
                }
            }
            if (events.length != 0) {
                let event;
                if (events.length == 1) {
                    [event] = events;
                }
                else {
                    event = new events_1.DocumentEventBatch(document, events);
                }
                document._trigger_on_change(event);
            }
        }
        on_change(properties, fn) {
            for (const property of (0, types_1.isArray)(properties) ? properties : [properties]) {
                this.connect(property.change, fn);
            }
        }
        stream_to(prop, new_data, rollover, { sync } = {}) {
            const data = prop.get_value();
            (0, patching_1.stream_to_columns)(data, new_data, rollover);
            this._clear_watchers();
            prop.set_value(data);
            this.streaming.emit();
            if (this.document != null) {
                const event = new events_1.ColumnsStreamedEvent(this.document, this, prop.attr, new_data, rollover);
                event.sync = sync ?? true;
                this.document._trigger_on_change(event);
            }
        }
        patch_to(prop, patches, { sync } = {}) {
            const data = prop.get_value();
            const patched = (0, patching_1.patch_to_columns)(data, patches);
            this._clear_watchers();
            prop.set_value(data);
            this.patching.emit([...patched]);
            if (this.document != null) {
                const event = new events_1.ColumnsPatchedEvent(this.document, this, prop.attr, patches);
                event.sync = sync ?? true;
                this.document._trigger_on_change(event);
            }
        }
    }
    exports.HasProps = HasProps;
},
/* core/signaling.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.Signalable = Signalable;
    // Based on https://github.com/phosphorjs/phosphor/blob/master/packages/signaling/src/index.ts
    const defer_1 = require(18) /* ./util/defer */;
    const array_1 = require(10) /* ./util/array */;
    class Signal {
        sender;
        name;
        constructor(sender, name) {
            this.sender = sender;
            this.name = name;
        }
        connect(slot, context = null) {
            if (!exports.receivers_for_sender.has(this.sender)) {
                exports.receivers_for_sender.set(this.sender, []);
            }
            const receivers = exports.receivers_for_sender.get(this.sender);
            if (find_connection(receivers, this, slot, context) != null) {
                return false;
            }
            const receiver = context ?? slot;
            if (!senders_for_receiver.has(receiver)) {
                senders_for_receiver.set(receiver, []);
            }
            const senders = senders_for_receiver.get(receiver);
            const connection = { signal: this, slot, context };
            receivers.push(connection);
            senders.push(connection);
            return true;
        }
        disconnect(slot, context = null) {
            const receivers = exports.receivers_for_sender.get(this.sender);
            if (receivers == null || receivers.length === 0) {
                return false;
            }
            const connection = find_connection(receivers, this, slot, context);
            if (connection == null) {
                return false;
            }
            const receiver = context ?? slot;
            const senders = senders_for_receiver.get(receiver);
            connection.signal = null;
            schedule_cleanup(receivers);
            schedule_cleanup(senders);
            return true;
        }
        emit(args) {
            const receivers = exports.receivers_for_sender.get(this.sender) ?? [];
            for (const { signal, slot, context } of receivers) {
                if (signal === this) {
                    slot.call(context, args, this.sender);
                }
            }
        }
    }
    exports.Signal = Signal;
    class Signal0 extends Signal {
        emit() {
            super.emit(undefined);
        }
    }
    exports.Signal0 = Signal0;
    (function (Signal) {
        function disconnect_between(sender, receiver) {
            const receivers = exports.receivers_for_sender.get(sender);
            if (receivers == null || receivers.length === 0) {
                return;
            }
            const senders = senders_for_receiver.get(receiver);
            if (senders == null || senders.length === 0) {
                return;
            }
            for (const connection of senders) {
                if (connection.signal == null) {
                    return;
                }
                if (connection.signal.sender === sender) {
                    connection.signal = null;
                }
            }
            schedule_cleanup(receivers);
            schedule_cleanup(senders);
        }
        Signal.disconnect_between = disconnect_between;
        function disconnect_sender(sender) {
            const receivers = exports.receivers_for_sender.get(sender);
            if (receivers == null || receivers.length === 0) {
                return;
            }
            for (const connection of receivers) {
                if (connection.signal == null) {
                    return;
                }
                const receiver = connection.context ?? connection.slot;
                connection.signal = null;
                schedule_cleanup(senders_for_receiver.get(receiver));
            }
            schedule_cleanup(receivers);
        }
        Signal.disconnect_sender = disconnect_sender;
        function disconnect_receiver(receiver, slot, except_senders) {
            const senders = senders_for_receiver.get(receiver);
            if (senders == null || senders.length === 0) {
                return;
            }
            for (const connection of senders) {
                if (connection.signal == null) {
                    return;
                }
                if (slot != null && connection.slot != slot) {
                    continue;
                }
                const sender = connection.signal.sender;
                if (except_senders != null && except_senders.has(sender)) {
                    continue;
                }
                connection.signal = null;
                schedule_cleanup(exports.receivers_for_sender.get(sender));
            }
            schedule_cleanup(senders);
        }
        Signal.disconnect_receiver = disconnect_receiver;
        function disconnect_all(obj) {
            const receivers = exports.receivers_for_sender.get(obj);
            if (receivers != null && receivers.length !== 0) {
                for (const connection of receivers) {
                    connection.signal = null;
                }
                schedule_cleanup(receivers);
            }
            const senders = senders_for_receiver.get(obj);
            if (senders != null && senders.length !== 0) {
                for (const connection of senders) {
                    connection.signal = null;
                }
                schedule_cleanup(senders);
            }
        }
        Signal.disconnect_all = disconnect_all;
    })(Signal || (exports.Signal = Signal = {}));
    function Signalable() {
        return class {
            connect(signal, slot) {
                return signal.connect(slot, this);
            }
            disconnect(signal, slot) {
                return signal.disconnect(slot, this);
            }
        };
    }
    /** @internal */
    exports.receivers_for_sender = new WeakMap();
    const senders_for_receiver = new WeakMap();
    function find_connection(conns, signal, slot, context) {
        return (0, array_1.find)(conns, conn => conn.signal === signal && conn.slot === slot && conn.context === context);
    }
    const dirty_set = new Set();
    function schedule_cleanup(connections) {
        if (dirty_set.size == 0) {
            void (async () => {
                await (0, defer_1.defer)();
                cleanup_dirty_set();
            })();
        }
        dirty_set.add(connections);
    }
    function cleanup_dirty_set() {
        for (const connections of dirty_set) {
            (0, array_1.remove_by)(connections, (connection) => connection.signal == null);
        }
        dirty_set.clear();
    }
},
/* core/util/defer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.defer = defer;
    exports.delay = delay;
    exports.poll = poll;
    exports.paint = paint;
    exports.idle = idle;
    const channel = new MessageChannel();
    const tasks = new Map();
    channel.port1.onmessage = (event) => {
        const handle = event.data;
        const fn = tasks.get(handle);
        if (fn != null) {
            try {
                fn();
            }
            finally {
                tasks.delete(handle);
            }
        }
    };
    let counter = 1;
    function defer() {
        return new Promise((resolve) => {
            const handle = counter++;
            tasks.set(handle, resolve);
            channel.port2.postMessage(handle);
        });
    }
    function delay(ms) {
        return new Promise((resolve) => setTimeout(resolve, ms));
    }
    async function poll(fn, interval = 50, timeout = 500) {
        while (!fn() && timeout >= 0) {
            await delay(interval);
            timeout -= interval;
        }
    }
    function paint() {
        return new Promise((resolve) => {
            requestAnimationFrame(() => resolve());
        });
    }
    function idle() {
        return new Promise((resolve) => {
            requestIdleCallback(() => resolve());
        });
    }
},
/* core/util/refs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.is_ref = is_ref;
    exports.is_HasRefs = is_HasRefs;
    exports.may_have_refs = may_have_refs;
    const types_1 = require(8) /* ./types */;
    function is_ref(obj) {
        return (0, types_1.isPlainObject)(obj) && "id" in obj && !("type" in obj);
    }
    exports.has_refs = Symbol("has_refs");
    function _is_HasRefs(v) {
        return exports.has_refs in v;
    }
    function is_HasRefs(v) {
        return (0, types_1.isObject)(v) && _is_HasRefs(v);
    }
    function may_have_refs(obj) {
        if (_is_HasRefs(obj)) {
            return obj[exports.has_refs];
        }
        const type = obj.constructor;
        if (is_HasRefs(type)) {
            return type[exports.has_refs];
        }
        if ((0, types_1.isTypedArray)(obj)) {
            return false;
        }
        return true;
    }
},
/* core/properties.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.TextBaselineSpec = exports.TextAlignSpec = exports.FontStyleSpec = exports.FontSizeSpec = exports.FontSpec = exports.LineDashSpec = exports.LineCapSpec = exports.LineJoinSpec = exports.MarkerSpec = exports.ExtMarkerType = exports.ArraySpec = exports.NullStringSpec = exports.StringSpec = void 0;
    exports.isSpec = isSpec;
    exports.use_theme = use_theme;
    exports.Alias = Alias;
    const tslib_1 = require(1) /* tslib */;
    const signaling_1 = require(17) /* ./signaling */;
    const logging_1 = require(11) /* ./logging */;
    const enums = tslib_1.__importStar(require(21) /* ./enums */);
    const types_1 = require(25) /* ./types */;
    const array_1 = require(10) /* ./util/array */;
    const arrayable_1 = require(14) /* ./util/arrayable */;
    const math_1 = require(12) /* ./util/math */;
    const color_1 = require(23) /* ./util/color */;
    const platform_1 = require(28) /* ./util/platform */;
    const types_2 = require(8) /* ./util/types */;
    const vectorization_1 = require(29) /* ./vectorization */;
    const settings_1 = require(30) /* ./settings */;
    const kinds_1 = require(22) /* ./kinds */;
    const ndarray_1 = require(31) /* ./util/ndarray */;
    const diagnostics_1 = require(39) /* ./diagnostics */;
    const assert_1 = require(13) /* ./util/assert */;
    const serialization_1 = require(33) /* ./serialization */;
    const uniforms_1 = require(40) /* ./uniforms */;
    __esExport("Uniform", uniforms_1.Uniform);
    __esExport("UniformScalar", uniforms_1.UniformScalar);
    __esExport("UniformVector", uniforms_1.UniformVector);
    class ValidationError extends Error {
    }
    exports.ValidationError = ValidationError;
    function valueToString(value) {
        try {
            return JSON.stringify(value);
        }
        catch {
            return value.toString();
        }
    }
    function isSpec(obj) {
        return (0, types_2.isPlainObject)(obj) &&
            ((obj.value === undefined ? 0 : 1) +
                (obj.field === undefined ? 0 : 1) +
                (obj.expr === undefined ? 0 : 1) == 1); // garbage JS XOR
    }
    let global_theme = null;
    function use_theme(theme = null) {
        global_theme = theme;
    }
    exports.unset = Symbol("unset");
    class UnsetValueError extends Error {
    }
    exports.UnsetValueError = UnsetValueError;
    class Property {
        obj;
        attr;
        kind;
        default_value;
        __value__;
        get syncable() {
            return !this.internal;
        }
        _value = exports.unset;
        get is_unset() {
            return this._value === exports.unset;
        }
        _initialized = false;
        get initialized() {
            return this._initialized;
        }
        initialize(initial_value = exports.unset) {
            if (this._initialized) {
                throw new Error(`${this} is already initialized`);
            }
            let attr_value = exports.unset;
            if (initial_value !== exports.unset) {
                attr_value = initial_value;
                this._dirty = true;
            }
            else {
                const value = this._default_override();
                if (value !== exports.unset) {
                    attr_value = value;
                }
                else {
                    let themed = false;
                    if (global_theme != null) {
                        const value = global_theme.get(this.obj, this.attr);
                        if (value !== undefined) {
                            attr_value = value;
                            themed = true;
                        }
                    }
                    if (!themed) {
                        attr_value = this.default_value(this.obj);
                    }
                }
            }
            if (attr_value !== exports.unset) {
                if (this.kind.coerce != null) {
                    attr_value = this.kind.coerce(attr_value);
                }
                this._update(attr_value);
            }
            else {
                this._value = exports.unset;
            }
            this._initialized = true;
        }
        get_value() {
            if (this._value !== exports.unset) {
                return this._value;
            }
            else {
                throw new UnsetValueError(`${this} is unset`);
            }
        }
        set_value(val) {
            if (!this._initialized) {
                this.initialize(val);
            }
            else {
                this._update(val);
                this._dirty = true;
            }
            diagnostics_1.diagnostics.report(this);
        }
        // abstract _intrinsic_default(): T
        _default_override() {
            return exports.unset;
        }
        _dirty = false;
        get dirty() {
            return this._dirty;
        }
        may_have_refs;
        change;
        /*readonly*/ internal;
        readonly;
        constructor(obj, attr, kind, default_value, options = {}) {
            this.obj = obj;
            this.attr = attr;
            this.kind = kind;
            this.default_value = default_value;
            this.change = new signaling_1.Signal0(this.obj, "change");
            this.internal = options.internal ?? false;
            this.readonly = options.readonly ?? false;
            this.convert = options.convert;
            this.on_update = options.on_update;
            this.may_have_refs = kind.may_have_refs();
        }
        //protected abstract _update(attr_value: T): void
        _update(attr_value) {
            this.validate(attr_value);
            if (this.convert != null) {
                const converted = this.convert(attr_value, this.obj);
                if (converted !== undefined) {
                    attr_value = converted;
                }
            }
            this._value = attr_value;
            this.on_update?.(attr_value, this.obj);
        }
        to_full_string() {
            return `Prop(${this}, value: ${valueToString(this._value)})`;
        }
        toString() {
            return `${this.obj}.${this.attr}`;
        }
        // ----- customizable policies
        normalize(values) {
            return values;
        }
        validate(value) {
            if (!this.valid(value)) {
                throw new ValidationError(`${this} given invalid value: ${valueToString(value)}`);
            }
        }
        valid(value) {
            return this.kind.valid(value);
        }
    }
    exports.Property = Property;
    class PropertyAlias {
        attr;
        constructor(attr) {
            this.attr = attr;
        }
    }
    exports.PropertyAlias = PropertyAlias;
    function Alias(attr) {
        return new PropertyAlias(attr);
    }
    //
    // Primitive Properties
    //
    class PrimitiveProperty extends Property {
    }
    exports.PrimitiveProperty = PrimitiveProperty;
    class Font extends PrimitiveProperty {
        _default_override() {
            return settings_1.settings.dev ? "Bokeh" : exports.unset;
        }
    }
    exports.Font = Font;
    //
    // DataSpec properties
    //
    class ScalarSpec extends Property {
        __scalar__;
        _value = exports.unset;
        get_value() {
            if (this._value !== exports.unset) {
                return this._value;
            }
            else {
                throw new Error(`${this} is unset`);
            }
        }
        _update(attr_value) {
            if (isSpec(attr_value)) {
                this._value = attr_value;
            }
            else {
                this._value = { value: attr_value }; // Value<T>
            }
            if ((0, types_2.isPlainObject)(this._value)) {
                const { _value } = this;
                this._value[serialization_1.serialize] = (serializer) => {
                    const { value, field, expr, transform, units } = _value;
                    return serializer.encode_struct((() => {
                        if (value !== undefined) {
                            return { type: "value", value, transform, units };
                        }
                        else if (field !== undefined) {
                            return { type: "field", field, transform, units };
                        }
                        else {
                            return { type: "expr", expr, transform, units };
                        }
                    })());
                };
            }
            if ((0, vectorization_1.isValue)(this._value)) {
                this.validate(this._value.value);
            }
        }
        materialize(value) {
            return value;
        }
        scalar(value, n) {
            return new uniforms_1.UniformScalar(value, n);
        }
        uniform(source) {
            const obj = this.get_value();
            const n = source.get_length() ?? 1;
            if ((0, vectorization_1.isExpr)(obj)) {
                const { expr, transform } = obj;
                let result = expr.compute(source);
                if (transform != null) {
                    result = transform.compute(result);
                }
                result = this.materialize(result);
                return this.scalar(result, n);
            }
            else {
                const { value, transform } = obj;
                let result = value;
                if (transform != null) {
                    result = transform.compute(result);
                }
                result = this.materialize(result);
                return this.scalar(result, n);
            }
        }
    }
    exports.ScalarSpec = ScalarSpec;
    /** @deprecated */
    class AnyScalar extends ScalarSpec {
    }
    exports.AnyScalar = AnyScalar;
    class DictScalar extends ScalarSpec {
    }
    exports.DictScalar = DictScalar;
    class ColorScalar extends ScalarSpec {
    }
    exports.ColorScalar = ColorScalar;
    class NumberScalar extends ScalarSpec {
    }
    exports.NumberScalar = NumberScalar;
    class StringScalar extends ScalarSpec {
    }
    exports.StringScalar = StringScalar;
    class NullStringScalar extends ScalarSpec {
    }
    exports.NullStringScalar = NullStringScalar;
    class ArrayScalar extends ScalarSpec {
    }
    exports.ArrayScalar = ArrayScalar;
    class LineJoinScalar extends ScalarSpec {
    }
    exports.LineJoinScalar = LineJoinScalar;
    class LineCapScalar extends ScalarSpec {
    }
    exports.LineCapScalar = LineCapScalar;
    class LineDashScalar extends ScalarSpec {
    }
    exports.LineDashScalar = LineDashScalar;
    class FontScalar extends ScalarSpec {
        _default_override() {
            return settings_1.settings.dev ? "Bokeh" : exports.unset;
        }
    }
    exports.FontScalar = FontScalar;
    class FontSizeScalar extends ScalarSpec {
    }
    exports.FontSizeScalar = FontSizeScalar;
    class FontStyleScalar extends ScalarSpec {
    }
    exports.FontStyleScalar = FontStyleScalar;
    class TextAlignScalar extends ScalarSpec {
    }
    exports.TextAlignScalar = TextAlignScalar;
    class TextBaselineScalar extends ScalarSpec {
    }
    exports.TextBaselineScalar = TextBaselineScalar;
    class VectorSpec extends Property {
        __vector__;
        _value = exports.unset;
        get_value() {
            if (this._value !== exports.unset) {
                return this._value;
            }
            else {
                throw new Error(`${this} is unset`);
            }
        }
        _update(attr_value) {
            if (isSpec(attr_value)) {
                this._value = attr_value;
            }
            else {
                this._value = { value: attr_value };
            } // Value<T>
            if ((0, types_2.isPlainObject)(this._value)) {
                const { _value } = this;
                this._value[serialization_1.serialize] = (serializer) => {
                    const { value, field, expr, transform, units } = _value;
                    return serializer.encode_struct((() => {
                        if (value !== undefined) {
                            return { type: "value", value, transform, units };
                        }
                        else if (field !== undefined) {
                            return { type: "field", field, transform, units };
                        }
                        else {
                            return { type: "expr", expr, transform, units };
                        }
                    })());
                };
            }
            if ((0, vectorization_1.isValue)(this._value)) {
                this.validate(this._value.value);
            }
        }
        materialize(value) {
            return value;
        }
        v_materialize(values) {
            return values;
        }
        scalar(value, n) {
            return new uniforms_1.UniformScalar(value, n);
        }
        vector(values) {
            return new uniforms_1.UniformVector(values);
        }
        uniform(source) {
            const obj = this.get_value();
            const n = source.get_length() ?? 1;
            if ((0, vectorization_1.isField)(obj)) {
                const { field, transform } = obj;
                let array = source.get_column(field);
                if (array != null) {
                    if (transform != null) {
                        array = transform.v_compute(array);
                    }
                    array = this.v_materialize(array);
                    return this.vector(array);
                }
                else {
                    const message = `attempted to retrieve property array for nonexistent field '${field}'`;
                    if (settings_1.settings.force_fields) {
                        throw new Error(message);
                    }
                    else {
                        logging_1.logger.warn(message);
                    }
                    return this.scalar(null, n);
                }
            }
            else if ((0, vectorization_1.isExpr)(obj)) {
                const { expr, transform } = obj;
                let array = expr.v_compute(source);
                if (transform != null) {
                    array = transform.v_compute(array);
                }
                array = this.v_materialize(array);
                return this.vector(array);
            }
            else if ((0, vectorization_1.isValue)(obj)) {
                const { value, transform } = obj;
                let result = value;
                if (transform != null) {
                    result = transform.compute(result);
                }
                result = this.materialize(result);
                return this.scalar(result, n);
            }
            else {
                (0, assert_1.unreachable)();
            }
        }
        array(source) {
            let array;
            const length = source.get_length() ?? 1;
            const obj = this.get_value();
            if ((0, vectorization_1.isField)(obj)) {
                const { field } = obj;
                const column = source.get_column(field);
                if (column != null) {
                    array = this.normalize(column);
                }
                else {
                    const message = `attempted to retrieve property array for nonexistent field '${field}'`;
                    if (settings_1.settings.force_fields) {
                        throw new Error(message);
                    }
                    else {
                        logging_1.logger.warn(message);
                    }
                    const missing = new Float64Array(length);
                    missing.fill(NaN);
                    array = missing;
                }
            }
            else if ((0, vectorization_1.isExpr)(obj)) {
                const { expr } = obj;
                array = this.normalize(expr.v_compute(source));
            }
            else {
                const value = this.normalize([obj.value])[0];
                if ((0, types_2.isNumber)(value)) {
                    const values = new Float64Array(length);
                    values.fill(value);
                    array = values;
                }
                else {
                    array = (0, array_1.repeat)(value, length);
                }
            }
            const { transform } = obj;
            if (transform != null) {
                array = transform.v_compute(array);
            }
            return array;
        }
    }
    exports.VectorSpec = VectorSpec;
    class DataSpec extends VectorSpec {
    }
    exports.DataSpec = DataSpec;
    class UnitsSpec extends VectorSpec {
        _value = exports.unset;
        _update(attr_value) {
            super._update(attr_value);
            if (this._value !== exports.unset) {
                const { units } = this._value;
                if (units != null && !(0, array_1.includes)(this.valid_units, units)) {
                    throw new Error(`units must be one of ${this.valid_units.join(", ")}; got: ${units}`);
                }
            }
        }
        get units() {
            return this._value !== exports.unset ? this._value.units ?? this.default_units : this.default_units;
        }
        set units(units) {
            if (this._value !== exports.unset) {
                if (units != this.default_units) {
                    this._value.units = units;
                }
                else {
                    delete this._value.units;
                }
            }
            else {
                throw new Error(`${this} is unset`);
            }
        }
    }
    exports.UnitsSpec = UnitsSpec;
    class NumberUnitsSpec extends UnitsSpec {
        array(source) {
            return new Float64Array(super.array(source));
        }
    }
    exports.NumberUnitsSpec = NumberUnitsSpec;
    class BaseCoordinateSpec extends DataSpec {
    }
    exports.BaseCoordinateSpec = BaseCoordinateSpec;
    class CoordinateSpec extends BaseCoordinateSpec {
    }
    exports.CoordinateSpec = CoordinateSpec;
    class CoordinateSeqSpec extends BaseCoordinateSpec {
    }
    exports.CoordinateSeqSpec = CoordinateSeqSpec;
    class CoordinateSeqSeqSeqSpec extends BaseCoordinateSpec {
    }
    exports.CoordinateSeqSeqSeqSpec = CoordinateSeqSeqSeqSpec;
    class XCoordinateSpec extends CoordinateSpec {
        dimension = "x";
    }
    exports.XCoordinateSpec = XCoordinateSpec;
    class YCoordinateSpec extends CoordinateSpec {
        dimension = "y";
    }
    exports.YCoordinateSpec = YCoordinateSpec;
    class XCoordinateSeqSpec extends CoordinateSeqSpec {
        dimension = "x";
    }
    exports.XCoordinateSeqSpec = XCoordinateSeqSpec;
    class YCoordinateSeqSpec extends CoordinateSeqSpec {
        dimension = "y";
    }
    exports.YCoordinateSeqSpec = YCoordinateSeqSpec;
    class XCoordinateSeqSeqSeqSpec extends CoordinateSeqSeqSeqSpec {
        dimension = "x";
    }
    exports.XCoordinateSeqSeqSeqSpec = XCoordinateSeqSeqSeqSpec;
    class YCoordinateSeqSeqSeqSpec extends CoordinateSeqSeqSeqSpec {
        dimension = "y";
    }
    exports.YCoordinateSeqSeqSeqSpec = YCoordinateSeqSeqSeqSpec;
    class AngleSpec extends NumberUnitsSpec {
        get default_units() {
            return "rad";
        }
        get valid_units() {
            return [...enums.AngleUnits];
        }
        materialize(value) {
            const coeff = -(0, math_1.to_radians_coeff)(this.units);
            return value * coeff;
        }
        v_materialize(values) {
            const coeff = -(0, math_1.to_radians_coeff)(this.units);
            const result = new Float32Array(values.length);
            (0, arrayable_1.mul)(values, coeff, result); // TODO: in-place?
            return result;
        }
        array(_source) {
            throw new Error("not supported");
        }
    }
    exports.AngleSpec = AngleSpec;
    class DistanceSpec extends NumberUnitsSpec {
        get default_units() {
            return "data";
        }
        get valid_units() {
            return [...enums.SpatialUnits];
        }
    }
    exports.DistanceSpec = DistanceSpec;
    class NullDistanceSpec extends DistanceSpec {
        materialize(value) {
            return value ?? NaN;
        }
    }
    exports.NullDistanceSpec = NullDistanceSpec;
    class BooleanSpec extends DataSpec {
        v_materialize(values) {
            return new Uint8Array(values);
        }
        array(source) {
            return new Uint8Array(super.array(source));
        }
    }
    exports.BooleanSpec = BooleanSpec;
    class IntSpec extends DataSpec {
        v_materialize(values) {
            return (0, types_2.isTypedArray)(values) ? values : new Int32Array(values);
        }
        array(source) {
            return new Int32Array(super.array(source));
        }
    }
    exports.IntSpec = IntSpec;
    class NumberSpec extends DataSpec {
        v_materialize(values) {
            return (0, types_2.isTypedArray)(values) ? values : new Float64Array(values);
        }
        array(source) {
            return new Float64Array(super.array(source));
        }
    }
    exports.NumberSpec = NumberSpec;
    class ScreenSizeSpec extends NumberSpec {
        valid(value) {
            return (0, types_2.isNumber)(value) && value >= 0;
        }
    }
    exports.ScreenSizeSpec = ScreenSizeSpec;
    class ColorSpec extends DataSpec {
        materialize(color) {
            return (0, color_1.encode_rgba)((0, color_1.color2rgba)(color));
        }
        v_materialize(colors) {
            if ((0, ndarray_1.is_NDArray)(colors)) {
                if (colors.dtype == "uint32" && colors.dimension == 1) {
                    const colors_copy = colors.slice();
                    (0, platform_1.to_big_endian)(colors_copy);
                    return colors_copy;
                }
                else if (colors.dtype == "uint8" && colors.dimension == 1) {
                    const [n] = colors.shape;
                    const array = new types_1.RGBAArray(4 * n);
                    let j = 0;
                    for (const gray of colors) {
                        array[j++] = gray;
                        array[j++] = gray;
                        array[j++] = gray;
                        array[j++] = 255;
                    }
                    return new types_1.ColorArray(array.buffer);
                }
                else if (colors.dtype == "uint8" && colors.dimension == 2) {
                    const [n, d] = colors.shape;
                    if (d == 4) {
                        return new types_1.ColorArray(colors.buffer);
                    }
                    else if (d == 3) {
                        const array = new types_1.RGBAArray(4 * n);
                        for (let i = 0, j = 0; i < d * n;) {
                            array[j++] = colors[i++];
                            array[j++] = colors[i++];
                            array[j++] = colors[i++];
                            array[j++] = 255;
                        }
                        return new types_1.ColorArray(array.buffer);
                    }
                }
                else if ((colors.dtype == "float32" || colors.dtype == "float64") && colors.dimension == 2) {
                    const [n, d] = colors.shape;
                    if (d == 3 || d == 4) {
                        const array = new types_1.RGBAArray(4 * n);
                        for (let i = 0, j = 0; i < d * n;) {
                            array[j++] = colors[i++] * 255;
                            array[j++] = colors[i++] * 255;
                            array[j++] = colors[i++] * 255;
                            array[j++] = (d == 3 ? 1 : colors[i++]) * 255;
                        }
                        return new types_1.ColorArray(array.buffer);
                    }
                }
                else if (colors.dtype == "object" && colors.dimension == 1) {
                    return this._from_css_array(colors);
                }
            }
            else {
                return this._from_css_array(colors);
            }
            throw new Error("invalid color array");
        }
        _from_css_array(colors) {
            const n = colors.length;
            const array = new types_1.RGBAArray(4 * n);
            let j = 0;
            for (const color of colors) {
                const [r, g, b, a] = (0, color_1.color2rgba)(color);
                array[j++] = r;
                array[j++] = g;
                array[j++] = b;
                array[j++] = a;
            }
            return new types_1.ColorArray(array.buffer);
        }
        vector(values) {
            return new uniforms_1.ColorUniformVector(values);
        }
    }
    exports.ColorSpec = ColorSpec;
    class NDArraySpec extends DataSpec {
    }
    exports.NDArraySpec = NDArraySpec;
    /** @deprecated */
    class AnySpec extends DataSpec {
    }
    exports.AnySpec = AnySpec;
    class StringSpec extends DataSpec {
    }
    exports.StringSpec = StringSpec;
    class NullStringSpec extends DataSpec {
    }
    exports.NullStringSpec = NullStringSpec;
    class ArraySpec extends DataSpec {
    }
    exports.ArraySpec = ArraySpec;
    exports.ExtMarkerType = (0, kinds_1.PrefixedStr)("@");
    class MarkerSpec extends DataSpec {
    }
    exports.MarkerSpec = MarkerSpec;
    class LineJoinSpec extends DataSpec {
    }
    exports.LineJoinSpec = LineJoinSpec;
    class LineCapSpec extends DataSpec {
    }
    exports.LineCapSpec = LineCapSpec;
    class LineDashSpec extends DataSpec {
    }
    exports.LineDashSpec = LineDashSpec;
    class FontSpec extends DataSpec {
        _default_override() {
            return settings_1.settings.dev ? "Bokeh" : exports.unset;
        }
    }
    exports.FontSpec = FontSpec;
    class FontSizeSpec extends DataSpec {
    }
    exports.FontSizeSpec = FontSizeSpec;
    class FontStyleSpec extends DataSpec {
    }
    exports.FontStyleSpec = FontStyleSpec;
    class TextAlignSpec extends DataSpec {
    }
    exports.TextAlignSpec = TextAlignSpec;
    class TextBaselineSpec extends DataSpec {
    }
    exports.TextBaselineSpec = TextBaselineSpec;
},
/* core/enums.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.ToolName = exports.ToolIcon = exports.WindowAxis = exports.VerticalAlign = exports.UpdateMode = exports.TooltipAttachment = exports.LabelOrientation = exports.TimedeltaResolutionType = exports.TextureRepetition = exports.TextBaseline = exports.TextAlign = exports.TapGesture = exports.TapBehavior = exports.StepMode = exports.StartEnd = exports.SpatialUnits = exports.Sort = exports.SizingMode = exports.Side = exports.SelectionMode = exports.RegionSelectionMode = exports.ScrollbarPolicy = void 0;
    const kinds_1 = require(22) /* ./kinds */;
    exports.Align = (0, kinds_1.Enum)("start", "center", "end");
    exports.HAlign = (0, kinds_1.Enum)("left", "center", "right");
    exports.VAlign = (0, kinds_1.Enum)("top", "center", "bottom");
    exports.Anchor = (0, kinds_1.Enum)("top_left", "top_center", "top_right", "center_left", "center_center", "center_right", "bottom_left", "bottom_center", "bottom_right", "top", "left", "center", "right", "bottom");
    exports.AngleUnits = (0, kinds_1.Enum)("deg", "rad", "grad", "turn");
    exports.AlternationPolicy = (0, kinds_1.Enum)("none", "even", "odd", "every");
    exports.AxisLabelStandoffMode = (0, kinds_1.Enum)("tick_labels", "axis");
    exports.BoxOrigin = (0, kinds_1.Enum)("corner", "center");
    exports.ButtonType = (0, kinds_1.Enum)("default", "primary", "success", "warning", "danger", "light");
    exports.CalendarPosition = (0, kinds_1.Enum)("auto", "above", "below");
    exports.Clock = (0, kinds_1.Enum)("12h", "24h");
    exports.CoordinateUnits = (0, kinds_1.Enum)("canvas", "screen", "data");
    exports.ContextWhich = (0, kinds_1.Enum)("start", "center", "end", "all");
    exports.Dimension = (0, kinds_1.Enum)("width", "height");
    exports.Dimensions = (0, kinds_1.Enum)("width", "height", "both");
    exports.Direction = (0, kinds_1.Enum)("clock", "anticlock");
    exports.Distribution = (0, kinds_1.Enum)("uniform", "normal");
    exports.Face = (0, kinds_1.Enum)("front", "back");
    exports.FlowMode = (0, kinds_1.Enum)("block", "inline");
    exports.FontStyle = (0, kinds_1.Enum)("normal", "italic", "bold", "bold italic");
    exports.HatchPatternType = (0, kinds_1.Enum)("blank", "dot", "ring", "horizontal_line", "vertical_line", "cross", "horizontal_dash", "vertical_dash", "spiral", "right_diagonal_line", "left_diagonal_line", "diagonal_cross", "right_diagonal_dash", "left_diagonal_dash", "horizontal_wave", "vertical_wave", "criss_cross", " ", ".", "o", "-", "|", "+", '"', ":", "@", "/", "\\", "x", ",", "`", "v", ">", "*");
    exports.BuiltinFormatter = (0, kinds_1.Enum)("raw", "basic", "numeral", "printf", "datetime");
    exports.HTTPMethod = (0, kinds_1.Enum)("POST", "GET");
    exports.HexTileOrientation = (0, kinds_1.Enum)("pointytop", "flattop");
    exports.HoverMode = (0, kinds_1.Enum)("mouse", "hline", "vline");
    exports.ImageOrigin = (0, kinds_1.Enum)("bottom_left", "top_left", "bottom_right", "top_right");
    exports.LatLon = (0, kinds_1.Enum)("lat", "lon");
    exports.LegendClickPolicy = (0, kinds_1.Enum)("none", "hide", "mute");
    exports.LegendLocation = exports.Anchor;
    exports.LineCap = (0, kinds_1.Enum)("butt", "round", "square");
    exports.LineDash = (0, kinds_1.Enum)("solid", "dashed", "dotted", "dotdash", "dashdot");
    exports.LineJoin = (0, kinds_1.Enum)("miter", "round", "bevel");
    exports.LinePolicy = (0, kinds_1.Enum)("prev", "next", "nearest", "interp", "none");
    exports.Location = (0, kinds_1.Enum)("above", "below", "left", "right");
    exports.Logo = (0, kinds_1.Enum)("normal", "grey");
    exports.MapType = (0, kinds_1.Enum)("satellite", "roadmap", "terrain", "hybrid");
    exports.MarkerType = (0, kinds_1.Enum)("asterisk", "circle", "circle_cross", "circle_dot", "circle_x", "circle_y", "cross", "dash", "diamond", "diamond_cross", "diamond_dot", "dot", "hex", "hex_dot", "inverted_triangle", "plus", "square", "square_cross", "square_dot", "square_pin", "square_x", "star", "star_dot", "triangle", "triangle_dot", "triangle_pin", "x", "y");
    exports.MutedPolicy = (0, kinds_1.Enum)("show", "ignore");
    exports.Orientation = (0, kinds_1.Enum)("vertical", "horizontal");
    exports.OutlineShapeName = (0, kinds_1.Enum)("none", "box", "rectangle", "square", "circle", "ellipse", "trapezoid", "parallelogram", "diamond", "triangle");
    exports.OutputBackend = (0, kinds_1.Enum)("canvas", "svg", "webgl");
    exports.PaddingUnits = (0, kinds_1.Enum)("percent", "absolute");
    exports.PanDirection = (0, kinds_1.Enum)("left", "right", "up", "down", "west", "east", "north", "south");
    exports.Place = (0, kinds_1.Enum)("above", "below", "left", "right", "center");
    exports.PointPolicy = (0, kinds_1.Enum)("snap_to_data", "follow_mouse", "none");
    exports.RadiusDimension = (0, kinds_1.Enum)("x", "y", "max", "min");
    exports.RenderLevel = (0, kinds_1.Enum)("image", "underlay", "glyph", "guide", "annotation", "overlay");
    exports.ResetPolicy = (0, kinds_1.Enum)("standard", "event_only");
    exports.ResolutionType = (0, kinds_1.Enum)("microseconds", "milliseconds", "seconds", "minsec", "minutes", "hourmin", "hours", "days", "months", "years");
    exports.RoundingFunction = (0, kinds_1.Enum)("round", "nearest", "floor", "rounddown", "ceil", "roundup");
    exports.ScrollbarPolicy = (0, kinds_1.Enum)("auto", "visible", "hidden");
    exports.RegionSelectionMode = (0, kinds_1.Enum)("replace", "append", "intersect", "subtract", "xor");
    exports.SelectionMode = (0, kinds_1.Enum)(...exports.RegionSelectionMode, "toggle");
    exports.Side = (0, kinds_1.Enum)("above", "below", "left", "right");
    exports.SizingMode = (0, kinds_1.Enum)("stretch_width", "stretch_height", "stretch_both", "scale_width", "scale_height", "scale_both", "fixed", "inherit");
    exports.Sort = (0, kinds_1.Enum)("ascending", "descending");
    exports.SpatialUnits = (0, kinds_1.Enum)("screen", "data");
    exports.StartEnd = (0, kinds_1.Enum)("start", "end");
    exports.StepMode = (0, kinds_1.Enum)("after", "before", "center");
    exports.TapBehavior = (0, kinds_1.Enum)("select", "inspect");
    exports.TapGesture = (0, kinds_1.Enum)("tap", "doubletap");
    exports.TextAlign = (0, kinds_1.Enum)("left", "right", "center");
    exports.TextBaseline = (0, kinds_1.Enum)("top", "middle", "bottom", "alphabetic", "hanging", "ideographic");
    exports.TextureRepetition = (0, kinds_1.Enum)("repeat", "repeat_x", "repeat_y", "no_repeat");
    exports.TimedeltaResolutionType = (0, kinds_1.Enum)("nanoseconds", "microseconds", "milliseconds", "seconds", "minsec", "minutes", "hourmin", "hours", "days");
    exports.LabelOrientation = (0, kinds_1.Enum)("vertical", "horizontal", "parallel", "normal");
    exports.TooltipAttachment = (0, kinds_1.Enum)("horizontal", "vertical", "left", "right", "above", "below");
    exports.UpdateMode = (0, kinds_1.Enum)("replace", "append");
    exports.VerticalAlign = (0, kinds_1.Enum)("top", "middle", "bottom");
    exports.WindowAxis = (0, kinds_1.Enum)("none", "x", "y");
    // Keep this in sync with bokehjs/src/less/icons.less
    exports.ToolIcon = (0, kinds_1.Enum)("append_mode", "arrow_down_to_bar", "arrow_up_from_bar", "auto_box_zoom", "bold", "box_edit", "box_select", "box_zoom", "caret_down", "caret_left", "caret_right", "caret_up", "check", "chevron_down", "chevron_left", "chevron_right", "chevron_up", "clear_selection", "copy", "crosshair", "dark_theme", "delete", "freehand_draw", "fullscreen", "help", "hover", "intersect_mode", "invert_selection", "italic", "lasso_select", "light_theme", "line_edit", "maximize", "minimize", "pan", "pin", "point_draw", "pointer", "poly_draw", "poly_edit", "polygon_select", "range", "redo", "replace_mode", "reset", "save", "see_off", "see_on", "settings", "square", "square_check", "subtract_mode", "tap_select", "text_align_center", "text_align_left", "text_align_right", "undo", "unknown", "unpin", "wheel_pan", "wheel_zoom", "x_box_select", "x_box_zoom", "x_grip", "x_pan", "xor_mode", "y_box_select", "y_box_zoom", "y_grip", "y_pan", "zoom_in", "zoom_out");
    exports.ToolName = (0, kinds_1.Enum)("auto_box_zoom", "box_select", "box_zoom", "click", "copy", "crosshair", "doubletap", "examine", "freehand_draw", "fullscreen", "help", "hover", "lasso_select", "pan", "pan_down", "pan_east", "pan_left", "pan_north", "pan_right", "pan_south", "pan_up", "pan_west", "poly_select", "redo", "reset", "save", "tap", "undo", "wheel_zoom", "xbox_select", "xbox_zoom", "xcrosshair", "xpan", "xwheel_pan", "xwheel_zoom", "xzoom_in", "xzoom_out", "ybox_select", "ybox_zoom", "ycrosshair", "ypan", "ywheel_pan", "ywheel_zoom", "yzoom_in", "yzoom_out", "zoom_in", "zoom_out");
},
/* core/kinds.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const tp = tslib_1.__importStar(require(8) /* ./util/types */);
    const color_1 = require(23) /* ./util/color */;
    const object_1 = require(9) /* ./util/object */;
    const refs_1 = require(19) /* ./util/refs */;
    const ESMap = globalThis.Map;
    const ESSet = globalThis.Set;
    const DOMNode = globalThis.Node;
    class Kind {
        get kind_name() {
            return this.constructor.name;
        }
        get kind_args() {
            return [];
        }
        toString() {
            const { kind_name, kind_args } = this;
            if (kind_args.length == 0) {
                return kind_name;
            }
            else {
                return `${kind_name}(${kind_args.map((arg) => `${arg}`).join(", ")})`;
            }
        }
    }
    exports.Kind = Kind;
    (function (Kinds) {
        class Primitive extends Kind {
            may_have_refs() {
                return false;
            }
        }
        Kinds.Primitive = Primitive;
        class Any extends Primitive {
            valid(value) {
                return value !== undefined;
            }
            may_have_refs() {
                return true;
            }
        }
        Kinds.Any = Any;
        class Unknown extends Primitive {
            valid(value) {
                return value !== undefined;
            }
            may_have_refs() {
                return true;
            }
        }
        Kinds.Unknown = Unknown;
        class Bool extends Primitive {
            valid(value) {
                return tp.isBoolean(value);
            }
        }
        Kinds.Bool = Bool;
        class Ref extends Kind {
            obj_type;
            constructor(obj_type) {
                super();
                this.obj_type = obj_type;
            }
            valid(value) {
                return value instanceof this.obj_type;
            }
            get type_name() {
                return this.obj_type.name;
            }
            toString() {
                return `${this.kind_name}(${this.type_name})`;
            }
            may_have_refs() {
                const { obj_type } = this;
                return refs_1.has_refs in obj_type ? obj_type[refs_1.has_refs] : true;
            }
        }
        Kinds.Ref = Ref;
        class AnyRef extends Kind {
            valid(value) {
                return tp.isObject(value);
            }
            may_have_refs() {
                return true;
            }
        }
        Kinds.AnyRef = AnyRef;
        class Float extends Primitive {
            valid(value) {
                return tp.isNumber(value);
            }
        }
        Kinds.Float = Float;
        class Int extends Float {
            valid(value) {
                return super.valid(value) && tp.isInteger(value);
            }
        }
        Kinds.Int = Int;
        class Percent extends Float {
            valid(value) {
                return super.valid(value) && 0 <= value && value <= 1;
            }
        }
        Kinds.Percent = Percent;
        class Or extends Kind {
            types;
            constructor(types) {
                super();
                this.types = types;
                this.types = types;
            }
            valid(value) {
                return this.types.some((type) => type.valid(value));
            }
            get kind_args() {
                return this.types;
            }
            may_have_refs() {
                return this.types.some((type) => type.may_have_refs());
            }
        }
        Kinds.Or = Or;
        class And extends Kind {
            types;
            constructor(type0, type1) {
                super();
                this.types = [type0, type1];
            }
            valid(value) {
                return this.types.some((type) => type.valid(value)); // TODO not sure if this is correct, probably not
            }
            get kind_args() {
                return this.types;
            }
            may_have_refs() {
                return this.types.some((type) => type.may_have_refs());
            }
        }
        Kinds.And = And;
        class Tuple extends Kind {
            types;
            constructor(types) {
                super();
                this.types = types;
                this.types = types;
            }
            valid(value) {
                if (!tp.isArray(value)) {
                    return false;
                }
                for (let i = 0; i < this.types.length; i++) {
                    const type = this.types[i];
                    const item = value[i];
                    if (!type.valid(item)) {
                        return false;
                    }
                }
                return true;
            }
            get kind_args() {
                return this.types;
            }
            may_have_refs() {
                return this.types.some((type) => type.may_have_refs());
            }
        }
        Kinds.Tuple = Tuple;
        class Struct extends Kind {
            struct_type;
            constructor(struct_type) {
                super();
                this.struct_type = struct_type;
            }
            valid(value) {
                if (!tp.isPlainObject(value)) {
                    return false;
                }
                const struct_type_proxy = new object_1.PlainObjectProxy(this.struct_type);
                for (const key of (0, object_1.keys)(value)) {
                    if (!struct_type_proxy.has(key)) {
                        return false;
                    }
                }
                for (const [key, item_type] of struct_type_proxy) {
                    const item = value[key];
                    if (!item_type.valid(item)) {
                        return false;
                    }
                }
                return true;
            }
            toString() {
                const items = (0, object_1.typed_entries)(this.struct_type).map(([key, kind]) => `${key.toString()}: ${kind}`).join(", ");
                return `${this.kind_name}({${items}})`;
            }
            may_have_refs() {
                return (0, object_1.typed_values)(this.struct_type).some((kind) => kind.may_have_refs());
            }
        }
        Kinds.Struct = Struct;
        class PartialStruct extends Kind {
            struct_type;
            constructor(struct_type) {
                super();
                this.struct_type = struct_type;
            }
            valid(value) {
                if (!tp.isPlainObject(value)) {
                    return false;
                }
                const value_proxy = new object_1.PlainObjectProxy(value);
                const struct_type_proxy = new object_1.PlainObjectProxy(this.struct_type);
                for (const key of value_proxy.keys()) {
                    if (!struct_type_proxy.has(key)) {
                        return false;
                    }
                }
                for (const [key, item_type] of struct_type_proxy) {
                    const item = value_proxy.get(key);
                    if (item === undefined) {
                        continue;
                    }
                    if (!item_type.valid(item)) {
                        return false;
                    }
                }
                return true;
            }
            toString() {
                const items = (0, object_1.typed_entries)(this.struct_type).map(([key, kind]) => `${key.toString()}?: ${kind}`).join(", ");
                return `${this.kind_name}({${items}})`;
            }
            may_have_refs() {
                return (0, object_1.typed_values)(this.struct_type).some((kind) => kind.may_have_refs());
            }
        }
        Kinds.PartialStruct = PartialStruct;
        class Iterable extends Kind {
            item_type;
            constructor(item_type) {
                super();
                this.item_type = item_type;
            }
            valid(value) {
                return tp.isIterable(value);
            }
            get kind_args() {
                return [this.item_type];
            }
            may_have_refs() {
                return this.item_type.may_have_refs();
            }
        }
        Kinds.Iterable = Iterable;
        class Arrayable extends Kind {
            item_type;
            constructor(item_type) {
                super();
                this.item_type = item_type;
            }
            valid(value) {
                return tp.isArray(value) || tp.isTypedArray(value); // TODO: too specific
            }
            get kind_args() {
                return [this.item_type];
            }
            may_have_refs() {
                return this.item_type.may_have_refs();
            }
        }
        Kinds.Arrayable = Arrayable;
        class List extends Kind {
            item_type;
            constructor(item_type) {
                super();
                this.item_type = item_type;
            }
            valid(value) {
                return tp.isArray(value) && value.every((item) => this.item_type.valid(item));
            }
            get kind_args() {
                return [this.item_type];
            }
            may_have_refs() {
                return this.item_type.may_have_refs();
            }
        }
        Kinds.List = List;
        class NonEmptyList extends List {
            valid(value) {
                return super.valid(value) && value.length != 0;
            }
            get kind_args() {
                return [this.item_type];
            }
        }
        Kinds.NonEmptyList = NonEmptyList;
        class Null extends Primitive {
            valid(value) {
                return value === null;
            }
        }
        Kinds.Null = Null;
        class Nullable extends Kind {
            base_type;
            constructor(base_type) {
                super();
                this.base_type = base_type;
            }
            valid(value) {
                return value === null || this.base_type.valid(value);
            }
            get kind_args() {
                return [this.base_type];
            }
            may_have_refs() {
                return this.base_type.may_have_refs();
            }
        }
        Kinds.Nullable = Nullable;
        class Opt extends Kind {
            base_type;
            constructor(base_type) {
                super();
                this.base_type = base_type;
            }
            valid(value) {
                return value === undefined || this.base_type.valid(value);
            }
            get kind_args() {
                return [this.base_type];
            }
            may_have_refs() {
                return this.base_type.may_have_refs();
            }
        }
        Kinds.Opt = Opt;
        class Bytes extends Kind {
            valid(value) {
                return value instanceof ArrayBuffer;
            }
            may_have_refs() {
                return false;
            }
        }
        Kinds.Bytes = Bytes;
        class Str extends Primitive {
            valid(value) {
                return tp.isString(value);
            }
        }
        Kinds.Str = Str;
        class PrefixedStr extends Primitive {
            prefix;
            constructor(prefix) {
                super();
                this.prefix = prefix;
            }
            valid(value) {
                return tp.isString(value) && value.startsWith(this.prefix);
            }
            get kind_args() {
                return [this.prefix];
            }
        }
        Kinds.PrefixedStr = PrefixedStr;
        class Regex extends Str {
            regex;
            constructor(regex) {
                super();
                this.regex = regex;
            }
            valid(value) {
                return super.valid(value) && this.regex.test(value);
            }
            get kind_args() {
                return [this.regex];
            }
        }
        Kinds.Regex = Regex;
        class Enum extends Primitive {
            values;
            constructor(values) {
                super();
                this.values = new ESSet(values);
            }
            valid(value) {
                return this.values.has(value);
            }
            *[Symbol.iterator]() {
                yield* this.values;
            }
            get kind_args() {
                return [...this.values];
            }
        }
        Kinds.Enum = Enum;
        class Dict extends Kind {
            item_type;
            constructor(item_type) {
                super();
                this.item_type = item_type;
            }
            valid(value) {
                if (!(value instanceof ESMap || tp.isPlainObject(value))) {
                    return false;
                }
                for (const item of (0, object_1.values)(value)) {
                    if (!this.item_type.valid(item)) {
                        return false;
                    }
                }
                return true;
            }
            get kind_args() {
                return [this.item_type];
            }
            may_have_refs() {
                return this.item_type.may_have_refs();
            }
        }
        Kinds.Dict = Dict;
        class KeyVal extends Kind {
            key_type;
            item_type;
            constructor(key_type, item_type) {
                super();
                this.key_type = key_type;
                this.item_type = item_type;
            }
            valid(value) {
                if (!(value instanceof ESMap || tp.isPlainObject(value))) {
                    return false;
                }
                for (const [key, item] of (0, object_1.entries)(value)) {
                    if (!this.key_type.valid(key) || !this.item_type.valid(item)) {
                        return false;
                    }
                }
                return true;
            }
            get kind_args() {
                return [this.key_type, this.item_type];
            }
            may_have_refs() {
                return this.key_type.may_have_refs() || this.item_type.may_have_refs();
            }
        }
        Kinds.KeyVal = KeyVal;
        class Mapping extends Kind {
            key_type;
            item_type;
            constructor(key_type, item_type) {
                super();
                this.key_type = key_type;
                this.item_type = item_type;
            }
            coerce(value) {
                // HACK accommodate for deserialization of {type: "map"}
                if (tp.isPlainObject(value) && (0, object_1.is_empty)(value)) {
                    return new ESMap();
                }
                else {
                    return value;
                }
            }
            valid(value) {
                if (!(value instanceof ESMap)) {
                    return false;
                }
                for (const [key, item] of value.entries()) {
                    if (!(this.key_type.valid(key) && this.item_type.valid(item))) {
                        return false;
                    }
                }
                return true;
            }
            get kind_args() {
                return [this.key_type, this.item_type];
            }
            may_have_refs() {
                return this.key_type.may_have_refs() || this.item_type.may_have_refs();
            }
        }
        Kinds.Mapping = Mapping;
        class Set extends Kind {
            item_type;
            constructor(item_type) {
                super();
                this.item_type = item_type;
            }
            valid(value) {
                if (!(value instanceof ESSet)) {
                    return false;
                }
                for (const item of value) {
                    if (!this.item_type.valid(item)) {
                        return false;
                    }
                }
                return true;
            }
            get kind_args() {
                return [this.item_type];
            }
            may_have_refs() {
                return this.item_type.may_have_refs();
            }
        }
        Kinds.Set = Set;
        class Color extends Kind {
            valid(value) {
                return (0, color_1.is_Color)(value);
            }
            may_have_refs() {
                return false;
            }
        }
        Kinds.Color = Color;
        class CSSLength extends Str {
        }
        Kinds.CSSLength = CSSLength;
        class Func extends Kind {
            args_types;
            ret_type;
            constructor(args_types, ret_type) {
                super();
                this.args_types = args_types;
                this.ret_type = ret_type;
            }
            valid(value) {
                return tp.isFunction(value);
            }
            toString() {
                const { args_types, ret_type } = this;
                const args = args_types == null ? "?" : args_types.map((type) => type.toString()).join(", ");
                const ret = ret_type == null ? "?" : ret_type.toString();
                return `${this.kind_name}((${args}), ${ret})`;
            }
            may_have_refs() {
                return false;
            }
        }
        Kinds.Func = Func;
        class NonNegative extends Kind {
            base_type;
            constructor(base_type) {
                super();
                this.base_type = base_type;
            }
            valid(value) {
                return this.base_type.valid(value) && value >= 0;
            }
            get kind_args() {
                return [this.base_type];
            }
            may_have_refs() {
                return this.base_type.may_have_refs();
            }
        }
        Kinds.NonNegative = NonNegative;
        class Positive extends Kind {
            base_type;
            constructor(base_type) {
                super();
                this.base_type = base_type;
            }
            valid(value) {
                return this.base_type.valid(value) && value > 0;
            }
            get kind_args() {
                return [this.base_type];
            }
            may_have_refs() {
                return this.base_type.may_have_refs();
            }
        }
        Kinds.Positive = Positive;
        class Node extends Kind {
            valid(value) {
                return value instanceof DOMNode;
            }
            may_have_refs() {
                return false;
            }
        }
        Kinds.Node = Node;
    })(exports.Kinds || (exports.Kinds = {}));
    exports.Any = new exports.Kinds.Any();
    exports.Unknown = new exports.Kinds.Unknown();
    exports.Bool = new exports.Kinds.Bool();
    exports.Float = new exports.Kinds.Float();
    exports.Int = new exports.Kinds.Int();
    exports.Bytes = new exports.Kinds.Bytes();
    exports.Str = new exports.Kinds.Str();
    const PrefixedStr = (prefix) => new exports.Kinds.PrefixedStr(prefix);
    exports.PrefixedStr = PrefixedStr;
    const Regex = (regex) => new exports.Kinds.Regex(regex);
    exports.Regex = Regex;
    exports.Null = new exports.Kinds.Null();
    const Nullable = (base_type) => new exports.Kinds.Nullable(base_type);
    exports.Nullable = Nullable;
    const Opt = (base_type) => new exports.Kinds.Opt(base_type);
    exports.Opt = Opt;
    const Or = (...types) => new exports.Kinds.Or(types);
    exports.Or = Or;
    const And = (type0, type1) => new exports.Kinds.And(type0, type1);
    exports.And = And;
    const Tuple = (...types) => new exports.Kinds.Tuple(types);
    exports.Tuple = Tuple;
    const Struct = (struct_type) => new exports.Kinds.Struct(struct_type);
    exports.Struct = Struct;
    const PartialStruct = (struct_type) => new exports.Kinds.PartialStruct(struct_type);
    exports.PartialStruct = PartialStruct;
    const Iterable = (item_type) => new exports.Kinds.Iterable(item_type);
    exports.Iterable = Iterable;
    const Arrayable = (item_type) => new exports.Kinds.Arrayable(item_type);
    exports.Arrayable = Arrayable;
    const List = (item_type) => new exports.Kinds.List(item_type);
    exports.List = List;
    const NonEmptyList = (item_type) => new exports.Kinds.NonEmptyList(item_type);
    exports.NonEmptyList = NonEmptyList;
    const Dict = (item_type) => new exports.Kinds.Dict(item_type);
    exports.Dict = Dict;
    const KeyVal = (key_type, item_type) => new exports.Kinds.KeyVal(key_type, item_type);
    exports.KeyVal = KeyVal;
    const Mapping = (key_type, item_type) => new exports.Kinds.Mapping(key_type, item_type);
    exports.Mapping = Mapping;
    const Set = (item_type) => new exports.Kinds.Set(item_type);
    exports.Set = Set;
    const Enum = (...values) => new exports.Kinds.Enum(values);
    exports.Enum = Enum;
    const Ref = (obj_type) => new exports.Kinds.Ref(obj_type);
    exports.Ref = Ref;
    const AnyRef = () => new exports.Kinds.AnyRef();
    exports.AnyRef = AnyRef;
    const Func = (args_types, ret_type) => new exports.Kinds.Func(args_types, ret_type);
    exports.Func = Func;
    const Func0 = (ret_type) => new exports.Kinds.Func([], ret_type);
    exports.Func0 = Func0;
    exports.Node = new exports.Kinds.Node();
    const NonNegative = (base_type) => new exports.Kinds.NonNegative(base_type);
    exports.NonNegative = NonNegative;
    const Positive = (base_type) => new exports.Kinds.Positive(base_type);
    exports.Positive = Positive;
    exports.Percent = new exports.Kinds.Percent();
    exports.Alpha = exports.Percent;
    exports.Color = new exports.Kinds.Color();
    exports.Auto = (0, exports.Enum)("auto");
    exports.CSSLength = new exports.Kinds.CSSLength();
    exports.FontSize = exports.Str;
    exports.Font = exports.Str;
    exports.Angle = exports.Float;
    // backwards compatibility aliases (these collide with built-in types)
    /** @deprecated */
    exports.Boolean = exports.Bool;
    /** @deprecated */
    exports.String = exports.Str;
    /** @deprecated */
    exports.Number = exports.Float;
    /** @deprecated */
    exports.Array = exports.List;
    /** @deprecated */
    exports.Map = exports.Mapping;
    /** @deprecated */
    exports.Function = exports.Func;
},
/* core/util/color.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.byte = byte;
    exports.transparent = transparent;
    exports.encode_rgba = encode_rgba;
    exports.decode_rgba = decode_rgba;
    exports.color2rgba = color2rgba;
    exports.rgba2css = rgba2css;
    exports.color2css = color2css;
    exports.color2hex = color2hex;
    exports.color2hexrgb = color2hexrgb;
    exports.css4_parse = css4_parse;
    exports.is_Color = is_Color;
    exports.is_dark = is_dark;
    exports.brightness = brightness;
    exports.luminance = luminance;
    const svg_colors_1 = require(24) /* ./svg_colors */;
    const math_1 = require(12) /* ./math */;
    const types_1 = require(8) /* ./types */;
    const { round, sqrt } = Math;
    function byte(v) {
        return (0, math_1.clamp)(round(v), 0, 255);
    }
    function transparent() {
        return [0, 0, 0, 0];
    }
    function encode_rgba([r, g, b, a]) {
        return r << 24 | g << 16 | b << 8 | a;
    }
    function decode_rgba(rgba) {
        const r = (rgba >> 24) & 0xff;
        const g = (rgba >> 16) & 0xff;
        const b = (rgba >> 8) & 0xff;
        const a = rgba & 0xff;
        return [r, g, b, a];
    }
    function color2rgba(color, alpha = 1.0) {
        const [r, g, b, a] = (() => {
            if (color == null) {
                return transparent();
            }
            else if ((0, types_1.isInteger)(color)) {
                return decode_rgba(color);
            }
            else if ((0, types_1.isString)(color)) {
                const [r, g, b, a] = css4_parse(color) ?? transparent();
                return [r, g, b, byte(a * 255)];
            }
            else {
                if (color.length == 2) {
                    const [name, alpha] = color;
                    return color2rgba(name, alpha);
                }
                else {
                    const [r, g, b, a = 1.0] = color;
                    return [r, g, b, byte(a * 255)];
                }
            }
        })();
        return [r, g, b, byte(alpha * a)];
    }
    const _hex_table = {
        0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9",
        10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f",
    };
    function hex(v) {
        return _hex_table[v >> 4] + _hex_table[v & 0xf];
    }
    function rgba2css([r, g, b, a]) {
        const alpha = a == 255 ? "" : ` / ${a / 255}`;
        return `rgb(${r} ${g} ${b}${alpha})`;
    }
    function color2css(color, alpha) {
        if ((0, types_1.isString)(color) && (alpha == null || alpha == 1.0)) {
            return color; // passthrough to persist color in its original form
        }
        else {
            const [r, g, b, a] = color2rgba(color, alpha);
            return rgba2css([r, g, b, a]);
        }
    }
    function color2hex(color, alpha) {
        const [r, g, b, a] = color2rgba(color, alpha);
        const rgb = `#${hex(r)}${hex(g)}${hex(b)}`;
        return a == 255 ? rgb : `${rgb}${hex(a)}`;
    }
    function color2hexrgb(color) {
        const [r, g, b] = color2rgba(color);
        return `#${hex(r)}${hex(g)}${hex(b)}`;
    }
    /*
    let _last_color = "transparent"
    let _last_alpha = 1.0
    let _last_rgba = transparent()
    
    export function _color2rgba(color: string | null, alpha: number = 1.0): RGBA {
      if (color == _last_color && alpha == _last_alpha)
        return [..._last_rgba]
    
      const [r, g, b, a] = parsed
      const rgba: RGBA = [r, g, b, a == 255 ? byte(alpha*255) : a]
      _last_color = color
      _last_alpha = alpha
      _last_rgba = rgba
      return rgba
    }
    */
    const rgb_modern = /^rgba?\(\s*(?<r>[^\s,]+?)\s+(?<g>[^\s,]+?)\s+(?<b>[^\s,]+?)(?:\s*\/\s*(?<a>[^\s,]+?))?\s*\)$/;
    const rgb_legacy = /^rgba?\(\s*(?<r>[^\s,]+?)\s*,\s*(?<g>[^\s,]+?)\s*,\s*(?<b>[^\s,]+?)(?:\s*,\s*(?<a>[^\s,]+?))?\s*\)$/;
    const css4_normalize = (() => {
        const canvas = document.createElement("canvas");
        canvas.width = 1;
        canvas.height = 1;
        const ctx = canvas.getContext("2d");
        const gradient = ctx.createLinearGradient(0, 0, 1, 1);
        return (color) => {
            ctx.fillStyle = gradient; // lgtm [js/useless-assignment-to-property]
            ctx.fillStyle = color;
            const style = ctx.fillStyle;
            return style != gradient ? style : null;
        };
    })();
    function css4_parse(color) {
        /**
          Parses CSS4 color strings:
      
          - transparent
          - named color
          - #RRGGBB[AA]
          - #RGB[A]
          - rgb[a](R G B[ / A])
          - rgb[a](R, G, B[, A])
          - other CSS4 syntax (browser dependent)
      
        */
        color = color.trim().toLowerCase();
        if (color == "") {
            return null;
        }
        else if (color == "transparent") {
            return transparent();
        }
        else if ((0, svg_colors_1.is_named_color)(color)) {
            const [r, g, b, a] = decode_rgba(svg_colors_1.named_colors[color]);
            return [r, g, b, a / 255];
        }
        else if (color[0] == "#") {
            const v = Number(`0x${color.substring(1)}`);
            if (isNaN(v)) {
                return null;
            }
            switch (color.length - 1) {
                case 3: {
                    const r = (v >> 8) & 0xf;
                    const g = (v >> 4) & 0xf;
                    const b = (v >> 0) & 0xf;
                    const rr = (r << 4) | r;
                    const gg = (g << 4) | g;
                    const bb = (b << 4) | b;
                    return [rr, gg, bb, 1.0];
                }
                case 4: {
                    const r = (v >> 12) & 0xf;
                    const g = (v >> 8) & 0xf;
                    const b = (v >> 4) & 0xf;
                    const a = (v >> 0) & 0xf;
                    const rr = (r << 4) | r;
                    const gg = (g << 4) | g;
                    const bb = (b << 4) | b;
                    const aa = (a << 4) | a;
                    return [rr, gg, bb, aa / 255];
                }
                case 6: {
                    const rr = (v >> 16) & 0xff;
                    const gg = (v >> 8) & 0xff;
                    const bb = (v >> 0) & 0xff;
                    return [rr, gg, bb, 1.0];
                }
                case 8: {
                    const rr = (v >> 24) & 0xff;
                    const gg = (v >> 16) & 0xff;
                    const bb = (v >> 8) & 0xff;
                    const aa = (v >> 0) & 0xff;
                    return [rr, gg, bb, aa / 255];
                }
            }
        }
        else if (color.startsWith("rgb")) {
            const result = color.match(rgb_modern) ?? color.match(rgb_legacy);
            if (result?.groups != null) {
                let { r, g, b, a = "1" } = result.groups;
                const rp = r.endsWith("%");
                const gp = g.endsWith("%");
                const bp = b.endsWith("%");
                const ap = a.endsWith("%");
                if (!(rp && gp && bp || (!rp && !gp && !bp))) {
                    return null;
                }
                if (rp) {
                    r = r.slice(0, -1);
                }
                if (gp) {
                    g = g.slice(0, -1);
                }
                if (bp) {
                    b = b.slice(0, -1);
                }
                if (ap) {
                    a = a.slice(0, -1);
                }
                let R = Number(r);
                let G = Number(g);
                let B = Number(b);
                let A = Number(a);
                if (isNaN(R + G + B + A)) {
                    return null;
                }
                if (rp) {
                    R = 255 * (R / 100);
                }
                if (gp) {
                    G = 255 * (G / 100);
                }
                if (bp) {
                    B = 255 * (B / 100);
                }
                A = ap ? A / 100 : A;
                R = byte(R);
                G = byte(G);
                B = byte(B);
                return [R, G, B, A];
            }
        }
        else {
            const style = css4_normalize(color);
            if (style != null) {
                return css4_parse(style);
            }
        }
        return null;
    }
    function is_Color(value) {
        if ((0, types_1.isInteger)(value)) {
            return true;
        }
        if ((0, types_1.isString)(value) && css4_parse(value) != null) {
            return true;
        }
        if ((0, types_1.isArray)(value) && (value.length == 3 || value.length == 4)) {
            return true;
        }
        return false;
    }
    function is_dark([r, g, b]) {
        const l = 1 - (0.299 * r + 0.587 * g + 0.114 * b) / 255;
        return l >= 0.6;
    }
    function brightness(color) {
        // Perceived brightness of a color in [0, 1] range.
        // http://alienryderflex.com/hsp.html
        const [r, g, b] = color2rgba(color);
        return sqrt(0.299 * r ** 2 + 0.587 * g ** 2 + 0.114 * b ** 2) / 255;
    }
    function luminance(color) {
        // Relative luminance of a color in [0, 1] range.
        // https://en.wikipedia.org/wiki/Relative_luminance
        const [r, g, b] = color2rgba(color);
        return (0.2126 * r ** 2.2 + 0.7152 * g ** 2.2 + 0.0722 * b ** 2.2) / 255 ** 2.2;
    }
},
/* core/util/svg_colors.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.is_named_color = is_named_color;
    const _named_colors = {
        aliceblue: 0xf0f8ffff,
        antiquewhite: 0xfaebd7ff,
        aqua: 0x00ffffff,
        aquamarine: 0x7fffd4ff,
        azure: 0xf0ffffff,
        beige: 0xf5f5dcff,
        bisque: 0xffe4c4ff,
        black: 0x000000ff,
        blanchedalmond: 0xffebcdff,
        blue: 0x0000ffff,
        blueviolet: 0x8a2be2ff,
        brown: 0xa52a2aff,
        burlywood: 0xdeb887ff,
        cadetblue: 0x5f9ea0ff,
        chartreuse: 0x7fff00ff,
        chocolate: 0xd2691eff,
        coral: 0xff7f50ff,
        cornflowerblue: 0x6495edff,
        cornsilk: 0xfff8dcff,
        crimson: 0xdc143cff,
        cyan: 0x00ffffff,
        darkblue: 0x00008bff,
        darkcyan: 0x008b8bff,
        darkgoldenrod: 0xb8860bff,
        darkgray: 0xa9a9a9ff,
        darkgreen: 0x006400ff,
        darkgrey: 0xa9a9a9ff,
        darkkhaki: 0xbdb76bff,
        darkmagenta: 0x8b008bff,
        darkolivegreen: 0x556b2fff,
        darkorange: 0xff8c00ff,
        darkorchid: 0x9932ccff,
        darkred: 0x8b0000ff,
        darksalmon: 0xe9967aff,
        darkseagreen: 0x8fbc8fff,
        darkslateblue: 0x483d8bff,
        darkslategray: 0x2f4f4fff,
        darkslategrey: 0x2f4f4fff,
        darkturquoise: 0x00ced1ff,
        darkviolet: 0x9400d3ff,
        deeppink: 0xff1493ff,
        deepskyblue: 0x00bfffff,
        dimgray: 0x696969ff,
        dimgrey: 0x696969ff,
        dodgerblue: 0x1e90ffff,
        firebrick: 0xb22222ff,
        floralwhite: 0xfffaf0ff,
        forestgreen: 0x228b22ff,
        fuchsia: 0xff00ffff,
        gainsboro: 0xdcdcdcff,
        ghostwhite: 0xf8f8ffff,
        gold: 0xffd700ff,
        goldenrod: 0xdaa520ff,
        gray: 0x808080ff,
        green: 0x008000ff,
        greenyellow: 0xadff2fff,
        grey: 0x808080ff,
        honeydew: 0xf0fff0ff,
        hotpink: 0xff69b4ff,
        indianred: 0xcd5c5cff,
        indigo: 0x4b0082ff,
        ivory: 0xfffff0ff,
        khaki: 0xf0e68cff,
        lavender: 0xe6e6faff,
        lavenderblush: 0xfff0f5ff,
        lawngreen: 0x7cfc00ff,
        lemonchiffon: 0xfffacdff,
        lightblue: 0xadd8e6ff,
        lightcoral: 0xf08080ff,
        lightcyan: 0xe0ffffff,
        lightgoldenrodyellow: 0xfafad2ff,
        lightgray: 0xd3d3d3ff,
        lightgreen: 0x90ee90ff,
        lightgrey: 0xd3d3d3ff,
        lightpink: 0xffb6c1ff,
        lightsalmon: 0xffa07aff,
        lightseagreen: 0x20b2aaff,
        lightskyblue: 0x87cefaff,
        lightslategray: 0x778899ff,
        lightslategrey: 0x778899ff,
        lightsteelblue: 0xb0c4deff,
        lightyellow: 0xffffe0ff,
        lime: 0x00ff00ff,
        limegreen: 0x32cd32ff,
        linen: 0xfaf0e6ff,
        magenta: 0xff00ffff,
        maroon: 0x800000ff,
        mediumaquamarine: 0x66cdaaff,
        mediumblue: 0x0000cdff,
        mediumorchid: 0xba55d3ff,
        mediumpurple: 0x9370dbff,
        mediumseagreen: 0x3cb371ff,
        mediumslateblue: 0x7b68eeff,
        mediumspringgreen: 0x00fa9aff,
        mediumturquoise: 0x48d1ccff,
        mediumvioletred: 0xc71585ff,
        midnightblue: 0x191970ff,
        mintcream: 0xf5fffaff,
        mistyrose: 0xffe4e1ff,
        moccasin: 0xffe4b5ff,
        navajowhite: 0xffdeadff,
        navy: 0x000080ff,
        oldlace: 0xfdf5e6ff,
        olive: 0x808000ff,
        olivedrab: 0x6b8e23ff,
        orange: 0xffa500ff,
        orangered: 0xff4500ff,
        orchid: 0xda70d6ff,
        palegoldenrod: 0xeee8aaff,
        palegreen: 0x98fb98ff,
        paleturquoise: 0xafeeeeff,
        palevioletred: 0xdb7093ff,
        papayawhip: 0xffefd5ff,
        peachpuff: 0xffdab9ff,
        peru: 0xcd853fff,
        pink: 0xffc0cbff,
        plum: 0xdda0ddff,
        powderblue: 0xb0e0e6ff,
        purple: 0x800080ff,
        rebeccapurple: 0x663399ff,
        red: 0xff0000ff,
        rosybrown: 0xbc8f8fff,
        royalblue: 0x4169e1ff,
        saddlebrown: 0x8b4513ff,
        salmon: 0xfa8072ff,
        sandybrown: 0xf4a460ff,
        seagreen: 0x2e8b57ff,
        seashell: 0xfff5eeff,
        sienna: 0xa0522dff,
        silver: 0xc0c0c0ff,
        skyblue: 0x87ceebff,
        slateblue: 0x6a5acdff,
        slategray: 0x708090ff,
        slategrey: 0x708090ff,
        snow: 0xfffafaff,
        springgreen: 0x00ff7fff,
        steelblue: 0x4682b4ff,
        tan: 0xd2b48cff,
        teal: 0x008080ff,
        thistle: 0xd8bfd8ff,
        tomato: 0xff6347ff,
        turquoise: 0x40e0d0ff,
        violet: 0xee82eeff,
        wheat: 0xf5deb3ff,
        white: 0xffffffff,
        whitesmoke: 0xf5f5f5ff,
        yellow: 0xffff00ff,
        yellowgreen: 0x9acd32ff,
    };
    exports.named_colors = _named_colors;
    function is_named_color(color) {
        return color in exports.named_colors;
    }
},
/* core/types.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.infer_type = infer_type;
    exports.to_screen = to_screen;
    exports.GeneratorFunction = Object.getPrototypeOf(function* () { }).constructor;
    exports.AsyncGeneratorFunction = Object.getPrototypeOf(async function* () { }).constructor;
    exports.ColorArray = Uint32Array;
    exports.RGBAArray = Uint8ClampedArray;
    function infer_type(a0, a1) {
        if (a0 instanceof Float64Array || a0 instanceof Array) {
            return Float64Array;
        }
        if (a1 instanceof Float64Array || a1 instanceof Array) {
            return Float64Array;
        }
        return Float32Array;
    }
    exports.ScreenArray = Float32Array;
    function to_screen(array) {
        if (!(array instanceof Float32Array)) {
            return Float32Array.from(array);
        }
        else {
            return array;
        }
    }
    var bitset_1 = require(26) /* ./util/bitset */;
    __esExport("Indices", bitset_1.BitSet);
},
/* core/util/bitset.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const eq_1 = require(27) /* ./eq */;
    const assert_1 = require(13) /* ./assert */;
    const refs_1 = require(19) /* ./refs */;
    const logging_1 = require(11) /* ../logging */;
    class BitSet {
        size;
        [Symbol.toStringTag] = "BitSet";
        static [refs_1.has_refs] = false;
        static _word_length = 32;
        _array;
        _nwords;
        constructor(size, init = 0) {
            this.size = size;
            this._nwords = Math.ceil(size / BitSet._word_length);
            if (init == 0 || init == 1) {
                this._array = new Uint32Array(this._nwords);
                if (init == 1) {
                    this._array.fill(0xffffffff);
                }
            }
            else {
                (0, assert_1.assert)(init.length == this._nwords, "Initializer size mismatch");
                this._array = init;
            }
        }
        clone() {
            return new BitSet(this.size, new Uint32Array(this._array));
        }
        [eq_1.equals](that, cmp) {
            if (!cmp.eq(this.size, that.size)) {
                return false;
            }
            const { _nwords } = this;
            const trailing = this.size % BitSet._word_length;
            const n = trailing == 0 ? _nwords : _nwords - 1;
            for (let i = 0; i < n; i++) {
                if (this._array[i] != that._array[i]) {
                    return false;
                }
            }
            if (trailing == 0) {
                return true;
            }
            else {
                const msb = 1 << (trailing - 1);
                const mask = (msb - 1) ^ msb;
                return (this._array[n] & mask) == (that._array[n] & mask);
            }
        }
        static all_set(size) {
            return new BitSet(size, 1);
        }
        static all_unset(size) {
            return new BitSet(size, 0);
        }
        static from_indices(size, indices) {
            const bits = new BitSet(size);
            for (const i of indices) {
                bits.set(i);
            }
            return bits;
        }
        static from_booleans(size, booleans) {
            const bits = new BitSet(size);
            let i = 0;
            for (const boolean of booleans) {
                if (i == size) {
                    break;
                }
                if (boolean) {
                    bits.set(i);
                }
                i += 1;
            }
            return bits;
        }
        get_unchecked(k) {
            const i = k >>> 5; // Math.floor(k/32)
            const j = k & 0x1f; // k % 32
            return ((this._array[i] >> j) & 0b1) == 0b1;
        }
        set_unchecked(k, v = true) {
            this._count = null;
            const i = k >>> 5; // Math.floor(k/32)
            const j = k & 0x1f; // k % 32
            if (v) {
                this._array[i] |= 0b1 << j;
            }
            else {
                this._array[i] &= ~(0b1 << j);
            }
        }
        get(k) {
            const { size } = this;
            if (0 <= k && k < size) {
                return this.get_unchecked(k);
            }
            else if (-size <= k && k <= -1) {
                return this.get_unchecked(size + k);
            }
            else {
                return false;
            }
        }
        set(k, v = true) {
            const { size } = this;
            if (0 <= k && k < size) {
                this.set_unchecked(k, v);
            }
            else if (-size <= k && k <= -1) {
                this.set_unchecked(size + k, v);
            }
            else {
                logging_1.logger.warn(`out of bounds access: index=${k >= 0 ? k : size + k} >= size=${size}`);
            }
        }
        unset(k) {
            this.set(k, false);
        }
        *[Symbol.iterator]() {
            yield* this.ones();
        }
        _count = null;
        get count() {
            let count = this._count;
            if (count == null) {
                this._count = count = this._get_count();
            }
            return count;
        }
        _get_count() {
            const { _array, _nwords, size } = this;
            let c = 0;
            for (let k = 0, i = 0; i < _nwords; i++) {
                const word = _array[i];
                if (word == 0) {
                    k += BitSet._word_length;
                }
                else {
                    for (let j = 0; j < BitSet._word_length && k < size; j++, k++) {
                        if (((word >>> j) & 0b1) == 0b1) {
                            c += 1;
                        }
                    }
                }
            }
            return c;
        }
        ones() {
            const indices = new Array(this.count);
            let index = 0;
            const { _array, _nwords, size } = this;
            for (let k = 0, i = 0; i < _nwords; i++) {
                const word = _array[i];
                if (word == 0) {
                    k += BitSet._word_length;
                    continue;
                }
                for (let j = 0; j < BitSet._word_length && k < size; j++, k++) {
                    if (((word >>> j) & 0b1) == 0b1) {
                        indices[index++] = k;
                    }
                }
            }
            return indices;
        }
        zeros() {
            const indices = new Array(this.count);
            let index = 0;
            const { _array, _nwords, size } = this;
            for (let k = 0, i = 0; i < _nwords; i++) {
                const word = _array[i];
                if (word == 0xffffffff) {
                    k += BitSet._word_length;
                    continue;
                }
                for (let j = 0; j < BitSet._word_length && k < size; j++, k++) {
                    if (((word >>> j) & 0b1) == 0b0) {
                        indices[index++] = k;
                    }
                }
            }
            return indices;
        }
        _check_size(other) {
            (0, assert_1.assert)(this.size == other.size, `Size mismatch (${this.size} != ${other.size})`);
        }
        invert() {
            for (let i = 0; i < this._nwords; i++) {
                this._array[i] = ~this._array[i] >>> 0;
            }
        }
        add(other) {
            this._check_size(other);
            for (let i = 0; i < this._nwords; i++) {
                this._array[i] |= other._array[i];
            }
        }
        intersect(other) {
            this._check_size(other);
            for (let i = 0; i < this._nwords; i++) {
                this._array[i] &= other._array[i];
            }
        }
        subtract(other) {
            this._check_size(other);
            for (let i = 0; i < this._nwords; i++) {
                const a = this._array[i];
                const b = other._array[i];
                this._array[i] = (a ^ b) & a;
            }
        }
        symmetric_subtract(other) {
            this._check_size(other);
            for (let i = 0; i < this._nwords; i++) {
                this._array[i] ^= other._array[i];
            }
        }
        inversion() {
            const result = this.clone();
            result.invert();
            return result;
        }
        union(other) {
            const result = this.clone();
            result.add(other);
            return result;
        }
        intersection(other) {
            const result = this.clone();
            result.intersect(other);
            return result;
        }
        difference(other) {
            const result = this.clone();
            result.subtract(other);
            return result;
        }
        symmetric_difference(other) {
            const result = this.clone();
            result.symmetric_subtract(other);
            return result;
        }
        select(array) {
            (0, assert_1.assert)(this.size <= array.length, "Size mismatch");
            const n = this.count;
            const result = new array.constructor(n);
            const indices = this.ones();
            let i = 0;
            for (let j = 0; j < indices.length; j++) {
                result[i++] = array[indices[j]];
            }
            return result;
        }
    }
    exports.BitSet = BitSet;
},
/* core/util/eq.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.is_equal = is_equal;
    exports.is_structurally_equal = is_structurally_equal;
    exports.is_similar = is_similar;
    // Based on Underscore.js 1.8.3 (http://underscorejs.org)
    const types_1 = require(8) /* ./types */;
    const { hasOwnProperty } = Object.prototype;
    exports.equals = Symbol("equals");
    function is_Equatable(obj) {
        return (0, types_1.isObject)(obj) && exports.equals in obj;
    }
    exports.wildcard = Symbol("wildcard");
    const toString = Object.prototype.toString;
    class EqNotImplemented extends Error {
    }
    exports.EqNotImplemented = EqNotImplemented;
    class Comparator {
        a_stack = [];
        b_stack = [];
        structural;
        no_fail;
        constructor(options = {}) {
            this.structural = options.structural ?? false;
            this.no_fail = options.no_fail ?? false;
        }
        eq(a, b) {
            if (a === b || Object.is(a, b)) {
                return true;
            }
            if (a === exports.wildcard || b === exports.wildcard) {
                return true;
            }
            if (a == null || b == null) {
                return a === b;
            }
            const class_name = toString.call(a);
            if (class_name != toString.call(b)) {
                return false;
            }
            switch (class_name) {
                case "[object Number]":
                    return this.numbers(a, b);
                case "[object Symbol]":
                    return a === b;
                case "[object RegExp]":
                case "[object String]":
                    return `${a}` == `${b}`;
                case "[object Date]":
                case "[object Boolean]":
                    return +a === +b;
            }
            // Assume equality for cyclic structures. The algorithm for detecting cyclic
            // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
            // Initializing stack of traversed objects.
            // It's done here since we only need them for objects and arrays comparison.
            const { a_stack, b_stack } = this;
            let length = a_stack.length;
            while (length-- > 0) {
                // Linear search. Performance is inversely proportional to the number of
                // unique nested structures.
                if (a_stack[length] === a) {
                    return b_stack[length] === b;
                }
            }
            a_stack.push(a);
            b_stack.push(b);
            const result = (() => {
                if (is_Equatable(a) && is_Equatable(b)) {
                    return a[exports.equals](b, this);
                }
                switch (class_name) {
                    case "[object Array]":
                    case "[object Uint8Array]":
                    case "[object Int8Array]":
                    case "[object Uint16Array]":
                    case "[object Int16Array]":
                    case "[object Uint32Array]":
                    case "[object Int32Array]":
                    case "[object Float32Array]":
                    case "[object Float64Array]": {
                        return this.arrays(a, b);
                    }
                    case "[object ArrayBuffer]":
                    case "[object SharedArrayBuffer]": {
                        return this.array_buffers(a, b);
                    }
                    case "[object Map]": {
                        return this.maps(a, b);
                    }
                    case "[object Set]": {
                        return this.sets(a, b);
                    }
                    case "[object Object]": {
                        if (a.constructor == b.constructor && (a.constructor == null || a.constructor === Object)) {
                            return this.objects(a, b);
                        }
                    }
                    case "[object Function]": {
                        if (a.constructor == b.constructor && a.constructor === Function) {
                            return this.eq(`${a}`, `${b}`);
                        }
                    }
                }
                if (typeof Node !== "undefined" && a instanceof Node) {
                    return this.nodes(a, b);
                }
                if (this.no_fail) {
                    return false;
                }
                else {
                    throw new EqNotImplemented(`can't compare objects of type ${class_name}`);
                }
            })();
            a_stack.pop();
            b_stack.pop();
            return result;
        }
        numbers(a, b) {
            return a === b || Object.is(a, b);
        }
        arrays(a, b) {
            const { length } = a;
            if (length != b.length) {
                return false;
            }
            for (let i = 0; i < length; i++) {
                if (!this.eq(a[i], b[i])) {
                    return false;
                }
            }
            return true;
        }
        array_buffers(a, b) {
            // compare array buffers byte-wise; this doesn't allocate any memory
            return this.arrays(new Uint8Array(a), new Uint8Array(b));
        }
        iterables(a, b) {
            const ai = a[Symbol.iterator]();
            const bi = b[Symbol.iterator]();
            while (true) {
                const an = ai.next();
                const bn = bi.next();
                const an_done = an.done ?? false;
                const bn_done = bn.done ?? false;
                if (an_done && bn_done) {
                    return true;
                }
                if (an_done || bn_done) {
                    return false;
                }
                if (!this.eq(an.value, bn.value)) {
                    return false;
                }
            }
        }
        maps(a, b) {
            if (a.size != b.size) {
                return false;
            }
            if (this.structural) {
                return this.iterables(a.entries(), b.entries());
            }
            else {
                for (const [key, val] of a) {
                    if (!b.has(key) || !this.eq(val, b.get(key))) {
                        return false;
                    }
                }
                return true;
            }
        }
        sets(a, b) {
            if (a.size != b.size) {
                return false;
            }
            if (this.structural) {
                return this.iterables(a.entries(), b.entries());
            }
            else {
                for (const key of a) {
                    if (!b.has(key)) {
                        return false;
                    }
                }
                return true;
            }
        }
        objects(a, b) {
            const keys = Object.keys(a);
            if (keys.length != Object.keys(b).length) {
                return false;
            }
            for (const key of keys) {
                if (!hasOwnProperty.call(b, key) || !this.eq(a[key], b[key])) {
                    return false;
                }
            }
            return true;
        }
        nodes(a, b) {
            if (this.structural) {
                if (a.nodeType != b.nodeType) {
                    return false;
                }
                if (a.textContent != b.textContent) {
                    return false;
                }
                if (!this.iterables(a.childNodes, b.childNodes)) {
                    return false;
                }
                return true;
            }
            else {
                return a === b;
            }
        }
    }
    exports.Comparator = Comparator;
    const { abs } = Math;
    class SimilarComparator extends Comparator {
        tolerance;
        constructor(tolerance = 1e-4) {
            super();
            this.tolerance = tolerance;
        }
        numbers(a, b) {
            return super.numbers(a, b) || abs(a - b) < this.tolerance;
        }
    }
    exports.SimilarComparator = SimilarComparator;
    function is_equal(a, b) {
        const comparator = new Comparator();
        return comparator.eq(a, b);
    }
    function is_structurally_equal(a, b) {
        const comparator = new Comparator({ structural: true });
        return comparator.eq(a, b);
    }
    function is_similar(a, b, tolerance) {
        const comparator = new SimilarComparator(tolerance);
        return comparator.eq(a, b);
    }
},
/* core/util/platform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.to_big_endian = to_big_endian;
    exports.is_mobile = (() => {
        return "ontouchstart" in globalThis || (typeof navigator !== "undefined" && navigator.maxTouchPoints > 0);
    })();
    exports.is_little_endian = (() => {
        const buf = new ArrayBuffer(4);
        const buf8 = new Uint8Array(buf);
        const buf32 = new Uint32Array(buf);
        buf32[1] = 0x0a0b0c0d;
        let little_endian = true;
        if (buf8[4] == 0x0a && buf8[5] == 0x0b && buf8[6] == 0x0c && buf8[7] == 0x0d) {
            little_endian = false;
        }
        return little_endian;
    })();
    exports.BYTE_ORDER = exports.is_little_endian ? "little" : "big";
    function to_big_endian(values) {
        if (exports.is_little_endian) {
            const bytes = new Uint8Array(values.buffer);
            const n_bytes = bytes.length;
            for (let i = 0; i < n_bytes; i += 4) {
                let temp_byte = bytes[i];
                bytes[i] = bytes[i + 3];
                bytes[i + 3] = temp_byte;
                temp_byte = bytes[i + 1];
                bytes[i + 1] = bytes[i + 2];
                bytes[i + 2] = temp_byte;
            }
        }
    }
},
/* core/vectorization.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.isValue = isValue;
    exports.isField = isField;
    exports.isExpr = isExpr;
    exports.isVectorized = isVectorized;
    const types_1 = require(8) /* ./util/types */;
    const object_1 = require(9) /* ./util/object */;
    function is_of_type(obj, field) {
        if (!(0, types_1.isPlainObject)(obj)) {
            return false;
        }
        if (!(field in obj)) {
            return false;
        }
        let n = (0, object_1.size)(obj) - 1;
        if ("transform" in obj) {
            n -= 1;
        }
        if ("units" in obj) {
            n -= 1;
        }
        return n == 0;
    }
    function isValue(obj) {
        return is_of_type(obj, "value");
    }
    function isField(obj) {
        return is_of_type(obj, "field");
    }
    function isExpr(obj) {
        return is_of_type(obj, "expr");
    }
    function isVectorized(obj) {
        return isValue(obj) || isField(obj) || isExpr(obj);
    }
},
/* core/settings.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    class Settings {
        _dev = false;
        _wireframe = false;
        _force_webgl = false;
        _force_fields = false;
        set dev(dev) {
            this._dev = dev;
        }
        get dev() {
            return this._dev;
        }
        set wireframe(wireframe) {
            this._wireframe = wireframe;
        }
        get wireframe() {
            return this._wireframe;
        }
        set force_webgl(force_webgl) {
            this._force_webgl = force_webgl;
        }
        get force_webgl() {
            return this._force_webgl;
        }
        set force_fields(force_fields) {
            this._force_fields = force_fields;
        }
        get force_fields() {
            return this._force_fields;
        }
    }
    exports.Settings = Settings;
    exports.settings = new Settings();
},
/* core/util/ndarray.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.is_NDArray = is_NDArray;
    exports.ndarray = ndarray;
    const types_1 = require(8) /* ./types */;
    const platform_1 = require(28) /* ./platform */;
    const eq_1 = require(27) /* ./eq */;
    const cloneable_1 = require(32) /* ./cloneable */;
    const serialization_1 = require(33) /* ../serialization */;
    const __ndarray__ = Symbol("__ndarray__");
    function encode_NDArray(array, serializer) {
        const encoded = serializer.encode(array.dtype == "object" ? Array.from(array) : array.buffer);
        return {
            type: "ndarray",
            array: encoded,
            order: platform_1.BYTE_ORDER,
            dtype: array.dtype,
            shape: array.shape,
        };
    }
    class BoolNDArray extends Uint8Array {
        [__ndarray__] = true;
        dtype = "bool";
        shape;
        dimension;
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this.shape = shape ?? (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new BoolNDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i] == 1;
        }
    }
    exports.BoolNDArray = BoolNDArray;
    class Uint8NDArray extends Uint8Array {
        [__ndarray__] = true;
        dtype = "uint8";
        shape;
        dimension;
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this.shape = shape ?? (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Uint8NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Uint8NDArray = Uint8NDArray;
    class Int8NDArray extends Int8Array {
        [__ndarray__] = true;
        dtype = "int8";
        shape;
        dimension;
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this.shape = shape ?? (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Int8NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Int8NDArray = Int8NDArray;
    class Uint16NDArray extends Uint16Array {
        [__ndarray__] = true;
        dtype = "uint16";
        shape;
        dimension;
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this.shape = shape ?? (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Uint16NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Uint16NDArray = Uint16NDArray;
    class Int16NDArray extends Int16Array {
        [__ndarray__] = true;
        dtype = "int16";
        shape;
        dimension;
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this.shape = shape ?? (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Int16NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Int16NDArray = Int16NDArray;
    class Uint32NDArray extends Uint32Array {
        [__ndarray__] = true;
        dtype = "uint32";
        shape;
        dimension;
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this.shape = shape ?? (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Uint32NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Uint32NDArray = Uint32NDArray;
    class Int32NDArray extends Int32Array {
        [__ndarray__] = true;
        dtype = "int32";
        shape;
        dimension;
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this.shape = shape ?? (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Int32NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Int32NDArray = Int32NDArray;
    class Float32NDArray extends Float32Array {
        [__ndarray__] = true;
        dtype = "float32";
        shape;
        dimension;
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this.shape = shape ?? (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Float32NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Float32NDArray = Float32NDArray;
    class Float64NDArray extends Float64Array {
        [__ndarray__] = true;
        dtype = "float64";
        shape;
        dimension;
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this.shape = shape ?? (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Float64NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Float64NDArray = Float64NDArray;
    class ObjectNDArray extends Array {
        [__ndarray__] = true;
        dtype = "object";
        _shape;
        get shape() {
            return this._shape ?? [this.length];
        }
        get dimension() {
            return this.shape.length;
        }
        constructor(init_, shape) {
            const init = (0, types_1.is_ArrayBufferLike)(init_) ? new Float64Array(init_) : init_;
            const size = (0, types_1.isNumber)(init) ? init : init.length;
            super(size);
            if (!(0, types_1.isNumber)(init)) {
                for (let i = 0; i < init.length; i++) {
                    this[i] = init[i];
                }
            }
            this._shape = shape ?? (is_NDArray(init) ? init.shape : undefined);
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new ObjectNDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.ObjectNDArray = ObjectNDArray;
    function is_NDArray(v) {
        return (0, types_1.isObject)(v) && __ndarray__ in v;
    }
    function ndarray(init, { dtype, shape } = {}) {
        if (dtype == null) {
            dtype = (() => {
                switch (true) {
                    case init instanceof Uint8Array: return "uint8";
                    case init instanceof Int8Array: return "int8";
                    case init instanceof Uint16Array: return "uint16";
                    case init instanceof Int16Array: return "int16";
                    case init instanceof Uint32Array: return "uint32";
                    case init instanceof Int32Array: return "int32";
                    case init instanceof Float32Array: return "float32";
                    case init instanceof Float64Array: return "float64";
                    default: {
                        if ((0, types_1.is_ArrayBufferLike)(init)) {
                            return "float64";
                        }
                        else {
                            return "object";
                        }
                    }
                }
            })();
        }
        switch (dtype) {
            case "bool": return new BoolNDArray(init, shape);
            case "uint8": return new Uint8NDArray(init, shape);
            case "int8": return new Int8NDArray(init, shape);
            case "uint16": return new Uint16NDArray(init, shape);
            case "int16": return new Int16NDArray(init, shape);
            case "uint32": return new Uint32NDArray(init, shape);
            case "int32": return new Int32NDArray(init, shape);
            case "float32": return new Float32NDArray(init, shape);
            case "float64": return new Float64NDArray(init, shape);
            case "object": return new ObjectNDArray(init, shape);
        }
    }
},
/* core/util/cloneable.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.is_Cloneable = is_Cloneable;
    const object_1 = require(9) /* ./object */;
    const types_1 = require(8) /* ./types */;
    exports.clone = Symbol("clone");
    function is_Cloneable(obj) {
        return (0, types_1.isObject)(obj) && exports.clone in obj;
    }
    class CloningError extends Error {
    }
    exports.CloningError = CloningError;
    class Cloner {
        constructor() { }
        clone(obj) {
            if (is_Cloneable(obj)) {
                return obj[exports.clone](this);
            }
            else if ((0, types_1.isPrimitive)(obj) || (0, types_1.isFunction)(obj)) {
                return obj;
            }
            else if ((0, types_1.isArray)(obj)) {
                const n = obj.length;
                const result = new Array(n);
                for (let i = 0; i < n; i++) {
                    const value = obj[i];
                    result[i] = this.clone(value);
                }
                return result;
            }
            else if ((0, types_1.isPlainObject)(obj)) {
                const result = {};
                for (const [key, value] of (0, object_1.entries)(obj)) {
                    result[key] = this.clone(value);
                }
                return result;
            }
            else if (obj instanceof Map) {
                return new Map([...obj].map(([k, v]) => [this.clone(k), this.clone(v)]));
            }
            else if (obj instanceof Set) {
                return new Set([...obj].map((v) => this.clone(v)));
            }
            else {
                throw new CloningError(`${Object.prototype.toString.call(obj)} is not cloneable`);
            }
        }
    }
    exports.Cloner = Cloner;
},
/* core/serialization/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    var serializer_1 = require(34) /* ./serializer */;
    __esExport("Serializer", serializer_1.Serializer);
    __esExport("SerializationError", serializer_1.SerializationError);
    __esExport("serialize", serializer_1.serialize);
    var buffer_1 = require(35) /* ./buffer */;
    __esExport("Buffer", buffer_1.Buffer);
    __esExport("Base64Buffer", buffer_1.Base64Buffer);
    tslib_1.__exportStar(require(38) /* ./reps */, exports);
},
/* core/serialization/serializer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const assert_1 = require(13) /* ../util/assert */;
    const object_1 = require(9) /* ../util/object */;
    const types_1 = require(8) /* ../util/types */;
    const iterator_1 = require(15) /* ../util/iterator */;
    const platform_1 = require(28) /* ../util/platform */;
    const buffer_1 = require(35) /* ./buffer */;
    // TypedArray?
    exports.serialize = Symbol("serialize");
    function is_Serializable(obj) {
        return (0, types_1.isObject)(obj) && exports.serialize in obj;
    }
    class SerializationError extends Error {
    }
    exports.SerializationError = SerializationError;
    class Serialized {
        value;
        constructor(value) {
            this.value = value;
        }
        to_json() {
            return JSON.stringify(this.value);
        }
    }
    class Serializer {
        _references;
        binary;
        include_defaults;
        _circular = new WeakSet();
        constructor(options) {
            this.binary = options?.binary ?? false;
            this.include_defaults = options?.include_defaults ?? false;
            const references = options?.references;
            this._references = references != null ? new Map(references) : new Map();
        }
        get_ref(obj) {
            return this._references.get(obj);
        }
        add_ref(obj, ref) {
            (0, assert_1.assert)(!this._references.has(obj));
            this._references.set(obj, ref);
        }
        to_serializable(obj) {
            return new Serialized(this.encode(obj));
        }
        encode(obj) {
            const ref = this.get_ref(obj);
            if (ref != null) {
                return ref;
            }
            if (!(0, types_1.isObject)(obj)) {
                return this._encode(obj);
            }
            else {
                if (this._circular.has(obj)) {
                    this.error("circular reference");
                }
                this._circular.add(obj);
                try {
                    return this._encode(obj);
                }
                finally {
                    this._circular.delete(obj);
                }
            }
        }
        _encode(obj) {
            if (is_Serializable(obj)) {
                return obj[exports.serialize](this);
            }
            else if ((0, types_1.isArray)(obj)) {
                const n = obj.length;
                const result = new Array(n);
                for (let i = 0; i < n; i++) {
                    const value = obj[i];
                    result[i] = this.encode(value);
                }
                return result;
            }
            else if ((0, types_1.isTypedArray)(obj)) {
                return this._encode_typed_array(obj);
            }
            else if (obj instanceof ArrayBuffer) {
                const data = this.binary ? new buffer_1.Buffer(obj) : new buffer_1.Base64Buffer(obj);
                return { type: "bytes", data };
            }
            else if ((0, types_1.isPlainObject)(obj)) {
                const items = (0, object_1.entries)(obj);
                if (items.length == 0) {
                    return { type: "map" };
                }
                else {
                    return { type: "map", entries: [...(0, iterator_1.map)(items, ([key, val]) => [this.encode(key), this.encode(val)])] };
                }
            }
            else if (obj === null || (0, types_1.isBoolean)(obj) || (0, types_1.isString)(obj)) {
                return obj;
            }
            else if ((0, types_1.isNumber)(obj)) {
                if (isNaN(obj)) {
                    return { type: "number", value: "nan" };
                }
                else if (!isFinite(obj)) {
                    return { type: "number", value: `${obj < 0 ? "-" : "+"}inf` };
                }
                else {
                    return obj;
                }
            }
            else if (obj instanceof Date) {
                const iso = obj.toISOString();
                return { type: "date", iso };
            }
            else if (obj instanceof Set) {
                if (obj.size == 0) {
                    return { type: "set" };
                }
                else {
                    return { type: "set", entries: [...(0, iterator_1.map)(obj.values(), (val) => this.encode(val))] };
                }
            }
            else if (obj instanceof Map) {
                if (obj.size == 0) {
                    return { type: "map" };
                }
                else {
                    return { type: "map", entries: [...(0, iterator_1.map)(obj.entries(), ([key, val]) => [this.encode(key), this.encode(val)])] };
                }
            }
            else if ((0, types_1.isSymbol)(obj) && obj.description != null) {
                return { type: "symbol", name: obj.description };
            }
            else {
                throw new SerializationError(`${Object.prototype.toString.call(obj)} is not serializable`);
            }
        }
        encode_struct(struct) {
            const result = {};
            for (const [key, val] of (0, object_1.entries)(struct)) {
                if (val !== undefined) {
                    result[key] = this.encode(val);
                }
            }
            return result;
        }
        error(message) {
            throw new SerializationError(message);
        }
        _encode_typed_array(obj) {
            const array = this.encode(obj.buffer);
            const dtype = (() => {
                switch (obj.constructor) {
                    case Uint8Array: return "uint8";
                    case Int8Array: return "int8";
                    case Uint16Array: return "uint16";
                    case Int16Array: return "int16";
                    case Uint32Array: return "uint32";
                    case Int32Array: return "int32";
                    // case BigUint64Array: return "uint64"
                    // case BigInt64Array: return "int64"
                    case Float32Array: return "float32";
                    case Float64Array: return "float64";
                    default:
                        this.error(`can't serialize typed array of type '${obj[Symbol.toStringTag]}'`);
                }
            })();
            return {
                type: "typed_array",
                array,
                order: platform_1.BYTE_ORDER,
                dtype,
            };
        }
    }
    exports.Serializer = Serializer;
},
/* core/serialization/buffer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const buffer_1 = require(36) /* ../util/buffer */;
    const eq_1 = require(27) /* ../util/eq */;
    class Buffer {
        buffer;
        constructor(buffer) {
            this.buffer = buffer;
        }
        to_base64() {
            return (0, buffer_1.buffer_to_base64)(this.buffer);
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.buffer, that.buffer);
        }
    }
    exports.Buffer = Buffer;
    class Base64Buffer extends Buffer {
        toJSON() {
            return this.to_base64();
        }
    }
    exports.Base64Buffer = Base64Buffer;
},
/* core/util/buffer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.buffer_to_base64 = buffer_to_base64;
    exports.base64_to_buffer = base64_to_buffer;
    exports.swap = swap;
    const fflate_1 = require(37) /* fflate */;
    exports.b64encode = (() => {
        if (typeof Uint8Array.prototype.toBase64 !== "undefined") {
            return (data) => data.toBase64();
        }
        else {
            return (data) => {
                const chars = Array.from(data).map((b) => String.fromCharCode(b));
                return btoa(chars.join(""));
            };
        }
    })();
    exports.b64decode = (() => {
        if (typeof Uint8Array.fromBase64 !== "undefined") {
            return (data) => Uint8Array.fromBase64(data);
        }
        else {
            return (data) => {
                const binary_string = atob(data);
                const len = binary_string.length;
                const bytes = new Uint8Array(len);
                for (let i = 0, end = len; i < end; i++) {
                    bytes[i] = binary_string.charCodeAt(i);
                }
                return bytes;
            };
        }
    })();
    function buffer_to_base64(buffer) {
        const bytes = new Uint8Array(buffer);
        // we do not want the result to be different depending on mtime, since that is
        // irrelevant and also makes things harder to test, so set mtime=0 here
        const compressed = (0, fflate_1.gzipSync)(bytes, { mtime: 0 });
        return (0, exports.b64encode)(compressed);
    }
    function base64_to_buffer(base64) {
        const bytes = (0, exports.b64decode)(base64);
        return (0, fflate_1.gunzipSync)(bytes).buffer;
    }
    // NOTE: swap{16,32,64} assume byteOffset == 0
    function swap16(buffer) {
        const x = new Uint8Array(buffer);
        for (let i = 0, end = x.length; i < end; i += 2) {
            const t = x[i];
            x[i] = x[i + 1];
            x[i + 1] = t;
        }
    }
    function swap32(buffer) {
        const x = new Uint8Array(buffer);
        for (let i = 0, end = x.length; i < end; i += 4) {
            let t = x[i];
            x[i] = x[i + 3];
            x[i + 3] = t;
            t = x[i + 1];
            x[i + 1] = x[i + 2];
            x[i + 2] = t;
        }
    }
    function swap64(buffer) {
        const x = new Uint8Array(buffer);
        for (let i = 0, end = x.length; i < end; i += 8) {
            let t = x[i];
            x[i] = x[i + 7];
            x[i + 7] = t;
            t = x[i + 1];
            x[i + 1] = x[i + 6];
            x[i + 6] = t;
            t = x[i + 2];
            x[i + 2] = x[i + 5];
            x[i + 5] = t;
            t = x[i + 3];
            x[i + 3] = x[i + 4];
            x[i + 4] = t;
        }
    }
    function swap(buffer, dtype) {
        switch (dtype) {
            case "uint16":
            case "int16":
                swap16(buffer);
                break;
            case "uint32":
            case "int32":
            case "float32":
                swap32(buffer);
                break;
            case "float64":
                swap64(buffer);
                break;
            case "object":
            case "uint8":
            case "int8":
            case "bool":
                break;
        }
    }
},
/* fflate/esm/browser.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.deflate = deflate;
    exports.deflateSync = deflateSync;
    exports.inflate = inflate;
    exports.inflateSync = inflateSync;
    exports.gzip = gzip;
    exports.compress = gzip;
    exports.gzipSync = gzipSync;
    exports.compressSync = gzipSync;
    exports.gunzip = gunzip;
    exports.gunzipSync = gunzipSync;
    exports.zlib = zlib;
    exports.zlibSync = zlibSync;
    exports.unzlib = unzlib;
    exports.unzlibSync = unzlibSync;
    exports.decompress = decompress;
    exports.decompressSync = decompressSync;
    exports.strToU8 = strToU8;
    exports.strFromU8 = strFromU8;
    exports.zip = zip;
    exports.zipSync = zipSync;
    exports.unzip = unzip;
    exports.unzipSync = unzipSync;
    // DEFLATE is a complex format; to read this code, you should probably check the RFC first:
    // https://tools.ietf.org/html/rfc1951
    // You may also wish to take a look at the guide I made about this program:
    // https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad
    // Some of the following code is similar to that of UZIP.js:
    // https://github.com/photopea/UZIP.js
    // However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size.
    // Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint
    // is better for memory in most engines (I *think*).
    var ch2 = {};
    var wk = (function (c, id, msg, transfer, cb) {
        var w = new Worker(ch2[id] || (ch2[id] = URL.createObjectURL(new Blob([
            c + ';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'
        ], { type: 'text/javascript' }))));
        w.onmessage = function (e) {
            var d = e.data, ed = d.$e$;
            if (ed) {
                var err = new Error(ed[0]);
                err['code'] = ed[1];
                err.stack = ed[2];
                cb(err, null);
            }
            else
                cb(null, d);
        };
        w.postMessage(msg, transfer);
        return w;
    });
    // aliases for shorter compressed code (most minifers don't do this)
    var u8 = Uint8Array, u16 = Uint16Array, i32 = Int32Array;
    // fixed length extra bits
    var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);
    // fixed distance extra bits
    var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);
    // code length index map
    var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
    // get base, reverse index map from extra bits
    var freb = function (eb, start) {
        var b = new u16(31);
        for (var i = 0; i < 31; ++i) {
            b[i] = start += 1 << eb[i - 1];
        }
        // numbers here are at max 18 bits
        var r = new i32(b[30]);
        for (var i = 1; i < 30; ++i) {
            for (var j = b[i]; j < b[i + 1]; ++j) {
                r[j] = ((j - b[i]) << 5) | i;
            }
        }
        return { b: b, r: r };
    };
    var _a = freb(fleb, 2), fl = _a.b, revfl = _a.r;
    // we can ignore the fact that the other numbers are wrong; they never happen anyway
    fl[28] = 258, revfl[258] = 28;
    var _b = freb(fdeb, 0), fd = _b.b, revfd = _b.r;
    // map of value to reverse (assuming 16 bits)
    var rev = new u16(32768);
    for (var i = 0; i < 32768; ++i) {
        // reverse table algorithm from SO
        var x = ((i & 0xAAAA) >> 1) | ((i & 0x5555) << 1);
        x = ((x & 0xCCCC) >> 2) | ((x & 0x3333) << 2);
        x = ((x & 0xF0F0) >> 4) | ((x & 0x0F0F) << 4);
        rev[i] = (((x & 0xFF00) >> 8) | ((x & 0x00FF) << 8)) >> 1;
    }
    // create huffman tree from u8 "map": index -> code length for code index
    // mb (max bits) must be at most 15
    // TODO: optimize/split up?
    var hMap = (function (cd, mb, r) {
        var s = cd.length;
        // index
        var i = 0;
        // u16 "map": index -> # of codes with bit length = index
        var l = new u16(mb);
        // length of cd must be 288 (total # of codes)
        for (; i < s; ++i) {
            if (cd[i])
                ++l[cd[i] - 1];
        }
        // u16 "map": index -> minimum code for bit length = index
        var le = new u16(mb);
        for (i = 1; i < mb; ++i) {
            le[i] = (le[i - 1] + l[i - 1]) << 1;
        }
        var co;
        if (r) {
            // u16 "map": index -> number of actual bits, symbol for code
            co = new u16(1 << mb);
            // bits to remove for reverser
            var rvb = 15 - mb;
            for (i = 0; i < s; ++i) {
                // ignore 0 lengths
                if (cd[i]) {
                    // num encoding both symbol and bits read
                    var sv = (i << 4) | cd[i];
                    // free bits
                    var r_1 = mb - cd[i];
                    // start value
                    var v = le[cd[i] - 1]++ << r_1;
                    // m is end value
                    for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {
                        // every 16 bit value starting with the code yields the same result
                        co[rev[v] >> rvb] = sv;
                    }
                }
            }
        }
        else {
            co = new u16(s);
            for (i = 0; i < s; ++i) {
                if (cd[i]) {
                    co[i] = rev[le[cd[i] - 1]++] >> (15 - cd[i]);
                }
            }
        }
        return co;
    });
    // fixed length tree
    var flt = new u8(288);
    for (var i = 0; i < 144; ++i)
        flt[i] = 8;
    for (var i = 144; i < 256; ++i)
        flt[i] = 9;
    for (var i = 256; i < 280; ++i)
        flt[i] = 7;
    for (var i = 280; i < 288; ++i)
        flt[i] = 8;
    // fixed distance tree
    var fdt = new u8(32);
    for (var i = 0; i < 32; ++i)
        fdt[i] = 5;
    // fixed length map
    var flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1);
    // fixed distance map
    var fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);
    // find max of array
    var max = function (a) {
        var m = a[0];
        for (var i = 1; i < a.length; ++i) {
            if (a[i] > m)
                m = a[i];
        }
        return m;
    };
    // read d, starting at bit p and mask with m
    var bits = function (d, p, m) {
        var o = (p / 8) | 0;
        return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m;
    };
    // read d, starting at bit p continuing for at least 16 bits
    var bits16 = function (d, p) {
        var o = (p / 8) | 0;
        return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7));
    };
    // get end of byte
    var shft = function (p) { return ((p + 7) / 8) | 0; };
    // typed array slice - allows garbage collector to free original reference,
    // while being more compatible than .slice
    var slc = function (v, s, e) {
        if (s == null || s < 0)
            s = 0;
        if (e == null || e > v.length)
            e = v.length;
        // can't use .constructor in case user-supplied
        return new u8(v.subarray(s, e));
    };
    /**
     * Codes for errors generated within this library
     */
    exports.FlateErrorCode = {
        UnexpectedEOF: 0,
        InvalidBlockType: 1,
        InvalidLengthLiteral: 2,
        InvalidDistance: 3,
        StreamFinished: 4,
        NoStreamHandler: 5,
        InvalidHeader: 6,
        NoCallback: 7,
        InvalidUTF8: 8,
        ExtraFieldTooLong: 9,
        InvalidDate: 10,
        FilenameTooLong: 11,
        StreamFinishing: 12,
        InvalidZipData: 13,
        UnknownCompressionMethod: 14
    };
    // error codes
    var ec = [
        'unexpected EOF',
        'invalid block type',
        'invalid length/literal',
        'invalid distance',
        'stream finished',
        'no stream handler',
        ,
        'no callback',
        'invalid UTF-8 data',
        'extra field too long',
        'date not in range 1980-2099',
        'filename too long',
        'stream finishing',
        'invalid zip data'
        // determined by unknown compression method
    ];
    ;
    var err = function (ind, msg, nt) {
        var e = new Error(msg || ec[ind]);
        e.code = ind;
        if (Error.captureStackTrace)
            Error.captureStackTrace(e, err);
        if (!nt)
            throw e;
        return e;
    };
    // expands raw DEFLATE data
    var inflt = function (dat, st, buf, dict) {
        // source length       dict length
        var sl = dat.length, dl = dict ? dict.length : 0;
        if (!sl || st.f && !st.l)
            return buf || new u8(0);
        var noBuf = !buf;
        // have to estimate size
        var resize = noBuf || st.i != 2;
        // no state
        var noSt = st.i;
        // Assumes roughly 33% compression ratio average
        if (noBuf)
            buf = new u8(sl * 3);
        // ensure buffer can fit at least l elements
        var cbuf = function (l) {
            var bl = buf.length;
            // need to increase size to fit
            if (l > bl) {
                // Double or set to necessary, whichever is greater
                var nbuf = new u8(Math.max(bl * 2, l));
                nbuf.set(buf);
                buf = nbuf;
            }
        };
        //  last chunk         bitpos           bytes
        var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
        // total bits
        var tbts = sl * 8;
        do {
            if (!lm) {
                // BFINAL - this is only 1 when last chunk is next
                final = bits(dat, pos, 1);
                // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman
                var type = bits(dat, pos + 1, 3);
                pos += 3;
                if (!type) {
                    // go to end of byte boundary
                    var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;
                    if (t > sl) {
                        if (noSt)
                            err(0);
                        break;
                    }
                    // ensure size
                    if (resize)
                        cbuf(bt + l);
                    // Copy over uncompressed data
                    buf.set(dat.subarray(s, t), bt);
                    // Get new bitpos, update byte count
                    st.b = bt += l, st.p = pos = t * 8, st.f = final;
                    continue;
                }
                else if (type == 1)
                    lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
                else if (type == 2) {
                    //  literal                            lengths
                    var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
                    var tl = hLit + bits(dat, pos + 5, 31) + 1;
                    pos += 14;
                    // length+distance tree
                    var ldt = new u8(tl);
                    // code length tree
                    var clt = new u8(19);
                    for (var i = 0; i < hcLen; ++i) {
                        // use index map to get real code
                        clt[clim[i]] = bits(dat, pos + i * 3, 7);
                    }
                    pos += hcLen * 3;
                    // code lengths bits
                    var clb = max(clt), clbmsk = (1 << clb) - 1;
                    // code lengths map
                    var clm = hMap(clt, clb, 1);
                    for (var i = 0; i < tl;) {
                        var r = clm[bits(dat, pos, clbmsk)];
                        // bits read
                        pos += r & 15;
                        // symbol
                        var s = r >> 4;
                        // code length to copy
                        if (s < 16) {
                            ldt[i++] = s;
                        }
                        else {
                            //  copy   count
                            var c = 0, n = 0;
                            if (s == 16)
                                n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
                            else if (s == 17)
                                n = 3 + bits(dat, pos, 7), pos += 3;
                            else if (s == 18)
                                n = 11 + bits(dat, pos, 127), pos += 7;
                            while (n--)
                                ldt[i++] = c;
                        }
                    }
                    //    length tree                 distance tree
                    var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
                    // max length bits
                    lbt = max(lt);
                    // max dist bits
                    dbt = max(dt);
                    lm = hMap(lt, lbt, 1);
                    dm = hMap(dt, dbt, 1);
                }
                else
                    err(1);
                if (pos > tbts) {
                    if (noSt)
                        err(0);
                    break;
                }
            }
            // Make sure the buffer can hold this + the largest possible addition
            // Maximum chunk size (practically, theoretically infinite) is 2^17
            if (resize)
                cbuf(bt + 131072);
            var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
            var lpos = pos;
            for (;; lpos = pos) {
                // bits read, code
                var c = lm[bits16(dat, pos) & lms], sym = c >> 4;
                pos += c & 15;
                if (pos > tbts) {
                    if (noSt)
                        err(0);
                    break;
                }
                if (!c)
                    err(2);
                if (sym < 256)
                    buf[bt++] = sym;
                else if (sym == 256) {
                    lpos = pos, lm = null;
                    break;
                }
                else {
                    var add = sym - 254;
                    // no extra bits needed if less
                    if (sym > 264) {
                        // index
                        var i = sym - 257, b = fleb[i];
                        add = bits(dat, pos, (1 << b) - 1) + fl[i];
                        pos += b;
                    }
                    // dist
                    var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
                    if (!d)
                        err(3);
                    pos += d & 15;
                    var dt = fd[dsym];
                    if (dsym > 3) {
                        var b = fdeb[dsym];
                        dt += bits16(dat, pos) & (1 << b) - 1, pos += b;
                    }
                    if (pos > tbts) {
                        if (noSt)
                            err(0);
                        break;
                    }
                    if (resize)
                        cbuf(bt + 131072);
                    var end = bt + add;
                    if (bt < dt) {
                        var shift = dl - dt, dend = Math.min(dt, end);
                        if (shift + bt < 0)
                            err(3);
                        for (; bt < dend; ++bt)
                            buf[bt] = dict[shift + bt];
                    }
                    for (; bt < end; ++bt)
                        buf[bt] = buf[bt - dt];
                }
            }
            st.l = lm, st.p = lpos, st.b = bt, st.f = final;
            if (lm)
                final = 1, st.m = lbt, st.d = dm, st.n = dbt;
        } while (!final);
        // don't reallocate for streams or user buffers
        return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
    };
    // starting at p, write the minimum number of bits that can hold v to d
    var wbits = function (d, p, v) {
        v <<= p & 7;
        var o = (p / 8) | 0;
        d[o] |= v;
        d[o + 1] |= v >> 8;
    };
    // starting at p, write the minimum number of bits (>8) that can hold v to d
    var wbits16 = function (d, p, v) {
        v <<= p & 7;
        var o = (p / 8) | 0;
        d[o] |= v;
        d[o + 1] |= v >> 8;
        d[o + 2] |= v >> 16;
    };
    // creates code lengths from a frequency table
    var hTree = function (d, mb) {
        // Need extra info to make a tree
        var t = [];
        for (var i = 0; i < d.length; ++i) {
            if (d[i])
                t.push({ s: i, f: d[i] });
        }
        var s = t.length;
        var t2 = t.slice();
        if (!s)
            return { t: et, l: 0 };
        if (s == 1) {
            var v = new u8(t[0].s + 1);
            v[t[0].s] = 1;
            return { t: v, l: 1 };
        }
        t.sort(function (a, b) { return a.f - b.f; });
        // after i2 reaches last ind, will be stopped
        // freq must be greater than largest possible number of symbols
        t.push({ s: -1, f: 25001 });
        var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;
        t[0] = { s: -1, f: l.f + r.f, l: l, r: r };
        // efficient algorithm from UZIP.js
        // i0 is lookbehind, i2 is lookahead - after processing two low-freq
        // symbols that combined have high freq, will start processing i2 (high-freq,
        // non-composite) symbols instead
        // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/
        while (i1 != s - 1) {
            l = t[t[i0].f < t[i2].f ? i0++ : i2++];
            r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];
            t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r };
        }
        var maxSym = t2[0].s;
        for (var i = 1; i < s; ++i) {
            if (t2[i].s > maxSym)
                maxSym = t2[i].s;
        }
        // code lengths
        var tr = new u16(maxSym + 1);
        // max bits in tree
        var mbt = ln(t[i1 - 1], tr, 0);
        if (mbt > mb) {
            // more algorithms from UZIP.js
            // TODO: find out how this code works (debt)
            //  ind    debt
            var i = 0, dt = 0;
            //    left            cost
            var lft = mbt - mb, cst = 1 << lft;
            t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; });
            for (; i < s; ++i) {
                var i2_1 = t2[i].s;
                if (tr[i2_1] > mb) {
                    dt += cst - (1 << (mbt - tr[i2_1]));
                    tr[i2_1] = mb;
                }
                else
                    break;
            }
            dt >>= lft;
            while (dt > 0) {
                var i2_2 = t2[i].s;
                if (tr[i2_2] < mb)
                    dt -= 1 << (mb - tr[i2_2]++ - 1);
                else
                    ++i;
            }
            for (; i >= 0 && dt; --i) {
                var i2_3 = t2[i].s;
                if (tr[i2_3] == mb) {
                    --tr[i2_3];
                    ++dt;
                }
            }
            mbt = mb;
        }
        return { t: new u8(tr), l: mbt };
    };
    // get the max length and assign length codes
    var ln = function (n, l, d) {
        return n.s == -1
            ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1))
            : (l[n.s] = d);
    };
    // length codes generation
    var lc = function (c) {
        var s = c.length;
        // Note that the semicolon was intentional
        while (s && !c[--s])
            ;
        var cl = new u16(++s);
        //  ind      num         streak
        var cli = 0, cln = c[0], cls = 1;
        var w = function (v) { cl[cli++] = v; };
        for (var i = 1; i <= s; ++i) {
            if (c[i] == cln && i != s)
                ++cls;
            else {
                if (!cln && cls > 2) {
                    for (; cls > 138; cls -= 138)
                        w(32754);
                    if (cls > 2) {
                        w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305);
                        cls = 0;
                    }
                }
                else if (cls > 3) {
                    w(cln), --cls;
                    for (; cls > 6; cls -= 6)
                        w(8304);
                    if (cls > 2)
                        w(((cls - 3) << 5) | 8208), cls = 0;
                }
                while (cls--)
                    w(cln);
                cls = 1;
                cln = c[i];
            }
        }
        return { c: cl.subarray(0, cli), n: s };
    };
    // calculate the length of output from tree, code lengths
    var clen = function (cf, cl) {
        var l = 0;
        for (var i = 0; i < cl.length; ++i)
            l += cf[i] * cl[i];
        return l;
    };
    // writes a fixed block
    // returns the new bit pos
    var wfblk = function (out, pos, dat) {
        // no need to write 00 as type: TypedArray defaults to 0
        var s = dat.length;
        var o = shft(pos + 2);
        out[o] = s & 255;
        out[o + 1] = s >> 8;
        out[o + 2] = out[o] ^ 255;
        out[o + 3] = out[o + 1] ^ 255;
        for (var i = 0; i < s; ++i)
            out[o + i + 4] = dat[i];
        return (o + 4 + s) * 8;
    };
    // writes a block
    var wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
        wbits(out, p++, final);
        ++lf[256];
        var _a = hTree(lf, 15), dlt = _a.t, mlb = _a.l;
        var _b = hTree(df, 15), ddt = _b.t, mdb = _b.l;
        var _c = lc(dlt), lclt = _c.c, nlc = _c.n;
        var _d = lc(ddt), lcdt = _d.c, ndc = _d.n;
        var lcfreq = new u16(19);
        for (var i = 0; i < lclt.length; ++i)
            ++lcfreq[lclt[i] & 31];
        for (var i = 0; i < lcdt.length; ++i)
            ++lcfreq[lcdt[i] & 31];
        var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l;
        var nlcc = 19;
        for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)
            ;
        var flen = (bl + 5) << 3;
        var ftlen = clen(lf, flt) + clen(df, fdt) + eb;
        var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18];
        if (bs >= 0 && flen <= ftlen && flen <= dtlen)
            return wfblk(out, p, dat.subarray(bs, bs + bl));
        var lm, ll, dm, dl;
        wbits(out, p, 1 + (dtlen < ftlen)), p += 2;
        if (dtlen < ftlen) {
            lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;
            var llm = hMap(lct, mlcb, 0);
            wbits(out, p, nlc - 257);
            wbits(out, p + 5, ndc - 1);
            wbits(out, p + 10, nlcc - 4);
            p += 14;
            for (var i = 0; i < nlcc; ++i)
                wbits(out, p + 3 * i, lct[clim[i]]);
            p += 3 * nlcc;
            var lcts = [lclt, lcdt];
            for (var it = 0; it < 2; ++it) {
                var clct = lcts[it];
                for (var i = 0; i < clct.length; ++i) {
                    var len = clct[i] & 31;
                    wbits(out, p, llm[len]), p += lct[len];
                    if (len > 15)
                        wbits(out, p, (clct[i] >> 5) & 127), p += clct[i] >> 12;
                }
            }
        }
        else {
            lm = flm, ll = flt, dm = fdm, dl = fdt;
        }
        for (var i = 0; i < li; ++i) {
            var sym = syms[i];
            if (sym > 255) {
                var len = (sym >> 18) & 31;
                wbits16(out, p, lm[len + 257]), p += ll[len + 257];
                if (len > 7)
                    wbits(out, p, (sym >> 23) & 31), p += fleb[len];
                var dst = sym & 31;
                wbits16(out, p, dm[dst]), p += dl[dst];
                if (dst > 3)
                    wbits16(out, p, (sym >> 5) & 8191), p += fdeb[dst];
            }
            else {
                wbits16(out, p, lm[sym]), p += ll[sym];
            }
        }
        wbits16(out, p, lm[256]);
        return p + ll[256];
    };
    // deflate options (nice << 13) | chain
    var deo = /*#__PURE__*/ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);
    // empty
    var et = /*#__PURE__*/ new u8(0);
    // compresses data into a raw DEFLATE buffer
    var dflt = function (dat, lvl, plvl, pre, post, st) {
        var s = st.z || dat.length;
        var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);
        // writing to this writes to the output buffer
        var w = o.subarray(pre, o.length - post);
        var lst = st.l;
        var pos = (st.r || 0) & 7;
        if (lvl) {
            if (pos)
                w[0] = st.r >> 3;
            var opt = deo[lvl - 1];
            var n = opt >> 13, c = opt & 8191;
            var msk_1 = (1 << plvl) - 1;
            //    prev 2-byte val map    curr 2-byte val map
            var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1);
            var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;
            var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; };
            // 24576 is an arbitrary number of maximum symbols per block
            // 424 buffer for last block
            var syms = new i32(25000);
            // length/literal freq   distance freq
            var lf = new u16(288), df = new u16(32);
            //  l/lcnt  exbits  index          l/lind  waitdx          blkpos
            var lc_1 = 0, eb = 0, i = st.i || 0, li = 0, wi = st.w || 0, bs = 0;
            for (; i + 2 < s; ++i) {
                // hash value
                var hv = hsh(i);
                // index mod 32768    previous index mod
                var imod = i & 32767, pimod = head[hv];
                prev[imod] = pimod;
                head[hv] = imod;
                // We always should modify head and prev, but only add symbols if
                // this data is not yet processed ("wait" for wait index)
                if (wi <= i) {
                    // bytes remaining
                    var rem = s - i;
                    if ((lc_1 > 7000 || li > 24576) && (rem > 423 || !lst)) {
                        pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);
                        li = lc_1 = eb = 0, bs = i;
                        for (var j = 0; j < 286; ++j)
                            lf[j] = 0;
                        for (var j = 0; j < 30; ++j)
                            df[j] = 0;
                    }
                    //  len    dist   chain
                    var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767;
                    if (rem > 2 && hv == hsh(i - dif)) {
                        var maxn = Math.min(n, rem) - 1;
                        var maxd = Math.min(32767, i);
                        // max possible length
                        // not capped at dif because decompressors implement "rolling" index population
                        var ml = Math.min(258, rem);
                        while (dif <= maxd && --ch_1 && imod != pimod) {
                            if (dat[i + l] == dat[i + l - dif]) {
                                var nl = 0;
                                for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)
                                    ;
                                if (nl > l) {
                                    l = nl, d = dif;
                                    // break out early when we reach "nice" (we are satisfied enough)
                                    if (nl > maxn)
                                        break;
                                    // now, find the rarest 2-byte sequence within this
                                    // length of literals and search for that instead.
                                    // Much faster than just using the start
                                    var mmd = Math.min(dif, nl - 2);
                                    var md = 0;
                                    for (var j = 0; j < mmd; ++j) {
                                        var ti = i - dif + j & 32767;
                                        var pti = prev[ti];
                                        var cd = ti - pti & 32767;
                                        if (cd > md)
                                            md = cd, pimod = ti;
                                    }
                                }
                            }
                            // check the previous match
                            imod = pimod, pimod = prev[imod];
                            dif += imod - pimod & 32767;
                        }
                    }
                    // d will be nonzero only when a match was found
                    if (d) {
                        // store both dist and len data in one int32
                        // Make sure this is recognized as a len/dist with 28th bit (2^28)
                        syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d];
                        var lin = revfl[l] & 31, din = revfd[d] & 31;
                        eb += fleb[lin] + fdeb[din];
                        ++lf[257 + lin];
                        ++df[din];
                        wi = i + l;
                        ++lc_1;
                    }
                    else {
                        syms[li++] = dat[i];
                        ++lf[dat[i]];
                    }
                }
            }
            for (i = Math.max(i, wi); i < s; ++i) {
                syms[li++] = dat[i];
                ++lf[dat[i]];
            }
            pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);
            if (!lst) {
                st.r = (pos & 7) | w[(pos / 8) | 0] << 3;
                // shft(pos) now 1 less if pos & 7 != 0
                pos -= 7;
                st.h = head, st.p = prev, st.i = i, st.w = wi;
            }
        }
        else {
            for (var i = st.w || 0; i < s + lst; i += 65535) {
                // end
                var e = i + 65535;
                if (e >= s) {
                    // write final block
                    w[(pos / 8) | 0] = lst;
                    e = s;
                }
                pos = wfblk(w, pos + 1, dat.subarray(i, e));
            }
            st.i = s;
        }
        return slc(o, 0, pre + shft(pos) + post);
    };
    // CRC32 table
    var crct = /*#__PURE__*/ (function () {
        var t = new Int32Array(256);
        for (var i = 0; i < 256; ++i) {
            var c = i, k = 9;
            while (--k)
                c = ((c & 1) && -306674912) ^ (c >>> 1);
            t[i] = c;
        }
        return t;
    })();
    // CRC32
    var crc = function () {
        var c = -1;
        return {
            p: function (d) {
                // closures have awful performance
                var cr = c;
                for (var i = 0; i < d.length; ++i)
                    cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8);
                c = cr;
            },
            d: function () { return ~c; }
        };
    };
    // Adler32
    var adler = function () {
        var a = 1, b = 0;
        return {
            p: function (d) {
                // closures have awful performance
                var n = a, m = b;
                var l = d.length | 0;
                for (var i = 0; i != l;) {
                    var e = Math.min(i + 2655, l);
                    for (; i < e; ++i)
                        m += n += d[i];
                    n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16);
                }
                a = n, b = m;
            },
            d: function () {
                a %= 65521, b %= 65521;
                return (a & 255) << 24 | (a & 0xFF00) << 8 | (b & 255) << 8 | (b >> 8);
            }
        };
    };
    ;
    // deflate with opts
    var dopt = function (dat, opt, pre, post, st) {
        if (!st) {
            st = { l: 1 };
            if (opt.dictionary) {
                var dict = opt.dictionary.subarray(-32768);
                var newDat = new u8(dict.length + dat.length);
                newDat.set(dict);
                newDat.set(dat, dict.length);
                dat = newDat;
                st.w = dict.length;
            }
        }
        return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? (st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20) : (12 + opt.mem), pre, post, st);
    };
    // Walmart object spread
    var mrg = function (a, b) {
        var o = {};
        for (var k in a)
            o[k] = a[k];
        for (var k in b)
            o[k] = b[k];
        return o;
    };
    // worker clone
    // This is possibly the craziest part of the entire codebase, despite how simple it may seem.
    // The only parameter to this function is a closure that returns an array of variables outside of the function scope.
    // We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization.
    // We will return an object mapping of true variable name to value (basically, the current scope as a JS object).
    // The reason we can't just use the original variable names is minifiers mangling the toplevel scope.
    // This took me three weeks to figure out how to do.
    var wcln = function (fn, fnStr, td) {
        var dt = fn();
        var st = fn.toString();
        var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\s+/g, '').split(',');
        for (var i = 0; i < dt.length; ++i) {
            var v = dt[i], k = ks[i];
            if (typeof v == 'function') {
                fnStr += ';' + k + '=';
                var st_1 = v.toString();
                if (v.prototype) {
                    // for global objects
                    if (st_1.indexOf('[native code]') != -1) {
                        var spInd = st_1.indexOf(' ', 8) + 1;
                        fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd));
                    }
                    else {
                        fnStr += st_1;
                        for (var t in v.prototype)
                            fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString();
                    }
                }
                else
                    fnStr += st_1;
            }
            else
                td[k] = v;
        }
        return fnStr;
    };
    var ch = [];
    // clone bufs
    var cbfs = function (v) {
        var tl = [];
        for (var k in v) {
            if (v[k].buffer) {
                tl.push((v[k] = new v[k].constructor(v[k])).buffer);
            }
        }
        return tl;
    };
    // use a worker to execute code
    var wrkr = function (fns, init, id, cb) {
        if (!ch[id]) {
            var fnStr = '', td_1 = {}, m = fns.length - 1;
            for (var i = 0; i < m; ++i)
                fnStr = wcln(fns[i], fnStr, td_1);
            ch[id] = { c: wcln(fns[m], fnStr, td_1), e: td_1 };
        }
        var td = mrg({}, ch[id].e);
        return wk(ch[id].c + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb);
    };
    // base async inflate fn
    var bInflt = function () { return [u8, u16, i32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gopt]; };
    var bDflt = function () { return [u8, u16, i32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; };
    // gzip extra
    var gze = function () { return [gzh, gzhl, wbytes, crc, crct]; };
    // gunzip extra
    var guze = function () { return [gzs, gzl]; };
    // zlib extra
    var zle = function () { return [zlh, wbytes, adler]; };
    // unzlib extra
    var zule = function () { return [zls]; };
    // post buf
    var pbf = function (msg) { return postMessage(msg, [msg.buffer]); };
    // get opts
    var gopt = function (o) {
        return o && {
            out: o.size && new u8(o.size),
            dictionary: o.dictionary
        };
    };
    // async helper
    var cbify = function (dat, opts, fns, init, id, cb) {
        var w = wrkr(fns, init, id, function (err, dat) {
            w.terminate();
            cb(err, dat);
        });
        w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []);
        return function () { w.terminate(); };
    };
    // auto stream
    var astrm = function (strm) {
        strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); };
        return function (ev) {
            if (ev.data.length) {
                strm.push(ev.data[0], ev.data[1]);
                postMessage([ev.data[0].length]);
            }
            else
                strm.flush();
        };
    };
    // async stream attach
    var astrmify = function (fns, strm, opts, init, id, flush, ext) {
        var t;
        var w = wrkr(fns, init, id, function (err, dat) {
            if (err)
                w.terminate(), strm.ondata.call(strm, err);
            else if (!Array.isArray(dat))
                ext(dat);
            else if (dat.length == 1) {
                strm.queuedSize -= dat[0];
                if (strm.ondrain)
                    strm.ondrain(dat[0]);
            }
            else {
                if (dat[1])
                    w.terminate();
                strm.ondata.call(strm, err, dat[0], dat[1]);
            }
        });
        w.postMessage(opts);
        strm.queuedSize = 0;
        strm.push = function (d, f) {
            if (!strm.ondata)
                err(5);
            if (t)
                strm.ondata(err(4, 0, 1), null, !!f);
            strm.queuedSize += d.length;
            w.postMessage([d, t = f], [d.buffer]);
        };
        strm.terminate = function () { w.terminate(); };
        if (flush) {
            strm.flush = function () { w.postMessage([]); };
        }
    };
    // read 2 bytes
    var b2 = function (d, b) { return d[b] | (d[b + 1] << 8); };
    // read 4 bytes
    var b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; };
    var b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); };
    // write bytes
    var wbytes = function (d, b, v) {
        for (; v; ++b)
            d[b] = v, v >>>= 8;
    };
    // gzip header
    var gzh = function (c, o) {
        var fn = o.filename;
        c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix
        if (o.mtime != 0)
            wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000));
        if (fn) {
            c[3] = 8;
            for (var i = 0; i <= fn.length; ++i)
                c[i + 10] = fn.charCodeAt(i);
        }
    };
    // gzip footer: -8 to -4 = CRC, -4 to -0 is length
    // gzip start
    var gzs = function (d) {
        if (d[0] != 31 || d[1] != 139 || d[2] != 8)
            err(6, 'invalid gzip data');
        var flg = d[3];
        var st = 10;
        if (flg & 4)
            st += (d[10] | d[11] << 8) + 2;
        for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])
            ;
        return st + (flg & 2);
    };
    // gzip length
    var gzl = function (d) {
        var l = d.length;
        return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0;
    };
    // gzip header length
    var gzhl = function (o) { return 10 + (o.filename ? o.filename.length + 1 : 0); };
    // zlib header
    var zlh = function (c, o) {
        var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;
        c[0] = 120, c[1] = (fl << 6) | (o.dictionary && 32);
        c[1] |= 31 - ((c[0] << 8) | c[1]) % 31;
        if (o.dictionary) {
            var h = adler();
            h.p(o.dictionary);
            wbytes(c, 2, h.d());
        }
    };
    // zlib start
    var zls = function (d, dict) {
        if ((d[0] & 15) != 8 || (d[0] >> 4) > 7 || ((d[0] << 8 | d[1]) % 31))
            err(6, 'invalid zlib data');
        if ((d[1] >> 5 & 1) == +!dict)
            err(6, 'invalid zlib data: ' + (d[1] & 32 ? 'need' : 'unexpected') + ' dictionary');
        return (d[1] >> 3 & 4) + 2;
    };
    function StrmOpt(opts, cb) {
        if (typeof opts == 'function')
            cb = opts, opts = {};
        this.ondata = cb;
        return opts;
    }
    /**
     * Streaming DEFLATE compression
     */
    var Deflate = /*#__PURE__*/ (function () {
        function Deflate(opts, cb) {
            if (typeof opts == 'function')
                cb = opts, opts = {};
            this.ondata = cb;
            this.o = opts || {};
            this.s = { l: 0, i: 32768, w: 32768, z: 32768 };
            // Buffer length must always be 0 mod 32768 for index calculations to be correct when modifying head and prev
            // 98304 = 32768 (lookback) + 65536 (common chunk size)
            this.b = new u8(98304);
            if (this.o.dictionary) {
                var dict = this.o.dictionary.subarray(-32768);
                this.b.set(dict, 32768 - dict.length);
                this.s.i = 32768 - dict.length;
            }
        }
        Deflate.prototype.p = function (c, f) {
            this.ondata(dopt(c, this.o, 0, 0, this.s), f);
        };
        /**
         * Pushes a chunk to be deflated
         * @param chunk The chunk to push
         * @param final Whether this is the last chunk
         */
        Deflate.prototype.push = function (chunk, final) {
            if (!this.ondata)
                err(5);
            if (this.s.l)
                err(4);
            var endLen = chunk.length + this.s.z;
            if (endLen > this.b.length) {
                if (endLen > 2 * this.b.length - 32768) {
                    var newBuf = new u8(endLen & -32768);
                    newBuf.set(this.b.subarray(0, this.s.z));
                    this.b = newBuf;
                }
                var split = this.b.length - this.s.z;
                this.b.set(chunk.subarray(0, split), this.s.z);
                this.s.z = this.b.length;
                this.p(this.b, false);
                this.b.set(this.b.subarray(-32768));
                this.b.set(chunk.subarray(split), 32768);
                this.s.z = chunk.length - split + 32768;
                this.s.i = 32766, this.s.w = 32768;
            }
            else {
                this.b.set(chunk, this.s.z);
                this.s.z += chunk.length;
            }
            this.s.l = final & 1;
            if (this.s.z > this.s.w + 8191 || final) {
                this.p(this.b, final || false);
                this.s.w = this.s.i, this.s.i -= 2;
            }
        };
        /**
         * Flushes buffered uncompressed data. Useful to immediately retrieve the
         * deflated output for small inputs.
         */
        Deflate.prototype.flush = function () {
            if (!this.ondata)
                err(5);
            if (this.s.l)
                err(4);
            this.p(this.b, false);
            this.s.w = this.s.i, this.s.i -= 2;
        };
        return Deflate;
    }());
    exports.Deflate = Deflate;
    /**
     * Asynchronous streaming DEFLATE compression
     */
    var AsyncDeflate = /*#__PURE__*/ (function () {
        function AsyncDeflate(opts, cb) {
            astrmify([
                bDflt,
                function () { return [astrm, Deflate]; }
            ], this, StrmOpt.call(this, opts, cb), function (ev) {
                var strm = new Deflate(ev.data);
                onmessage = astrm(strm);
            }, 6, 1);
        }
        return AsyncDeflate;
    }());
    exports.AsyncDeflate = AsyncDeflate;
    function deflate(data, opts, cb) {
        if (!cb)
            cb = opts, opts = {};
        if (typeof cb != 'function')
            err(7);
        return cbify(data, opts, [
            bDflt,
        ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb);
    }
    /**
     * Compresses data with DEFLATE without any wrapper
     * @param data The data to compress
     * @param opts The compression options
     * @returns The deflated version of the data
     */
    function deflateSync(data, opts) {
        return dopt(data, opts || {}, 0, 0);
    }
    /**
     * Streaming DEFLATE decompression
     */
    var Inflate = /*#__PURE__*/ (function () {
        function Inflate(opts, cb) {
            // no StrmOpt here to avoid adding to workerizer
            if (typeof opts == 'function')
                cb = opts, opts = {};
            this.ondata = cb;
            var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768);
            this.s = { i: 0, b: dict ? dict.length : 0 };
            this.o = new u8(32768);
            this.p = new u8(0);
            if (dict)
                this.o.set(dict);
        }
        Inflate.prototype.e = function (c) {
            if (!this.ondata)
                err(5);
            if (this.d)
                err(4);
            if (!this.p.length)
                this.p = c;
            else if (c.length) {
                var n = new u8(this.p.length + c.length);
                n.set(this.p), n.set(c, this.p.length), this.p = n;
            }
        };
        Inflate.prototype.c = function (final) {
            this.s.i = +(this.d = final || false);
            var bts = this.s.b;
            var dt = inflt(this.p, this.s, this.o);
            this.ondata(slc(dt, bts, this.s.b), this.d);
            this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;
            this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7;
        };
        /**
         * Pushes a chunk to be inflated
         * @param chunk The chunk to push
         * @param final Whether this is the final chunk
         */
        Inflate.prototype.push = function (chunk, final) {
            this.e(chunk), this.c(final);
        };
        return Inflate;
    }());
    exports.Inflate = Inflate;
    /**
     * Asynchronous streaming DEFLATE decompression
     */
    var AsyncInflate = /*#__PURE__*/ (function () {
        function AsyncInflate(opts, cb) {
            astrmify([
                bInflt,
                function () { return [astrm, Inflate]; }
            ], this, StrmOpt.call(this, opts, cb), function (ev) {
                var strm = new Inflate(ev.data);
                onmessage = astrm(strm);
            }, 7, 0);
        }
        return AsyncInflate;
    }());
    exports.AsyncInflate = AsyncInflate;
    function inflate(data, opts, cb) {
        if (!cb)
            cb = opts, opts = {};
        if (typeof cb != 'function')
            err(7);
        return cbify(data, opts, [
            bInflt
        ], function (ev) { return pbf(inflateSync(ev.data[0], gopt(ev.data[1]))); }, 1, cb);
    }
    /**
     * Expands DEFLATE data with no wrapper
     * @param data The data to decompress
     * @param opts The decompression options
     * @returns The decompressed version of the data
     */
    function inflateSync(data, opts) {
        return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);
    }
    // before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize.
    /**
     * Streaming GZIP compression
     */
    var Gzip = /*#__PURE__*/ (function () {
        function Gzip(opts, cb) {
            this.c = crc();
            this.l = 0;
            this.v = 1;
            Deflate.call(this, opts, cb);
        }
        /**
         * Pushes a chunk to be GZIPped
         * @param chunk The chunk to push
         * @param final Whether this is the last chunk
         */
        Gzip.prototype.push = function (chunk, final) {
            this.c.p(chunk);
            this.l += chunk.length;
            Deflate.prototype.push.call(this, chunk, final);
        };
        Gzip.prototype.p = function (c, f) {
            var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, this.s);
            if (this.v)
                gzh(raw, this.o), this.v = 0;
            if (f)
                wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l);
            this.ondata(raw, f);
        };
        /**
         * Flushes buffered uncompressed data. Useful to immediately retrieve the
         * GZIPped output for small inputs.
         */
        Gzip.prototype.flush = function () {
            Deflate.prototype.flush.call(this);
        };
        return Gzip;
    }());
    exports.Gzip = Gzip;
    exports.Compress = Gzip;
    /**
     * Asynchronous streaming GZIP compression
     */
    var AsyncGzip = /*#__PURE__*/ (function () {
        function AsyncGzip(opts, cb) {
            astrmify([
                bDflt,
                gze,
                function () { return [astrm, Deflate, Gzip]; }
            ], this, StrmOpt.call(this, opts, cb), function (ev) {
                var strm = new Gzip(ev.data);
                onmessage = astrm(strm);
            }, 8, 1);
        }
        return AsyncGzip;
    }());
    exports.AsyncGzip = AsyncGzip;
    exports.AsyncCompress = AsyncGzip;
    function gzip(data, opts, cb) {
        if (!cb)
            cb = opts, opts = {};
        if (typeof cb != 'function')
            err(7);
        return cbify(data, opts, [
            bDflt,
            gze,
            function () { return [gzipSync]; }
        ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb);
    }
    /**
     * Compresses data with GZIP
     * @param data The data to compress
     * @param opts The compression options
     * @returns The gzipped version of the data
     */
    function gzipSync(data, opts) {
        if (!opts)
            opts = {};
        var c = crc(), l = data.length;
        c.p(data);
        var d = dopt(data, opts, gzhl(opts), 8), s = d.length;
        return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;
    }
    /**
     * Streaming single or multi-member GZIP decompression
     */
    var Gunzip = /*#__PURE__*/ (function () {
        function Gunzip(opts, cb) {
            this.v = 1;
            this.r = 0;
            Inflate.call(this, opts, cb);
        }
        /**
         * Pushes a chunk to be GUNZIPped
         * @param chunk The chunk to push
         * @param final Whether this is the last chunk
         */
        Gunzip.prototype.push = function (chunk, final) {
            Inflate.prototype.e.call(this, chunk);
            this.r += chunk.length;
            if (this.v) {
                var p = this.p.subarray(this.v - 1);
                var s = p.length > 3 ? gzs(p) : 4;
                if (s > p.length) {
                    if (!final)
                        return;
                }
                else if (this.v > 1 && this.onmember) {
                    this.onmember(this.r - p.length);
                }
                this.p = p.subarray(s), this.v = 0;
            }
            // necessary to prevent TS from using the closure value
            // This allows for workerization to function correctly
            Inflate.prototype.c.call(this, final);
            // process concatenated GZIP
            if (this.s.f && !this.s.l && !final) {
                this.v = shft(this.s.p) + 9;
                this.s = { i: 0 };
                this.o = new u8(0);
                this.push(new u8(0), final);
            }
        };
        return Gunzip;
    }());
    exports.Gunzip = Gunzip;
    /**
     * Asynchronous streaming single or multi-member GZIP decompression
     */
    var AsyncGunzip = /*#__PURE__*/ (function () {
        function AsyncGunzip(opts, cb) {
            var _this = this;
            astrmify([
                bInflt,
                guze,
                function () { return [astrm, Inflate, Gunzip]; }
            ], this, StrmOpt.call(this, opts, cb), function (ev) {
                var strm = new Gunzip(ev.data);
                strm.onmember = function (offset) { return postMessage(offset); };
                onmessage = astrm(strm);
            }, 9, 0, function (offset) { return _this.onmember && _this.onmember(offset); });
        }
        return AsyncGunzip;
    }());
    exports.AsyncGunzip = AsyncGunzip;
    function gunzip(data, opts, cb) {
        if (!cb)
            cb = opts, opts = {};
        if (typeof cb != 'function')
            err(7);
        return cbify(data, opts, [
            bInflt,
            guze,
            function () { return [gunzipSync]; }
        ], function (ev) { return pbf(gunzipSync(ev.data[0], ev.data[1])); }, 3, cb);
    }
    /**
     * Expands GZIP data
     * @param data The data to decompress
     * @param opts The decompression options
     * @returns The decompressed version of the data
     */
    function gunzipSync(data, opts) {
        var st = gzs(data);
        if (st + 8 > data.length)
            err(6, 'invalid gzip data');
        return inflt(data.subarray(st, -8), { i: 2 }, opts && opts.out || new u8(gzl(data)), opts && opts.dictionary);
    }
    /**
     * Streaming Zlib compression
     */
    var Zlib = /*#__PURE__*/ (function () {
        function Zlib(opts, cb) {
            this.c = adler();
            this.v = 1;
            Deflate.call(this, opts, cb);
        }
        /**
         * Pushes a chunk to be zlibbed
         * @param chunk The chunk to push
         * @param final Whether this is the last chunk
         */
        Zlib.prototype.push = function (chunk, final) {
            this.c.p(chunk);
            Deflate.prototype.push.call(this, chunk, final);
        };
        Zlib.prototype.p = function (c, f) {
            var raw = dopt(c, this.o, this.v && (this.o.dictionary ? 6 : 2), f && 4, this.s);
            if (this.v)
                zlh(raw, this.o), this.v = 0;
            if (f)
                wbytes(raw, raw.length - 4, this.c.d());
            this.ondata(raw, f);
        };
        /**
         * Flushes buffered uncompressed data. Useful to immediately retrieve the
         * zlibbed output for small inputs.
         */
        Zlib.prototype.flush = function () {
            Deflate.prototype.flush.call(this);
        };
        return Zlib;
    }());
    exports.Zlib = Zlib;
    /**
     * Asynchronous streaming Zlib compression
     */
    var AsyncZlib = /*#__PURE__*/ (function () {
        function AsyncZlib(opts, cb) {
            astrmify([
                bDflt,
                zle,
                function () { return [astrm, Deflate, Zlib]; }
            ], this, StrmOpt.call(this, opts, cb), function (ev) {
                var strm = new Zlib(ev.data);
                onmessage = astrm(strm);
            }, 10, 1);
        }
        return AsyncZlib;
    }());
    exports.AsyncZlib = AsyncZlib;
    function zlib(data, opts, cb) {
        if (!cb)
            cb = opts, opts = {};
        if (typeof cb != 'function')
            err(7);
        return cbify(data, opts, [
            bDflt,
            zle,
            function () { return [zlibSync]; }
        ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb);
    }
    /**
     * Compress data with Zlib
     * @param data The data to compress
     * @param opts The compression options
     * @returns The zlib-compressed version of the data
     */
    function zlibSync(data, opts) {
        if (!opts)
            opts = {};
        var a = adler();
        a.p(data);
        var d = dopt(data, opts, opts.dictionary ? 6 : 2, 4);
        return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;
    }
    /**
     * Streaming Zlib decompression
     */
    var Unzlib = /*#__PURE__*/ (function () {
        function Unzlib(opts, cb) {
            Inflate.call(this, opts, cb);
            this.v = opts && opts.dictionary ? 2 : 1;
        }
        /**
         * Pushes a chunk to be unzlibbed
         * @param chunk The chunk to push
         * @param final Whether this is the last chunk
         */
        Unzlib.prototype.push = function (chunk, final) {
            Inflate.prototype.e.call(this, chunk);
            if (this.v) {
                if (this.p.length < 6 && !final)
                    return;
                this.p = this.p.subarray(zls(this.p, this.v - 1)), this.v = 0;
            }
            if (final) {
                if (this.p.length < 4)
                    err(6, 'invalid zlib data');
                this.p = this.p.subarray(0, -4);
            }
            // necessary to prevent TS from using the closure value
            // This allows for workerization to function correctly
            Inflate.prototype.c.call(this, final);
        };
        return Unzlib;
    }());
    exports.Unzlib = Unzlib;
    /**
     * Asynchronous streaming Zlib decompression
     */
    var AsyncUnzlib = /*#__PURE__*/ (function () {
        function AsyncUnzlib(opts, cb) {
            astrmify([
                bInflt,
                zule,
                function () { return [astrm, Inflate, Unzlib]; }
            ], this, StrmOpt.call(this, opts, cb), function (ev) {
                var strm = new Unzlib(ev.data);
                onmessage = astrm(strm);
            }, 11, 0);
        }
        return AsyncUnzlib;
    }());
    exports.AsyncUnzlib = AsyncUnzlib;
    function unzlib(data, opts, cb) {
        if (!cb)
            cb = opts, opts = {};
        if (typeof cb != 'function')
            err(7);
        return cbify(data, opts, [
            bInflt,
            zule,
            function () { return [unzlibSync]; }
        ], function (ev) { return pbf(unzlibSync(ev.data[0], gopt(ev.data[1]))); }, 5, cb);
    }
    /**
     * Expands Zlib data
     * @param data The data to decompress
     * @param opts The decompression options
     * @returns The decompressed version of the data
     */
    function unzlibSync(data, opts) {
        return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary);
    }
    /**
     * Streaming GZIP, Zlib, or raw DEFLATE decompression
     */
    var Decompress = /*#__PURE__*/ (function () {
        function Decompress(opts, cb) {
            this.o = StrmOpt.call(this, opts, cb) || {};
            this.G = Gunzip;
            this.I = Inflate;
            this.Z = Unzlib;
        }
        // init substream
        // overriden by AsyncDecompress
        Decompress.prototype.i = function () {
            var _this = this;
            this.s.ondata = function (dat, final) {
                _this.ondata(dat, final);
            };
        };
        /**
         * Pushes a chunk to be decompressed
         * @param chunk The chunk to push
         * @param final Whether this is the last chunk
         */
        Decompress.prototype.push = function (chunk, final) {
            if (!this.ondata)
                err(5);
            if (!this.s) {
                if (this.p && this.p.length) {
                    var n = new u8(this.p.length + chunk.length);
                    n.set(this.p), n.set(chunk, this.p.length);
                }
                else
                    this.p = chunk;
                if (this.p.length > 2) {
                    this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8)
                        ? new this.G(this.o)
                        : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31))
                            ? new this.I(this.o)
                            : new this.Z(this.o);
                    this.i();
                    this.s.push(this.p, final);
                    this.p = null;
                }
            }
            else
                this.s.push(chunk, final);
        };
        return Decompress;
    }());
    exports.Decompress = Decompress;
    /**
     * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression
     */
    var AsyncDecompress = /*#__PURE__*/ (function () {
        function AsyncDecompress(opts, cb) {
            Decompress.call(this, opts, cb);
            this.queuedSize = 0;
            this.G = AsyncGunzip;
            this.I = AsyncInflate;
            this.Z = AsyncUnzlib;
        }
        AsyncDecompress.prototype.i = function () {
            var _this = this;
            this.s.ondata = function (err, dat, final) {
                _this.ondata(err, dat, final);
            };
            this.s.ondrain = function (size) {
                _this.queuedSize -= size;
                if (_this.ondrain)
                    _this.ondrain(size);
            };
        };
        /**
         * Pushes a chunk to be decompressed
         * @param chunk The chunk to push
         * @param final Whether this is the last chunk
         */
        AsyncDecompress.prototype.push = function (chunk, final) {
            this.queuedSize += chunk.length;
            Decompress.prototype.push.call(this, chunk, final);
        };
        return AsyncDecompress;
    }());
    exports.AsyncDecompress = AsyncDecompress;
    function decompress(data, opts, cb) {
        if (!cb)
            cb = opts, opts = {};
        if (typeof cb != 'function')
            err(7);
        return (data[0] == 31 && data[1] == 139 && data[2] == 8)
            ? gunzip(data, opts, cb)
            : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))
                ? inflate(data, opts, cb)
                : unzlib(data, opts, cb);
    }
    /**
     * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format
     * @param data The data to decompress
     * @param opts The decompression options
     * @returns The decompressed version of the data
     */
    function decompressSync(data, opts) {
        return (data[0] == 31 && data[1] == 139 && data[2] == 8)
            ? gunzipSync(data, opts)
            : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))
                ? inflateSync(data, opts)
                : unzlibSync(data, opts);
    }
    // flatten a directory structure
    var fltn = function (d, p, t, o) {
        for (var k in d) {
            var val = d[k], n = p + k, op = o;
            if (Array.isArray(val))
                op = mrg(o, val[1]), val = val[0];
            if (val instanceof u8)
                t[n] = [val, op];
            else {
                t[n += '/'] = [new u8(0), op];
                fltn(val, n, t, o);
            }
        }
    };
    // text encoder
    var te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder();
    // text decoder
    var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder();
    // text decoder stream
    var tds = 0;
    try {
        td.decode(et, { stream: true });
        tds = 1;
    }
    catch (e) { }
    // decode UTF8
    var dutf8 = function (d) {
        for (var r = '', i = 0;;) {
            var c = d[i++];
            var eb = (c > 127) + (c > 223) + (c > 239);
            if (i + eb > d.length)
                return { s: r, r: slc(d, i - 1) };
            if (!eb)
                r += String.fromCharCode(c);
            else if (eb == 3) {
                c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536,
                    r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023));
            }
            else if (eb & 1)
                r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63));
            else
                r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63));
        }
    };
    /**
     * Streaming UTF-8 decoding
     */
    var DecodeUTF8 = /*#__PURE__*/ (function () {
        /**
         * Creates a UTF-8 decoding stream
         * @param cb The callback to call whenever data is decoded
         */
        function DecodeUTF8(cb) {
            this.ondata = cb;
            if (tds)
                this.t = new TextDecoder();
            else
                this.p = et;
        }
        /**
         * Pushes a chunk to be decoded from UTF-8 binary
         * @param chunk The chunk to push
         * @param final Whether this is the last chunk
         */
        DecodeUTF8.prototype.push = function (chunk, final) {
            if (!this.ondata)
                err(5);
            final = !!final;
            if (this.t) {
                this.ondata(this.t.decode(chunk, { stream: true }), final);
                if (final) {
                    if (this.t.decode().length)
                        err(8);
                    this.t = null;
                }
                return;
            }
            if (!this.p)
                err(4);
            var dat = new u8(this.p.length + chunk.length);
            dat.set(this.p);
            dat.set(chunk, this.p.length);
            var _a = dutf8(dat), s = _a.s, r = _a.r;
            if (final) {
                if (r.length)
                    err(8);
                this.p = null;
            }
            else
                this.p = r;
            this.ondata(s, final);
        };
        return DecodeUTF8;
    }());
    exports.DecodeUTF8 = DecodeUTF8;
    /**
     * Streaming UTF-8 encoding
     */
    var EncodeUTF8 = /*#__PURE__*/ (function () {
        /**
         * Creates a UTF-8 decoding stream
         * @param cb The callback to call whenever data is encoded
         */
        function EncodeUTF8(cb) {
            this.ondata = cb;
        }
        /**
         * Pushes a chunk to be encoded to UTF-8
         * @param chunk The string data to push
         * @param final Whether this is the last chunk
         */
        EncodeUTF8.prototype.push = function (chunk, final) {
            if (!this.ondata)
                err(5);
            if (this.d)
                err(4);
            this.ondata(strToU8(chunk), this.d = final || false);
        };
        return EncodeUTF8;
    }());
    exports.EncodeUTF8 = EncodeUTF8;
    /**
     * Converts a string into a Uint8Array for use with compression/decompression methods
     * @param str The string to encode
     * @param latin1 Whether or not to interpret the data as Latin-1. This should
     *               not need to be true unless decoding a binary string.
     * @returns The string encoded in UTF-8/Latin-1 binary
     */
    function strToU8(str, latin1) {
        if (latin1) {
            var ar_1 = new u8(str.length);
            for (var i = 0; i < str.length; ++i)
                ar_1[i] = str.charCodeAt(i);
            return ar_1;
        }
        if (te)
            return te.encode(str);
        var l = str.length;
        var ar = new u8(str.length + (str.length >> 1));
        var ai = 0;
        var w = function (v) { ar[ai++] = v; };
        for (var i = 0; i < l; ++i) {
            if (ai + 5 > ar.length) {
                var n = new u8(ai + 8 + ((l - i) << 1));
                n.set(ar);
                ar = n;
            }
            var c = str.charCodeAt(i);
            if (c < 128 || latin1)
                w(c);
            else if (c < 2048)
                w(192 | (c >> 6)), w(128 | (c & 63));
            else if (c > 55295 && c < 57344)
                c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023),
                    w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));
            else
                w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));
        }
        return slc(ar, 0, ai);
    }
    /**
     * Converts a Uint8Array to a string
     * @param dat The data to decode to string
     * @param latin1 Whether or not to interpret the data as Latin-1. This should
     *               not need to be true unless encoding to binary string.
     * @returns The original UTF-8/Latin-1 string
     */
    function strFromU8(dat, latin1) {
        if (latin1) {
            var r = '';
            for (var i = 0; i < dat.length; i += 16384)
                r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384));
            return r;
        }
        else if (td) {
            return td.decode(dat);
        }
        else {
            var _a = dutf8(dat), s = _a.s, r = _a.r;
            if (r.length)
                err(8);
            return s;
        }
    }
    ;
    // deflate bit flag
    var dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; };
    // skip local zip header
    var slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); };
    // read zip header
    var zh = function (d, b, z) {
        var fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl, bs = b4(d, b + 20);
        var _a = z && bs == 4294967295 ? z64e(d, es) : [bs, b4(d, b + 24), b4(d, b + 42)], sc = _a[0], su = _a[1], off = _a[2];
        return [b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off];
    };
    // read zip64 extra field
    var z64e = function (d, b) {
        for (; b2(d, b) != 1; b += 4 + b2(d, b + 2))
            ;
        return [b8(d, b + 12), b8(d, b + 4), b8(d, b + 20)];
    };
    // extra field length
    var exfl = function (ex) {
        var le = 0;
        if (ex) {
            for (var k in ex) {
                var l = ex[k].length;
                if (l > 65535)
                    err(9);
                le += l + 4;
            }
        }
        return le;
    };
    // write zip header
    var wzh = function (d, b, f, fn, u, c, ce, co) {
        var fl = fn.length, ex = f.extra, col = co && co.length;
        var exl = exfl(ex);
        wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4;
        if (ce != null)
            d[b++] = 20, d[b++] = f.os;
        d[b] = 20, b += 2; // spec compliance? what's that?
        d[b++] = (f.flag << 1) | (c < 0 && 8), d[b++] = u && 8;
        d[b++] = f.compression & 255, d[b++] = f.compression >> 8;
        var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;
        if (y < 0 || y > 119)
            err(10);
        wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >> 1)), b += 4;
        if (c != -1) {
            wbytes(d, b, f.crc);
            wbytes(d, b + 4, c < 0 ? -c - 2 : c);
            wbytes(d, b + 8, f.size);
        }
        wbytes(d, b + 12, fl);
        wbytes(d, b + 14, exl), b += 16;
        if (ce != null) {
            wbytes(d, b, col);
            wbytes(d, b + 6, f.attrs);
            wbytes(d, b + 10, ce), b += 14;
        }
        d.set(fn, b);
        b += fl;
        if (exl) {
            for (var k in ex) {
                var exf = ex[k], l = exf.length;
                wbytes(d, b, +k);
                wbytes(d, b + 2, l);
                d.set(exf, b + 4), b += 4 + l;
            }
        }
        if (col)
            d.set(co, b), b += col;
        return b;
    };
    // write zip footer (end of central directory)
    var wzf = function (o, b, c, d, e) {
        wbytes(o, b, 0x6054B50); // skip disk
        wbytes(o, b + 8, c);
        wbytes(o, b + 10, c);
        wbytes(o, b + 12, d);
        wbytes(o, b + 16, e);
    };
    /**
     * A pass-through stream to keep data uncompressed in a ZIP archive.
     */
    var ZipPassThrough = /*#__PURE__*/ (function () {
        /**
         * Creates a pass-through stream that can be added to ZIP archives
         * @param filename The filename to associate with this data stream
         */
        function ZipPassThrough(filename) {
            this.filename = filename;
            this.c = crc();
            this.size = 0;
            this.compression = 0;
        }
        /**
         * Processes a chunk and pushes to the output stream. You can override this
         * method in a subclass for custom behavior, but by default this passes
         * the data through. You must call this.ondata(err, chunk, final) at some
         * point in this method.
         * @param chunk The chunk to process
         * @param final Whether this is the last chunk
         */
        ZipPassThrough.prototype.process = function (chunk, final) {
            this.ondata(null, chunk, final);
        };
        /**
         * Pushes a chunk to be added. If you are subclassing this with a custom
         * compression algorithm, note that you must push data from the source
         * file only, pre-compression.
         * @param chunk The chunk to push
         * @param final Whether this is the last chunk
         */
        ZipPassThrough.prototype.push = function (chunk, final) {
            if (!this.ondata)
                err(5);
            this.c.p(chunk);
            this.size += chunk.length;
            if (final)
                this.crc = this.c.d();
            this.process(chunk, final || false);
        };
        return ZipPassThrough;
    }());
    exports.ZipPassThrough = ZipPassThrough;
    // I don't extend because TypeScript extension adds 1kB of runtime bloat
    /**
     * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate
     * for better performance
     */
    var ZipDeflate = /*#__PURE__*/ (function () {
        /**
         * Creates a DEFLATE stream that can be added to ZIP archives
         * @param filename The filename to associate with this data stream
         * @param opts The compression options
         */
        function ZipDeflate(filename, opts) {
            var _this = this;
            if (!opts)
                opts = {};
            ZipPassThrough.call(this, filename);
            this.d = new Deflate(opts, function (dat, final) {
                _this.ondata(null, dat, final);
            });
            this.compression = 8;
            this.flag = dbf(opts.level);
        }
        ZipDeflate.prototype.process = function (chunk, final) {
            try {
                this.d.push(chunk, final);
            }
            catch (e) {
                this.ondata(e, null, final);
            }
        };
        /**
         * Pushes a chunk to be deflated
         * @param chunk The chunk to push
         * @param final Whether this is the last chunk
         */
        ZipDeflate.prototype.push = function (chunk, final) {
            ZipPassThrough.prototype.push.call(this, chunk, final);
        };
        return ZipDeflate;
    }());
    exports.ZipDeflate = ZipDeflate;
    /**
     * Asynchronous streaming DEFLATE compression for ZIP archives
     */
    var AsyncZipDeflate = /*#__PURE__*/ (function () {
        /**
         * Creates an asynchronous DEFLATE stream that can be added to ZIP archives
         * @param filename The filename to associate with this data stream
         * @param opts The compression options
         */
        function AsyncZipDeflate(filename, opts) {
            var _this = this;
            if (!opts)
                opts = {};
            ZipPassThrough.call(this, filename);
            this.d = new AsyncDeflate(opts, function (err, dat, final) {
                _this.ondata(err, dat, final);
            });
            this.compression = 8;
            this.flag = dbf(opts.level);
            this.terminate = this.d.terminate;
        }
        AsyncZipDeflate.prototype.process = function (chunk, final) {
            this.d.push(chunk, final);
        };
        /**
         * Pushes a chunk to be deflated
         * @param chunk The chunk to push
         * @param final Whether this is the last chunk
         */
        AsyncZipDeflate.prototype.push = function (chunk, final) {
            ZipPassThrough.prototype.push.call(this, chunk, final);
        };
        return AsyncZipDeflate;
    }());
    exports.AsyncZipDeflate = AsyncZipDeflate;
    // TODO: Better tree shaking
    /**
     * A zippable archive to which files can incrementally be added
     */
    var Zip = /*#__PURE__*/ (function () {
        /**
         * Creates an empty ZIP archive to which files can be added
         * @param cb The callback to call whenever data for the generated ZIP archive
         *           is available
         */
        function Zip(cb) {
            this.ondata = cb;
            this.u = [];
            this.d = 1;
        }
        /**
         * Adds a file to the ZIP archive
         * @param file The file stream to add
         */
        Zip.prototype.add = function (file) {
            var _this = this;
            if (!this.ondata)
                err(5);
            // finishing or finished
            if (this.d & 2)
                this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false);
            else {
                var f = strToU8(file.filename), fl_1 = f.length;
                var com = file.comment, o = com && strToU8(com);
                var u = fl_1 != file.filename.length || (o && (com.length != o.length));
                var hl_1 = fl_1 + exfl(file.extra) + 30;
                if (fl_1 > 65535)
                    this.ondata(err(11, 0, 1), null, false);
                var header = new u8(hl_1);
                wzh(header, 0, file, f, u, -1);
                var chks_1 = [header];
                var pAll_1 = function () {
                    for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) {
                        var chk = chks_2[_i];
                        _this.ondata(null, chk, false);
                    }
                    chks_1 = [];
                };
                var tr_1 = this.d;
                this.d = 0;
                var ind_1 = this.u.length;
                var uf_1 = mrg(file, {
                    f: f,
                    u: u,
                    o: o,
                    t: function () {
                        if (file.terminate)
                            file.terminate();
                    },
                    r: function () {
                        pAll_1();
                        if (tr_1) {
                            var nxt = _this.u[ind_1 + 1];
                            if (nxt)
                                nxt.r();
                            else
                                _this.d = 1;
                        }
                        tr_1 = 1;
                    }
                });
                var cl_1 = 0;
                file.ondata = function (err, dat, final) {
                    if (err) {
                        _this.ondata(err, dat, final);
                        _this.terminate();
                    }
                    else {
                        cl_1 += dat.length;
                        chks_1.push(dat);
                        if (final) {
                            var dd = new u8(16);
                            wbytes(dd, 0, 0x8074B50);
                            wbytes(dd, 4, file.crc);
                            wbytes(dd, 8, cl_1);
                            wbytes(dd, 12, file.size);
                            chks_1.push(dd);
                            uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size;
                            if (tr_1)
                                uf_1.r();
                            tr_1 = 1;
                        }
                        else if (tr_1)
                            pAll_1();
                    }
                };
                this.u.push(uf_1);
            }
        };
        /**
         * Ends the process of adding files and prepares to emit the final chunks.
         * This *must* be called after adding all desired files for the resulting
         * ZIP file to work properly.
         */
        Zip.prototype.end = function () {
            var _this = this;
            if (this.d & 2) {
                this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true);
                return;
            }
            if (this.d)
                this.e();
            else
                this.u.push({
                    r: function () {
                        if (!(_this.d & 1))
                            return;
                        _this.u.splice(-1, 1);
                        _this.e();
                    },
                    t: function () { }
                });
            this.d = 3;
        };
        Zip.prototype.e = function () {
            var bt = 0, l = 0, tl = 0;
            for (var _i = 0, _a = this.u; _i < _a.length; _i++) {
                var f = _a[_i];
                tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0);
            }
            var out = new u8(tl + 22);
            for (var _b = 0, _c = this.u; _b < _c.length; _b++) {
                var f = _c[_b];
                wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o);
                bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b;
            }
            wzf(out, bt, this.u.length, tl, l);
            this.ondata(null, out, true);
            this.d = 2;
        };
        /**
         * A method to terminate any internal workers used by the stream. Subsequent
         * calls to add() will fail.
         */
        Zip.prototype.terminate = function () {
            for (var _i = 0, _a = this.u; _i < _a.length; _i++) {
                var f = _a[_i];
                f.t();
            }
            this.d = 2;
        };
        return Zip;
    }());
    exports.Zip = Zip;
    function zip(data, opts, cb) {
        if (!cb)
            cb = opts, opts = {};
        if (typeof cb != 'function')
            err(7);
        var r = {};
        fltn(data, '', r, opts);
        var k = Object.keys(r);
        var lft = k.length, o = 0, tot = 0;
        var slft = lft, files = new Array(lft);
        var term = [];
        var tAll = function () {
            for (var i = 0; i < term.length; ++i)
                term[i]();
        };
        var cbd = function (a, b) {
            mt(function () { cb(a, b); });
        };
        mt(function () { cbd = cb; });
        var cbf = function () {
            var out = new u8(tot + 22), oe = o, cdl = tot - o;
            tot = 0;
            for (var i = 0; i < slft; ++i) {
                var f = files[i];
                try {
                    var l = f.c.length;
                    wzh(out, tot, f, f.f, f.u, l);
                    var badd = 30 + f.f.length + exfl(f.extra);
                    var loc = tot + badd;
                    out.set(f.c, loc);
                    wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l;
                }
                catch (e) {
                    return cbd(e, null);
                }
            }
            wzf(out, o, files.length, cdl, oe);
            cbd(null, out);
        };
        if (!lft)
            cbf();
        var _loop_1 = function (i) {
            var fn = k[i];
            var _a = r[fn], file = _a[0], p = _a[1];
            var c = crc(), size = file.length;
            c.p(file);
            var f = strToU8(fn), s = f.length;
            var com = p.comment, m = com && strToU8(com), ms = m && m.length;
            var exl = exfl(p.extra);
            var compression = p.level == 0 ? 0 : 8;
            var cbl = function (e, d) {
                if (e) {
                    tAll();
                    cbd(e, null);
                }
                else {
                    var l = d.length;
                    files[i] = mrg(p, {
                        size: size,
                        crc: c.d(),
                        c: d,
                        f: f,
                        m: m,
                        u: s != fn.length || (m && (com.length != ms)),
                        compression: compression
                    });
                    o += 30 + s + exl + l;
                    tot += 76 + 2 * (s + exl) + (ms || 0) + l;
                    if (!--lft)
                        cbf();
                }
            };
            if (s > 65535)
                cbl(err(11, 0, 1), null);
            if (!compression)
                cbl(null, file);
            else if (size < 160000) {
                try {
                    cbl(null, deflateSync(file, p));
                }
                catch (e) {
                    cbl(e, null);
                }
            }
            else
                term.push(deflate(file, p, cbl));
        };
        // Cannot use lft because it can decrease
        for (var i = 0; i < slft; ++i) {
            _loop_1(i);
        }
        return tAll;
    }
    /**
     * Synchronously creates a ZIP file. Prefer using `zip` for better performance
     * with more than one file.
     * @param data The directory structure for the ZIP archive
     * @param opts The main options, merged with per-file options
     * @returns The generated ZIP archive
     */
    function zipSync(data, opts) {
        if (!opts)
            opts = {};
        var r = {};
        var files = [];
        fltn(data, '', r, opts);
        var o = 0;
        var tot = 0;
        for (var fn in r) {
            var _a = r[fn], file = _a[0], p = _a[1];
            var compression = p.level == 0 ? 0 : 8;
            var f = strToU8(fn), s = f.length;
            var com = p.comment, m = com && strToU8(com), ms = m && m.length;
            var exl = exfl(p.extra);
            if (s > 65535)
                err(11);
            var d = compression ? deflateSync(file, p) : file, l = d.length;
            var c = crc();
            c.p(file);
            files.push(mrg(p, {
                size: file.length,
                crc: c.d(),
                c: d,
                f: f,
                m: m,
                u: s != fn.length || (m && (com.length != ms)),
                o: o,
                compression: compression
            }));
            o += 30 + s + exl + l;
            tot += 76 + 2 * (s + exl) + (ms || 0) + l;
        }
        var out = new u8(tot + 22), oe = o, cdl = tot - o;
        for (var i = 0; i < files.length; ++i) {
            var f = files[i];
            wzh(out, f.o, f, f.f, f.u, f.c.length);
            var badd = 30 + f.f.length + exfl(f.extra);
            out.set(f.c, f.o + badd);
            wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);
        }
        wzf(out, o, files.length, cdl, oe);
        return out;
    }
    /**
     * Streaming pass-through decompression for ZIP archives
     */
    var UnzipPassThrough = /*#__PURE__*/ (function () {
        function UnzipPassThrough() {
        }
        UnzipPassThrough.prototype.push = function (data, final) {
            this.ondata(null, data, final);
        };
        UnzipPassThrough.compression = 0;
        return UnzipPassThrough;
    }());
    exports.UnzipPassThrough = UnzipPassThrough;
    /**
     * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for
     * better performance.
     */
    var UnzipInflate = /*#__PURE__*/ (function () {
        /**
         * Creates a DEFLATE decompression that can be used in ZIP archives
         */
        function UnzipInflate() {
            var _this = this;
            this.i = new Inflate(function (dat, final) {
                _this.ondata(null, dat, final);
            });
        }
        UnzipInflate.prototype.push = function (data, final) {
            try {
                this.i.push(data, final);
            }
            catch (e) {
                this.ondata(e, null, final);
            }
        };
        UnzipInflate.compression = 8;
        return UnzipInflate;
    }());
    exports.UnzipInflate = UnzipInflate;
    /**
     * Asynchronous streaming DEFLATE decompression for ZIP archives
     */
    var AsyncUnzipInflate = /*#__PURE__*/ (function () {
        /**
         * Creates a DEFLATE decompression that can be used in ZIP archives
         */
        function AsyncUnzipInflate(_, sz) {
            var _this = this;
            if (sz < 320000) {
                this.i = new Inflate(function (dat, final) {
                    _this.ondata(null, dat, final);
                });
            }
            else {
                this.i = new AsyncInflate(function (err, dat, final) {
                    _this.ondata(err, dat, final);
                });
                this.terminate = this.i.terminate;
            }
        }
        AsyncUnzipInflate.prototype.push = function (data, final) {
            if (this.i.terminate)
                data = slc(data, 0);
            this.i.push(data, final);
        };
        AsyncUnzipInflate.compression = 8;
        return AsyncUnzipInflate;
    }());
    exports.AsyncUnzipInflate = AsyncUnzipInflate;
    /**
     * A ZIP archive decompression stream that emits files as they are discovered
     */
    var Unzip = /*#__PURE__*/ (function () {
        /**
         * Creates a ZIP decompression stream
         * @param cb The callback to call whenever a file in the ZIP archive is found
         */
        function Unzip(cb) {
            this.onfile = cb;
            this.k = [];
            this.o = {
                0: UnzipPassThrough
            };
            this.p = et;
        }
        /**
         * Pushes a chunk to be unzipped
         * @param chunk The chunk to push
         * @param final Whether this is the last chunk
         */
        Unzip.prototype.push = function (chunk, final) {
            var _this = this;
            if (!this.onfile)
                err(5);
            if (!this.p)
                err(4);
            if (this.c > 0) {
                var len = Math.min(this.c, chunk.length);
                var toAdd = chunk.subarray(0, len);
                this.c -= len;
                if (this.d)
                    this.d.push(toAdd, !this.c);
                else
                    this.k[0].push(toAdd);
                chunk = chunk.subarray(len);
                if (chunk.length)
                    return this.push(chunk, final);
            }
            else {
                var f = 0, i = 0, is = void 0, buf = void 0;
                if (!this.p.length)
                    buf = chunk;
                else if (!chunk.length)
                    buf = this.p;
                else {
                    buf = new u8(this.p.length + chunk.length);
                    buf.set(this.p), buf.set(chunk, this.p.length);
                }
                var l = buf.length, oc = this.c, add = oc && this.d;
                var _loop_2 = function () {
                    var _a;
                    var sig = b4(buf, i);
                    if (sig == 0x4034B50) {
                        f = 1, is = i;
                        this_1.d = null;
                        this_1.c = 0;
                        var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28);
                        if (l > i + 30 + fnl + es) {
                            var chks_3 = [];
                            this_1.k.unshift(chks_3);
                            f = 2;
                            var sc_1 = b4(buf, i + 18), su_1 = b4(buf, i + 22);
                            var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u);
                            if (sc_1 == 4294967295) {
                                _a = dd ? [-2] : z64e(buf, i), sc_1 = _a[0], su_1 = _a[1];
                            }
                            else if (dd)
                                sc_1 = -1;
                            i += es;
                            this_1.c = sc_1;
                            var d_1;
                            var file_1 = {
                                name: fn_1,
                                compression: cmp_1,
                                start: function () {
                                    if (!file_1.ondata)
                                        err(5);
                                    if (!sc_1)
                                        file_1.ondata(null, et, true);
                                    else {
                                        var ctr = _this.o[cmp_1];
                                        if (!ctr)
                                            file_1.ondata(err(14, 'unknown compression type ' + cmp_1, 1), null, false);
                                        d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1);
                                        d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); };
                                        for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) {
                                            var dat = chks_4[_i];
                                            d_1.push(dat, false);
                                        }
                                        if (_this.k[0] == chks_3 && _this.c)
                                            _this.d = d_1;
                                        else
                                            d_1.push(et, true);
                                    }
                                },
                                terminate: function () {
                                    if (d_1 && d_1.terminate)
                                        d_1.terminate();
                                }
                            };
                            if (sc_1 >= 0)
                                file_1.size = sc_1, file_1.originalSize = su_1;
                            this_1.onfile(file_1);
                        }
                        return "break";
                    }
                    else if (oc) {
                        if (sig == 0x8074B50) {
                            is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0;
                            return "break";
                        }
                        else if (sig == 0x2014B50) {
                            is = i -= 4, f = 3, this_1.c = 0;
                            return "break";
                        }
                    }
                };
                var this_1 = this;
                for (; i < l - 4; ++i) {
                    var state_1 = _loop_2();
                    if (state_1 === "break")
                        break;
                }
                this.p = et;
                if (oc < 0) {
                    var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i);
                    if (add)
                        add.push(dat, !!f);
                    else
                        this.k[+(f == 2)].push(dat);
                }
                if (f & 2)
                    return this.push(buf.subarray(i), final);
                this.p = buf.subarray(i);
            }
            if (final) {
                if (this.c)
                    err(13);
                this.p = null;
            }
        };
        /**
         * Registers a decoder with the stream, allowing for files compressed with
         * the compression type provided to be expanded correctly
         * @param decoder The decoder constructor
         */
        Unzip.prototype.register = function (decoder) {
            this.o[decoder.compression] = decoder;
        };
        return Unzip;
    }());
    exports.Unzip = Unzip;
    var mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) { fn(); };
    function unzip(data, opts, cb) {
        if (!cb)
            cb = opts, opts = {};
        if (typeof cb != 'function')
            err(7);
        var term = [];
        var tAll = function () {
            for (var i = 0; i < term.length; ++i)
                term[i]();
        };
        var files = {};
        var cbd = function (a, b) {
            mt(function () { cb(a, b); });
        };
        mt(function () { cbd = cb; });
        var e = data.length - 22;
        for (; b4(data, e) != 0x6054B50; --e) {
            if (!e || data.length - e > 65558) {
                cbd(err(13, 0, 1), null);
                return tAll;
            }
        }
        ;
        var lft = b2(data, e + 8);
        if (lft) {
            var c = lft;
            var o = b4(data, e + 16);
            var z = o == 4294967295 || c == 65535;
            if (z) {
                var ze = b4(data, e - 12);
                z = b4(data, ze) == 0x6064B50;
                if (z) {
                    c = lft = b4(data, ze + 32);
                    o = b4(data, ze + 48);
                }
            }
            var fltr = opts && opts.filter;
            var _loop_3 = function (i) {
                var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);
                o = no;
                var cbl = function (e, d) {
                    if (e) {
                        tAll();
                        cbd(e, null);
                    }
                    else {
                        if (d)
                            files[fn] = d;
                        if (!--lft)
                            cbd(null, files);
                    }
                };
                if (!fltr || fltr({
                    name: fn,
                    size: sc,
                    originalSize: su,
                    compression: c_1
                })) {
                    if (!c_1)
                        cbl(null, slc(data, b, b + sc));
                    else if (c_1 == 8) {
                        var infl = data.subarray(b, b + sc);
                        // Synchronously decompress under 512KB, or barely-compressed data
                        if (su < 524288 || sc > 0.8 * su) {
                            try {
                                cbl(null, inflateSync(infl, { out: new u8(su) }));
                            }
                            catch (e) {
                                cbl(e, null);
                            }
                        }
                        else
                            term.push(inflate(infl, { size: su }, cbl));
                    }
                    else
                        cbl(err(14, 'unknown compression type ' + c_1, 1), null);
                }
                else
                    cbl(null, null);
            };
            for (var i = 0; i < c; ++i) {
                _loop_3(i);
            }
        }
        else
            cbd(null, {});
        return tAll;
    }
    /**
     * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better
     * performance with more than one file.
     * @param data The raw compressed ZIP file
     * @param opts The ZIP extraction options
     * @returns The decompressed files
     */
    function unzipSync(data, opts) {
        var files = {};
        var e = data.length - 22;
        for (; b4(data, e) != 0x6054B50; --e) {
            if (!e || data.length - e > 65558)
                err(13);
        }
        ;
        var c = b2(data, e + 8);
        if (!c)
            return {};
        var o = b4(data, e + 16);
        var z = o == 4294967295 || c == 65535;
        if (z) {
            var ze = b4(data, e - 12);
            z = b4(data, ze) == 0x6064B50;
            if (z) {
                c = b4(data, ze + 32);
                o = b4(data, ze + 48);
            }
        }
        var fltr = opts && opts.filter;
        for (var i = 0; i < c; ++i) {
            var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);
            o = no;
            if (!fltr || fltr({
                name: fn,
                size: sc,
                originalSize: su,
                compression: c_2
            })) {
                if (!c_2)
                    files[fn] = slc(data, b, b + sc);
                else if (c_2 == 8)
                    files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) });
                else
                    err(14, 'unknown compression type ' + c_2);
            }
        }
        return files;
    }
},
/* core/serialization/reps.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
},
/* core/diagnostics.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    class Diagnostics {
        listeners = new Set();
        connect(listener) {
            this.listeners.add(listener);
        }
        disconnect(listener) {
            this.listeners.delete(listener);
        }
        report(obj) {
            for (const listener of this.listeners) {
                listener(obj);
            }
        }
    }
    exports.Diagnostics = Diagnostics;
    exports.diagnostics = new Diagnostics();
},
/* core/uniforms.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.min = min;
    exports.max = max;
    exports.some = some;
    exports.every = every;
    const tslib_1 = require(1) /* tslib */;
    const eq_1 = require(27) /* ./util/eq */;
    const arrayable = tslib_1.__importStar(require(14) /* ./util/arrayable */);
    class Uniform {
        is_Scalar() {
            return this.is_scalar;
        }
        is_Vector() {
            return !this.is_scalar;
        }
    }
    exports.Uniform = Uniform;
    class UniformScalar extends Uniform {
        value;
        length;
        is_scalar = true;
        constructor(value, length) {
            super();
            this.value = value;
            this.length = length;
        }
        get(_i) {
            return this.value;
        }
        *[Symbol.iterator]() {
            const { length, value } = this;
            for (let i = 0; i < length; i++) {
                yield value;
            }
        }
        select(indices) {
            return new UniformScalar(this.value, indices.count);
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.length, that.length) && cmp.eq(this.value, that.value);
        }
        map(fn) {
            return new UniformScalar(fn(this.value), this.length);
        }
        unique() {
            return [this.value];
        }
    }
    exports.UniformScalar = UniformScalar;
    class UniformVector extends Uniform {
        array;
        is_scalar = false;
        length;
        constructor(array) {
            super();
            this.array = array;
            this.length = this.array.length;
        }
        get(i) {
            return this.array[i];
        }
        *[Symbol.iterator]() {
            yield* this.array;
        }
        select(indices) {
            const array = indices.select(this.array);
            return new this.constructor(array);
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.length, that.length) && cmp.eq(this.array, that.array);
        }
        map(fn) {
            return new UniformVector(arrayable.map(this.array, fn));
        }
        unique() {
            return [...new Set(this.array)];
        }
    }
    exports.UniformVector = UniformVector;
    class ColorUniformVector extends UniformVector {
        array;
        _view;
        constructor(array) {
            super(array);
            this.array = array;
            this._view = new DataView(array.buffer);
        }
        get(i) {
            return this._view.getUint32(4 * i);
        }
        *[Symbol.iterator]() {
            const n = this.length;
            for (let i = 0; i < n; i++) {
                yield this.get(i);
            }
        }
        copy_buffer() {
            return this.array.buffer.slice();
        }
    }
    exports.ColorUniformVector = ColorUniformVector;
    function min(u) {
        return u.is_Scalar() ? u.value : arrayable.min(u.array);
    }
    function max(u) {
        return u.is_Scalar() ? u.value : arrayable.max(u.array);
    }
    function some(u, predicate) {
        return u.is_Scalar() ? predicate(u.value) : arrayable.some(u.array, predicate);
    }
    function every(u, predicate) {
        return u.is_Scalar() ? predicate(u.value) : arrayable.every(u.array, predicate);
    }
},
/* core/util/string.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.uuid4 = uuid4;
    exports.unique_id = unique_id;
    exports.escape = escape;
    exports.unescape = unescape;
    exports.use_strict = use_strict;
    exports.to_fixed = to_fixed;
    exports.insert_text_on_position = insert_text_on_position;
    const settings_1 = require(30) /* ../settings */;
    function uuid4() {
        // from ipython project
        // http://www.ietf.org/rfc/rfc4122.txt
        const s = new Array(32);
        const hex_digits = "0123456789ABCDEF";
        for (let i = 0; i < 32; i++) {
            s[i] = hex_digits[Math.floor(Math.random() * 0x10)];
        }
        s[12] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[16] = hex_digits[(s[16].charCodeAt(0) & 0x3) | 0x8]; // bits 6-7 of the clock_seq_hi_and_reserved to 01
        return s.join("");
    }
    let counter = 1000;
    function unique_id(prefix) {
        const id = settings_1.settings.dev ? `j${counter++}` : uuid4();
        if (prefix != null) {
            return `${prefix}-${id}`;
        }
        else {
            return id;
        }
    }
    function escape(s) {
        return s.replace(/(?:[&<>"'`])/g, (ch) => {
            switch (ch) {
                case "&": return "&amp;";
                case "<": return "&lt;";
                case ">": return "&gt;";
                case '"': return "&quot;";
                case "'": return "&#x27;";
                case "`": return "&#x60;";
                default: return ch;
            }
        });
    }
    function unescape(s) {
        return s.replace(/&(amp|lt|gt|quot|#x27|#x60);/g, (_, entity) => {
            switch (entity) {
                case "amp": return "&";
                case "lt": return "<";
                case "gt": return ">";
                case "quot": return '"';
                case "#x27": return "'";
                case "#x60": return "`";
                default: return entity;
            }
        });
    }
    function use_strict(code) {
        return `'use strict';\n${code}`;
    }
    function to_fixed(val, precision) {
        return val.toFixed(precision).replace(/(\.[0-9]*?)0+$/, "$1").replace(/\.$/, "");
    }
    function insert_text_on_position(destination, position, text_to_be_inserted) {
        const result_text = [];
        result_text.push(destination.slice(0, position));
        result_text.push(text_to_be_inserted);
        result_text.push(destination.slice(position));
        return result_text.join("");
    }
},
/* document/events.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const eq_1 = require(27) /* ../core/util/eq */;
    const serialization_1 = require(33) /* ../core/serialization */;
    class DocumentEvent {
        document;
        constructor(document) {
            this.document = document;
        }
        get [Symbol.toStringTag]() {
            return this.constructor.name;
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.document, that.document);
        }
        /**
         * Indicates whether this event should be emitted internally within bokehjs,
         * or whether it should also be synchronized with the server, if any session
         * is listening for such events.
         */
        sync = true;
    }
    exports.DocumentEvent = DocumentEvent;
    class DocumentEventBatch extends DocumentEvent {
        events;
        constructor(document, events) {
            super(document);
            this.events = events;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.events, that.events);
        }
    }
    exports.DocumentEventBatch = DocumentEventBatch;
    class DocumentChangedEvent extends DocumentEvent {
    }
    exports.DocumentChangedEvent = DocumentChangedEvent;
    class MessageSentEvent extends DocumentChangedEvent {
        msg_type;
        msg_data;
        kind = "MessageSent";
        constructor(document, msg_type, msg_data) {
            super(document);
            this.msg_type = msg_type;
            this.msg_data = msg_data;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.msg_type, that.msg_type) &&
                cmp.eq(this.msg_data, that.msg_data);
        }
        [serialization_1.serialize](serializer) {
            return {
                kind: this.kind,
                msg_type: this.msg_type,
                msg_data: serializer.encode(this.msg_data),
            };
        }
    }
    exports.MessageSentEvent = MessageSentEvent;
    class ModelChangedEvent extends DocumentChangedEvent {
        model;
        attr;
        value;
        kind = "ModelChanged";
        constructor(document, model, attr, value) {
            super(document);
            this.model = model;
            this.attr = attr;
            this.value = value;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.model, that.model) &&
                cmp.eq(this.attr, that.attr) &&
                cmp.eq(this.value, that.value);
        }
        [serialization_1.serialize](serializer) {
            return {
                kind: this.kind,
                model: this.model.ref(),
                attr: this.attr,
                new: serializer.encode(this.value),
            };
        }
    }
    exports.ModelChangedEvent = ModelChangedEvent;
    class ColumnDataChangedEvent extends DocumentChangedEvent {
        model;
        attr;
        data;
        cols;
        kind = "ColumnDataChanged";
        constructor(document, model, attr, data, cols) {
            super(document);
            this.model = model;
            this.attr = attr;
            this.data = data;
            this.cols = cols;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.model, that.model) &&
                cmp.eq(this.attr, that.attr) &&
                cmp.eq(this.data, that.data) &&
                cmp.eq(this.cols, that.cols);
        }
        [serialization_1.serialize](serializer) {
            return {
                kind: this.kind,
                model: this.model.ref(),
                attr: this.attr,
                data: serializer.encode(this.data),
                cols: this.cols,
            };
        }
    }
    exports.ColumnDataChangedEvent = ColumnDataChangedEvent;
    class ColumnsStreamedEvent extends DocumentChangedEvent {
        model;
        attr;
        data;
        rollover;
        kind = "ColumnsStreamed";
        constructor(document, model, attr, data, rollover) {
            super(document);
            this.model = model;
            this.attr = attr;
            this.data = data;
            this.rollover = rollover;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.model, that.model) &&
                cmp.eq(this.attr, that.attr) &&
                cmp.eq(this.data, that.data) &&
                cmp.eq(this.rollover, that.rollover);
        }
        [serialization_1.serialize](serializer) {
            return {
                kind: this.kind,
                model: this.model.ref(),
                attr: this.attr,
                data: serializer.encode(this.data),
                rollover: this.rollover,
            };
        }
    }
    exports.ColumnsStreamedEvent = ColumnsStreamedEvent;
    class ColumnsPatchedEvent extends DocumentChangedEvent {
        model;
        attr;
        patches;
        kind = "ColumnsPatched";
        constructor(document, model, attr, patches) {
            super(document);
            this.model = model;
            this.attr = attr;
            this.patches = patches;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.model, that.model) &&
                cmp.eq(this.attr, that.attr) &&
                cmp.eq(this.patches, that.patches);
        }
        [serialization_1.serialize](serializer) {
            return {
                kind: this.kind,
                attr: this.attr,
                model: this.model.ref(),
                patches: serializer.encode(this.patches),
            };
        }
    }
    exports.ColumnsPatchedEvent = ColumnsPatchedEvent;
    class TitleChangedEvent extends DocumentChangedEvent {
        title;
        kind = "TitleChanged";
        constructor(document, title) {
            super(document);
            this.title = title;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.title, that.title);
        }
        [serialization_1.serialize](_serializer) {
            return {
                kind: this.kind,
                title: this.title,
            };
        }
    }
    exports.TitleChangedEvent = TitleChangedEvent;
    class RootAddedEvent extends DocumentChangedEvent {
        model;
        kind = "RootAdded";
        constructor(document, model) {
            super(document);
            this.model = model;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.model, that.model);
        }
        [serialization_1.serialize](serializer) {
            return {
                kind: this.kind,
                model: serializer.encode(this.model),
            };
        }
    }
    exports.RootAddedEvent = RootAddedEvent;
    class RootRemovedEvent extends DocumentChangedEvent {
        model;
        kind = "RootRemoved";
        constructor(document, model) {
            super(document);
            this.model = model;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.model, that.model);
        }
        [serialization_1.serialize](_serializer) {
            return {
                kind: this.kind,
                model: this.model.ref(),
            };
        }
    }
    exports.RootRemovedEvent = RootRemovedEvent;
},
/* core/util/pretty.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.to_string = to_string;
    const types_1 = require(8) /* ./types */;
    const object_1 = require(9) /* ./object */;
    exports.pretty = Symbol("pretty");
    function is_Printable(obj) {
        return (0, types_1.isObject)(obj) && exports.pretty in obj;
    }
    class Printer {
        precision;
        visited = new Set();
        constructor(options) {
            this.precision = options?.precision;
        }
        to_string(obj) {
            if ((0, types_1.isObject)(obj)) {
                if (this.visited.has(obj)) {
                    return "<circular>";
                }
                else {
                    this.visited.add(obj);
                }
            }
            if (is_Printable(obj)) {
                return obj[exports.pretty](this);
            }
            else if ((0, types_1.isBoolean)(obj)) {
                return this.boolean(obj);
            }
            else if ((0, types_1.isNumber)(obj)) {
                return this.number(obj);
            }
            else if ((0, types_1.isString)(obj)) {
                return this.string(obj);
            }
            else if ((0, types_1.isArray)(obj)) {
                return this.array(obj);
            }
            else if ((0, types_1.isIterable)(obj)) {
                return this.iterable(obj);
            }
            else if ((0, types_1.isPlainObject)(obj)) {
                return this.object(obj);
            }
            else if ((0, types_1.isSymbol)(obj)) {
                return this.symbol(obj);
            }
            else if (obj instanceof ArrayBuffer) {
                return this.array_buffer(obj);
            }
            else {
                return `${obj}`;
            }
        }
        token(val) {
            return val;
        }
        boolean(val) {
            return `${val}`;
        }
        number(val) {
            if (this.precision != null) {
                return val.toFixed(this.precision);
            }
            else {
                return `${val}`;
            }
        }
        string(val) {
            const sq = val.includes("'");
            const dq = val.includes('"');
            if (sq && dq) {
                return `\`${val.replace(/`/g, "\\`")}\``;
            }
            else if (dq) {
                return `'${val}'`;
            }
            else {
                return `"${val}"`;
            }
        }
        symbol(val) {
            return val.toString();
        }
        array(obj) {
            const T = this.token;
            const items = [];
            for (const entry of obj) {
                items.push(this.to_string(entry));
            }
            return `${T("[")}${items.join(`${T(",")} `)}${T("]")}`;
        }
        iterable(obj) {
            const T = this.token;
            const tag = Object(obj)[Symbol.toStringTag] ?? "Object";
            const items = this.array(obj);
            return `${tag}${T("(")}${items}${T(")")}`;
        }
        object(obj) {
            const T = this.token;
            const items = [];
            for (const [key, val] of (0, object_1.entries)(obj)) {
                items.push(`${key}${T(":")} ${this.to_string(val)}`);
            }
            return `${T("{")}${items.join(`${T(",")} `)}${T("}")}`;
        }
        array_buffer(obj) {
            return `ArrayBuffer(#${obj.byteLength})`;
        }
    }
    exports.Printer = Printer;
    function to_string(obj, options) {
        const printer = new Printer(options);
        return printer.to_string(obj);
    }
},
/* core/patching.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.stream_to_column = stream_to_column;
    exports.slice = slice;
    exports.patch_to_column = patch_to_column;
    exports.stream_to_columns = stream_to_columns;
    exports.patch_to_columns = patch_to_columns;
    const tslib_1 = require(1) /* tslib */;
    const types_1 = require(8) /* ./util/types */;
    const object_1 = require(9) /* ./util/object */;
    const set_1 = require(45) /* ./util/set */;
    const typed_array = tslib_1.__importStar(require(46) /* ./util/typed_array */);
    // exported for testing
    function stream_to_column(col, new_col, rollover) {
        if ((0, types_1.isArray)(col) && (0, types_1.isArray)(new_col)) {
            const result = col.concat(new_col);
            if (rollover != null && result.length > rollover) {
                return result.slice(-rollover);
            }
            else {
                return result;
            }
        }
        const total_len = col.length + new_col.length;
        // handle rollover case for typed arrays
        if (rollover != null && total_len > rollover) {
            const start = total_len - rollover;
            const end = col.length;
            // resize col if it is shorter than the rollover length
            const result = (() => {
                if (col.length < rollover) {
                    const ctor = (() => {
                        if ((0, types_1.isTypedArray)(col)) {
                            return col.constructor;
                        }
                        else if ((0, types_1.isTypedArray)(new_col)) {
                            return new_col.constructor;
                        }
                        else {
                            throw new Error("unsupported array types");
                        }
                    })();
                    const result = new ctor(rollover);
                    result.set(col, 0);
                    return result;
                }
                else {
                    return col;
                }
            })();
            // shift values in original col to accommodate new_col
            for (let i = start, endi = end; i < endi; i++) {
                result[i - start] = result[i];
            }
            // update end values in col with new_col
            for (let i = 0, endi = new_col.length; i < endi; i++) {
                result[i + (end - start)] = new_col[i];
            }
            return result;
        }
        else {
            const col_ = (() => {
                if ((0, types_1.isTypedArray)(col)) {
                    return col;
                }
                else if ((0, types_1.isTypedArray)(new_col)) {
                    return new new_col.constructor(col);
                }
                else {
                    throw new Error("unsupported array types");
                }
            })();
            return typed_array.concat(col_, new_col);
        }
    }
    // exported for testing
    function slice(ind, length) {
        let start, step, stop;
        if ((0, types_1.isNumber)(ind)) {
            start = ind;
            stop = ind + 1;
            step = 1;
        }
        else {
            start = ind.start != null ? ind.start : 0;
            stop = ind.stop != null ? ind.stop : length;
            step = ind.step != null ? ind.step : 1;
        }
        return [start, stop, step];
    }
    // exported for testing
    function patch_to_column(col, patch) {
        const patched = new Set();
        let patched_range = false;
        for (const [ind, val] of patch) {
            // make the single index case look like the length-3 multi-index case
            let shape;
            let item;
            let index;
            let value;
            if ((0, types_1.isArray)(ind)) {
                const [i] = ind;
                patched.add(i);
                shape = col[i].shape;
                item = col[i];
                value = val;
                // this is basically like NumPy's "newaxis", inserting an empty dimension
                // makes length 2 and 3 multi-index cases uniform, so that the same code
                // can handle both
                if (ind.length === 2) {
                    shape = [1, shape[0]];
                    index = [ind[0], 0, ind[1]];
                }
                else {
                    index = ind;
                }
            }
            else {
                if ((0, types_1.isNumber)(ind)) {
                    value = [val];
                    patched.add(ind);
                }
                else {
                    value = val;
                    patched_range = true;
                }
                index = [0, 0, ind];
                shape = [1, col.length];
                item = col;
            }
            // now this one nested loop handles all cases
            let flat_index = 0;
            const [istart, istop, istep] = slice(index[1], shape[0]);
            const [jstart, jstop, jstep] = slice(index[2], shape[1]);
            for (let i = istart; i < istop; i += istep) {
                for (let j = jstart; j < jstop; j += jstep) {
                    if (patched_range) {
                        patched.add(j);
                    }
                    item[i * shape[1] + j] = value[flat_index];
                    flat_index++;
                }
            }
        }
        return patched;
    }
    function stream_to_columns(old_data, new_data, rollover) {
        const data = (0, object_1.dict)(old_data);
        for (const [name, new_column] of (0, object_1.dict)(new_data)) {
            const old_column = data.get(name) ?? [];
            data.set(name, stream_to_column(old_column, new_column, rollover));
        }
    }
    function patch_to_columns(old_data, patches) {
        const data = (0, object_1.dict)(old_data);
        let patched = new Set();
        for (const [name, patch] of (0, object_1.dict)(patches)) {
            const old_column = data.get(name) ?? [];
            patched = (0, set_1.union)(patched, patch_to_column(old_column, patch)); // XXX: any
        }
        return patched;
    }
},
/* core/util/set.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.union = union;
    exports.intersection = intersection;
    exports.difference = difference;
    function union(...sets) {
        const result = new Set();
        for (const set of sets) {
            for (const item of set) {
                result.add(item);
            }
        }
        return result;
    }
    function intersection(set, ...sets) {
        const result = new Set();
        top: for (const item of set) {
            for (const other of sets) {
                if (!other.has(item)) {
                    continue top;
                }
            }
            result.add(item);
        }
        return result;
    }
    function difference(set, ...sets) {
        const result = new Set(set);
        for (const item of union(...sets)) {
            result.delete(item);
        }
        return result;
    }
},
/* core/util/typed_array.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.concat = concat;
    function concat(array0, ...arrays) {
        let n = array0.length;
        for (const array of arrays) {
            n += array.length;
        }
        const result = new array0.constructor(n);
        result.set(array0, 0);
        let i = array0.length;
        for (const array of arrays) {
            result.set(array, i);
            i += array.length;
        }
        return result;
    }
},
/* core/resolvers.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    class ModelResolver {
        parent;
        _known_models = new Map();
        constructor(parent, models = []) {
            this.parent = parent;
            for (const model of models) {
                this.register(model);
            }
        }
        get(name) {
            return this._known_models.get(name) ?? this.parent?.get(name) ?? null;
        }
        register(model, force = false) {
            const name = model.__qualified__;
            if (force || this.get(name) == null) {
                this._known_models.set(name, model);
            }
            else {
                console.warn(`Model '${name}' was already registered with this resolver`);
            }
        }
        get names() {
            return [...this._known_models.keys()].sort();
        }
    }
    exports.ModelResolver = ModelResolver;
},
/* core/serialization/deserializer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const logging_1 = require(11) /* ../logging */;
    const refs_1 = require(19) /* ../util/refs */;
    const ndarray_1 = require(31) /* ../util/ndarray */;
    const object_1 = require(9) /* ../util/object */;
    const array_1 = require(10) /* ../util/array */;
    const platform_1 = require(28) /* ../util/platform */;
    const buffer_1 = require(36) /* ../util/buffer */;
    const types_1 = require(8) /* ../util/types */;
    const slice_1 = require(49) /* ../util/slice */;
    const _decoders = new Map();
    class DeserializationError extends Error {
    }
    exports.DeserializationError = DeserializationError;
    class Deserializer {
        resolver;
        references;
        finalize;
        static register(type, decoder) {
            if (!_decoders.has(type)) {
                _decoders.set(type, decoder);
            }
            else {
                throw new Error(`'${type}' already registered for decoding`);
            }
        }
        constructor(resolver, references = new Map(), finalize) {
            this.resolver = resolver;
            this.references = references;
            this.finalize = finalize;
        }
        _decoding = false;
        _buffers = new Map();
        _finalizable = new Set();
        decode(obj /*AnyVal*/, buffers) {
            if (buffers != null) {
                for (const [id, buffer] of buffers) {
                    this._buffers.set(id, buffer);
                }
            }
            if (this._decoding) {
                return this._decode(obj);
            }
            this._decoding = true;
            let finalizable;
            const decoded = (() => {
                try {
                    return this._decode(obj);
                }
                finally {
                    finalizable = new Set(this._finalizable);
                    this._decoding = false;
                    this._buffers.clear();
                    this._finalizable.clear();
                }
            })();
            for (const instance of finalizable) {
                this.finalize?.(instance);
                instance.finalize();
                instance.assert_initialized();
            }
            // `connect_signals` has to be executed last because it may rely on properties
            // of dependencies that are initialized only in `finalize`. It's a problem
            // that appears when there are circular references, e.g. as in
            // CDS -> CustomJS (on data change) -> GlyphRenderer (in args) -> CDS.
            for (const instance of finalizable) {
                instance.connect_signals();
            }
            return decoded;
        }
        _decode(obj /*AnyVal*/) {
            if ((0, types_1.isArray)(obj)) {
                return this._decode_plain_array(obj);
            }
            else if ((0, types_1.isPlainObject)(obj)) {
                if ((0, types_1.isString)(obj.type)) {
                    const decoder = _decoders.get(obj.type);
                    if (decoder != null) {
                        return decoder(obj, this);
                    }
                    switch (obj.type) {
                        case "ref":
                            return this._decode_ref(obj);
                        case "symbol":
                            return this._decode_symbol(obj);
                        case "number":
                            return this._decode_number(obj);
                        case "array":
                            return this._decode_array(obj);
                        case "set":
                            return this._decode_set(obj);
                        case "map":
                            return this._decode_map(obj);
                        case "bytes":
                            return this._decode_bytes(obj);
                        case "slice":
                            return this._decode_slice(obj);
                        case "date":
                            return this._decode_date(obj);
                        case "value":
                            return this._decode_value(obj);
                        case "field":
                            return this._decode_field(obj);
                        case "expr":
                            return this._decode_expr(obj);
                        case "typed_array":
                            return this._decode_typed_array(obj);
                        case "ndarray":
                            return this._decode_ndarray(obj);
                        case "object": {
                            if ((0, types_1.isString)(obj.id)) {
                                return this._decode_object_ref(obj);
                            }
                            else {
                                return this._decode_object(obj);
                            }
                        }
                        default: {
                            this.error(`unable to decode an object of type '${obj.type}'`);
                        }
                    }
                }
                else if ((0, types_1.isString)(obj.id)) {
                    return this._decode_ref(obj);
                }
                else {
                    return this._decode_plain_object(obj);
                }
            }
            else {
                return obj;
            }
        }
        _decode_symbol(obj) {
            this.error(`can't resolve named symbol '${obj.name}'`); // TODO: implement symbol resolution
        }
        _decode_number(obj) {
            if ("value" in obj) {
                const { value } = obj;
                if ((0, types_1.isString)(value)) {
                    switch (value) {
                        case "nan": return NaN;
                        case "+inf": return +Infinity;
                        case "-inf": return -Infinity;
                    }
                }
                else if ((0, types_1.isNumber)(value)) {
                    return value;
                }
            }
            this.error(`invalid number representation '${obj}'`);
        }
        _decode_plain_array(obj) {
            return (0, array_1.map)(obj, (item) => this._decode(item));
        }
        _decode_plain_object(obj) {
            const decoded = {};
            for (const [key, val] of (0, object_1.entries)(obj)) {
                decoded[key] = this._decode(val);
            }
            return decoded;
        }
        _decode_array(obj) {
            const decoded = [];
            for (const entry of obj.entries ?? []) {
                decoded.push(this._decode(entry));
            }
            return decoded;
        }
        _decode_set(obj) {
            const decoded = new Set();
            for (const entry of obj.entries ?? []) {
                decoded.add(this._decode(entry));
            }
            return decoded;
        }
        _decode_map(obj) {
            const entries = (0, array_1.map)(obj.entries ?? [], ([key, val]) => [this._decode(key), this._decode(val)]);
            const is_plain = entries.every(([key, _val]) => (0, types_1.isString)(key));
            // An empty container will result in a plain object, not a Map, thus in the case of
            // kinds.Mapping property type, one needs to accommodate for this in all instances.
            // Fortunately there are few of these scattered across `src/lib/models/`. See HACK
            // in `Mapping.coerce()` in `core/util/kinds`.
            if (is_plain) {
                return Object.fromEntries(entries);
            }
            else {
                return new Map(entries);
            }
        }
        _decode_bytes(obj) {
            const { data } = obj;
            if ((0, refs_1.is_ref)(data)) {
                const buffer = this._buffers.get(data.id);
                if (buffer != null) {
                    return buffer;
                }
                else {
                    this.error(`buffer for id=${data.id} not found`);
                }
            }
            else if ((0, types_1.isString)(data)) {
                return (0, buffer_1.base64_to_buffer)(data);
            }
            else {
                return data.buffer;
            }
        }
        _decode_slice(obj) {
            const start = this._decode(obj.start);
            const stop = this._decode(obj.stop);
            const step = this._decode(obj.step);
            return new slice_1.Slice({ start, stop, step });
        }
        _decode_date(obj) {
            const iso = this._decode(obj.iso);
            return new Date(iso);
        }
        _decode_value(obj) {
            const value = this._decode(obj.value);
            const transform = obj.transform != null ? this._decode(obj.transform) : undefined;
            const units = obj.units != null ? this._decode(obj.units) : undefined;
            return { value, transform, units };
        }
        _decode_field(obj) {
            const field = this._decode(obj.field);
            const transform = obj.transform != null ? this._decode(obj.transform) : undefined;
            const units = obj.units != null ? this._decode(obj.units) : undefined;
            return { field, transform, units };
        }
        _decode_expr(obj) {
            const expr = this._decode(obj.expr);
            const transform = obj.transform != null ? this._decode(obj.transform) : undefined;
            const units = obj.units != null ? this._decode(obj.units) : undefined;
            return { expr, transform, units };
        }
        _decode_typed_array(obj) {
            const { array, order, dtype } = obj;
            const buffer = this._decode(array);
            if (order != platform_1.BYTE_ORDER) {
                (0, buffer_1.swap)(buffer, dtype);
            }
            switch (dtype) {
                case "uint8": return new Uint8Array(buffer);
                case "int8": return new Int8Array(buffer);
                case "uint16": return new Uint16Array(buffer);
                case "int16": return new Int16Array(buffer);
                case "uint32": return new Uint32Array(buffer);
                case "int32": return new Int32Array(buffer);
                // case "uint64": return new BigInt64Array(buffer)
                // case "int64":  return new BigInt64Array(buffer)
                case "float32": return new Float32Array(buffer);
                case "float64": return new Float64Array(buffer);
                default:
                    this.error(`unsupported dtype '${dtype}'`);
            }
        }
        _decode_ndarray(obj) {
            const { array, order, dtype, shape } = obj;
            const decoded = this._decode(array);
            if (decoded instanceof ArrayBuffer && order != platform_1.BYTE_ORDER) {
                (0, buffer_1.swap)(decoded, dtype);
            }
            return (0, ndarray_1.ndarray)(decoded /*XXX*/, { dtype, shape });
        }
        _decode_object(obj) {
            const { name: type, attributes } = obj;
            const cls = this._resolve_type(type);
            if (attributes != null) {
                return new cls(this._decode(attributes));
            }
            else {
                return new cls();
            }
        }
        _decode_ref(obj) {
            const instance = this.references.get(obj.id);
            if (instance != null) {
                return instance;
            }
            else {
                this.error(`reference ${obj.id} isn't known`);
            }
        }
        _decode_object_ref(obj) {
            const { id, name: type, attributes } = obj;
            const ref = this.references.get(id);
            if (ref != null) {
                if (ref.type == type) {
                    const decoded_attributes = this._decode(attributes ?? {});
                    ref.setv(decoded_attributes, { sync: false });
                    return ref;
                }
                else {
                    this.error(`type mismatch for an existing reference '${ref}', expected '${type}'`);
                }
            }
            else {
                const cls = this._resolve_type(type);
                const instance = new cls({ id });
                this.references.set(id, instance);
                const decoded_attributes = this._decode(attributes ?? {});
                instance.initialize_props(decoded_attributes);
                this._finalizable.add(instance);
                return instance;
            }
        }
        error(message) {
            throw new DeserializationError(message);
        }
        warning(message) {
            logging_1.logger.warn(message);
        }
        _resolve_type(type) {
            const cls = this.resolver.get(type);
            if (cls != null) {
                return cls;
            }
            else {
                this.error(`could not resolve type '${type}', which could be due to a widget or a custom model not being registered before first usage`);
            }
        }
    }
    exports.Deserializer = Deserializer;
},
/* core/util/slice.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const serialization_1 = require(33) /* ../serialization */;
    class Slice {
        start;
        stop;
        step;
        constructor({ start, stop, step } = {}) {
            this.start = start ?? null;
            this.stop = stop ?? null;
            this.step = step ?? null;
        }
        [serialization_1.serialize](serializer) {
            return {
                type: "slice",
                start: serializer.encode(this.start),
                stop: serializer.encode(this.stop),
                step: serializer.encode(this.step),
            };
        }
    }
    exports.Slice = Slice;
},
/* core/util/version.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const eq_1 = require(27) /* ./eq */;
    const version_re = /^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(?:(?<type>-dev\.|-rc\.|.dev|rc)(?<revision>\d+))?(?:\+(?<build>\d+)\..+)?$/;
    (function (ReleaseType) {
        ReleaseType[ReleaseType["Dev"] = 0] = "Dev";
        ReleaseType[ReleaseType["Candidate"] = 1] = "Candidate";
        ReleaseType[ReleaseType["Release"] = 2] = "Release";
    })(exports.ReleaseType || (exports.ReleaseType = {}));
    class Version {
        major;
        minor;
        patch;
        type;
        revision;
        build;
        constructor(major, minor, patch, type = exports.ReleaseType.Release, revision = 0, build = 0) {
            this.major = major;
            this.minor = minor;
            this.patch = patch;
            this.type = type;
            this.revision = revision;
            this.build = build;
        }
        static from(version) {
            return parse_version(version);
        }
        toString() {
            const { major, minor, patch, type, revision, build } = this;
            let version = `${major}.${minor}.${patch}`;
            switch (type) {
                case exports.ReleaseType.Dev: version += `-dev.${revision}`;
                case exports.ReleaseType.Candidate: version += `-rc.${revision}`;
                case exports.ReleaseType.Release:
            }
            if (build != 0) {
                version += `+${build}`;
            }
            return version;
        }
        [eq_1.equals](that) {
            // ignore build field, because bokehjs doesn't provide it
            const { major, minor, patch, type, revision } = this;
            return major == that.major &&
                minor == that.minor &&
                patch == that.patch &&
                type == that.type &&
                revision == that.revision;
        }
    }
    exports.Version = Version;
    function parse_version(version) {
        const result = version_re.exec(version);
        if (result == null || result.groups == null) {
            return null;
        }
        const { groups } = result;
        const major = Number(groups.major);
        const minor = Number(groups.minor);
        const patch = Number(groups.patch);
        const type = (() => {
            switch (groups.type) {
                case "-dev.":
                case ".dev": return exports.ReleaseType.Dev;
                case "-rc.":
                case "rc": return exports.ReleaseType.Candidate;
                default: return exports.ReleaseType.Release;
            }
        })();
        // typeof due to bad stdlib typings or enable exactOptionalPropertyTypes
        const revision = typeof groups.revision == "undefined" ? 0 : Number(groups.revision);
        const build = typeof groups.build == "undefined" ? 0 : Number(groups.build);
        return new Version(major, minor, patch, type, revision, build);
    }
},
/* core/util/callbacks.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.execute = execute;
    exports.execute_sync = execute_sync;
    const types_1 = require(8) /* ./types */;
    function execute(cb, obj, ...args) {
        if ((0, types_1.isFunction)(cb)) {
            return cb(obj, ...args);
        }
        else {
            return cb.execute(obj, ...args);
        }
    }
    function execute_sync(cb, obj, ...args) {
        if ((0, types_1.isFunction)(cb)) {
            return cb(obj, ...args);
        }
        else {
            return cb.execute_sync(obj, ...args);
        }
    }
},
/* model.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const has_props_1 = require(16) /* ./core/has_props */;
    const types_1 = require(8) /* ./core/util/types */;
    const object_1 = require(9) /* ./core/util/object */;
    const eq_1 = require(27) /* ./core/util/eq */;
    const logging_1 = require(11) /* ./core/logging */;
    const callbacks_1 = require(51) /* ./core/util/callbacks */;
    const kinds_1 = require(22) /* ./core/kinds */;
    const JSCallbacks = (0, kinds_1.Mapping)(kinds_1.Str, (0, kinds_1.List)((0, kinds_1.Func)()));
    class Model extends has_props_1.HasProps {
        get is_syncable() {
            return this.syncable;
        }
        [eq_1.equals](that, cmp) {
            return (cmp.structural ? true : cmp.eq(this.id, that.id)) && super[eq_1.equals](that, cmp);
        }
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Any, Unknown, Bool, Str, List, Set, Dict, Nullable }) => ({
                tags: [List(Unknown), []],
                name: [Nullable(Str), null],
                js_property_callbacks: [Dict(List(Any /*TODO*/)), {}],
                js_event_callbacks: [Dict(List(Any /*TODO*/)), {}],
                subscribed_events: [Set(Str), new globalThis.Set()],
                syncable: [Bool, true],
            }));
            this.internal({
                _js_callbacks: [JSCallbacks, new Map(), { readonly: true }],
            });
        }
        connect_signals() {
            super.connect_signals();
            this._update_property_callbacks();
            this.connect(this.properties.js_property_callbacks.change, () => this._update_property_callbacks());
            this.connect(this.properties.js_event_callbacks.change, () => this._update_event_callbacks());
            this.connect(this.properties.subscribed_events.change, () => this._update_event_callbacks());
        }
        /*protected*/ _process_event(event) {
            for (const callback of (0, object_1.dict)(this.js_event_callbacks).get(event.event_name) ?? []) {
                void (0, callbacks_1.execute)(callback, event);
            }
            if (this.document != null && this.subscribed_events.has(event.event_name)) {
                this.document.event_manager.send_event(event);
            }
        }
        trigger_event(event) {
            if (this.document != null) {
                event.origin = this;
                this.document.event_manager.trigger(event);
            }
        }
        _update_event_callbacks() {
            if (this.document == null) {
                logging_1.logger.warn("WARNING: Document not defined for updating event callbacks");
                return;
            }
            this.document.event_manager.subscribed_models.add(this);
        }
        _update_property_callbacks() {
            const signal_for = (event) => {
                const [evt, attr = null] = event.split(":");
                return attr != null ? this.properties[attr][evt] : this[evt];
            };
            for (const [event, callbacks] of this._js_callbacks) {
                const signal = signal_for(event);
                for (const cb of callbacks) {
                    this.disconnect(signal, cb);
                }
            }
            this._js_callbacks.clear();
            for (const [event, callbacks] of (0, object_1.dict)(this.js_property_callbacks)) {
                const wrappers = callbacks.map((cb) => () => (0, callbacks_1.execute)(cb, this));
                this._js_callbacks.set(event, wrappers);
                const signal = signal_for(event);
                for (const cb of wrappers) {
                    this.connect(signal, cb);
                }
            }
        }
        _doc_attached() {
            super._doc_attached();
            if (this.js_event_callbacks.size != 0 || this.subscribed_events.size != 0) {
                this._update_event_callbacks();
            }
        }
        _doc_detached() {
            super._doc_detached();
            this.document?.event_manager.subscribed_models.delete(this);
        }
        select(selector) {
            if ((0, types_1.isString)(selector)) {
                return [...this.references()].filter((ref) => ref instanceof Model && ref.name === selector);
            }
            else if ((0, types_1.isPlainObject)(selector) && "type" in selector) {
                return [...this.references()].filter((ref) => ref.type == selector.type);
            }
            else if (selector.prototype instanceof has_props_1.HasProps) {
                return [...this.references()].filter((ref) => ref instanceof selector);
            }
            else {
                throw new Error(`invalid selector ${selector}`);
            }
        }
        select_one(selector) {
            const result = this.select(selector);
            switch (result.length) {
                case 0:
                    return null;
                case 1:
                    return result[0];
                default:
                    throw new Error(`found multiple objects matching the given selector ${selector}`);
            }
        }
        get_one(selector) {
            const result = this.select_one(selector);
            if (result != null) {
                return result;
            }
            else {
                throw new Error(`could not find any objects matching the given selector ${selector}`);
            }
        }
        on_event(event, callback) {
            const name = (0, types_1.isString)(event) ? event : event.prototype.event_name;
            const js_event_callbacks = (0, object_1.dict)(this.js_event_callbacks);
            const callbacks = js_event_callbacks.get(name) ?? [];
            js_event_callbacks.set(name, [...callbacks, callback]);
        }
    }
    exports.Model = Model;
},
/* document/config.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../model */;
    const notifications_1 = require(54) /* ../models/ui/notifications */;
    class DocumentConfig extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Bool, Ref, Nullable }) => ({
                reconnect_session: [Bool, true],
                notify_connection_status: [Bool, true],
                notifications: [Nullable(Ref(notifications_1.Notifications)), () => new notifications_1.Notifications()],
            }));
        }
    }
    exports.DocumentConfig = DocumentConfig;
},
/* models/ui/notifications.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const ui_element_1 = require(55) /* ./ui_element */;
    const dom_1 = require(61) /* ../../core/dom */;
    const signaling_1 = require(17) /* ../../core/signaling */;
    const base_css = tslib_1.__importStar(require(70) /* ../../styles/base.css */);
    const icons_css = tslib_1.__importStar(require(76) /* ../../styles/icons.css */);
    const buttons_css = tslib_1.__importStar(require(77) /* ../../styles/buttons.css */);
    const notifications_css = tslib_1.__importStar(require(78) /* ../../styles/notifications.css */);
    exports.notifications_el = (() => {
        const el = (0, dom_1.div)();
        const shadow_el = el.attachShadow({ mode: "open" });
        new dom_1.InlineStyleSheet(base_css.default).install(shadow_el);
        new dom_1.InlineStyleSheet(icons_css.default).install(shadow_el);
        new dom_1.InlineStyleSheet(buttons_css.default).install(shadow_el);
        new dom_1.InlineStyleSheet(notifications_css.default).install(shadow_el);
        const entries_el = (0, dom_1.div)({ class: "entries" });
        shadow_el.append(entries_el);
        void (0, dom_1.dom_ready)().then(() => document.body.append(el));
        return entries_el;
    })();
    class NotificationsView extends ui_element_1.UIElementView {
        _connection_el = null;
        _connection_timer = null;
        initialize() {
            super.initialize();
            this.model.push.connect((message) => {
                const dismiss_el = (0, dom_1.div)({ class: "close", title: "Close" });
                const message_el = (0, dom_1.div)({ class: message.type }, message.text, dismiss_el);
                exports.notifications_el.append(message_el);
                const clear = () => message_el.remove();
                dismiss_el.addEventListener("click", clear);
                const timeout = message.timeout ?? 5000;
                if (isFinite(timeout)) {
                    setTimeout(clear, timeout);
                }
            });
            const { document } = this.model;
            if (document == null) {
                return; // this shouldn't happen
            }
            document.on_event("connection_lost", (_, event) => {
                if (!document.config.notify_connection_status) {
                    return;
                }
                this._connection_el?.remove();
                if (this._connection_timer != null) {
                    clearTimeout(this._connection_timer);
                    this._connection_timer = null;
                }
                const { timeout } = event;
                if (timeout == null) {
                    const try_el = (0, dom_1.span)({ class: "try" }, "Try");
                    try_el.addEventListener("click", () => {
                        this._connection_el?.remove();
                        event.reconnect();
                    });
                    const dismiss_el = (0, dom_1.div)({ class: "close", title: "Close" });
                    dismiss_el.addEventListener("click", () => this._connection_el?.remove());
                    this._connection_el = (0, dom_1.div)({ class: "error" }, "Client connection was lost permanently. ", try_el, " to reconnect manually.", dismiss_el);
                    exports.notifications_el.append(this._connection_el);
                }
                else {
                    let current_timeout = timeout;
                    const timeout_el = (0, dom_1.span)();
                    const set_timeout = () => {
                        const timeout = Math.max(0, Math.round(current_timeout / 1000));
                        if (timeout == 0) {
                            timeout_el.textContent = "Reconnecting now.";
                        }
                        else {
                            timeout_el.textContent = `Reconnection will be attempted in ${timeout} s.`;
                        }
                    };
                    set_timeout();
                    this._connection_el = (0, dom_1.div)({ class: "error" }, "Client connection was lost. ", timeout_el);
                    exports.notifications_el.append(this._connection_el);
                    this._connection_timer = setInterval(() => { current_timeout -= 1000; set_timeout(); }, 1000);
                }
            });
            document.on_event("client_reconnected", (_, _event) => {
                if (!document.config.notify_connection_status) {
                    return;
                }
                this._connection_el?.remove();
                if (this._connection_timer != null) {
                    clearTimeout(this._connection_timer);
                    this._connection_timer = null;
                }
                this._connection_el = (0, dom_1.div)({ class: "success" }, "Client connect was reestablished.");
                exports.notifications_el.append(this._connection_el);
                this._connection_timer = setTimeout(() => this._connection_el?.remove(), 5000);
            });
        }
    }
    exports.NotificationsView = NotificationsView;
    class Notifications extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
        push = new signaling_1.Signal(this, "push");
        static {
            this.prototype.default_view = NotificationsView;
            this.define(() => ({}));
        }
    }
    exports.Notifications = Notifications;
},
/* models/ui/ui_element.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const styled_element_1 = require(56) /* ./styled_element */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const dom_1 = require(61) /* ../../core/dom */;
    const canvas_1 = require(71) /* ../../core/util/canvas */;
    const bbox_1 = require(62) /* ../../core/util/bbox */;
    const types_1 = require(8) /* ../../core/util/types */;
    const defer_1 = require(18) /* ../../core/util/defer */;
    const ui_css_1 = tslib_1.__importDefault(require(75) /* ../../styles/ui.css */);
    const { round, floor } = Math;
    class UIElementView extends styled_element_1.StyledElementView {
        display = new dom_1.InlineStyleSheet("", "display");
        computed_stylesheets() {
            return [...super.computed_stylesheets(), this.display];
        }
        stylesheets() {
            return [...super.stylesheets(), ui_css_1.default];
        }
        update_style() {
            this.style.clear();
        }
        box_sizing() {
            return {
                width_policy: "auto", height_policy: "auto",
                width: null, height: null,
                aspect_ratio: null,
            };
        }
        _bbox = new bbox_1.BBox();
        get bbox() {
            return this._bbox;
        }
        update_bbox() {
            return this._update_bbox();
        }
        _update_bbox() {
            const displayed = (() => {
                // Consider using Element.checkVisibility() in the future.
                // https://w3c.github.io/csswg-drafts/cssom-view-1/#dom-element-checkvisibility
                if (!this.el.isConnected) {
                    return false;
                }
                else if (this.el.offsetParent != null) {
                    return true;
                }
                else {
                    const { position, display } = getComputedStyle(this.el);
                    return position == "fixed" && display != "none";
                }
            })();
            const bbox = !displayed ? new bbox_1.BBox() : (() => {
                const self = this.el.getBoundingClientRect();
                const { left, top } = (() => {
                    if (this.parent != null) {
                        const parent = this.parent.el.getBoundingClientRect();
                        return {
                            left: self.left - parent.left,
                            top: self.top - parent.top,
                        };
                    }
                    else {
                        return { left: 0, top: 0 };
                    }
                })();
                return new bbox_1.BBox({
                    left: round(left),
                    top: round(top),
                    width: floor(self.width),
                    height: floor(self.height),
                });
            })();
            const changed = !this._bbox.equals(bbox);
            this._bbox = bbox;
            this._is_displayed = displayed;
            return changed;
        }
        _resize_observer;
        _context_menu = null;
        children_views() {
            return [...super.children_views(), this._context_menu];
        }
        /**
         * Allows to provide a context dependent menu when `UIElement.context_menu` is `"auto"`.
         */
        _provide_context_menu() {
            return null;
        }
        initialize() {
            super.initialize();
            this._resize_observer = new ResizeObserver((_entries) => this.after_resize());
            this._resize_observer.observe(this.el, { box: "border-box" });
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const menu = (() => {
                const { context_menu } = this.model;
                if (context_menu == "auto") {
                    return this._provide_context_menu();
                }
                else {
                    return context_menu;
                }
            })();
            if (menu != null) {
                this._context_menu = await (0, build_views_1.build_view)(menu, { parent: this });
            }
        }
        connect_signals() {
            super.connect_signals();
            const { visible } = this.model.properties;
            this.on_change(visible, () => this._update_visible());
            this.el.addEventListener("contextmenu", (event) => this.show_context_menu(event));
        }
        get_context_menu(_xy) {
            return this._context_menu;
        }
        show_context_menu(event) {
            if (!event.shiftKey) {
                const rect = this.el.getBoundingClientRect();
                const x = event.x - rect.x;
                const y = event.y - rect.y;
                const context_menu = this.get_context_menu({ x, y });
                if (context_menu != null) {
                    if (context_menu.show({ x, y })) {
                        event.stopPropagation();
                        event.preventDefault();
                    }
                }
            }
        }
        remove() {
            this._resize_observer.disconnect();
            super.remove();
        }
        _resized = false;
        _after_resize() { }
        after_resize() {
            this._resized = true;
            if (this.update_bbox()) {
                this._after_resize();
            }
            this.finish();
        }
        render() {
            super.render();
            this._apply_visible();
        }
        _after_render() {
            this.update_style();
            this.update_bbox();
        }
        after_render() {
            super.after_render();
            this._after_render();
            if (!this._has_finished) {
                // If not displayed, then after_resize() will not be called.
                if (!this.is_displayed) {
                    this.force_finished();
                }
                else {
                    // In case after_resize() wasn't called (see regression test for issue
                    // #9113), then wait one macro task and consider this view finished.
                    void (0, defer_1.defer)().then(() => {
                        if (!this._resized) {
                            this.finish();
                        }
                    });
                }
            }
        }
        _is_displayed = false;
        get is_displayed() {
            return this._is_displayed;
        }
        _apply_visible() {
            if (this.model.visible) {
                this.display.clear();
            }
            else {
                this.display.replace(":host { display: none; }");
            }
        }
        _update_visible() {
            this._apply_visible();
        }
        export(type = "auto", hidpi = true) {
            const output_backend = type == "auto" || type == "png" ? "canvas" : "svg";
            const canvas = new canvas_1.CanvasLayer(output_backend, hidpi);
            const { width, height } = this.bbox;
            canvas.resize(width, height);
            return canvas;
        }
        resolve_symbol(node) {
            const value = this.bbox.resolve(node.symbol);
            const { offset } = node;
            if ((0, types_1.isNumber)(value)) {
                return value + offset;
            }
            else {
                const { x, y } = value;
                return { x: x + offset, y: y + offset };
            }
        }
    }
    exports.UIElementView = UIElementView;
    class UIElement extends styled_element_1.StyledElement {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Bool, AnyRef, Nullable, Or, Auto }) => ({
                visible: [Bool, true],
                context_menu: [Nullable(Or(AnyRef(), Auto)), null],
            }));
        }
    }
    exports.UIElement = UIElement;
},
/* models/ui/styled_element.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    const node_1 = require(57) /* ../coordinates/node */;
    const styles_1 = require(59) /* ../dom/styles */;
    const stylesheets_1 = require(60) /* ../dom/stylesheets */;
    const dom_view_1 = require(64) /* ../../core/dom_view */;
    const css_1 = require(63) /* ../../core/css */;
    const dom_1 = require(61) /* ../../core/dom */;
    const object_1 = require(9) /* ../../core/util/object */;
    const types_1 = require(8) /* ../../core/util/types */;
    const kinds_1 = require(22) /* ../../core/kinds */;
    exports.StylesLike = (0, kinds_1.Or)((0, kinds_1.Dict)((0, kinds_1.Nullable)(kinds_1.Str)), (0, kinds_1.Ref)(styles_1.Styles)); // TODO: add validation for CSSStyles
    exports.StyleSheets = (0, kinds_1.List)((0, kinds_1.Or)((0, kinds_1.Ref)(stylesheets_1.StyleSheet), kinds_1.Str, (0, kinds_1.Dict)(exports.StylesLike)));
    exports.CSSVariables = (0, kinds_1.Dict)((0, kinds_1.Or)((0, kinds_1.Ref)(node_1.Node), kinds_1.Str));
    class StyledElementView extends dom_view_1.DOMComponentView {
        /**
         * Computed styles applied to self.
         */
        style = new dom_1.InlineStyleSheet("", "style"); // TODO rename to `self_style`
        /**
         * Computed styles append by the parent.
         */
        parent_style = new dom_1.InlineStyleSheet("", "parent", true);
        computed_stylesheets() {
            return [...super.computed_stylesheets(), this.style, this.parent_style];
        }
        connect_signals() {
            super.connect_signals();
            const { html_attributes, html_id, styles, css_classes, css_variables, stylesheets } = this.model.properties;
            this.on_change([html_attributes, html_id, css_classes, styles], () => this._apply_html_attributes());
            this.on_transitive_change(css_variables, () => this._apply_html_attributes());
            this.on_transitive_change(stylesheets, () => this._update_stylesheets());
        }
        *_css_classes() {
            yield* super._css_classes();
            yield* this.model.css_classes;
        }
        *_css_variables() {
            yield* super._css_variables();
            for (const [key, val] of (0, object_1.entries)(this.model.css_variables)) {
                if (val instanceof node_1.Node) {
                    const value = this.resolve_coordinate(val);
                    if ((0, types_1.isNumber)(value)) {
                        yield [key, `${value}px`];
                    }
                    else if ((0, types_1.isString)(value)) {
                        yield [key, value];
                    }
                }
                else {
                    yield [key, val];
                }
            }
        }
        user_stylesheets() {
            return [...super.user_stylesheets(), ...this._user_stylesheets()];
        }
        *_user_stylesheets() {
            for (const stylesheet of this.model.stylesheets) {
                if (stylesheet instanceof stylesheets_1.StyleSheet) {
                    yield stylesheet.underlying();
                }
                else {
                    yield new dom_1.InlineStyleSheet(stylesheet);
                }
            }
        }
        _apply_html_attributes() {
            for (const key of this._applied_html_attributes) {
                this.el.removeAttribute(key);
            }
            this._applied_html_attributes = [];
            this._update_css_classes();
            for (const [key, val] of (0, object_1.entries)(this.model.html_attributes)) {
                if (key == "class") {
                    const classes = val.split(/ +/);
                    this._applied_css_classes.push(...classes);
                    this.class_list.add(...classes);
                }
                else {
                    this.el.setAttribute(key, val);
                    this._applied_html_attributes.push(key);
                }
            }
            const id = this.model.html_id;
            if (id != null) {
                this.el.setAttribute("id", id);
                this._applied_html_attributes.push("id");
            }
            this._apply_styles();
            this._update_css_variables();
        }
        _apply_styles() {
            (0, css_1.apply_styles)(this.el.style, this.model.styles);
        }
    }
    exports.StyledElementView = StyledElementView;
    class StyledElement extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define({
                html_attributes: [(0, kinds_1.Dict)(kinds_1.Str), {}],
                html_id: [(0, kinds_1.Nullable)(kinds_1.Str), null],
                css_classes: [(0, kinds_1.List)(kinds_1.Str), []],
                css_variables: [exports.CSSVariables, {}],
                styles: [exports.StylesLike, {}],
                stylesheets: [exports.StyleSheets, []],
            });
        }
    }
    exports.StyledElement = StyledElement;
},
/* models/coordinates/node.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const coordinate_1 = require(58) /* ./coordinate */;
    const model_1 = require(52) /* ../../model */;
    const kinds_1 = require(22) /* ../../core/kinds */;
    exports.ImplicitTarget = (0, kinds_1.Enum)("canvas", "plot", "frame", "parent");
    exports.NodeTarget = (0, kinds_1.Or)((0, kinds_1.Ref)(model_1.Model), exports.ImplicitTarget);
    class BoxNodes {
        target;
        frozen;
        constructor(target, frozen = false) {
            this.target = target;
            this.frozen = frozen;
        }
        _node(symbol) {
            const { target, frozen } = this;
            const node = new Node({ target, symbol });
            if (frozen) {
                this[`_${symbol}`] = node;
            }
            return node;
        }
        _left = null;
        get left() {
            return this._left ?? this._node("left");
        }
        _right = null;
        get right() {
            return this._right ?? this._node("right");
        }
        _top = null;
        get top() {
            return this._top ?? this._node("top");
        }
        _bottom = null;
        get bottom() {
            return this._bottom ?? this._node("bottom");
        }
        freeze() {
            return new BoxNodes(this.target, true);
        }
    }
    exports.BoxNodes = BoxNodes;
    class Node extends coordinate_1.Coordinate {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Str, Int }) => ({
                target: [exports.NodeTarget],
                symbol: [Str],
                offset: [Int, 0],
            }));
        }
        static _frame_nodes = new BoxNodes("frame");
        static get frame() {
            return this._frame_nodes;
        }
        static _canvas_nodes = new BoxNodes("canvas");
        static get canvas() {
            return this._canvas_nodes;
        }
    }
    exports.Node = Node;
},
/* models/coordinates/coordinate.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    class Coordinate extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Coordinate = Coordinate;
},
/* models/dom/styles.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    class Styles extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Str, Nullable }) => ({
                align_content: [Nullable(Str), null],
                align_items: [Nullable(Str), null],
                align_self: [Nullable(Str), null],
                alignment_baseline: [Nullable(Str), null],
                all: [Nullable(Str), null],
                animation: [Nullable(Str), null],
                animation_delay: [Nullable(Str), null],
                animation_direction: [Nullable(Str), null],
                animation_duration: [Nullable(Str), null],
                animation_fill_mode: [Nullable(Str), null],
                animation_iteration_count: [Nullable(Str), null],
                animation_name: [Nullable(Str), null],
                animation_play_state: [Nullable(Str), null],
                animation_timing_function: [Nullable(Str), null],
                aspect_ratio: [Nullable(Str), null],
                backface_visibility: [Nullable(Str), null],
                background: [Nullable(Str), null],
                background_attachment: [Nullable(Str), null],
                background_clip: [Nullable(Str), null],
                background_color: [Nullable(Str), null],
                background_image: [Nullable(Str), null],
                background_origin: [Nullable(Str), null],
                background_position: [Nullable(Str), null],
                background_position_x: [Nullable(Str), null],
                background_position_y: [Nullable(Str), null],
                background_repeat: [Nullable(Str), null],
                background_size: [Nullable(Str), null],
                baseline_shift: [Nullable(Str), null],
                block_size: [Nullable(Str), null],
                border: [Nullable(Str), null],
                border_block_end: [Nullable(Str), null],
                border_block_end_color: [Nullable(Str), null],
                border_block_end_style: [Nullable(Str), null],
                border_block_end_width: [Nullable(Str), null],
                border_block_start: [Nullable(Str), null],
                border_block_start_color: [Nullable(Str), null],
                border_block_start_style: [Nullable(Str), null],
                border_block_start_width: [Nullable(Str), null],
                border_bottom: [Nullable(Str), null],
                border_bottom_color: [Nullable(Str), null],
                border_bottom_left_radius: [Nullable(Str), null],
                border_bottom_right_radius: [Nullable(Str), null],
                border_bottom_style: [Nullable(Str), null],
                border_bottom_width: [Nullable(Str), null],
                border_collapse: [Nullable(Str), null],
                border_color: [Nullable(Str), null],
                border_image: [Nullable(Str), null],
                border_image_outset: [Nullable(Str), null],
                border_image_repeat: [Nullable(Str), null],
                border_image_slice: [Nullable(Str), null],
                border_image_source: [Nullable(Str), null],
                border_image_width: [Nullable(Str), null],
                border_inline_end: [Nullable(Str), null],
                border_inline_end_color: [Nullable(Str), null],
                border_inline_end_style: [Nullable(Str), null],
                border_inline_end_width: [Nullable(Str), null],
                border_inline_start: [Nullable(Str), null],
                border_inline_start_color: [Nullable(Str), null],
                border_inline_start_style: [Nullable(Str), null],
                border_inline_start_width: [Nullable(Str), null],
                border_left: [Nullable(Str), null],
                border_left_color: [Nullable(Str), null],
                border_left_style: [Nullable(Str), null],
                border_left_width: [Nullable(Str), null],
                border_radius: [Nullable(Str), null],
                border_right: [Nullable(Str), null],
                border_right_color: [Nullable(Str), null],
                border_right_style: [Nullable(Str), null],
                border_right_width: [Nullable(Str), null],
                border_spacing: [Nullable(Str), null],
                border_style: [Nullable(Str), null],
                border_top: [Nullable(Str), null],
                border_top_color: [Nullable(Str), null],
                border_top_left_radius: [Nullable(Str), null],
                border_top_right_radius: [Nullable(Str), null],
                border_top_style: [Nullable(Str), null],
                border_top_width: [Nullable(Str), null],
                border_width: [Nullable(Str), null],
                bottom: [Nullable(Str), null],
                box_shadow: [Nullable(Str), null],
                box_sizing: [Nullable(Str), null],
                break_after: [Nullable(Str), null],
                break_before: [Nullable(Str), null],
                break_inside: [Nullable(Str), null],
                caption_side: [Nullable(Str), null],
                caret_color: [Nullable(Str), null],
                clear: [Nullable(Str), null],
                clip: [Nullable(Str), null],
                clip_path: [Nullable(Str), null],
                clip_rule: [Nullable(Str), null],
                color: [Nullable(Str), null],
                color_interpolation: [Nullable(Str), null],
                color_interpolation_filters: [Nullable(Str), null],
                column_count: [Nullable(Str), null],
                column_fill: [Nullable(Str), null],
                column_gap: [Nullable(Str), null],
                column_rule: [Nullable(Str), null],
                column_rule_color: [Nullable(Str), null],
                column_rule_style: [Nullable(Str), null],
                column_rule_width: [Nullable(Str), null],
                column_span: [Nullable(Str), null],
                column_width: [Nullable(Str), null],
                columns: [Nullable(Str), null],
                content: [Nullable(Str), null],
                counter_increment: [Nullable(Str), null],
                counter_reset: [Nullable(Str), null],
                cursor: [Nullable(Str), null],
                direction: [Nullable(Str), null],
                display: [Nullable(Str), null],
                dominant_baseline: [Nullable(Str), null],
                empty_cells: [Nullable(Str), null],
                fill: [Nullable(Str), null],
                fill_opacity: [Nullable(Str), null],
                fill_rule: [Nullable(Str), null],
                filter: [Nullable(Str), null],
                flex: [Nullable(Str), null],
                flex_basis: [Nullable(Str), null],
                flex_direction: [Nullable(Str), null],
                flex_flow: [Nullable(Str), null],
                flex_grow: [Nullable(Str), null],
                flex_shrink: [Nullable(Str), null],
                flex_wrap: [Nullable(Str), null],
                float: [Nullable(Str), null],
                flood_color: [Nullable(Str), null],
                flood_opacity: [Nullable(Str), null],
                font: [Nullable(Str), null],
                font_family: [Nullable(Str), null],
                font_feature_settings: [Nullable(Str), null],
                font_kerning: [Nullable(Str), null],
                font_size: [Nullable(Str), null],
                font_size_adjust: [Nullable(Str), null],
                font_stretch: [Nullable(Str), null],
                font_style: [Nullable(Str), null],
                font_synthesis: [Nullable(Str), null],
                font_variant: [Nullable(Str), null],
                font_variant_caps: [Nullable(Str), null],
                font_variant_east_asian: [Nullable(Str), null],
                font_variant_ligatures: [Nullable(Str), null],
                font_variant_numeric: [Nullable(Str), null],
                font_variant_position: [Nullable(Str), null],
                font_weight: [Nullable(Str), null],
                gap: [Nullable(Str), null],
                glyph_orientation_vertical: [Nullable(Str), null],
                grid: [Nullable(Str), null],
                grid_area: [Nullable(Str), null],
                grid_auto_columns: [Nullable(Str), null],
                grid_auto_flow: [Nullable(Str), null],
                grid_auto_rows: [Nullable(Str), null],
                grid_column: [Nullable(Str), null],
                grid_column_end: [Nullable(Str), null],
                grid_column_gap: [Nullable(Str), null],
                grid_column_start: [Nullable(Str), null],
                grid_gap: [Nullable(Str), null],
                grid_row: [Nullable(Str), null],
                grid_row_end: [Nullable(Str), null],
                grid_row_gap: [Nullable(Str), null],
                grid_row_start: [Nullable(Str), null],
                grid_template: [Nullable(Str), null],
                grid_template_areas: [Nullable(Str), null],
                grid_template_columns: [Nullable(Str), null],
                grid_template_rows: [Nullable(Str), null],
                height: [Nullable(Str), null],
                hyphens: [Nullable(Str), null],
                image_orientation: [Nullable(Str), null],
                image_rendering: [Nullable(Str), null],
                inline_size: [Nullable(Str), null],
                justify_content: [Nullable(Str), null],
                justify_items: [Nullable(Str), null],
                justify_self: [Nullable(Str), null],
                left: [Nullable(Str), null],
                letter_spacing: [Nullable(Str), null],
                lighting_color: [Nullable(Str), null],
                line_break: [Nullable(Str), null],
                line_height: [Nullable(Str), null],
                list_style: [Nullable(Str), null],
                list_style_image: [Nullable(Str), null],
                list_style_position: [Nullable(Str), null],
                list_style_type: [Nullable(Str), null],
                margin: [Nullable(Str), null],
                margin_block_end: [Nullable(Str), null],
                margin_block_start: [Nullable(Str), null],
                margin_bottom: [Nullable(Str), null],
                margin_inline_end: [Nullable(Str), null],
                margin_inline_start: [Nullable(Str), null],
                margin_left: [Nullable(Str), null],
                margin_right: [Nullable(Str), null],
                margin_top: [Nullable(Str), null],
                marker: [Nullable(Str), null],
                marker_end: [Nullable(Str), null],
                marker_mid: [Nullable(Str), null],
                marker_start: [Nullable(Str), null],
                mask: [Nullable(Str), null],
                mask_composite: [Nullable(Str), null],
                mask_image: [Nullable(Str), null],
                mask_position: [Nullable(Str), null],
                mask_repeat: [Nullable(Str), null],
                mask_size: [Nullable(Str), null],
                mask_type: [Nullable(Str), null],
                max_block_size: [Nullable(Str), null],
                max_height: [Nullable(Str), null],
                max_inline_size: [Nullable(Str), null],
                max_width: [Nullable(Str), null],
                min_block_size: [Nullable(Str), null],
                min_height: [Nullable(Str), null],
                min_inline_size: [Nullable(Str), null],
                min_width: [Nullable(Str), null],
                object_fit: [Nullable(Str), null],
                object_position: [Nullable(Str), null],
                opacity: [Nullable(Str), null],
                order: [Nullable(Str), null],
                orphans: [Nullable(Str), null],
                outline: [Nullable(Str), null],
                outline_color: [Nullable(Str), null],
                outline_offset: [Nullable(Str), null],
                outline_style: [Nullable(Str), null],
                outline_width: [Nullable(Str), null],
                overflow: [Nullable(Str), null],
                overflow_anchor: [Nullable(Str), null],
                overflow_wrap: [Nullable(Str), null],
                overflow_x: [Nullable(Str), null],
                overflow_y: [Nullable(Str), null],
                overscroll_behavior: [Nullable(Str), null],
                overscroll_behavior_block: [Nullable(Str), null],
                overscroll_behavior_inline: [Nullable(Str), null],
                overscroll_behavior_x: [Nullable(Str), null],
                overscroll_behavior_y: [Nullable(Str), null],
                padding: [Nullable(Str), null],
                padding_block_end: [Nullable(Str), null],
                padding_block_start: [Nullable(Str), null],
                padding_bottom: [Nullable(Str), null],
                padding_inline_end: [Nullable(Str), null],
                padding_inline_start: [Nullable(Str), null],
                padding_left: [Nullable(Str), null],
                padding_right: [Nullable(Str), null],
                padding_top: [Nullable(Str), null],
                page_break_after: [Nullable(Str), null],
                page_break_before: [Nullable(Str), null],
                page_break_inside: [Nullable(Str), null],
                paint_order: [Nullable(Str), null],
                perspective: [Nullable(Str), null],
                perspective_origin: [Nullable(Str), null],
                place_content: [Nullable(Str), null],
                place_items: [Nullable(Str), null],
                place_self: [Nullable(Str), null],
                pointer_events: [Nullable(Str), null],
                position: [Nullable(Str), null],
                quotes: [Nullable(Str), null],
                resize: [Nullable(Str), null],
                right: [Nullable(Str), null],
                rotate: [Nullable(Str), null],
                row_gap: [Nullable(Str), null],
                ruby_align: [Nullable(Str), null],
                ruby_position: [Nullable(Str), null],
                scale: [Nullable(Str), null],
                scroll_behavior: [Nullable(Str), null],
                shape_rendering: [Nullable(Str), null],
                stop_color: [Nullable(Str), null],
                stop_opacity: [Nullable(Str), null],
                stroke: [Nullable(Str), null],
                stroke_dasharray: [Nullable(Str), null],
                stroke_dashoffset: [Nullable(Str), null],
                stroke_linecap: [Nullable(Str), null],
                stroke_linejoin: [Nullable(Str), null],
                stroke_miterlimit: [Nullable(Str), null],
                stroke_opacity: [Nullable(Str), null],
                stroke_width: [Nullable(Str), null],
                tab_size: [Nullable(Str), null],
                table_layout: [Nullable(Str), null],
                text_align: [Nullable(Str), null],
                text_align_last: [Nullable(Str), null],
                text_anchor: [Nullable(Str), null],
                text_combine_upright: [Nullable(Str), null],
                text_decoration: [Nullable(Str), null],
                text_decoration_color: [Nullable(Str), null],
                text_decoration_line: [Nullable(Str), null],
                text_decoration_style: [Nullable(Str), null],
                text_emphasis: [Nullable(Str), null],
                text_emphasis_color: [Nullable(Str), null],
                text_emphasis_position: [Nullable(Str), null],
                text_emphasis_style: [Nullable(Str), null],
                text_indent: [Nullable(Str), null],
                text_justify: [Nullable(Str), null],
                text_orientation: [Nullable(Str), null],
                text_overflow: [Nullable(Str), null],
                text_rendering: [Nullable(Str), null],
                text_shadow: [Nullable(Str), null],
                text_transform: [Nullable(Str), null],
                text_underline_position: [Nullable(Str), null],
                top: [Nullable(Str), null],
                touch_action: [Nullable(Str), null],
                transform: [Nullable(Str), null],
                transform_box: [Nullable(Str), null],
                transform_origin: [Nullable(Str), null],
                transform_style: [Nullable(Str), null],
                transition: [Nullable(Str), null],
                transition_delay: [Nullable(Str), null],
                transition_duration: [Nullable(Str), null],
                transition_property: [Nullable(Str), null],
                transition_timing_function: [Nullable(Str), null],
                translate: [Nullable(Str), null],
                unicode_bidi: [Nullable(Str), null],
                user_select: [Nullable(Str), null],
                vertical_align: [Nullable(Str), null],
                visibility: [Nullable(Str), null],
                white_space: [Nullable(Str), null],
                widows: [Nullable(Str), null],
                width: [Nullable(Str), null],
                will_change: [Nullable(Str), null],
                word_break: [Nullable(Str), null],
                word_spacing: [Nullable(Str), null],
                word_wrap: [Nullable(Str), null],
                writing_mode: [Nullable(Str), null],
                z_index: [Nullable(Str), null],
            }));
        }
    }
    exports.Styles = Styles;
},
/* models/dom/stylesheets.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const model_1 = require(52) /* ../../model */;
    const dom = tslib_1.__importStar(require(61) /* ../../core/dom */);
    class StyleSheet extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.StyleSheet = StyleSheet;
    class InlineStyleSheet extends StyleSheet {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Str }) => ({
                css: [Str],
            }));
        }
        underlying() {
            return new dom.InlineStyleSheet(this.css);
        }
    }
    exports.InlineStyleSheet = InlineStyleSheet;
    class ImportedStyleSheet extends StyleSheet {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Str }) => ({
                url: [Str],
            }));
        }
        underlying() {
            return new dom.ImportedStyleSheet(this.url);
        }
    }
    exports.ImportedStyleSheet = ImportedStyleSheet;
    class GlobalInlineStyleSheet extends InlineStyleSheet {
        constructor(attrs) {
            super(attrs);
        }
        _underlying = null;
        underlying() {
            if (this._underlying == null) {
                this._underlying = new dom.GlobalInlineStyleSheet(this.css);
            }
            return this._underlying;
        }
    }
    exports.GlobalInlineStyleSheet = GlobalInlineStyleSheet;
    class GlobalImportedStyleSheet extends ImportedStyleSheet {
        constructor(attrs) {
            super(attrs);
        }
        _underlying = null;
        underlying() {
            if (this._underlying == null) {
                this._underlying = new dom.GlobalImportedStyleSheet(this.url);
            }
            return this._underlying;
        }
    }
    exports.GlobalImportedStyleSheet = GlobalImportedStyleSheet;
},
/* core/dom.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.textarea = exports.template = exports.td = exports.tbody = exports.table = exports.sup = exports.summary = exports.sub = exports.style = exports.strong = exports.span = exports.source = exports.small = exports.slot = exports.select = exports.section = exports.search = exports.script = exports.samp = exports.s = exports.ruby = exports.rt = exports.rp = exports.q = exports.progress = exports.pre = exports.picture = exports.p = exports.output = exports.option = exports.optgroup = exports.ol = exports.object = exports.noscript = exports.nav = exports.meter = exports.meta = exports.menu = exports.mark = exports.map = exports.main = exports.link = exports.li = exports.legend = exports.label = exports.kbd = exports.ins = exports.input = exports.img = exports.iframe = void 0;
    exports.supports_adopted_stylesheets = exports.GlobalImportedStyleSheet = exports.ImportedStyleSheet = exports.GlobalInlineStyleSheet = exports.InlineStyleSheet = exports.StyleSheet = exports.MouseButton = exports.ClassList = exports.wbr = exports.video = exports.ul = exports.u = exports.track = exports.tr = exports.title = exports.time = exports.thead = exports.th = exports.tfoot = void 0;
    exports.create_element = create_element;
    exports.createSVGElement = createSVGElement;
    exports.text = text;
    exports.nbsp = nbsp;
    exports.prepend = prepend;
    exports.empty = empty;
    exports.contains = contains;
    exports.display = display;
    exports.undisplay = undisplay;
    exports.show = show;
    exports.hide = hide;
    exports.offset_bbox = offset_bbox;
    exports.parent = parent;
    exports.extents = extents;
    exports.size = size;
    exports.scroll_size = scroll_size;
    exports.outer_size = outer_size;
    exports.content_size = content_size;
    exports.bounding_box = bounding_box;
    exports.box_size = box_size;
    exports.position = position;
    exports.classes = classes;
    exports.toggle_attribute = toggle_attribute;
    exports.dom_ready = dom_ready;
    exports.px = px;
    exports.has_focus = has_focus;
    const types_1 = require(8) /* ./util/types */;
    const object_1 = require(9) /* ./util/object */;
    const bbox_1 = require(62) /* ./util/bbox */;
    const css_1 = require(63) /* ./css */;
    const logging_1 = require(11) /* ./logging */;
    const _element = (tag) => {
        return (attrs = {}, ...children) => {
            const element = document.createElement(tag);
            if (!(0, types_1.isPlainObject)(attrs)) {
                children = [attrs, ...children];
                attrs = {};
            }
            else {
                attrs = { ...attrs };
            }
            if (attrs.class != null) {
                const classes = (() => {
                    if ((0, types_1.isString)(attrs.class)) {
                        return attrs.class.split(/\s+/);
                    }
                    else {
                        return attrs.class;
                    }
                })();
                for (const cls of classes) {
                    if (cls != null) {
                        element.classList.add(cls);
                    }
                }
                delete attrs.class;
            }
            if (attrs.style != null) {
                if ((0, types_1.isString)(attrs.style)) {
                    element.setAttribute("style", attrs.style);
                }
                else {
                    (0, css_1.apply_styles)(element.style, attrs.style);
                }
                delete attrs.style;
            }
            if (attrs.data != null) {
                for (const [key, data] of (0, object_1.entries)(attrs.data)) {
                    if (data != null) {
                        element.dataset[key] = data;
                    }
                }
                delete attrs.data;
            }
            for (const [attr, value] of (0, object_1.entries)(attrs)) {
                if (value == null) {
                    continue;
                }
                else if ((0, types_1.isBoolean)(value)) {
                    element.toggleAttribute(attr, value);
                }
                else if ((0, types_1.isNumber)(value)) {
                    element.setAttribute(attr, `${value}`);
                }
                else if ((0, types_1.isString)(value)) {
                    element.setAttribute(attr, value);
                }
                else {
                    logging_1.logger.warn(`unable to set attribute: ${attr} = ${value}`);
                }
            }
            function append(child) {
                if ((0, types_1.isString)(child)) {
                    element.append(document.createTextNode(child));
                }
                else if (child instanceof Node) {
                    element.append(child);
                }
                else if (child instanceof NodeList || child instanceof HTMLCollection) {
                    element.append(...child);
                }
                else if (child != null && child !== false) {
                    throw new Error(`expected a DOM element, string, false or null, got ${JSON.stringify(child)}`);
                }
            }
            for (const child of children) {
                if ((0, types_1.isArray)(child)) {
                    for (const _child of child) {
                        append(_child);
                    }
                }
                else {
                    append(child);
                }
            }
            return element;
        };
    };
    function create_element(tag, attrs, ...children) {
        return _element(tag)(attrs, ...children);
    }
    exports.a = _element("a");
    exports.abbr = _element("abbr");
    exports.address = _element("address");
    exports.area = _element("area");
    exports.article = _element("article");
    exports.aside = _element("aside");
    exports.audio = _element("audio");
    exports.b = _element("b");
    exports.base = _element("base");
    exports.bdi = _element("bdi");
    exports.bdo = _element("bdo");
    exports.blockquote = _element("blockquote");
    exports.body = _element("body");
    exports.br = _element("br");
    exports.button = _element("button");
    exports.canvas = _element("canvas");
    exports.caption = _element("caption");
    exports.cite = _element("cite");
    exports.code = _element("code");
    exports.col = _element("col");
    exports.colgroup = _element("colgroup");
    exports.data = _element("data");
    exports.datalist = _element("datalist");
    exports.dd = _element("dd");
    exports.del = _element("del");
    exports.details = _element("details");
    exports.dfn = _element("dfn");
    exports.dialog = _element("dialog");
    exports.div = _element("div");
    exports.dl = _element("dl");
    exports.dt = _element("dt");
    exports.em = _element("em");
    exports.embed = _element("embed");
    exports.fieldset = _element("fieldset");
    exports.figcaption = _element("figcaption");
    exports.figure = _element("figure");
    exports.footer = _element("footer");
    exports.form = _element("form");
    exports.h1 = _element("h1");
    exports.h2 = _element("h2");
    exports.h3 = _element("h3");
    exports.h4 = _element("h4");
    exports.h5 = _element("h5");
    exports.h6 = _element("h6");
    exports.head = _element("head");
    exports.header = _element("header");
    exports.hgroup = _element("hgroup");
    exports.hr = _element("hr");
    exports.html = _element("html");
    exports.i = _element("i");
    exports.iframe = _element("iframe");
    exports.img = _element("img");
    exports.input = _element("input");
    exports.ins = _element("ins");
    exports.kbd = _element("kbd");
    exports.label = _element("label");
    exports.legend = _element("legend");
    exports.li = _element("li");
    exports.link = _element("link");
    exports.main = _element("main");
    exports.map = _element("map");
    exports.mark = _element("mark");
    exports.menu = _element("menu");
    exports.meta = _element("meta");
    exports.meter = _element("meter");
    exports.nav = _element("nav");
    exports.noscript = _element("noscript");
    exports.object = _element("object");
    exports.ol = _element("ol");
    exports.optgroup = _element("optgroup");
    exports.option = _element("option");
    exports.output = _element("output");
    exports.p = _element("p");
    exports.picture = _element("picture");
    exports.pre = _element("pre");
    exports.progress = _element("progress");
    exports.q = _element("q");
    exports.rp = _element("rp");
    exports.rt = _element("rt");
    exports.ruby = _element("ruby");
    exports.s = _element("s");
    exports.samp = _element("samp");
    exports.script = _element("script");
    exports.search = _element("search");
    exports.section = _element("section");
    exports.select = _element("select");
    exports.slot = _element("slot");
    exports.small = _element("small");
    exports.source = _element("source");
    exports.span = _element("span");
    exports.strong = _element("strong");
    exports.style = _element("style");
    exports.sub = _element("sub");
    exports.summary = _element("summary");
    exports.sup = _element("sup");
    exports.table = _element("table");
    exports.tbody = _element("tbody");
    exports.td = _element("td");
    exports.template = _element("template");
    exports.textarea = _element("textarea");
    exports.tfoot = _element("tfoot");
    exports.th = _element("th");
    exports.thead = _element("thead");
    exports.time = _element("time");
    exports.title = _element("title");
    exports.tr = _element("tr");
    exports.track = _element("track");
    exports.u = _element("u");
    exports.ul = _element("ul");
    exports.video = _element("video");
    exports.wbr = _element("wbr");
    function createSVGElement(tag, attrs = null, ...children) {
        const element = document.createElementNS("http://www.w3.org/2000/svg", tag);
        for (const [attr, value] of (0, object_1.entries)(attrs ?? {})) {
            if (value == null || value === false) {
                continue;
            }
            element.setAttribute(attr, value);
        }
        function append(child) {
            if ((0, types_1.isString)(child)) {
                element.appendChild(document.createTextNode(child));
            }
            else if (child instanceof Node) {
                element.appendChild(child);
            }
            else if (child instanceof NodeList || child instanceof HTMLCollection) {
                for (const el of child) {
                    element.appendChild(el);
                }
            }
            else if (child != null && child !== false) {
                throw new Error(`expected a DOM element, string, false or null, got ${JSON.stringify(child)}`);
            }
        }
        for (const child of children) {
            if ((0, types_1.isArray)(child)) {
                for (const _child of child) {
                    append(_child);
                }
            }
            else {
                append(child);
            }
        }
        return element;
    }
    function text(str) {
        return document.createTextNode(str);
    }
    function nbsp() {
        return text("\u00a0");
    }
    function prepend(element, ...nodes) {
        const first = element.firstChild;
        for (const node of nodes) {
            element.insertBefore(node, first);
        }
    }
    function empty(node, attrs = false) {
        let child;
        while ((child = node.firstChild) != null) {
            node.removeChild(child);
        }
        if (attrs && node instanceof Element) {
            for (const attr of node.attributes) {
                node.removeAttributeNode(attr);
            }
        }
    }
    function contains(element, child) {
        /**
         * Like Node.contains(), but traverses Shadow DOM boundaries.
         */
        let current = child;
        while (current.parentNode != null) {
            const parent = current.parentNode;
            if (parent == element) {
                return true;
            }
            else if (parent instanceof ShadowRoot) {
                current = parent.host;
            }
            else {
                current = parent;
            }
        }
        return false;
    }
    function display(element, display = true) {
        element.style.display = display ? "" : "none";
    }
    function undisplay(element) {
        element.style.display = "none";
    }
    function show(element) {
        element.style.visibility = "";
    }
    function hide(element) {
        element.style.visibility = "hidden";
    }
    function offset_bbox(element) {
        const { top, left, width, height } = element.getBoundingClientRect();
        return new bbox_1.BBox({
            left: left + scrollX - document.documentElement.clientLeft,
            top: top + scrollY - document.documentElement.clientTop,
            width,
            height,
        });
    }
    function parent(el, selector) {
        let node = el;
        while ((node = node.parentElement) != null) {
            if (node.matches(selector)) {
                return node;
            }
        }
        return null;
    }
    function num(value) {
        const num = parseFloat(value);
        return isFinite(num) ? num : 0;
    }
    function extents(el) {
        const style = getComputedStyle(el);
        return {
            border: {
                top: num(style.borderTopWidth),
                bottom: num(style.borderBottomWidth),
                left: num(style.borderLeftWidth),
                right: num(style.borderRightWidth),
            },
            margin: {
                top: num(style.marginTop),
                bottom: num(style.marginBottom),
                left: num(style.marginLeft),
                right: num(style.marginRight),
            },
            padding: {
                top: num(style.paddingTop),
                bottom: num(style.paddingBottom),
                left: num(style.paddingLeft),
                right: num(style.paddingRight),
            },
        };
    }
    function size(el) {
        const rect = el.getBoundingClientRect();
        return {
            width: Math.ceil(rect.width),
            height: Math.ceil(rect.height),
        };
    }
    function scroll_size(el) {
        return {
            width: Math.ceil(el.scrollWidth),
            height: Math.ceil(el.scrollHeight),
        };
    }
    function outer_size(el) {
        const { margin: { left, right, top, bottom } } = extents(el);
        const { width, height } = size(el);
        return {
            width: Math.ceil(width + left + right),
            height: Math.ceil(height + top + bottom),
        };
    }
    function content_size(el) {
        const { left, top } = el.getBoundingClientRect();
        const { padding } = extents(el);
        let width = 0;
        let height = 0;
        for (const child of (el.shadowRoot ?? el).children) {
            const rect = child.getBoundingClientRect();
            width = Math.max(width, Math.ceil(rect.left - left - padding.left + rect.width));
            height = Math.max(height, Math.ceil(rect.top - top - padding.top + rect.height));
        }
        return { width, height };
    }
    function bounding_box(el) {
        const { x, y, width, height } = el.getBoundingClientRect();
        return new bbox_1.BBox({ x, y, width, height });
    }
    function box_size(el) {
        const { width, height } = el.getBoundingClientRect();
        return { width, height };
    }
    function position(el, box, margin) {
        const { style } = el;
        style.left = `${box.x}px`;
        style.top = `${box.y}px`;
        style.width = `${box.width}px`;
        style.height = `${box.height}px`;
        if (margin == null) {
            style.margin = "";
        }
        else {
            const { top, right, bottom, left } = margin;
            style.margin = `${top}px ${right}px ${bottom}px ${left}px`;
        }
    }
    class ClassList {
        class_list;
        constructor(class_list) {
            this.class_list = class_list;
        }
        get values() {
            const values = [];
            for (let i = 0; i < this.class_list.length; i++) {
                const item = this.class_list.item(i);
                if (item != null) {
                    values.push(item);
                }
            }
            return values;
        }
        has(cls) {
            return this.class_list.contains(cls);
        }
        add(...classes) {
            for (const cls of classes) {
                this.class_list.add(cls);
            }
            return this;
        }
        remove(...classes) {
            for (const cls of classes) {
                if ((0, types_1.isArray)(cls)) {
                    cls.forEach((cls) => this.class_list.remove(cls));
                }
                else {
                    this.class_list.remove(cls);
                }
            }
            return this;
        }
        clear() {
            for (const cls of this.values) {
                this.class_list.remove(cls);
            }
            return this;
        }
        toggle(cls, activate) {
            return this.class_list.toggle(cls, activate);
        }
    }
    exports.ClassList = ClassList;
    function classes(el) {
        return new ClassList(el.classList);
    }
    function toggle_attribute(el, attr, state) {
        if (state == null) {
            state = !el.hasAttribute(attr);
        }
        if (state) {
            el.setAttribute(attr, "true");
        }
        else {
            el.removeAttribute(attr);
        }
    }
    (function (MouseButton) {
        MouseButton[MouseButton["None"] = 0] = "None";
        MouseButton[MouseButton["Primary"] = 1] = "Primary";
        MouseButton[MouseButton["Secondary"] = 2] = "Secondary";
        MouseButton[MouseButton["Auxiliary"] = 4] = "Auxiliary";
        MouseButton[MouseButton["Left"] = 1] = "Left";
        MouseButton[MouseButton["Right"] = 2] = "Right";
        MouseButton[MouseButton["Middle"] = 4] = "Middle";
    })(exports.MouseButton || (exports.MouseButton = {}));
    class StyleSheet {
        el;
        install(el) {
            el.append(this.el);
        }
        uninstall() {
            this.el.remove();
        }
    }
    exports.StyleSheet = StyleSheet;
    class InlineStyleSheet extends StyleSheet {
        persistent;
        el = (0, exports.style)();
        constructor(css, id, persistent = false) {
            super();
            this.persistent = persistent;
            if ((0, types_1.isString)(css)) {
                this._update(css);
            }
            else if (css != null) {
                this._update((0, css_1.compose_stylesheet)(css));
            }
            if (id != null) {
                this.el.dataset.css = id;
            }
        }
        get css() {
            return this.el.textContent;
        }
        _update(css) {
            this.el.textContent = css;
        }
        clear() {
            this.replace("");
        }
        _to_css(css, styles) {
            if (styles == null) {
                return css;
            }
            else {
                return (0, css_1.compose_stylesheet)({ [css]: styles });
            }
        }
        replace(css, styles) {
            this._update(this._to_css(css, styles));
        }
        prepend(css, styles) {
            this._update(`${this._to_css(css, styles)}\n${this.css}`);
        }
        append(css, styles) {
            this._update(`${this.css}\n${this._to_css(css, styles)}`);
        }
        remove() {
            this.el.remove();
        }
    }
    exports.InlineStyleSheet = InlineStyleSheet;
    class GlobalInlineStyleSheet extends InlineStyleSheet {
        install() {
            if (!this.el.isConnected) {
                document.head.appendChild(this.el);
            }
        }
    }
    exports.GlobalInlineStyleSheet = GlobalInlineStyleSheet;
    class ImportedStyleSheet extends StyleSheet {
        el;
        constructor(url) {
            super();
            this.el = (0, exports.link)({ rel: "stylesheet", href: url });
        }
        replace(url) {
            this.el.href = url;
        }
        remove() {
            this.el.remove();
        }
    }
    exports.ImportedStyleSheet = ImportedStyleSheet;
    class GlobalImportedStyleSheet extends ImportedStyleSheet {
        install() {
            if (!this.el.isConnected) {
                document.head.appendChild(this.el);
            }
        }
    }
    exports.GlobalImportedStyleSheet = GlobalImportedStyleSheet;
    async function dom_ready() {
        if (document.readyState == "loading") {
            return new Promise((resolve, _reject) => {
                document.addEventListener("DOMContentLoaded", () => resolve(), { once: true });
            });
        }
    }
    function px(value) {
        return (0, types_1.isNumber)(value) ? `${value}px` : value;
    }
    exports.supports_adopted_stylesheets = "adoptedStyleSheets" in ShadowRoot.prototype;
    function has_focus(el) {
        const root = el.getRootNode();
        if (root instanceof ShadowRoot || root instanceof Document) {
            return root.activeElement === el;
        }
        else {
            return false;
        }
    }
},
/* core/util/bbox.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.empty = empty;
    exports.full = full;
    exports.x_range = x_range;
    exports.y_range = y_range;
    exports.positive_x = positive_x;
    exports.negative_x = negative_x;
    exports.positive_y = positive_y;
    exports.negative_y = negative_y;
    exports.union = union;
    exports.isXY = isXY;
    const types_1 = require(25) /* ../types */;
    const eq_1 = require(27) /* ./eq */;
    const arrayable_1 = require(14) /* ./arrayable */;
    const types_2 = require(8) /* ./types */;
    const { min, max, round } = Math;
    function empty() {
        return {
            x0: Infinity,
            y0: Infinity,
            x1: -Infinity,
            y1: -Infinity,
        };
    }
    function full() {
        return {
            x0: -Infinity,
            y0: -Infinity,
            x1: Infinity,
            y1: Infinity,
        };
    }
    function x_range(x0, x1) {
        return {
            x0,
            y0: -Infinity,
            x1,
            y1: Infinity,
        };
    }
    function y_range(y0, y1) {
        return {
            x0: -Infinity,
            y0,
            x1: Infinity,
            y1,
        };
    }
    function positive_x() {
        return x_range(Number.MIN_VALUE, Infinity);
    }
    function negative_x() {
        return x_range(-Infinity, -Number.MIN_VALUE);
    }
    function positive_y() {
        return y_range(Number.MIN_VALUE, Infinity);
    }
    function negative_y() {
        return y_range(-Infinity, -Number.MIN_VALUE);
    }
    function _min(a, b) {
        if (isNaN(a)) {
            return b;
        }
        else if (isNaN(b)) {
            return a;
        }
        else {
            return min(a, b);
        }
    }
    function _max(a, b) {
        if (isNaN(a)) {
            return b;
        }
        else if (isNaN(b)) {
            return a;
        }
        else {
            return max(a, b);
        }
    }
    function union(a, b) {
        return {
            x0: _min(a.x0, b.x0),
            x1: _max(a.x1, b.x1),
            y0: _min(a.y0, b.y0),
            y1: _max(a.y1, b.y1),
        };
    }
    function isXY(obj) {
        return (0, types_2.isPlainObject)(obj) && "x" in obj && "y" in obj;
    }
    class BBox {
        x0;
        y0;
        x1;
        y1;
        constructor(box, correct = false) {
            if (box == null) {
                this.x0 = 0;
                this.y0 = 0;
                this.x1 = 0;
                this.y1 = 0;
            }
            else if ("x0" in box) {
                const { x0, y0, x1, y1 } = box;
                if (!isFinite(x0 + y0 + x1 + y1)) {
                    this.x0 = NaN;
                    this.y0 = NaN;
                    this.x1 = NaN;
                    this.y1 = NaN;
                }
                else {
                    if (!(x0 <= x1 && y0 <= y1)) {
                        throw new Error(`invalid bbox {x0: ${x0}, y0: ${y0}, x1: ${x1}, y1: ${y1}}`);
                    }
                    this.x0 = x0;
                    this.y0 = y0;
                    this.x1 = x1;
                    this.y1 = y1;
                }
            }
            else if ("x" in box) {
                const { x, y, width, height, origin = "top_left" } = box;
                if (!(width >= 0 && height >= 0)) {
                    throw new Error(`invalid bbox {x: ${x}, y: ${y}, width: ${width}, height: ${height}}`);
                }
                const base_origin = (() => {
                    switch (origin) {
                        case "left": return "center_left";
                        case "right": return "center_right";
                        case "top": return "top_center";
                        case "bottom": return "bottom_center";
                        case "center": return "center_center";
                        default: return origin;
                    }
                })();
                const [y_align, x_align] = base_origin.split("_", 2);
                const y_coeff = (() => {
                    switch (y_align) {
                        case "top": return 0.0;
                        case "center": return 0.5;
                        case "bottom": return 1.0;
                    }
                })();
                const x_coeff = (() => {
                    switch (x_align) {
                        case "left": return 0.0;
                        case "center": return 0.5;
                        case "right": return 1.0;
                    }
                })();
                const d_width = x_coeff * width;
                const d_height = y_coeff * height;
                const x0 = x - d_width;
                const y0 = y - d_height;
                const x1 = x0 + width;
                const y1 = y0 + height;
                this.x0 = x0;
                this.y0 = y0;
                this.x1 = x1;
                this.y1 = y1;
            }
            else {
                let left, right;
                let top, bottom;
                if ("width" in box) {
                    if ("left" in box) {
                        left = box.left;
                        right = left + box.width;
                    }
                    else if ("right" in box) {
                        right = box.right;
                        left = right - box.width;
                    }
                    else {
                        const w2 = box.width / 2;
                        left = box.hcenter - w2;
                        right = box.hcenter + w2;
                    }
                }
                else {
                    left = box.left;
                    right = box.right;
                }
                if ("height" in box) {
                    if ("top" in box) {
                        top = box.top;
                        bottom = top + box.height;
                    }
                    else if ("bottom" in box) {
                        bottom = box.bottom;
                        top = bottom - box.height;
                    }
                    else {
                        const h2 = box.height / 2;
                        top = box.vcenter - h2;
                        bottom = box.vcenter + h2;
                    }
                }
                else {
                    top = box.top;
                    bottom = box.bottom;
                }
                if (left > right || top > bottom) {
                    if (correct) {
                        if (left > right) {
                            left = right;
                        }
                        if (top > bottom) {
                            top = bottom;
                        }
                    }
                    else {
                        throw new Error(`invalid bbox {left: ${left}, top: ${top}, right: ${right}, bottom: ${bottom}}`);
                    }
                }
                this.x0 = left;
                this.y0 = top;
                this.x1 = right;
                this.y1 = bottom;
            }
        }
        static from_lrtb({ left, right, top, bottom }) {
            return new BBox({
                x0: min(left, right),
                y0: min(top, bottom),
                x1: max(left, right),
                y1: max(top, bottom),
            });
        }
        static from_rect({ x0, y0, x1, y1 }) {
            return new BBox({
                x0: min(x0, x1),
                y0: min(y0, y1),
                x1: max(x0, x1),
                y1: max(y0, y1),
            });
        }
        static empty() {
            return new BBox({ x0: 0, y0: 0, x1: 0, y1: 0 });
        }
        static invalid() {
            return new BBox({ x0: NaN, y0: NaN, x1: NaN, y1: NaN });
        }
        clone() {
            return new BBox(this);
        }
        equals(that) {
            return this.x0 == that.x0 && this.y0 == that.y0 &&
                this.x1 == that.x1 && this.y1 == that.y1;
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.x0, that.x0) && cmp.eq(this.y0, that.y0) &&
                cmp.eq(this.x1, that.x1) && cmp.eq(this.y1, that.y1);
        }
        toString() {
            return `BBox({left: ${this.left}, top: ${this.top}, width: ${this.width}, height: ${this.height}})`;
        }
        get is_valid() {
            const { x0, x1, y0, y1 } = this;
            return isFinite(x0 + x1 + y0 + y1);
        }
        get is_empty() {
            const { x0, x1, y0, y1 } = this;
            return x0 == 0 && x1 == 0 && y0 == 0 && y1 == 0;
        }
        get left() {
            return this.x0;
        }
        get top() {
            return this.y0;
        }
        get right() {
            return this.x1;
        }
        get bottom() {
            return this.y1;
        }
        get p0() {
            return { x: this.x0, y: this.y0 };
        }
        get p1() {
            return { x: this.x1, y: this.y1 };
        }
        get x() {
            return this.x0;
        }
        get y() {
            return this.y0;
        }
        get width() {
            return this.x1 - this.x0;
        }
        get height() {
            return this.y1 - this.y0;
        }
        get size() {
            return { width: this.width, height: this.height };
        }
        get rect() {
            const { x0, y0, x1, y1 } = this;
            return {
                p0: { x: x0, y: y0 },
                p1: { x: x1, y: y0 },
                p2: { x: x1, y: y1 },
                p3: { x: x0, y: y1 },
            };
        }
        get box() {
            const { x, y, width, height } = this;
            return { x, y, width, height };
        }
        get lrtb() {
            const { left, right, top, bottom } = this;
            return { left, right, top, bottom };
        }
        get args() {
            const { x, y, width, height } = this;
            return [x, y, width, height];
        }
        get x_range() {
            return { start: this.x0, end: this.x1 };
        }
        get y_range() {
            return { start: this.y0, end: this.y1 };
        }
        get h_range() {
            return this.x_range;
        }
        get v_range() {
            return this.y_range;
        }
        get ranges() {
            return [this.x_range, this.y_range];
        }
        get aspect() {
            return this.width / this.height;
        }
        get x_center() {
            return (this.left + this.right) / 2;
        }
        get y_center() {
            return (this.top + this.bottom) / 2;
        }
        get hcenter() {
            return this.x_center;
        }
        get vcenter() {
            return this.y_center;
        }
        get area() {
            return this.width * this.height;
        }
        resolve(symbol) {
            switch (symbol) {
                case "top_left": return this.top_left;
                case "top_center": return this.top_center;
                case "top_right": return this.top_right;
                case "center_left": return this.center_left;
                case "center_center": return this.center_center;
                case "center_right": return this.center_right;
                case "bottom_left": return this.bottom_left;
                case "bottom_center": return this.bottom_center;
                case "bottom_right": return this.bottom_right;
                case "center": return this.center;
                case "top": return this.top;
                case "left": return this.left;
                case "right": return this.right;
                case "bottom": return this.bottom;
                case "width": return this.width;
                case "height": return this.height;
                default: return { x: NaN, y: NaN };
            }
        }
        get top_left() {
            return { x: this.left, y: this.top };
        }
        get top_center() {
            return { x: this.hcenter, y: this.top };
        }
        get top_right() {
            return { x: this.right, y: this.top };
        }
        get center_left() {
            return { x: this.left, y: this.vcenter };
        }
        get center_center() {
            return { x: this.hcenter, y: this.vcenter };
        }
        get center_right() {
            return { x: this.right, y: this.vcenter };
        }
        get bottom_left() {
            return { x: this.left, y: this.bottom };
        }
        get bottom_center() {
            return { x: this.hcenter, y: this.bottom };
        }
        get bottom_right() {
            return { x: this.right, y: this.bottom };
        }
        get center() {
            return { x: this.hcenter, y: this.vcenter };
        }
        round() {
            return new BBox({
                x0: round(this.x0),
                x1: round(this.x1),
                y0: round(this.y0),
                y1: round(this.y1),
            });
        }
        relative() {
            const { width, height } = this;
            return new BBox({ x: 0, y: 0, width, height });
        }
        relative_to(to) {
            const { x, y, width, height } = this;
            return new BBox({ x: x - to.x, y: y - to.y, width, height });
        }
        translate(tx, ty) {
            const { x, y, width, height } = this;
            return new BBox({ x: tx + x, y: ty + y, width, height });
        }
        scale(factor) {
            return new BBox({
                x0: this.x0 * factor,
                x1: this.x1 * factor,
                y0: this.y0 * factor,
                y1: this.y1 * factor,
            });
        }
        relativize(x, y) {
            return [x - this.x, y - this.y];
        }
        contains(x, y) {
            return this.x0 <= x && x <= this.x1 && this.y0 <= y && y <= this.y1;
        }
        clip(x, y) {
            if (x < this.x0) {
                x = this.x0;
            }
            else if (x > this.x1) {
                x = this.x1;
            }
            if (y < this.y0) {
                y = this.y0;
            }
            else if (y > this.y1) {
                y = this.y1;
            }
            return [x, y];
        }
        grow_by(size) {
            return new BBox({
                left: this.left - size,
                right: this.right + size,
                top: this.top - size,
                bottom: this.bottom + size,
            });
        }
        shrink_by(size) {
            return new BBox({
                left: this.left + size,
                right: this.right - size,
                top: this.top + size,
                bottom: this.bottom - size,
            }, true);
        }
        union(that) {
            return new BBox({
                x0: min(this.x0, that.x0),
                y0: min(this.y0, that.y0),
                x1: max(this.x1, that.x1),
                y1: max(this.y1, that.y1),
            });
        }
        intersection(that) {
            if (!this.intersects(that)) {
                return null;
            }
            else {
                return new BBox({
                    x0: max(this.x0, that.x0),
                    y0: max(this.y0, that.y0),
                    x1: min(this.x1, that.x1),
                    y1: min(this.y1, that.y1),
                });
            }
        }
        intersects(that) {
            return !(that.x1 < this.x0 || that.x0 > this.x1 ||
                that.y1 < this.y0 || that.y0 > this.y1);
        }
        _x_percent;
        get x_percent() {
            const self = this;
            return this._x_percent ?? (this._x_percent = {
                compute(x) {
                    return self.left + x * self.width;
                },
                invert(sx) {
                    return (sx - self.left) / self.width;
                },
                v_compute(xs) {
                    const { left, width } = self;
                    return new types_1.ScreenArray((0, arrayable_1.map)(xs, (x) => left + x * width));
                },
                v_invert(sxs) {
                    const { left, width } = self;
                    return (0, arrayable_1.map)(sxs, (sx) => (sx - left) / width);
                },
                get source_range() {
                    return self.x_range;
                },
                get target_range() {
                    return self.x_range;
                },
            });
        }
        _y_percent;
        get y_percent() {
            const self = this;
            return this._y_percent ?? (this._y_percent = {
                compute(y) {
                    return self.top + y * self.height;
                },
                invert(sy) {
                    return (sy - self.top) / self.height;
                },
                v_compute(ys) {
                    const { top, height } = self;
                    return new types_1.ScreenArray((0, arrayable_1.map)(ys, (y) => top + y * height));
                },
                v_invert(sys) {
                    const { top, height } = self;
                    return (0, arrayable_1.map)(sys, (sy) => (sy - top) / height);
                },
                get source_range() {
                    return self.y_range;
                },
                get target_range() {
                    return self.y_range;
                },
            });
        }
        _x_screen;
        get x_screen() {
            const self = this;
            return this._x_screen ?? (this._x_screen = {
                compute(x) {
                    return self.left + x;
                },
                invert(sx) {
                    return sx - self.left;
                },
                v_compute(xs) {
                    const { left } = self;
                    return new types_1.ScreenArray((0, arrayable_1.map)(xs, (x) => left + x));
                },
                v_invert(sxs) {
                    const { left } = self;
                    return (0, arrayable_1.map)(sxs, (sx) => sx - left);
                },
                get source_range() {
                    return self.x_range;
                },
                get target_range() {
                    return self.x_range;
                },
            });
        }
        _y_screen;
        get y_screen() {
            const self = this;
            return this._y_screen ?? (this._y_screen = {
                compute(y) {
                    return self.top + y;
                },
                invert(sy) {
                    return sy - self.top;
                },
                v_compute(ys) {
                    const { top } = self;
                    return new types_1.ScreenArray((0, arrayable_1.map)(ys, (y) => top + y));
                },
                v_invert(sys) {
                    const { top } = self;
                    return (0, arrayable_1.map)(sys, (sy) => sy - top);
                },
                get source_range() {
                    return self.y_range;
                },
                get target_range() {
                    return self.y_range;
                },
            });
        }
        _x_view;
        get x_view() {
            const self = this;
            return this._x_view ?? (this._x_view = {
                compute(x) {
                    return self.left + x;
                },
                invert(sx) {
                    return sx - self.left;
                },
                v_compute(xs) {
                    const { left } = self;
                    return new types_1.ScreenArray((0, arrayable_1.map)(xs, (x) => left + x));
                },
                v_invert(sxs) {
                    const { left } = self;
                    return (0, arrayable_1.map)(sxs, (sx) => sx - left);
                },
                get source_range() {
                    return self.x_range;
                },
                get target_range() {
                    return self.x_range;
                },
            });
        }
        _y_view;
        get y_view() {
            const self = this;
            return this._y_view ?? (this._y_view = {
                compute(y) {
                    return self.bottom - y;
                },
                invert(sy) {
                    return self.bottom - sy;
                },
                v_compute(ys) {
                    const { bottom } = self;
                    return new types_1.ScreenArray((0, arrayable_1.map)(ys, (y) => bottom - y));
                },
                v_invert(sys) {
                    const { bottom } = self;
                    return (0, arrayable_1.map)(sys, (sy) => bottom - sy);
                },
                get source_range() {
                    return self.y_range;
                },
                get target_range() {
                    return { start: self.bottom, end: self.top };
                },
            });
        }
        get xview() {
            return this.x_view;
        }
        get yview() {
            return this.y_view;
        }
    }
    exports.BBox = BBox;
},
/* core/css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.apply_styles = apply_styles;
    exports.compose_stylesheet = compose_stylesheet;
    const logging_1 = require(11) /* ./logging */;
    const object_1 = require(9) /* ./util/object */;
    const types_1 = require(8) /* ./util/types */;
    const _style_decl = document.createElement("div").style;
    function _css_name(attr) {
        if (attr.startsWith("--")) {
            return attr;
        }
        const name = attr.replaceAll(/_/g, "-").replaceAll(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
        // XXX hasOwnProperty() doesn't work for unknown reasons (e.g. in Firefox)
        if (name in _style_decl) {
            return name;
        }
        const webkit_name = `-webkit-${name}`;
        if (webkit_name in _style_decl) {
            return webkit_name;
        }
        const moz_name = `-moz-${name}`;
        if (moz_name in _style_decl) {
            return moz_name;
        }
        logging_1.logger.warn(`unknown CSS property '${attr}'`);
        return null;
    }
    function* _iter_styles(styles) {
        if ((0, types_1.isPlainObject)(styles) || styles instanceof Map) {
            for (const [key, val] of (0, object_1.entries)(styles)) {
                const name = _css_name(key);
                if (name != null) {
                    yield [name, val];
                }
            }
        }
        else {
            for (const prop of styles.own_properties()) {
                if (prop.dirty) {
                    const name = _css_name(prop.attr);
                    if (name != null) {
                        yield [name, prop.get_value()];
                    }
                }
            }
        }
    }
    function apply_styles(declaration, styles) {
        for (const [name, value] of _iter_styles(styles)) {
            if ((0, types_1.isString)(value)) {
                declaration.setProperty(name, value);
            }
            else {
                declaration.removeProperty(name);
            }
        }
    }
    function compose_stylesheet(stylesheet) {
        const css = [];
        for (const [selector, styles] of (0, object_1.entries)(stylesheet)) {
            css.push(`${selector} {`);
            for (const [name, value] of _iter_styles(styles)) {
                if ((0, types_1.isString)(value) && value.length != 0) {
                    css.push(`  ${name}: ${value};`);
                }
            }
            css.push("}");
        }
        return css.join("\n");
    }
},
/* core/dom_view.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const view_1 = require(65) /* ./view */;
    const dom_1 = require(61) /* ./dom */;
    const types_1 = require(8) /* ./util/types */;
    const assert_1 = require(13) /* ./util/assert */;
    const base_css_1 = tslib_1.__importDefault(require(70) /* ../styles/base.css */);
    class DOMView extends view_1.View {
        static tag_name = "div";
        static aria_role;
        el;
        shadow_el;
        get bbox() {
            return undefined;
        }
        serializable_state() {
            const state = super.serializable_state();
            const { bbox } = this;
            return bbox != null ? { ...state, bbox: bbox.round() } : state;
        }
        get children_el() {
            return this.shadow_el ?? this.el;
        }
        initialize() {
            super.initialize();
            this.el = this._create_element();
        }
        remove() {
            this.el.remove();
            super.remove();
        }
        stylesheets() {
            return [];
        }
        css_classes() {
            return [];
        }
        rerender() {
            this.render();
            this.r_after_render();
        }
        render_to(target) {
            this.render();
            target.appendChild(this.el);
        }
        after_render() {
            this.reposition();
        }
        r_after_render() {
            for (const child_view of this.children()) {
                if (child_view instanceof DOMView) {
                    child_view.r_after_render();
                }
            }
            this.after_render();
            this._was_built = true;
        }
        _create_element() {
            return (0, dom_1.create_element)(this.constructor.tag_name, { role: this.constructor.aria_role });
        }
        reposition(_displayed) { }
        _was_built = false;
        /**
         * Build a top-level DOM view (e.g. during embedding).
         */
        build(target) {
            (0, assert_1.assert)(this.is_root);
            this.render_to(target);
            this.r_after_render();
            this.notify_finished();
        }
        /**
         * Define where to render this element or let the parent decide.
         *
         * This is useful when creating "floating" components or adding
         * components to canvas' layers.
         */
        rendering_target() {
            return null;
        }
    }
    exports.DOMView = DOMView;
    class DOMElementView extends DOMView {
        class_list;
        initialize() {
            super.initialize();
            this.class_list = new dom_1.ClassList(this.el.classList);
        }
        get self_target() {
            return this.el;
        }
    }
    exports.DOMElementView = DOMElementView;
    class DOMComponentView extends DOMElementView {
        get self_target() {
            return this.shadow_el;
        }
        initialize() {
            super.initialize();
            this.shadow_el = this.el.attachShadow({ mode: "open" });
        }
        _base_style = new dom_1.InlineStyleSheet(base_css_1.default, "base");
        _css_vars = new dom_1.InlineStyleSheet("", "vars");
        stylesheets() {
            return [...super.stylesheets(), this._base_style];
        }
        /**
         * Baseline stylesheets, e.g. imported CSS modules.
         */
        static_stylesheets() {
            return this.stylesheets();
        }
        /**
         * Stylesheets computed by the component.
         */
        computed_stylesheets() {
            return [this._css_vars];
        }
        /**
         * Other stylesheets, e.g. provided by user.
         */
        user_stylesheets() {
            return [];
        }
        empty() {
            (0, dom_1.empty)(this.shadow_el);
            this.class_list.clear();
            this._applied_css_classes = [];
            this._applied_stylesheets = [];
            for (const stylesheet of this.computed_stylesheets()) {
                if (!stylesheet.persistent) {
                    stylesheet.clear();
                }
            }
        }
        render() {
            this.empty();
            this._update_stylesheets();
            this._apply_html_attributes();
        }
        _applied_html_attributes = [];
        _apply_html_attributes() {
            this._update_css_classes();
        }
        reposition(_displayed) {
            this._update_css_variables(); // TODO remove this when node invalidation is implemented
        }
        *_stylesheets() {
            yield* this.static_stylesheets();
            yield* this.computed_stylesheets();
            yield* this.user_stylesheets();
        }
        *_css_classes() {
            yield `bk-${this.model.type.replace(/\./g, "-")}`;
            yield* this.css_classes();
        }
        *_css_variables() { }
        _applied_stylesheets = [];
        _apply_stylesheets(stylesheets) {
            const resolved_stylesheets = stylesheets.map((style) => (0, types_1.isString)(style) ? new dom_1.InlineStyleSheet(style) : style);
            this._applied_stylesheets.push(...resolved_stylesheets);
            resolved_stylesheets.forEach((stylesheet) => stylesheet.install(this.shadow_el));
        }
        _applied_css_classes = [];
        _apply_css_classes(classes) {
            this._applied_css_classes.push(...classes);
            this.class_list.add(...classes);
        }
        _update_stylesheets() {
            this._applied_stylesheets.forEach((stylesheet) => stylesheet.uninstall());
            this._applied_stylesheets = [];
            this._apply_stylesheets([...this._stylesheets()]);
        }
        _update_css_classes() {
            this.class_list.remove(this._applied_css_classes);
            this._applied_css_classes = [];
            this._apply_css_classes([...this._css_classes()]);
        }
        _update_css_variables() {
            const vars = [];
            for (const [name, value] of this._css_variables()) {
                const full_name = name.startsWith("--") ? name : `--${name}`;
                vars.push(`${full_name}: ${value};\n`);
            }
            if (vars.length == 0) {
                this._css_vars.clear();
            }
            else {
                this._css_vars.replace(`:host {\n${vars}}`);
            }
        }
    }
    exports.DOMComponentView = DOMComponentView;
},
/* core/view.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const has_props_1 = require(16) /* ./has_props */;
    const signaling_1 = require(17) /* ./signaling */;
    const types_1 = require(8) /* ./util/types */;
    const node_1 = require(57) /* ../models/coordinates/node */;
    const xy_1 = require(66) /* ../models/coordinates/xy */;
    const indexed_1 = require(67) /* ../models/coordinates/indexed */;
    const view_manager_1 = require(68) /* ./view_manager */;
    const eq_1 = require(27) /* ./util/eq */;
    const logging_1 = require(11) /* ./logging */;
    /**
     * Shared abort reason. Aborting without one makes the browser construct a
     * `DOMException` with a stack trace, which is an order of magnitude more
     * expensive and is paid by every view being removed.
     */
    const view_removed = new DOMException("view removed", "AbortError");
    class View {
        removed = new signaling_1.Signal0(this, "removed");
        _abort_controller = new AbortController();
        model;
        parent;
        root;
        owner;
        views = new view_manager_1.ViewQuery(this);
        _ready = Promise.resolve(undefined);
        get ready() {
            return this._ready;
        }
        _await_ready(promise) {
            this._ready = this._ready.then(() => promise);
            if (this.root != this) {
                this.root._ready = this.root._ready.then(() => this._ready);
            }
        }
        /** @internal */
        _slots = new WeakMap();
        connect(signal, slot) {
            let new_slot = this._slots.get(slot);
            if (new_slot == null) {
                new_slot = (args, sender) => {
                    this._await_ready(Promise.resolve(slot.call(this, args, sender)));
                };
                this._slots.set(slot, new_slot);
            }
            return signal.connect(new_slot, this);
        }
        disconnect(signal, slot) {
            const new_slot = this._slots.get(slot);
            return new_slot != null ? signal.disconnect(new_slot, this) : false;
        }
        constructor(options) {
            const { model, parent, owner } = options;
            this.model = model;
            this.parent = (0, types_1.isFunction)(parent) ? parent(this.model) : parent;
            if (this.parent == null) {
                this.root = this;
                this.owner = owner ?? new view_manager_1.ViewManager([this]);
            }
            else {
                this.root = this.parent.root;
                this.owner = this.root.owner;
            }
        }
        initialize() { }
        async lazy_initialize() { }
        /**
         * An `AbortSignal` that is aborted when this view is removed.
         *
         * Pass it as `{signal: this.abort_signal}` to `addEventListener()` when
         * subscribing to an event target that outlives this view (e.g. `document`,
         * `window` or `visualViewport`). Such a target retains the listener, and
         * through its closure this view and its model, for the lifetime of the page.
         *
         * Don't use it for listeners on elements this view owns. Those are released
         * with the element itself, and registering an abort algorithm for them only
         * adds a reference from this view to DOM it would otherwise let go of.
         */
        get abort_signal() {
            return this._abort_controller.signal;
        }
        _destroyed = false;
        remove() {
            if (this._destroyed) {
                logging_1.logger.warn(`${this}.remove(): view was already destroyed`);
                return;
            }
            this.disconnect_signals();
            this._abort_controller.abort(view_removed);
            for (const view of this.children_views()) {
                view?.remove();
            }
            this.owner.remove(this);
            this.removed.emit();
            this._destroyed = true;
        }
        get is_destroyed() {
            return this._destroyed;
        }
        toString() {
            return `${this.model.type}View(${this.model.id})`;
        }
        [eq_1.equals](that, _cmp) {
            return Object.is(this, that);
        }
        /** @deprecated use children_views */
        *children() {
            yield* this.children_views().filter((view) => view != null);
        }
        children_views() {
            return [];
        }
        _has_finished = false;
        mark_finished() {
            this._has_finished = true;
        }
        /**
         * Mark as finished even if e.g. external resources were not loaded yet.
         */
        force_finished() {
            this.mark_finished();
        }
        finish() {
            this.mark_finished();
            this.notify_finished();
        }
        _idle_notified = false;
        notify_finished() {
            if (!this.is_root) {
                this.root.notify_finished();
            }
            else {
                if (!this._idle_notified && this.has_finished()) {
                    const { document } = this.model;
                    if (document != null) {
                        this._idle_notified = true;
                        document.notify_idle(this.model);
                    }
                }
            }
        }
        serializable_children() {
            return [...this.children()].filter((view) => view.model.is_syncable);
        }
        serializable_state() {
            const children = this.serializable_children()
                .map((view) => view.serializable_state())
                .filter((item) => item.bbox != null && item.bbox.is_valid && !item.bbox.is_empty); // TODO move this to a common base class for UI views
            return {
                type: this.model.type,
                children,
            };
        }
        get is_root() {
            return this.parent == null;
        }
        has_finished() {
            return this._has_finished;
        }
        get is_idle() {
            return this.has_finished();
        }
        connect_signals() { }
        disconnect_signals() {
            signaling_1.Signal.disconnect_receiver(this);
        }
        on_change(properties, fn) {
            for (const property of (0, types_1.isArray)(properties) ? properties : [properties]) {
                this.connect(property.change, fn);
            }
        }
        on_transitive_change(property, fn, { recursive = false, signal = (obj) => obj.change } = {}) {
            const slot = () => fn();
            const collect = () => {
                const value = property.is_unset ? [] : property.get_value();
                return has_props_1.HasProps.references(value, { recursive });
            };
            const connect = (models) => {
                for (const model of models) {
                    this.connect(signal(model), slot);
                }
            };
            const disconnect = (models) => {
                for (const model of models) {
                    this.disconnect(signal(model), slot);
                }
            };
            let models = collect();
            connect(models);
            this.on_change(property, () => {
                disconnect(models);
                models = collect();
                connect(models);
                fn();
            });
        }
        cursor(_sx, _sy) {
            return null;
        }
        resolve_frame() {
            return null;
        }
        resolve_canvas() {
            return null;
        }
        resolve_plot() {
            return null;
        }
        resolve_target(target) {
            if ((0, types_1.isString)(target)) {
                const ascend = (fn) => {
                    let obj = this;
                    while (obj != null) {
                        const view = fn(obj);
                        if (view != null) {
                            return view;
                        }
                        else {
                            obj = obj.parent;
                        }
                    }
                    return null;
                };
                switch (target) {
                    case "parent": return this.parent;
                    case "frame": return ascend((view) => view.resolve_frame());
                    case "canvas": return ascend((view) => view.resolve_canvas());
                    case "plot": return ascend((view) => view.resolve_plot());
                }
            }
            else {
                const queue = [this.root];
                while (true) {
                    const child = queue.shift();
                    if (child == null) {
                        break;
                    }
                    else if (child.model == target) {
                        return child;
                    }
                    else {
                        queue.push(...child.children());
                    }
                }
                return null;
            }
        }
        resolve_symbol(_node) {
            return { x: NaN, y: NaN };
        }
        resolve_node(node) {
            const target = this.resolve_target(node.target);
            if (target != null) {
                return target.resolve_symbol(node);
            }
            else {
                return { x: NaN, y: NaN };
            }
        }
        resolve_coordinate(coord) {
            if (coord instanceof xy_1.XY) {
                let obj = this;
                while (obj != null && obj.resolve_xy == null) {
                    obj = obj.parent;
                }
                return obj?.resolve_xy?.(coord) ?? { x: NaN, y: NaN };
            }
            else if (coord instanceof indexed_1.Indexed) {
                let obj = this;
                while (obj != null && obj.resolve_indexed == null) {
                    obj = obj.parent;
                }
                return obj?.resolve_indexed?.(coord) ?? { x: NaN, y: NaN };
            }
            else if (coord instanceof node_1.Node) {
                return this.resolve_node(coord);
            }
            else {
                return { x: NaN, y: NaN };
            }
        }
        resolve_as_xy(coord) {
            const value = this.resolve_coordinate(coord);
            return (0, types_1.isNumber)(value) ? { x: NaN, y: NaN } : value;
        }
        resolve_as_scalar(coord, dim) {
            const value = this.resolve_coordinate(coord);
            return (0, types_1.isNumber)(value) ? value : value[dim];
        }
    }
    exports.View = View;
},
/* models/coordinates/xy.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const coordinate_1 = require(58) /* ./coordinate */;
    class XY extends coordinate_1.Coordinate {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Float }) => ({
                x: [Float],
                y: [Float],
            }));
        }
    }
    exports.XY = XY;
},
/* models/coordinates/indexed.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const coordinate_1 = require(58) /* ./coordinate */;
    class Indexed extends coordinate_1.Coordinate {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Int, AnyRef }) => ({
                index: [Int],
                renderer: [AnyRef()],
            }));
        }
    }
    exports.Indexed = Indexed;
},
/* core/view_manager.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const build_views_1 = require(69) /* ./build_views */;
    class AbstractViewQuery {
        *all_views() {
            yield* this.query(() => true);
        }
        *query(fn) {
            const visited = new Set();
            const query_result = [];
            function descend(view) {
                if (visited.has(view)) {
                    return;
                }
                visited.add(view);
                if (fn(view)) {
                    query_result.push(view);
                }
                for (const child of view.children()) {
                    descend(child);
                }
            }
            for (const view of this) {
                descend(view);
            }
            yield* query_result;
        }
        query_one(fn) {
            for (const view of this.query(fn)) {
                return view;
            }
            return null;
        }
        *find(model) {
            yield* this.query((view) => view.model == model);
        }
        *find_by_id(id) {
            yield* this.query((view) => view.model.id == id);
        }
        find_one(model) {
            for (const view of this.find(model)) {
                return view;
            }
            return null;
        }
        find_one_by_id(id) {
            for (const view of this.find_by_id(id)) {
                return view;
            }
            return null;
        }
        get_one(model) {
            const view = this.find_one(model);
            if (view != null) {
                return view;
            }
            else {
                throw new Error(`cannot find a view for ${model}`);
            }
        }
        get_one_by_id(id) {
            const view = this.find_one_by_id(id);
            if (view != null) {
                return view;
            }
            else {
                throw new Error(`cannot find a view for a model with '${id}' identity`);
            }
        }
        find_all(model) {
            return [...this.find(model)];
        }
        find_all_by_id(id) {
            return [...this.find_by_id(id)];
        }
        select(models) {
            return models.map((model) => this.find_one(model)).filter((view) => view != null);
        }
    }
    class ViewQuery extends AbstractViewQuery {
        view;
        constructor(view) {
            super();
            this.view = view;
        }
        *[Symbol.iterator]() {
            yield this.view;
        }
        toString() {
            return `ViewQuery(${this.view})`;
        }
    }
    exports.ViewQuery = ViewQuery;
    class ViewManager extends AbstractViewQuery {
        global;
        _roots;
        constructor(roots = [], global) {
            super();
            this.global = global;
            this._roots = new Set(roots);
        }
        toString() {
            const views = [...this._roots].map((view) => `${view}`).join(", ");
            return `ViewManager(${views})`;
        }
        async build_view(model, parent = null) {
            const view = await (0, build_views_1.build_view)(model, { owner: this, parent });
            if (parent == null) {
                this.add(view);
            }
            return view;
        }
        get(model) {
            for (const view of this._roots) {
                if (view.model == model) {
                    return view;
                }
            }
            return null;
        }
        get_by_id(id) {
            for (const view of this._roots) {
                if (view.model.id == id) {
                    return view;
                }
            }
            return null;
        }
        add(view) {
            this._roots.add(view);
            this.global?.add(view);
        }
        delete(view) {
            this._roots.delete(view);
            this.global?.delete(view);
        }
        remove(view) {
            this.delete(view);
        }
        clear() {
            for (const view of this) {
                view.remove();
            }
        }
        /* TODO (TS 5.2)
        [Symbol.dispose](): void {
          this.clear()
        }
        */
        get roots() {
            return [...this._roots];
        }
        *[Symbol.iterator]() {
            yield* this._roots;
        }
    }
    exports.ViewManager = ViewManager;
},
/* core/build_views.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.build_view = build_view;
    exports.build_views = build_views;
    exports.remove_views = remove_views;
    exports.traverse_views = traverse_views;
    const array_1 = require(10) /* ./util/array */;
    const assert_1 = require(13) /* ./util/assert */;
    async function _build_view(view_cls, model, options) {
        (0, assert_1.assert)(view_cls != null, "model doesn't implement a view");
        const view = new view_cls({ ...options, model });
        view.initialize();
        await view.lazy_initialize();
        return view;
    }
    async function build_view(model, options = { parent: null }, cls = (model) => model.default_view) {
        const view = await _build_view(cls(model), model, options);
        view.connect_signals();
        return view;
    }
    async function build_views(view_storage, models, options = { parent: null }, cls = (model) => model.default_view) {
        const to_remove = (0, array_1.difference)([...view_storage.keys()], models);
        const removed_views = [];
        for (const model of to_remove) {
            const view = view_storage.get(model);
            if (view != null) {
                view_storage.delete(model);
                removed_views.push(view);
                view.remove();
            }
        }
        const created_views = [];
        const new_models = models.filter((model) => !view_storage.has(model));
        for (const model of new_models) {
            const view = await _build_view(cls(model), model, options);
            view_storage.set(model, view);
            created_views.push(view);
        }
        for (const view of created_views) {
            view.connect_signals();
        }
        return {
            created: created_views,
            removed: removed_views,
        };
    }
    function remove_views(view_storage) {
        for (const [model, view] of view_storage) {
            view.remove();
            view_storage.delete(model);
        }
    }
    function traverse_views(views, fn) {
        const visited = new Set();
        const queue = [...views];
        while (true) {
            const view = queue.shift();
            if (view === undefined) {
                break;
            }
            if (visited.has(view)) {
                continue;
            }
            visited.add(view);
            queue.push(...view.children());
            fn(view);
        }
    }
},
/* styles/base.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = `:host{--base-font:var(--bokeh-base-font, Helvetica, Arial, sans-serif);--mono-font:var(--bokeh-mono-font, monospace);--font-size:var(--bokeh-font-size, 12px);--line-height:calc(20 / 14);--line-height-computed:calc(var(--font-size) * var(--line-height));--border-radius:4px;--padding-vertical:6px;--padding-horizontal:12px;--bokeh-top-level:10000;--color:#18191D;--background-color:#fff;--hover-color:#F9F9F9;--disabled-color:#747679;--border-color:#BBBBBD;--divider-color:#D7D7D8;--shortcut-color:#747679;--highlight-color:#65A2CB;--active-bg:#C3DBEB;--active-border:#65A2CB;--active-fg:#267BB6;--inactive-bg:#EBEBEB;--inactive-fg:#9A9B9D;--icon-color:var(--bokeh-icon-color, #747679);--icon-color-disabled:var(--bokeh-icon-color-disabled, #D7D7D8);--error:#D14250;--inverted-color:#fff;--placeholder-color:#9A9B9D;--surface-background-color:#EBEBEB;--disabled-background-color:#EBEBEB;--input-focus-border-color:#65A2CB;--input-focus-halo-color:rgba(101, 162, 203, 0.6);--border-style:solid;--border-width:1px;--border:var(--border-color) var(--border-style) var(--border-width);--box-shadow-color:rgba(0, 0, 0, 0.175);--box-shadow-inset:inset 0 3px 5px rgba(0, 0, 0, 0.125);--box-shadow-x-symmetric:0 6px 12px var(--box-shadow-color);--box-shadow:2px 4px 8px var(--box-shadow-color);--divider-width:1px;--divider:1px var(--divider-color) solid;--outline-color:#BBBBBD;--outline-style:dotted;--outline-width:1px;--outline:var(--outline-color) var(--outline-style) var(--outline-width);--button-width:30px;--button-height:30px;--button-color:lightgray;}:host{box-sizing:border-box;font-family:var(--base-font);font-size:var(--font-size);line-height:var(--line-height);}*,*:before,*:after{box-sizing:inherit;font-family:inherit;}pre,code,tt{font-family:var(--mono-font);margin:0;}`;
},
/* core/util/canvas.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.is_Exportable = is_Exportable;
    const svg_1 = require(72) /* ./svg */;
    const bbox_1 = require(62) /* ./bbox */;
    const dom_1 = require(61) /* ../dom */;
    const types_1 = require(8) /* ./types */;
    exports.exportable = Symbol("exportable");
    function is_Exportable(obj) {
        return (0, types_1.isObject)(obj) && exports.exportable in obj;
    }
    class CanvasLayer {
        backend;
        hidpi;
        _canvas;
        get canvas() {
            return this._canvas;
        }
        _ctx;
        get ctx() {
            return this._ctx;
        }
        _el;
        get el() {
            return this._el;
        }
        _pixel_ratio = 1;
        get pixel_ratio() {
            return this._pixel_ratio;
        }
        bbox = new bbox_1.BBox();
        constructor(backend, hidpi) {
            this.backend = backend;
            this.hidpi = hidpi;
            switch (backend) {
                case "webgl":
                case "canvas": {
                    this._el = this._canvas = (0, dom_1.canvas)({ class: "bk-layer" });
                    const ctx = this.canvas.getContext("2d");
                    if (ctx == null) {
                        throw new Error("unable to obtain 2D rendering context");
                    }
                    this._ctx = ctx;
                    if (hidpi) {
                        this._pixel_ratio = devicePixelRatio;
                    }
                    break;
                }
                case "svg": {
                    const ctx = new svg_1.SVGRenderingContext2D();
                    this._ctx = ctx;
                    this._canvas = ctx.get_svg();
                    this._el = (0, dom_1.div)({ class: "bk-layer" });
                    const shadow_el = this._el.attachShadow({ mode: "open" });
                    shadow_el.appendChild(this._canvas);
                    break;
                }
            }
            Object.assign(this._ctx, {
                layer: this,
                rect_bbox(bbox) {
                    const { x, y, width, height } = bbox;
                    this.rect(x, y, width, height);
                },
            });
        }
        get pixel_ratio_changed() {
            if (this.hidpi && (this.backend == "canvas" || this.backend == "webgl")) {
                return this.pixel_ratio != devicePixelRatio;
            }
            else {
                return false;
            }
        }
        resize(width, height) {
            const size_changed = this.bbox.width != width || this.bbox.height != height;
            const { pixel_ratio_changed } = this;
            if (!size_changed && !pixel_ratio_changed) {
                return;
            }
            if (pixel_ratio_changed) {
                this._pixel_ratio = devicePixelRatio;
            }
            this.bbox = new bbox_1.BBox({ left: 0, top: 0, width, height });
            const { target } = this;
            target.width = width * this.pixel_ratio;
            target.height = height * this.pixel_ratio;
        }
        get target() {
            return this._ctx instanceof svg_1.SVGRenderingContext2D ? this._ctx : this.canvas;
        }
        undo_transform(fn) {
            const { ctx } = this;
            const current_transform = ctx.getTransform();
            ctx.resetTransform();
            try {
                fn(ctx);
            }
            finally {
                ctx.setTransform(current_transform);
            }
        }
        prepare() {
            const { ctx, hidpi, pixel_ratio } = this;
            ctx.save();
            if (hidpi) {
                ctx.scale(pixel_ratio, pixel_ratio);
                ctx.translate(0.5, 0.5);
            }
            this.clear();
            return ctx;
        }
        clear() {
            const { x, y, width, height } = this.bbox;
            this.ctx.clearRect(x, y, width, height);
        }
        finish() {
            this.ctx.restore();
        }
        to_blob() {
            const { _canvas } = this;
            if (_canvas instanceof HTMLCanvasElement) {
                return new Promise((resolve, reject) => {
                    _canvas.toBlob((blob) => blob != null ? resolve(blob) : reject(), "image/png");
                });
            }
            else {
                const ctx = this._ctx;
                const svg = ctx.get_serialized_svg(true);
                const blob = new Blob([svg], { type: "image/svg+xml" });
                return Promise.resolve(blob);
            }
        }
    }
    exports.CanvasLayer = CanvasLayer;
},
/* core/util/svg.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    /**
     * Based on https://github.com/gliffy/canvas2svg
     */
    const affine_1 = require(73) /* ./affine */;
    const types_1 = require(8) /* ./types */;
    const color_1 = require(23) /* ./color */;
    const object_1 = require(9) /* ./object */;
    const random_1 = require(74) /* ./random */;
    const math_1 = require(12) /* ./math */;
    const dom_1 = require(61) /* ../dom */;
    // helper function to map named to numbered entities
    function createNamedToNumberedLookup(input, radix) {
        const lookup = new Map();
        const items = input.split(",");
        radix = radix ?? 10;
        // Map from named to numbered entities.
        for (let i = 0; i < items.length; i += 2) {
            const entity = `&${items[i + 1]};`;
            const base10 = parseInt(items[i], radix);
            lookup.set(entity, `&#${base10};`);
        }
        // FF and IE need to create a regex from hex values ie &nbsp; == \xa0
        lookup.set("\\xa0", "&#160;");
        return lookup;
    }
    // helper function to map canvas-textAlign to svg-textAnchor
    function getTextAnchor(textAlign) {
        // TODO: support rtl languages
        const mapping = { left: "start", right: "end", center: "middle", start: "start", end: "end" };
        return textAlign in mapping ? mapping[textAlign] : mapping.start;
    }
    // helper function to map canvas-textBaseline to svg-dominantBaseline
    function getDominantBaseline(textBaseline) {
        // INFO: not supported in all browsers
        const mapping = { alphabetic: "alphabetic", hanging: "hanging", top: "text-before-edge", bottom: "text-after-edge", middle: "central" };
        return textBaseline in mapping ? mapping[textBaseline] : mapping.alphabetic;
    }
    // Unpack entities lookup where the numbers are in radix 32 to reduce the size
    // entity mapping courtesy of tinymce
    const namedEntities = createNamedToNumberedLookup("50,nbsp,51,iexcl,52,cent,53,pound,54,curren,55,yen,56,brvbar,57,sect,58,uml,59,copy," +
        "5a,ordf,5b,laquo,5c,not,5d,shy,5e,reg,5f,macr,5g,deg,5h,plusmn,5i,sup2,5j,sup3,5k,acute," +
        "5l,micro,5m,para,5n,middot,5o,cedil,5p,sup1,5q,ordm,5r,raquo,5s,frac14,5t,frac12,5u,frac34," +
        "5v,iquest,60,Agrave,61,Aacute,62,Acirc,63,Atilde,64,Auml,65,Aring,66,AElig,67,Ccedil," +
        "68,Egrave,69,Eacute,6a,Ecirc,6b,Euml,6c,Igrave,6d,Iacute,6e,Icirc,6f,Iuml,6g,ETH,6h,Ntilde," +
        "6i,Ograve,6j,Oacute,6k,Ocirc,6l,Otilde,6m,Ouml,6n,times,6o,Oslash,6p,Ugrave,6q,Uacute," +
        "6r,Ucirc,6s,Uuml,6t,Yacute,6u,THORN,6v,szlig,70,agrave,71,aacute,72,acirc,73,atilde,74,auml," +
        "75,aring,76,aelig,77,ccedil,78,egrave,79,eacute,7a,ecirc,7b,euml,7c,igrave,7d,iacute,7e,icirc," +
        "7f,iuml,7g,eth,7h,ntilde,7i,ograve,7j,oacute,7k,ocirc,7l,otilde,7m,ouml,7n,divide,7o,oslash," +
        "7p,ugrave,7q,uacute,7r,ucirc,7s,uuml,7t,yacute,7u,thorn,7v,yuml,ci,fnof,sh,Alpha,si,Beta," +
        "sj,Gamma,sk,Delta,sl,Epsilon,sm,Zeta,sn,Eta,so,Theta,sp,Iota,sq,Kappa,sr,Lambda,ss,Mu," +
        "st,Nu,su,Xi,sv,Omicron,t0,Pi,t1,Rho,t3,Sigma,t4,Tau,t5,Upsilon,t6,Phi,t7,Chi,t8,Psi," +
        "t9,Omega,th,alpha,ti,beta,tj,gamma,tk,delta,tl,epsilon,tm,zeta,tn,eta,to,theta,tp,iota," +
        "tq,kappa,tr,lambda,ts,mu,tt,nu,tu,xi,tv,omicron,u0,pi,u1,rho,u2,sigmaf,u3,sigma,u4,tau," +
        "u5,upsilon,u6,phi,u7,chi,u8,psi,u9,omega,uh,thetasym,ui,upsih,um,piv,812,bull,816,hellip," +
        "81i,prime,81j,Prime,81u,oline,824,frasl,88o,weierp,88h,image,88s,real,892,trade,89l,alefsym," +
        "8cg,larr,8ch,uarr,8ci,rarr,8cj,darr,8ck,harr,8dl,crarr,8eg,lArr,8eh,uArr,8ei,rArr,8ej,dArr," +
        "8ek,hArr,8g0,forall,8g2,part,8g3,exist,8g5,empty,8g7,nabla,8g8,isin,8g9,notin,8gb,ni,8gf,prod," +
        "8gh,sum,8gi,minus,8gn,lowast,8gq,radic,8gt,prop,8gu,infin,8h0,ang,8h7,and,8h8,or,8h9,cap,8ha,cup," +
        "8hb,int,8hk,there4,8hs,sim,8i5,cong,8i8,asymp,8j0,ne,8j1,equiv,8j4,le,8j5,ge,8k2,sub,8k3,sup,8k4," +
        "nsub,8k6,sube,8k7,supe,8kl,oplus,8kn,otimes,8l5,perp,8m5,sdot,8o8,lceil,8o9,rceil,8oa,lfloor,8ob," +
        "rfloor,8p9,lang,8pa,rang,9ea,loz,9j0,spades,9j3,clubs,9j5,hearts,9j6,diams,ai,OElig,aj,oelig,b0," +
        "Scaron,b1,scaron,bo,Yuml,m6,circ,ms,tilde,802,ensp,803,emsp,809,thinsp,80c,zwnj,80d,zwj,80e,lrm," +
        "80f,rlm,80j,ndash,80k,mdash,80o,lsquo,80p,rsquo,80q,sbquo,80s,ldquo,80t,rdquo,80u,bdquo,810,dagger," +
        "811,Dagger,81g,permil,81p,lsaquo,81q,rsaquo,85c,euro", 32);
    // Some basic mappings for attributes and default values.
    const STYLES = {
        strokeStyle: {
            svgAttr: "stroke", // corresponding svg attribute
            canvas: "#000000", // canvas default
            svg: "none", // svg default
            apply: "stroke", // apply on stroke() or fill()
        },
        fillStyle: {
            svgAttr: "fill",
            canvas: "#000000",
            svg: null, // svg default is black, but we need to special case this to handle canvas stroke without fill
            apply: "fill",
        },
        lineCap: {
            svgAttr: "stroke-linecap",
            canvas: "butt",
            svg: "butt",
            apply: "stroke",
        },
        lineJoin: {
            svgAttr: "stroke-linejoin",
            canvas: "miter",
            svg: "miter",
            apply: "stroke",
        },
        miterLimit: {
            svgAttr: "stroke-miterlimit",
            canvas: 10,
            svg: 4,
            apply: "stroke",
        },
        lineWidth: {
            svgAttr: "stroke-width",
            canvas: 1,
            svg: 1,
            apply: "stroke",
        },
        globalAlpha: {
            svgAttr: "opacity",
            canvas: 1,
            svg: 1,
            apply: "fill stroke",
        },
        shadowColor: {
            canvas: "#000000",
        },
        shadowOffsetX: {
            canvas: 0,
        },
        shadowOffsetY: {
            canvas: 0,
        },
        shadowBlur: {
            canvas: 0,
        },
        lineDash: {
            svgAttr: "stroke-dasharray",
            canvas: [],
            svg: null,
            apply: "stroke",
        },
        lineDashOffset: {
            svgAttr: "stroke-dashoffset",
            canvas: 0,
            svg: 0,
            apply: "stroke",
        },
        direction: {
            canvas: "inherit",
        },
        font: {
            // font converts to multiple svg attributes, there is custom logic for this
            canvas: "10px sans-serif",
        },
        fontKerning: {
            canvas: "auto",
        },
        fontStretch: {
            canvas: "normal",
        },
        fontVariantCaps: {
            canvas: "normal",
        },
        letterSpacing: {
            canvas: "0px",
        },
        textAlign: {
            canvas: "start",
        },
        textBaseline: {
            canvas: "alphabetic",
        },
        textRendering: {
            canvas: "auto",
        },
        wordSpacing: {
            canvas: "0px",
        },
    };
    function is_VideoFrame(image) {
        return typeof VideoFrame !== "undefined" && image instanceof VideoFrame;
    }
    function width_height(image) {
        if (is_VideoFrame(image)) {
            return [image.codedWidth, image.codedHeight]; // TODO not sure if this makes any sense
        }
        else {
            function to_number(val) {
                return (0, types_1.isNumber)(val) ? val : val.baseVal.value;
            }
            const { width, height } = image;
            return [to_number(width), to_number(height)];
        }
    }
    class CanvasGradient {
        __root;
        __ctx;
        constructor(gradientNode, ctx) {
            this.__root = gradientNode;
            this.__ctx = ctx;
        }
        /**
         * Adds a color stop to the gradient root
         */
        addColorStop(offset, color) {
            if (this.__root.nodeName === "linearGradient" &&
                this.__root.getAttribute("x1") === this.__root.getAttribute("x2") &&
                this.__root.getAttribute("y1") === this.__root.getAttribute("y2")) {
                return;
            }
            if (this.__root.nodeName === "radialGradient" &&
                this.__root.getAttribute("cx") === this.__root.getAttribute("fx") &&
                this.__root.getAttribute("cy") === this.__root.getAttribute("fy") &&
                this.__root.getAttribute("r") === this.__root.getAttribute("r0")) {
                return;
            }
            const stop = this.__ctx.__createElement("stop");
            stop.setAttribute("offset", `${offset}`);
            if (color.indexOf("rgba") !== -1) {
                // separate alpha value, since webkit can't handle it
                const regex = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?\.?\d*)\s*\)/gi;
                const matches = regex.exec(color);
                const [, r, g, b, a] = matches;
                stop.setAttribute("stop-color", `rgb(${r},${g},${b})`);
                stop.setAttribute("stop-opacity", a);
            }
            else {
                stop.setAttribute("stop-color", color);
            }
            this.__root.appendChild(stop);
        }
    }
    class CanvasPattern {
        __root;
        __ctx;
        constructor(pattern, ctx) {
            this.__root = pattern;
            this.__ctx = ctx;
        }
        setTransform(_transform) {
            throw new Error("not implemented");
        }
    }
    class SVGRenderingContext2D {
        __canvas;
        __ctx;
        __root;
        __ids;
        __defs;
        __stack;
        __document;
        __currentElement;
        __currentDefaultPath = "";
        __currentPosition = null;
        //__currentElementsToStyle: {element: SVGElement, children: SVGElement[]} | null = null
        static __random = random_1.random;
        get canvas() {
            // XXX: point back to this instance
            return this;
        }
        strokeStyle;
        fillStyle;
        lineCap;
        lineJoin;
        miterLimit;
        lineWidth;
        globalAlpha = 1.0;
        globalCompositeOperation; // TODO: implement
        shadowColor;
        shadowOffsetX;
        shadowOffsetY;
        shadowBlur;
        lineDash;
        lineDashOffset;
        filter; // TODO: implement
        imageSmoothingEnabled; // TODO: implement
        imageSmoothingQuality; // TODO: implement
        direction; // TODO
        font;
        fontKerning; // TODO
        fontStretch; // TODO
        fontVariantCaps; // TODO
        letterSpacing; // TODO
        textAlign;
        textBaseline;
        textRendering; // TODO
        wordSpacing; // TODO
        _width;
        _height;
        get width() {
            return this._width;
        }
        set width(width) {
            this._width = width;
            this.__root.setAttribute("width", `${width}`);
        }
        get height() {
            return this._height;
        }
        set height(height) {
            this._height = height;
            this.__root.setAttribute("height", `${height}`);
        }
        _transform = new affine_1.AffineTransform();
        constructor(options) {
            this.__document = options?.document ?? document;
            // allow passing in an existing context to wrap around
            // if a context is passed in, we know a canvas already exist
            if (options?.ctx != null) {
                this.__ctx = options.ctx;
            }
            else {
                this.__canvas = this.__document.createElement("canvas");
                this.__ctx = this.__canvas.getContext("2d");
            }
            this.reset();
            // the root svg element
            this.__root = this.__document.createElementNS("http://www.w3.org/2000/svg", "svg");
            this.__root.setAttribute("version", "1.1");
            this.__root.setAttribute("xmlns", "http://www.w3.org/2000/svg");
            this.__currentElement = this.__root;
            this.width = options?.width ?? 500;
            this.height = options?.height ?? 500;
            // make sure we don't generate the same ids in defs
            this.__ids = new Set();
            // defs tag
            this.__defs = this.__document.createElementNS("http://www.w3.org/2000/svg", "defs");
            this.__root.appendChild(this.__defs);
        }
        // helper function that generates a random string
        _random_string() {
            const chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
            let str;
            do {
                str = SVGRenderingContext2D.__random.choices(12, chars).join("");
            } while (this.__ids.has(str));
            return str;
        }
        /**
         * Creates the specified svg element
         */
        __createElement(elementName, properties = {}, resetFill = false) {
            const element = this.__document.createElementNS("http://www.w3.org/2000/svg", elementName);
            if (resetFill) {
                // if fill or stroke is not specified, the svg element should not display. By default SVG's fill is black.
                element.setAttribute("fill", "none");
                element.setAttribute("stroke", "none");
            }
            const keys = Object.keys(properties);
            for (const key of keys) {
                element.setAttribute(key, `${properties[key]}`);
            }
            return element;
        }
        /**
         * Applies default canvas styles to the context
         */
        __setDefaultStyles() {
            // default 2d canvas context properties see:http://www.w3.org/TR/2dcontext/
            for (const [key, val] of (0, object_1.typed_entries)(STYLES)) {
                this[key] = val.canvas;
            }
        }
        /**
         * Applies styles on restore
         */
        __applyStyleState(style_state) {
            for (const [key, val] of (0, object_1.typed_entries)(style_state)) {
                this[key] = val;
            }
        }
        /**
         * Gets the current style state
         */
        __getStyleState() {
            const style_state = {};
            for (const [key, _val] of (0, object_1.typed_entries)(STYLES)) {
                style_state[key] = this[key];
            }
            return style_state;
        }
        /**
         * Apples the current styles to the current SVG element. On "ctx.fill" or "ctx.stroke"
         */
        __applyStyleToCurrentElement(type) {
            const currentElement = this.__currentElement;
            /*
            const currentStyleGroup = this.__currentElementsToStyle
            if (currentStyleGroup != null) {
              currentElement.setAttribute(type, "")
              currentElement = currentStyleGroup.element
              for (const node of currentStyleGroup.children) {
                node.setAttribute(type, "")
              }
            }
            */
            for (const [key, style] of (0, object_1.typed_entries)(STYLES)) {
                const value = this[key];
                if (style.apply != null && style.apply.includes(type)) {
                    if (value instanceof CanvasPattern) {
                        for (const def of [...value.__ctx.__defs.childNodes]) {
                            if (def instanceof Element) {
                                const id = def.getAttribute("id");
                                this.__ids.add(id);
                                this.__defs.appendChild(def);
                            }
                        }
                        const id = value.__root.getAttribute("id");
                        currentElement.setAttribute(style.apply, `url(#${id})`);
                    }
                    else if (value instanceof CanvasGradient) {
                        const id = value.__root.getAttribute("id");
                        currentElement.setAttribute(style.apply, `url(#${id})`);
                    }
                    else if (style.svg !== value) {
                        if ((style.svgAttr === "stroke" || style.svgAttr === "fill") && (0, types_1.isString)(value) && value.indexOf("rgb") !== -1) {
                            // convert CSS4 -> CSS3 and separate alpha value, since illustrator can't handle it
                            const [r, g, b, a] = (0, color_1.css4_parse)(value) ?? (0, color_1.transparent)();
                            const opacity = a * this.globalAlpha;
                            currentElement.setAttribute(style.svgAttr, `rgb(${r},${g},${b})`);
                            currentElement.setAttribute(`${style.svgAttr}-opacity`, `${opacity}`);
                        }
                        else {
                            let attr = style.svgAttr;
                            if (key === "globalAlpha") {
                                attr = `${type}-${style.svgAttr}`;
                                if (currentElement.getAttribute(attr) != null) {
                                    // fill-opacity or stroke-opacity has already been set by stroke or fill.
                                    continue;
                                }
                            }
                            // otherwise only update attribute if right type, and not svg default
                            currentElement.setAttribute(attr, `${value}`);
                        }
                    }
                }
            }
        }
        /**
          * Returns the serialized value of the svg so far
          * @param fixNamedEntities - Standalone SVG doesn't support named entities, which document.createTextNode encodes.
          *                           If true, we attempt to find all named entities and encode it as a numeric entity.
          * @return serialized svg
          */
        get_serialized_svg(fixNamedEntities = false) {
            let serialized = new XMLSerializer().serializeToString(this.__root);
            if (fixNamedEntities) {
                // loop over each named entity and replace with the proper equivalent.
                for (const [key, value] of namedEntities) {
                    const regexp = new RegExp(key, "gi");
                    if (regexp.test(serialized)) {
                        serialized = serialized.replace(regexp, value);
                    }
                }
            }
            return serialized;
        }
        get_svg() {
            return this.__root;
        }
        /**
          * Will generate a group tag.
          */
        save() {
            this.__stack.push({
                transform: this._transform,
                clip_path: this._clip_path,
                attributes: this.__getStyleState(),
            });
            this._transform = this._transform.clone();
        }
        /**
          * Sets current element to parent, or just root if already root
          */
        restore() {
            if (this.__stack.length == 0) {
                return;
            }
            const { transform, clip_path, attributes } = this.__stack.pop();
            this._transform = transform;
            this._clip_path = clip_path;
            this.__applyStyleState(attributes);
        }
        isContextLost() {
            return false;
        }
        reset() {
            this.__setDefaultStyles();
            this.__stack = [];
        }
        _apply_transform(element, transform = this._transform) {
            if (!transform.is_identity) {
                element.setAttribute("transform", transform.toString());
            }
        }
        _apply_global_alpha(element) {
            if (this.globalAlpha != 1.0) {
                element.setAttribute("opacity", `${this.globalAlpha}`);
            }
        }
        _apply_clip_path(element) {
            if (this._clip_path != null) {
                element.setAttribute("clip-path", this._clip_path);
            }
        }
        /**
          *  scales the current element
          */
        scale(x, y) {
            if (!isFinite(x) || (y != null && !isFinite(y))) {
                return;
            }
            this._transform.scale(x, y ?? x);
        }
        /**
          * rotates the current element
          */
        rotate(angle) {
            if (!isFinite(angle)) {
                return;
            }
            this._transform.rotate(angle);
        }
        /**
          * translates the current element
          */
        translate(x, y) {
            if (!isFinite(x + y)) {
                return;
            }
            this._transform.translate(x, y);
        }
        /**
          * applies a transform to the current element
          */
        transform(a, b, c, d, e, f) {
            if (!isFinite(a + b + c + d + e + f)) {
                return;
            }
            this._transform.transform(a, b, c, d, e, f);
        }
        /**
          * Create a new Path Element
          */
        beginPath() {
            // Note that there is only one current default path, it is not part of the drawing state.
            // See also: https://html.spec.whatwg.org/multipage/scripting.html#current-default-path
            this.__currentDefaultPath = "";
            this.__currentPosition = null;
            this.__init_element();
        }
        __init_element() {
            const path = this.__createElement("path", {}, true);
            this.__root.appendChild(path);
            this.__currentElement = path;
        }
        /**
          * Helper function to apply currentDefaultPath to current path element
          */
        __applyCurrentDefaultPath() {
            const currentElement = this.__currentElement;
            if (currentElement.nodeName === "path") {
                currentElement.setAttribute("d", this.__currentDefaultPath);
            }
            else {
                console.error("Attempted to apply path command to node", currentElement.nodeName);
            }
        }
        /**
          * Helper function to add path command
          */
        __addPathCommand(x, y, path) {
            const separator = this.__currentDefaultPath == "" ? "" : " ";
            this.__currentDefaultPath += separator + path;
            this.__currentPosition = { x, y };
        }
        get _hasCurrentDefaultPath() {
            return this.__currentDefaultPath != "";
        }
        /**
          * Adds the move command to the current path element,
          * if the currentPathElement is not empty create a new path element
          */
        moveTo(x, y) {
            if (!isFinite(x + y)) {
                return;
            }
            const currentElement = this.__currentElement;
            if (currentElement.nodeName !== "path") {
                this.beginPath();
            }
            // creates a new subpath with the given point
            const [tx, ty] = this._transform.apply(x, y);
            this.__addPathCommand(tx, ty, `M ${tx} ${ty}`);
        }
        /**
          * Closes the current path
          */
        closePath() {
            if (this._hasCurrentDefaultPath) {
                this.__addPathCommand(NaN, NaN, "Z");
            }
        }
        /**
          * Adds a line to command
          */
        lineTo(x, y) {
            if (!isFinite(x + y)) {
                return;
            }
            if (!this._hasCurrentDefaultPath) {
                this.moveTo(x, y);
            }
            else {
                const [tx, ty] = this._transform.apply(x, y);
                this.__addPathCommand(tx, ty, `L ${tx} ${ty}`);
            }
        }
        /**
          * Add a bezier command
          */
        bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) {
            if (!isFinite(cp1x + cp1y + cp2x + cp2y + x + y)) {
                return;
            }
            const [tx, ty] = this._transform.apply(x, y);
            const [tcp1x, tcp1y] = this._transform.apply(cp1x, cp1y);
            const [tcp2x, tcp2y] = this._transform.apply(cp2x, cp2y);
            this.__addPathCommand(tx, ty, `C ${tcp1x} ${tcp1y} ${tcp2x} ${tcp2y} ${tx} ${ty}`);
        }
        /**
          * Adds a quadratic curve to command
          */
        quadraticCurveTo(cpx, cpy, x, y) {
            if (!isFinite(cpx + cpy + x + y)) {
                return;
            }
            const [tx, ty] = this._transform.apply(x, y);
            const [tcpx, tcpy] = this._transform.apply(cpx, cpy);
            this.__addPathCommand(tx, ty, `Q ${tcpx} ${tcpy} ${tx} ${ty}`);
        }
        /**
          * Adds the arcTo to the current path
          *
          * @see http://www.w3.org/TR/2015/WD-2dcontext-20150514/#dom-context-2d-arcto
          */
        arcTo(x1, y1, x2, y2, radius) {
            if (!isFinite(x1 + y1 + x2 + y2 + radius)) {
                return;
            }
            // Let the point (x0, y0) be the last point in the subpath.
            if (this.__currentPosition == null) {
                return;
            }
            // Issue #12699.
            // this.__currentPosition has already been transformed using this._transform.
            // Arguments to this function have not been transformed, so to compare the two need
            // to inverse transform this.__currentPosition.
            const inverse = this._transform.inverse();
            const [x0, y0] = inverse.apply(this.__currentPosition.x, this.__currentPosition.y);
            // Negative values for radius must cause the implementation to throw an IndexSizeError exception.
            if (radius < 0) {
                throw new Error(`IndexSizeError: The radius provided (${radius}) is negative.`);
            }
            // If the point (x0, y0) is equal to the point (x1, y1),
            // or if the point (x1, y1) is equal to the point (x2, y2),
            // or if the radius radius is zero,
            // then the method must add the point (x1, y1) to the subpath,
            // and connect that point to the previous point (x0, y0) by a straight line.
            if (((x0 === x1) && (y0 === y1)) || ((x1 === x2) && (y1 === y2)) || (radius === 0)) {
                this.lineTo(x1, y1);
                return;
            }
            function normalize([x, y]) {
                const len = Math.sqrt(x ** 2 + y ** 2);
                return [x / len, y / len];
            }
            // Otherwise, if the points (x0, y0), (x1, y1), and (x2, y2) all lie on a single straight line,
            // then the method must add the point (x1, y1) to the subpath,
            // and connect that point to the previous point (x0, y0) by a straight line.
            const unit_vec_p1_p0 = normalize([x0 - x1, y0 - y1]);
            const unit_vec_p1_p2 = normalize([x2 - x1, y2 - y1]);
            if (unit_vec_p1_p0[0] * unit_vec_p1_p2[1] === unit_vec_p1_p0[1] * unit_vec_p1_p2[0]) {
                this.lineTo(x1, y1);
                return;
            }
            // Otherwise, let The Arc be the shortest arc given by circumference of the circle that has radius radius,
            // and that has one point tangent to the half-infinite line that crosses the point (x0, y0) and ends at the point (x1, y1),
            // and that has a different point tangent to the half-infinite line that ends at the point (x1, y1), and crosses the point (x2, y2).
            // The points at which this circle touches these two lines are called the start and end tangent points respectively.
            // note that both vectors are unit vectors, so the length is 1
            const cos = (unit_vec_p1_p0[0] * unit_vec_p1_p2[0] + unit_vec_p1_p0[1] * unit_vec_p1_p2[1]);
            const theta = Math.acos(Math.abs(cos));
            // Calculate origin
            const unit_vec_p1_origin = normalize([
                unit_vec_p1_p0[0] + unit_vec_p1_p2[0],
                unit_vec_p1_p0[1] + unit_vec_p1_p2[1],
            ]);
            const len_p1_origin = radius / Math.sin(theta / 2);
            const x = x1 + len_p1_origin * unit_vec_p1_origin[0];
            const y = y1 + len_p1_origin * unit_vec_p1_origin[1];
            // Calculate start angle and end angle
            // rotate 90deg clockwise (note that y axis points to its down)
            const unit_vec_origin_start_tangent = [
                -unit_vec_p1_p0[1],
                unit_vec_p1_p0[0],
            ];
            // rotate 90deg counter clockwise (note that y axis points to its down)
            const unit_vec_origin_end_tangent = [
                unit_vec_p1_p2[1],
                -unit_vec_p1_p2[0],
            ];
            function getAngle(vector) {
                // get angle (clockwise) between vector and (1, 0)
                const x = vector[0];
                const y = vector[1];
                if (y >= 0) { // note that y axis points to its down
                    return Math.acos(x);
                }
                else {
                    return -Math.acos(x);
                }
            }
            const startAngle = getAngle(unit_vec_origin_start_tangent);
            const endAngle = getAngle(unit_vec_origin_end_tangent);
            // Connect the point (x0, y0) to the start tangent point by a straight line
            this.lineTo(x + unit_vec_origin_start_tangent[0] * radius, y + unit_vec_origin_start_tangent[1] * radius);
            // Connect the start tangent point to the end tangent point by arc
            // and adding the end tangent point to the subpath.
            this.arc(x, y, radius, startAngle, endAngle);
        }
        /**
          * Sets the stroke property on the current element
          */
        stroke() {
            if (this.__currentElement.nodeName === "path") {
                this.__currentElement.setAttribute("paint-order", "fill");
            }
            this.__applyCurrentDefaultPath();
            this.__applyStyleToCurrentElement("stroke");
            if (this._clip_path != null) {
                this.__currentElement.setAttribute("clip-path", this._clip_path);
            }
        }
        fill(path_or_fill_rule, fill_rule) {
            let path = null;
            if (path_or_fill_rule instanceof Path2D) {
                path = path_or_fill_rule;
            }
            else if (fill_rule == null) {
                fill_rule = path_or_fill_rule;
            }
            else {
                throw new Error("invalid arguments");
            }
            if (path != null) {
                throw new Error("not implemented");
            }
            // XXX: hack (?) to allow fill and hatch visuals on same canvas path
            if (this.__currentElement.getAttribute("fill") != "none") {
                this.__init_element();
            }
            if (this.__currentElement.nodeName === "path") {
                this.__currentElement.setAttribute("paint-order", "stroke");
            }
            this.__applyCurrentDefaultPath();
            this.__applyStyleToCurrentElement("fill");
            if (fill_rule != null && fill_rule != "nonzero") { // don't apply the default
                this.__currentElement.setAttribute("fill-rule", fill_rule);
            }
            if (this._clip_path != null) {
                this.__currentElement.setAttribute("clip-path", this._clip_path);
            }
        }
        /**
          *  Adds a rectangle to the path.
          */
        rect(x, y, width, height) {
            if (!isFinite(x + y + width + height)) {
                return;
            }
            this.moveTo(x, y);
            this.lineTo(x + width, y);
            this.lineTo(x + width, y + height);
            this.lineTo(x, y + height);
            this.lineTo(x, y);
            this.closePath();
        }
        /**
          * adds a rectangle element
          */
        fillRect(x, y, width, height) {
            if (!isFinite(x + y + width + height)) {
                return;
            }
            this.beginPath();
            this.rect(x, y, width, height);
            this.fill();
        }
        /**
          * Draws a rectangle with no fill
          * @param x
          * @param y
          * @param width
          * @param height
          */
        strokeRect(x, y, width, height) {
            if (!isFinite(x + y + width + height)) {
                return;
            }
            this.beginPath();
            this.rect(x, y, width, height);
            this.stroke();
        }
        /**
          * Clear entire canvas:
          * 1. save current transforms
          * 2. remove all the childNodes of the root g element
          */
        __clearCanvas() {
            (0, dom_1.empty)(this.__defs);
            (0, dom_1.empty)(this.__root);
            this.__root.appendChild(this.__defs);
            this.__currentElement = this.__root;
        }
        /**
          * "Clears" a canvas by just drawing a white rectangle in the current group.
          */
        clearRect(x, y, width, height) {
            if (!isFinite(x + y + width + height)) {
                return;
            }
            if (x === 0 && y === 0 && width === this.width && height === this.height) {
                this.__clearCanvas();
                return;
            }
            const rect = this.__createElement("rect", { x, y, width, height, fill: "#FFFFFF" }, true);
            this._apply_transform(rect);
            this.__root.appendChild(rect);
        }
        roundRect(_x, _y, _w, _h, _radii) {
            throw new Error("not implemented");
        }
        /**
          * Adds a linear gradient to a defs tag.
          * Returns a canvas gradient object that has a reference to it's parent def
          */
        createLinearGradient(x1, y1, x2, y2) {
            if (!isFinite(x1 + y1 + x2 + y2)) {
                throw new Error("The provided double value is non-finite");
            }
            const [tx1, ty1] = this._transform.apply(x1, y1);
            const [tx2, ty2] = this._transform.apply(x2, y2);
            const grad = this.__createElement("linearGradient", {
                id: this._random_string(),
                x1: `${tx1}px`,
                x2: `${tx2}px`,
                y1: `${ty1}px`,
                y2: `${ty2}px`,
                gradientUnits: "userSpaceOnUse",
            }, false);
            this.__defs.appendChild(grad);
            return new CanvasGradient(grad, this);
        }
        /**
          * Adds a radial gradient to a defs tag.
          * Returns a canvas gradient object that has a reference to it's parent def
          */
        createRadialGradient(x0, y0, r0, x1, y1, r1) {
            if (!isFinite(x0 + y0 + r0 + x1 + y1 + r1)) {
                throw new Error("The provided double value is non-finite");
            }
            const [tx0, ty0] = this._transform.apply(x0, y0);
            const [tx1, ty1] = this._transform.apply(x1, y1);
            const grad = this.__createElement("radialGradient", {
                id: this._random_string(),
                cx: `${tx1}px`,
                cy: `${ty1}px`,
                r: `${r1}px`,
                r0: `${r0}px`,
                fx: `${tx0}px`,
                fy: `${ty0}px`,
                gradientUnits: "userSpaceOnUse",
            }, false);
            this.__defs.appendChild(grad);
            return new CanvasGradient(grad, this);
        }
        createConicGradient(_start_angle, _x, _y) {
            throw Error("not implemented");
        }
        /**
          * Parses the font string and returns svg mapping
          */
        __parseFont() {
            const regex = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\'\"\sa-z0-9]+?)\s*$/i;
            const [, style, decoration, weight, size, , family] = regex.exec(this.font); // XXX: RegExpExecArray is incorrecdt
            const data = {
                style: style ?? "normal",
                size: size ?? "10px",
                family: family ?? "sans-serif",
                weight: weight ?? "normal",
                decoration: decoration ?? "normal",
            };
            return data;
        }
        /**
          * Fills or strokes text
          */
        __applyText(text, x, y, action) {
            const font = this.__parseFont();
            const text_el = this.__createElement("text", {
                "font-family": font.family,
                "font-size": font.size,
                "font-style": font.style,
                "font-weight": font.weight,
                "text-decoration": font.decoration,
                x,
                y,
                "text-anchor": getTextAnchor(this.textAlign),
                "dominant-baseline": getDominantBaseline(this.textBaseline),
            }, true);
            text_el.appendChild(this.__document.createTextNode(text));
            this._apply_transform(text_el);
            this.__currentElement = text_el;
            this.__applyStyleToCurrentElement(action);
            const el = (() => {
                if (this._clip_path != null) {
                    const g = this.__createElement("g");
                    g.setAttribute("clip-path", this._clip_path);
                    g.appendChild(text_el);
                    return g;
                }
                else {
                    return text_el;
                }
            })();
            this.__root.appendChild(el);
        }
        /**
          * Creates a text element, in position x,y
          */
        fillText(text, x, y) {
            if (!isFinite(x + y)) {
                return;
            }
            this.__applyText(text, x, y, "fill");
        }
        /**
          * Strokes text
          */
        strokeText(text, x, y) {
            if (!isFinite(x + y)) {
                return;
            }
            this.__applyText(text, x, y, "stroke");
        }
        /**
          * No need to implement this for svg.
          */
        measureText(text) {
            this.__ctx.font = this.font;
            return this.__ctx.measureText(text);
        }
        arc(x, y, radius, start_angle, end_angle, counterclockwise = false) {
            this.ellipse(x, y, radius, radius, 0, start_angle, end_angle, counterclockwise);
        }
        ellipse(x, y, radius_x, radius_y, rotation, start_angle, end_angle, counterclockwise = false) {
            if (!isFinite(x + y + radius_x + radius_y + rotation + start_angle + end_angle)) {
                return;
            }
            if (radius_x < 0 || radius_y < 0) {
                throw new DOMException("IndexSizeError, radius can't be negative");
            }
            const initial_diff = counterclockwise ? end_angle - start_angle : start_angle - end_angle;
            start_angle = start_angle % (2 * Math.PI);
            end_angle = end_angle % (2 * Math.PI);
            const transform = new affine_1.AffineTransform().translate(x, y).rotate(rotation);
            const dx = radius_x * Math.cos(start_angle);
            const dy = radius_y * Math.sin(start_angle);
            const [start_x, start_y] = transform.apply(dx, dy);
            this.lineTo(start_x, start_y);
            // Canvas ellipse defines rotation in radians and SVG elliptical arc is defined in degrees
            const rotation_in_degrees = rotation * 180 / Math.PI;
            const sweep_flag = counterclockwise ? 0 : 1;
            /**
             * Check if need to draw full ellipse (issue #11475). When testing if angular difference is
             * equal to an integer multiple of 2*pi radians, need to account for float64 to float32 rounding
             * error on both the start and end angles, hence the factor of 2. Do not assume full circle if
             * start and end angles are close, but test here depends on combination of sign of angular
             * difference and wedge direction (clockwise/counterclockwise) to obtain the same results as on
             * canvas.
             */
            if (Math.abs(start_angle - end_angle) < 2 * math_1.float32_epsilon &&
                !(Math.abs(initial_diff) < 2 * math_1.float32_epsilon && initial_diff < 0)) {
                // Draw full ellipse. SVG elliptical arc cannot do this, so instead use two semi ellipses.
                const [tstart_x, tstart_y] = this._transform.apply(start_x, start_y);
                const dx = radius_x * Math.cos(start_angle + Math.PI);
                const dy = radius_y * Math.sin(start_angle + Math.PI);
                const [mid_x, mid_y] = transform.apply(dx, dy);
                const [tmid_x, tmid_y] = this._transform.apply(mid_x, mid_y);
                this.__addPathCommand(tstart_x, tstart_y, `A ${radius_x} ${radius_y} ${rotation_in_degrees} 0 ${sweep_flag} ${tmid_x} ${tmid_y} A ${radius_x} ${radius_y} ${rotation_in_degrees} 0 ${sweep_flag} ${tstart_x} ${tstart_y}`);
            }
            else {
                // Draw partial ellipse only.
                const dx = radius_x * Math.cos(end_angle);
                const dy = radius_y * Math.sin(end_angle);
                const [end_x, end_y] = transform.apply(dx, dy);
                let diff = end_angle - start_angle;
                // https://github.com/gliffy/canvas2svg/issues/4
                if (diff < 0) {
                    diff += 2 * Math.PI;
                }
                const large_arc_flag = (counterclockwise !== diff > Math.PI) ? 1 : 0; // imitation xor
                const [tend_x, tend_y] = this._transform.apply(end_x, end_y);
                this.__addPathCommand(tend_x, tend_y, `A ${radius_x} ${radius_y} ${rotation_in_degrees} ${large_arc_flag} ${sweep_flag} ${tend_x} ${tend_y}`);
            }
        }
        _clip_path = null;
        clip(path_or_fill_rule, fill_rule) {
            let path = null;
            if (path_or_fill_rule instanceof Path2D) {
                path = path_or_fill_rule;
            }
            else if (fill_rule == null) {
                fill_rule = path_or_fill_rule;
            }
            else {
                throw new Error("invalid arguments");
            }
            if (path != null) {
                throw new Error("not implemented");
            }
            const clip_path = this.__createElement("clipPath");
            const id = this._random_string();
            this.__applyCurrentDefaultPath();
            if (fill_rule != null) {
                this.__currentElement.setAttribute("clip-rule", fill_rule);
            }
            clip_path.setAttribute("id", id);
            clip_path.appendChild(this.__currentElement);
            this.__defs.appendChild(clip_path);
            this._clip_path = `url(#${id})`;
        }
        /**
          * Draws a canvas, image or mock context to this canvas.
          * Note that all svg dom manipulation uses node.childNodes rather than node.children for IE support.
          * http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-drawimage
          */
        drawImage(image, ...args) {
            let dx, dy;
            let dw, dh;
            let sx, sy;
            let sw, sh;
            if (args.length == 2) {
                [dx, dy] = args;
                if (!isFinite(dx + dy)) {
                    return;
                }
                sx = 0;
                sy = 0;
                const [w, h] = width_height(image);
                dw = sw = w;
                dh = sh = h;
            }
            else if (args.length == 4) {
                [dx, dy, dw, dh] = args;
                if (!isFinite(dx + dy + dw + dh)) {
                    return;
                }
                sx = 0;
                sy = 0;
                const [w, h] = width_height(image);
                sw = w;
                sh = h;
            }
            else if (args.length === 8) {
                [sx, sy, sw, sh, dx, dy, dw, dh] = args;
                if (!isFinite(sx + sy + sw + sh + dx + dy + dw + dh)) {
                    return;
                }
            }
            else {
                throw new Error(`Invalid number of arguments passed to drawImage: ${arguments.length}`);
            }
            // parent, svg, defs, group, currentElement, svgImage, canvas, context, id
            const parent = this.__root;
            const transform = this._transform.clone().translate(dx, dy);
            if (image instanceof SVGRenderingContext2D || image instanceof SVGSVGElement) {
                // In the future we may want to clone nodes instead.
                // also I'm currently ignoring dw, dh, sw, sh, sx, sy for a mock context.
                const svg_node = image instanceof SVGSVGElement ? image : image.get_svg();
                const svg = svg_node.cloneNode(true);
                let scope;
                if (transform.is_identity && this.globalAlpha == 1.0 && this._clip_path == null) {
                    scope = parent;
                }
                else {
                    scope = this.__createElement("g");
                    parent.appendChild(scope);
                    // `transform` affects `clip-path`, so if both are present, then apply
                    // them separately in `clip-path`, `transform` order.
                    if (this._clip_path != null) {
                        this._apply_clip_path(scope);
                        if (!transform.is_identity) {
                            const outer = scope;
                            scope = this.__createElement("g");
                            outer.appendChild(scope);
                        }
                    }
                    this._apply_transform(scope, transform);
                    this._apply_global_alpha(scope);
                }
                for (const child of [...svg.childNodes]) {
                    if (child instanceof SVGDefsElement) {
                        for (const def of [...child.childNodes]) {
                            if (def instanceof Element) {
                                const id = def.getAttribute("id");
                                this.__ids.add(id);
                                this.__defs.appendChild(def.cloneNode(true));
                            }
                        }
                    }
                    else {
                        scope.appendChild(child.cloneNode(true));
                    }
                }
            }
            else if (image instanceof HTMLImageElement || image instanceof SVGImageElement) {
                const svgImage = this.__createElement("image");
                svgImage.setAttribute("width", `${dw}`);
                svgImage.setAttribute("height", `${dh}`);
                svgImage.setAttribute("preserveAspectRatio", "none");
                if (this.globalAlpha != 1.0) {
                    svgImage.setAttribute("opacity", `${this.globalAlpha}`);
                }
                if (sx != 0 || sy != 0 || sw !== image.width || sh !== image.height) {
                    // crop the image using a temporary canvas
                    const canvas = this.__document.createElement("canvas");
                    canvas.width = dw;
                    canvas.height = dh;
                    const context = canvas.getContext("2d");
                    context.drawImage(image, sx, sy, sw, sh, 0, 0, dw, dh);
                    image = canvas;
                }
                this._apply_transform(svgImage, transform);
                const url = image instanceof HTMLCanvasElement ? image.toDataURL() : image.getAttribute("src");
                svgImage.setAttribute("href", url);
                if (this._clip_path != null) {
                    const scope = this.__createElement("g");
                    scope.setAttribute("clip-path", this._clip_path);
                    scope.appendChild(svgImage);
                    parent.appendChild(scope);
                }
                else {
                    parent.appendChild(svgImage);
                }
            }
            else if (image instanceof HTMLCanvasElement) {
                const svgImage = this.__createElement("image");
                svgImage.setAttribute("width", `${dw}`);
                svgImage.setAttribute("height", `${dh}`);
                svgImage.setAttribute("preserveAspectRatio", "none");
                if (this.globalAlpha != 1.0) {
                    svgImage.setAttribute("opacity", `${this.globalAlpha}`);
                }
                // draw canvas onto temporary canvas so that smoothing can be handled
                const canvas = this.__document.createElement("canvas");
                canvas.width = dw;
                canvas.height = dh;
                const context = canvas.getContext("2d");
                context.imageSmoothingEnabled = false;
                context.drawImage(image, sx, sy, sw, sh, 0, 0, dw, dh);
                image = canvas;
                this._apply_transform(svgImage, transform);
                svgImage.setAttribute("href", image.toDataURL());
                if (this._clip_path != null) {
                    const scope = this.__createElement("g");
                    scope.setAttribute("clip-path", this._clip_path);
                    scope.appendChild(svgImage);
                    parent.appendChild(scope);
                }
                else {
                    parent.appendChild(svgImage);
                }
            }
        }
        /**
          * Generates a pattern tag
          */
        createPattern(image, _repetition) {
            const pattern = this.__document.createElementNS("http://www.w3.org/2000/svg", "pattern");
            const id = this._random_string();
            const [width, height] = width_height(image);
            pattern.setAttribute("id", id);
            pattern.setAttribute("width", `${width}`);
            pattern.setAttribute("height", `${height}`);
            pattern.setAttribute("patternUnits", "userSpaceOnUse");
            if (image instanceof HTMLCanvasElement || image instanceof HTMLImageElement || image instanceof SVGImageElement) {
                const img = this.__document.createElementNS("http://www.w3.org/2000/svg", "image");
                const url = image instanceof HTMLCanvasElement ? image.toDataURL() : image.getAttribute("src");
                img.setAttribute("href", url);
                pattern.appendChild(img);
                this.__defs.appendChild(pattern);
            }
            else if (image instanceof SVGRenderingContext2D) {
                for (const child of [...image.__root.childNodes]) {
                    if (!(child instanceof SVGDefsElement)) {
                        pattern.appendChild(child.cloneNode(true));
                    }
                }
                //pattern.appendChild(image.__root.childNodes[1])
                this.__defs.appendChild(pattern);
            }
            else if (image instanceof SVGSVGElement) {
                for (const child of [...image.childNodes]) {
                    if (!(child instanceof SVGDefsElement)) {
                        pattern.appendChild(child.cloneNode(true));
                    }
                }
                //pattern.appendChild(image.__root.childNodes[1])
                this.__defs.appendChild(pattern);
            }
            else {
                throw new Error("unsupported");
            }
            return new CanvasPattern(pattern, this);
        }
        getLineDash() {
            const { lineDash } = this;
            if ((0, types_1.isString)(lineDash)) {
                return lineDash.split(",").map((v) => parseInt(v));
            }
            else if (lineDash == null) {
                return [];
            }
            else {
                return lineDash;
            }
        }
        setLineDash(segments) {
            if (segments.length > 0) {
                this.lineDash = segments.join(",");
            }
            else {
                this.lineDash = null;
            }
        }
        getTransform() {
            return this._transform.to_DOMMatrix();
        }
        setTransform(...args) {
            let matrix;
            if ((0, types_1.isNumber)(args[0])) {
                matrix = new DOMMatrix(args);
            }
            else if (args[0] instanceof DOMMatrix) {
                matrix = args[0];
            }
            else {
                matrix = new DOMMatrix(Object.values(args[0] == null));
            }
            this._transform = affine_1.AffineTransform.from_DOMMatrix(matrix);
        }
        resetTransform() {
            this._transform = new affine_1.AffineTransform();
        }
        isPointInPath(..._args) {
            throw new Error("not implemented");
        }
        isPointInStroke(..._args) {
            throw new Error("not implemented");
        }
        createImageData(..._args) {
            throw new Error("not implemented");
        }
        getImageData(_sx, _sy, _sw, _sh) {
            throw new Error("not implemented");
        }
        putImageData(..._args) {
            throw new Error("not implemented");
        }
        drawFocusIfNeeded(..._args) {
            throw new Error("not implemented");
        }
        scrollPathIntoView(..._args) {
            throw new Error("not implemented");
        }
    }
    exports.SVGRenderingContext2D = SVGRenderingContext2D;
},
/* core/util/affine.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.rotate_around = rotate_around;
    const eq_1 = require(27) /* ./eq */;
    const { sin, cos } = Math;
    class AffineTransform {
        a;
        b;
        c;
        d;
        e;
        f;
        constructor(a = 1, b = 0, c = 0, d = 1, e = 0, f = 0) {
            this.a = a;
            this.b = b;
            this.c = c;
            this.d = d;
            this.e = e;
            this.f = f;
        }
        toString() {
            const { a, b, c, d, e, f } = this;
            return `matrix(${a}, ${b}, ${c}, ${d}, ${e}, ${f})`;
        }
        static from_DOMMatrix(matrix) {
            const { a, b, c, d, e, f } = matrix;
            return new AffineTransform(a, b, c, d, e, f);
        }
        to_DOMMatrix() {
            const { a, b, c, d, e, f } = this;
            return new DOMMatrix([a, b, c, d, e, f]);
        }
        clone() {
            const { a, b, c, d, e, f } = this;
            return new AffineTransform(a, b, c, d, e, f);
        }
        [eq_1.equals](that, cmp) {
            return (cmp.eq(this.a, that.a) &&
                cmp.eq(this.b, that.b) &&
                cmp.eq(this.c, that.c) &&
                cmp.eq(this.d, that.d) &&
                cmp.eq(this.e, that.e) &&
                cmp.eq(this.f, that.f));
        }
        reset() {
            this.a = 1;
            this.b = 0;
            this.c = 0;
            this.d = 1;
            this.e = 0;
            this.f = 0;
        }
        get is_identity() {
            const { a, b, c, d, e, f } = this;
            return a == 1 && b == 0 && c == 0 && d == 1 && e == 0 && f == 0;
        }
        apply_point(p) {
            const [x, y] = this.apply(p.x, p.y);
            return { x, y };
        }
        apply_rect(rect) {
            const p0 = this.apply_point(rect.p0);
            const p1 = this.apply_point(rect.p1);
            const p2 = this.apply_point(rect.p2);
            const p3 = this.apply_point(rect.p3);
            return { p0, p1, p2, p3 };
        }
        apply(x, y) {
            const { a, b, c, d, e, f } = this;
            return [
                a * x + c * y + e,
                b * x + d * y + f,
            ];
        }
        iv_apply(xs, ys) {
            const { a, b, c, d, e, f } = this;
            const n = xs.length;
            for (let i = 0; i < n; i++) {
                const x = xs[i];
                const y = ys[i];
                xs[i] = a * x + c * y + e;
                ys[i] = b * x + d * y + f;
            }
        }
        transform(A, B, C, D, E, F) {
            const { a, b, c, d, e, f } = this;
            this.a = a * A + c * B;
            this.c = a * C + c * D;
            this.e = a * E + c * F + e;
            this.b = b * A + d * B;
            this.d = b * C + d * D;
            this.f = b * E + d * F + f;
            return this;
        }
        translate(tx, ty) {
            return this.transform(1, 0, 0, 1, tx, ty);
        }
        scale(cx, cy) {
            return this.transform(cx, 0, 0, cy, 0, 0);
        }
        skew(sx, sy) {
            return this.transform(1, sy, sx, 1, 0, 0);
        }
        rotate(angle) {
            if (angle == 0) {
                return this;
            }
            const s = sin(angle);
            const c = cos(angle);
            return this.transform(c, s, -s, c, 0, 0);
        }
        rotate_ccw(angle) {
            return this.rotate(-angle);
        }
        rotate_around(x, y, angle) {
            this.translate(x, y);
            this.rotate(angle);
            this.translate(-x, -y);
            return this;
        }
        translate_x(tx) {
            return this.translate(tx, 0);
        }
        translate_y(ty) {
            return this.translate(0, ty);
        }
        flip() {
            return this.scale(-1, -1);
        }
        flip_x() {
            return this.scale(1, -1);
        }
        flip_y() {
            return this.scale(-1, 1);
        }
        inverse() {
            return AffineTransform.from_DOMMatrix(this.to_DOMMatrix().inverse());
        }
    }
    exports.AffineTransform = AffineTransform;
    function rotate_around(point, center, angle) {
        if (angle == 0) {
            return point;
        }
        else {
            const tr = new AffineTransform();
            tr.rotate_around(center.x, center.y, angle);
            const [x, y] = tr.apply(point.x, point.y);
            return { x, y };
        }
    }
},
/* core/util/random.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const { PI, log, sin, cos, sqrt, floor } = Math;
    exports.MAX_INT32 = 2147483647;
    class AbstractRandom {
        float() {
            return (this.integer() - 1) / (exports.MAX_INT32 - 1);
        }
        floats(n, a = 0, b = 1) {
            const result = new Array(n);
            for (let i = 0; i < n; i++) {
                result[i] = a + this.float() * (b - a);
            }
            return result;
        }
        choices(n, items) {
            const k = items.length;
            const result = new Array(n);
            for (let i = 0; i < n; i++) {
                result[i] = items[this.integer() % k];
            }
            return result;
        }
        uniform(loc, scale) {
            return loc + (this.float() - 0.5) * scale;
        }
        uniforms(loc, scale, size) {
            return Float64Array.from({ length: size }, () => this.uniform(loc, scale));
        }
        normal(loc, scale) {
            return this.normals(loc, scale, 1)[0];
        }
        normals(loc, scale, size) {
            const [mu, sigma] = [loc, scale];
            const array = new Float64Array(size);
            for (let i = 0; i < size; i += 2) {
                // Box-Muller transform from uniform to normal distribution.
                const u = this.float();
                const v = this.float();
                const common = sqrt(-2.0 * log(u));
                array[i] = mu + sigma * (common * cos(2.0 * PI * v));
                if (i + 1 < size) {
                    array[i + 1] = mu + sigma * (common * sin(2.0 * PI * v));
                }
            }
            return array;
        }
    }
    exports.AbstractRandom = AbstractRandom;
    class SystemRandom extends AbstractRandom {
        integer() {
            return floor(Math.random() * exports.MAX_INT32);
        }
    }
    exports.SystemRandom = SystemRandom;
    // Park-Miller LCG
    class LCGRandom extends AbstractRandom {
        _seed;
        constructor(seed) {
            super();
            this._seed = seed % exports.MAX_INT32;
            if (this._seed <= 0) {
                this._seed += exports.MAX_INT32 - 1;
            }
        }
        integer() {
            this._seed = (48271 * this._seed) % exports.MAX_INT32;
            return this._seed;
        }
    }
    exports.LCGRandom = LCGRandom;
    class Random extends LCGRandom {
    } // for compatibility
    exports.Random = Random;
    exports.random = new Random(Date.now());
},
/* styles/ui.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = `:host{position:relative;pointer-events:auto;}`;
},
/* styles/icons.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.tool_icon_dark_theme = exports.tool_icon_light_theme = exports.tool_icon_list = exports.tool_icon_square_check = exports.tool_icon_square = exports.tool_icon_check = exports.tool_icon_text_align_right = exports.tool_icon_text_align_center = exports.tool_icon_text_align_left = exports.tool_icon_italic = exports.tool_icon_bold = exports.tool_icon_delete = exports.tool_icon_pointer = exports.tool_icon_unpin = exports.tool_icon_pin = exports.tool_icon_maximize = exports.tool_icon_minimize = exports.tool_icon_arrow_up_from_bar = exports.tool_icon_arrow_down_to_bar = exports.tool_icon_y_grip = exports.tool_icon_x_grip = exports.tool_icon_see_off = exports.tool_icon_see_on = exports.tool_icon_caret_right = exports.tool_icon_caret_left = exports.tool_icon_caret_down = exports.tool_icon_caret_up = exports.tool_icon_chevron_right = exports.tool_icon_chevron_left = void 0;
    exports.tool_icon_copy = "bk-tool-icon-copy";
    exports.tool_icon_open = "bk-tool-icon-open";
    exports.tool_icon_replace_mode = "bk-tool-icon-replace-mode";
    exports.tool_icon_toggle_mode = "bk-tool-icon-toggle-mode";
    exports.tool_icon_append_mode = "bk-tool-icon-append-mode";
    exports.tool_icon_intersect_mode = "bk-tool-icon-intersect-mode";
    exports.tool_icon_subtract_mode = "bk-tool-icon-subtract-mode";
    exports.tool_icon_xor_mode = "bk-tool-icon-xor-mode";
    exports.tool_icon_invert_selection = "bk-tool-icon-invert-selection";
    exports.tool_icon_clear_selection = "bk-tool-icon-clear-selection";
    exports.tool_icon_box_select = "bk-tool-icon-box-select";
    exports.tool_icon_x_box_select = "bk-tool-icon-x-box-select";
    exports.tool_icon_y_box_select = "bk-tool-icon-y-box-select";
    exports.tool_icon_box_zoom = "bk-tool-icon-box-zoom";
    exports.tool_icon_x_box_zoom = "bk-tool-icon-x-box-zoom";
    exports.tool_icon_y_box_zoom = "bk-tool-icon-y-box-zoom";
    exports.tool_icon_auto_box_zoom = "bk-tool-icon-auto-box-zoom";
    exports.tool_icon_zoom_in = "bk-tool-icon-zoom-in";
    exports.tool_icon_zoom_out = "bk-tool-icon-zoom-out";
    exports.tool_icon_help = "bk-tool-icon-help";
    exports.tool_icon_hover = "bk-tool-icon-hover";
    exports.tool_icon_crosshair = "bk-tool-icon-crosshair";
    exports.tool_icon_lasso_select = "bk-tool-icon-lasso-select";
    exports.tool_icon_pan = "bk-tool-icon-pan";
    exports.tool_icon_x_pan = "bk-tool-icon-x-pan";
    exports.tool_icon_y_pan = "bk-tool-icon-y-pan";
    exports.tool_icon_pan_left = "bk-tool-icon-pan-left";
    exports.tool_icon_pan_right = "bk-tool-icon-pan-right";
    exports.tool_icon_pan_up = "bk-tool-icon-pan-up";
    exports.tool_icon_pan_down = "bk-tool-icon-pan-down";
    exports.tool_icon_range = "bk-tool-icon-range";
    exports.tool_icon_polygon_select = "bk-tool-icon-polygon-select";
    exports.tool_icon_redo = "bk-tool-icon-redo";
    exports.tool_icon_reset = "bk-tool-icon-reset";
    exports.tool_icon_save = "bk-tool-icon-save";
    exports.tool_icon_tap_select = "bk-tool-icon-tap-select";
    exports.tool_icon_undo = "bk-tool-icon-undo";
    exports.tool_icon_wheel_pan = "bk-tool-icon-wheel-pan";
    exports.tool_icon_wheel_zoom = "bk-tool-icon-wheel-zoom";
    exports.tool_icon_box_edit = "bk-tool-icon-box-edit";
    exports.tool_icon_freehand_draw = "bk-tool-icon-freehand-draw";
    exports.tool_icon_poly_draw = "bk-tool-icon-poly-draw";
    exports.tool_icon_point_draw = "bk-tool-icon-point-draw";
    exports.tool_icon_poly_edit = "bk-tool-icon-poly-edit";
    exports.tool_icon_line_edit = "bk-tool-icon-line-edit";
    exports.tool_icon_settings = "bk-tool-icon-settings";
    exports.tool_icon_unknown = "bk-tool-icon-unknown";
    exports.tool_icon_fullscreen = "bk-tool-icon-fullscreen";
    exports.tool_icon_chevron_up = "bk-tool-icon-chevron-up";
    exports.tool_icon_chevron_down = "bk-tool-icon-chevron-down";
    exports.tool_icon_chevron_left = "bk-tool-icon-chevron-left";
    exports.tool_icon_chevron_right = "bk-tool-icon-chevron-right";
    exports.tool_icon_caret_up = "bk-tool-icon-caret-up";
    exports.tool_icon_caret_down = "bk-tool-icon-caret-down";
    exports.tool_icon_caret_left = "bk-tool-icon-caret-left";
    exports.tool_icon_caret_right = "bk-tool-icon-caret-right";
    exports.tool_icon_see_on = "bk-tool-icon-see-on";
    exports.tool_icon_see_off = "bk-tool-icon-see-off";
    exports.tool_icon_x_grip = "bk-tool-icon-x-grip";
    exports.tool_icon_y_grip = "bk-tool-icon-y-grip";
    exports.tool_icon_arrow_down_to_bar = "bk-tool-icon-arrow-down-to-bar";
    exports.tool_icon_arrow_up_from_bar = "bk-tool-icon-arrow-up-from-bar";
    exports.tool_icon_minimize = "bk-tool-icon-minimize";
    exports.tool_icon_maximize = "bk-tool-icon-maximize";
    exports.tool_icon_pin = "bk-tool-icon-pin";
    exports.tool_icon_unpin = "bk-tool-icon-unpin";
    exports.tool_icon_pointer = "bk-tool-icon-pointer";
    exports.tool_icon_delete = "bk-tool-icon-delete";
    exports.tool_icon_bold = "bk-tool-icon-bold";
    exports.tool_icon_italic = "bk-tool-icon-italic";
    exports.tool_icon_text_align_left = "bk-tool-icon-text-align-left";
    exports.tool_icon_text_align_center = "bk-tool-icon-text-align-center";
    exports.tool_icon_text_align_right = "bk-tool-icon-text-align-right";
    exports.tool_icon_check = "bk-tool-icon-check";
    exports.tool_icon_square = "bk-tool-icon-square";
    exports.tool_icon_square_check = "bk-tool-icon-square-check";
    exports.tool_icon_list = "bk-tool-icon-list";
    exports.tool_icon_light_theme = "bk-tool-icon-light-theme";
    exports.tool_icon_dark_theme = "bk-tool-icon-dark-theme";
    exports.default = `.bk-tool-icon-copy{background-color:var(--icon-color);mask-image:var(--bokeh-icon-copy);-webkit-mask-image:var(--bokeh-icon-copy);}.bk-tool-icon-open{background-color:var(--icon-color);mask-image:var(--bokeh-icon-open);-webkit-mask-image:var(--bokeh-icon-open);}.bk-tool-icon-replace-mode{background-color:var(--icon-color);mask-image:var(--bokeh-icon-replace-mode);-webkit-mask-image:var(--bokeh-icon-replace-mode);}.bk-tool-icon-toggle-mode{background-color:var(--icon-color);mask-image:var(--bokeh-icon-toggle-mode);-webkit-mask-image:var(--bokeh-icon-toggle-mode);}.bk-tool-icon-append-mode{background-color:var(--icon-color);mask-image:var(--bokeh-icon-append-mode);-webkit-mask-image:var(--bokeh-icon-append-mode);}.bk-tool-icon-intersect-mode{background-color:var(--icon-color);mask-image:var(--bokeh-icon-intersect-mode);-webkit-mask-image:var(--bokeh-icon-intersect-mode);}.bk-tool-icon-subtract-mode{background-color:var(--icon-color);mask-image:var(--bokeh-icon-subtract-mode);-webkit-mask-image:var(--bokeh-icon-subtract-mode);}.bk-tool-icon-xor-mode{background-color:var(--icon-color);mask-image:var(--bokeh-icon-xor-mode);-webkit-mask-image:var(--bokeh-icon-xor-mode);}.bk-tool-icon-invert-selection{background-color:var(--icon-color);mask-image:var(--bokeh-icon-invert-selection);-webkit-mask-image:var(--bokeh-icon-invert-selection);}.bk-tool-icon-clear-selection{background-color:var(--icon-color);mask-image:var(--bokeh-icon-clear-selection);-webkit-mask-image:var(--bokeh-icon-clear-selection);}.bk-tool-icon-box-select{background-color:var(--icon-color);mask-image:var(--bokeh-icon-box-select);-webkit-mask-image:var(--bokeh-icon-box-select);}.bk-tool-icon-x-box-select{background-color:var(--icon-color);mask-image:var(--bokeh-icon-x-box-select);-webkit-mask-image:var(--bokeh-icon-x-box-select);}.bk-tool-icon-y-box-select{background-color:var(--icon-color);mask-image:var(--bokeh-icon-y-box-select);-webkit-mask-image:var(--bokeh-icon-y-box-select);}.bk-tool-icon-box-zoom{background-color:var(--icon-color);mask-image:var(--bokeh-icon-box-zoom);-webkit-mask-image:var(--bokeh-icon-box-zoom);}.bk-tool-icon-x-box-zoom{background-color:var(--icon-color);mask-image:var(--bokeh-icon-x-box-zoom);-webkit-mask-image:var(--bokeh-icon-x-box-zoom);}.bk-tool-icon-y-box-zoom{background-color:var(--icon-color);mask-image:var(--bokeh-icon-y-box-zoom);-webkit-mask-image:var(--bokeh-icon-y-box-zoom);}.bk-tool-icon-auto-box-zoom{background-color:var(--icon-color);mask-image:var(--bokeh-icon-auto-box-zoom);-webkit-mask-image:var(--bokeh-icon-auto-box-zoom);}.bk-tool-icon-zoom-in{background-color:var(--icon-color);mask-image:var(--bokeh-icon-zoom-in);-webkit-mask-image:var(--bokeh-icon-zoom-in);}.bk-tool-icon-zoom-out{background-color:var(--icon-color);mask-image:var(--bokeh-icon-zoom-out);-webkit-mask-image:var(--bokeh-icon-zoom-out);}.bk-tool-icon-help{background-color:var(--icon-color);mask-image:var(--bokeh-icon-help);-webkit-mask-image:var(--bokeh-icon-help);}.bk-tool-icon-hover{background-color:var(--icon-color);mask-image:var(--bokeh-icon-hover);-webkit-mask-image:var(--bokeh-icon-hover);}.bk-tool-icon-crosshair{background-color:var(--icon-color);mask-image:var(--bokeh-icon-crosshair);-webkit-mask-image:var(--bokeh-icon-crosshair);}.bk-tool-icon-lasso-select{background-color:var(--icon-color);mask-image:var(--bokeh-icon-lasso-select);-webkit-mask-image:var(--bokeh-icon-lasso-select);}.bk-tool-icon-pan{background-color:var(--icon-color);mask-image:var(--bokeh-icon-pan);-webkit-mask-image:var(--bokeh-icon-pan);}.bk-tool-icon-x-pan{background-color:var(--icon-color);mask-image:var(--bokeh-icon-x-pan);-webkit-mask-image:var(--bokeh-icon-x-pan);}.bk-tool-icon-y-pan{background-color:var(--icon-color);mask-image:var(--bokeh-icon-y-pan);-webkit-mask-image:var(--bokeh-icon-y-pan);}.bk-tool-icon-pan-left{background-color:var(--icon-color);mask-image:var(--bokeh-icon-pan-left);-webkit-mask-image:var(--bokeh-icon-pan-left);}.bk-tool-icon-pan-right{background-color:var(--icon-color);mask-image:var(--bokeh-icon-pan-right);-webkit-mask-image:var(--bokeh-icon-pan-right);}.bk-tool-icon-pan-up{background-color:var(--icon-color);mask-image:var(--bokeh-icon-pan-up);-webkit-mask-image:var(--bokeh-icon-pan-up);}.bk-tool-icon-pan-down{background-color:var(--icon-color);mask-image:var(--bokeh-icon-pan-down);-webkit-mask-image:var(--bokeh-icon-pan-down);}.bk-tool-icon-range{background-color:var(--icon-color);mask-image:var(--bokeh-icon-range);-webkit-mask-image:var(--bokeh-icon-range);}.bk-tool-icon-polygon-select{background-color:var(--icon-color);mask-image:var(--bokeh-icon-polygon-select);-webkit-mask-image:var(--bokeh-icon-polygon-select);}.bk-tool-icon-redo{background-color:var(--icon-color);mask-image:var(--bokeh-icon-redo);-webkit-mask-image:var(--bokeh-icon-redo);}.bk-tool-icon-reset{background-color:var(--icon-color);mask-image:var(--bokeh-icon-reset);-webkit-mask-image:var(--bokeh-icon-reset);}.bk-tool-icon-save{background-color:var(--icon-color);mask-image:var(--bokeh-icon-save);-webkit-mask-image:var(--bokeh-icon-save);}.bk-tool-icon-tap-select{background-color:var(--icon-color);mask-image:var(--bokeh-icon-tap-select);-webkit-mask-image:var(--bokeh-icon-tap-select);}.bk-tool-icon-undo{background-color:var(--icon-color);mask-image:var(--bokeh-icon-undo);-webkit-mask-image:var(--bokeh-icon-undo);}.bk-tool-icon-wheel-pan{background-color:var(--icon-color);mask-image:var(--bokeh-icon-wheel-pan);-webkit-mask-image:var(--bokeh-icon-wheel-pan);}.bk-tool-icon-wheel-zoom{background-color:var(--icon-color);mask-image:var(--bokeh-icon-wheel-zoom);-webkit-mask-image:var(--bokeh-icon-wheel-zoom);}.bk-tool-icon-box-edit{background-color:var(--icon-color);mask-image:var(--bokeh-icon-box-edit);-webkit-mask-image:var(--bokeh-icon-box-edit);}.bk-tool-icon-freehand-draw{background-color:var(--icon-color);mask-image:var(--bokeh-icon-freehand-draw);-webkit-mask-image:var(--bokeh-icon-freehand-draw);}.bk-tool-icon-poly-draw{background-color:var(--icon-color);mask-image:var(--bokeh-icon-poly-draw);-webkit-mask-image:var(--bokeh-icon-poly-draw);}.bk-tool-icon-point-draw{background-color:var(--icon-color);mask-image:var(--bokeh-icon-point-draw);-webkit-mask-image:var(--bokeh-icon-point-draw);}.bk-tool-icon-poly-edit{background-color:var(--icon-color);mask-image:var(--bokeh-icon-poly-edit);-webkit-mask-image:var(--bokeh-icon-poly-edit);}.bk-tool-icon-line-edit{background-color:var(--icon-color);mask-image:var(--bokeh-icon-line-edit);-webkit-mask-image:var(--bokeh-icon-line-edit);}.bk-tool-icon-settings{background-color:var(--icon-color);mask-image:var(--bokeh-icon-settings);-webkit-mask-image:var(--bokeh-icon-settings);}.bk-tool-icon-unknown{background-color:var(--icon-color);mask-image:var(--bokeh-icon-unknown);-webkit-mask-image:var(--bokeh-icon-unknown);}.bk-tool-icon-fullscreen{background-color:var(--icon-color);mask-image:var(--bokeh-icon-fullscreen);-webkit-mask-image:var(--bokeh-icon-fullscreen);}.bk-tool-icon-chevron-up{background-color:var(--icon-color);mask-image:var(--bokeh-icon-chevron-up);-webkit-mask-image:var(--bokeh-icon-chevron-up);}.bk-tool-icon-chevron-down{background-color:var(--icon-color);mask-image:var(--bokeh-icon-chevron-down);-webkit-mask-image:var(--bokeh-icon-chevron-down);}.bk-tool-icon-chevron-left{background-color:var(--icon-color);mask-image:var(--bokeh-icon-chevron-left);-webkit-mask-image:var(--bokeh-icon-chevron-left);}.bk-tool-icon-chevron-right{background-color:var(--icon-color);mask-image:var(--bokeh-icon-chevron-right);-webkit-mask-image:var(--bokeh-icon-chevron-right);}.bk-tool-icon-caret-up{background-color:var(--icon-color);mask-image:var(--bokeh-icon-caret-up);-webkit-mask-image:var(--bokeh-icon-caret-up);}.bk-tool-icon-caret-down{background-color:var(--icon-color);mask-image:var(--bokeh-icon-caret-down);-webkit-mask-image:var(--bokeh-icon-caret-down);}.bk-tool-icon-caret-left{background-color:var(--icon-color);mask-image:var(--bokeh-icon-caret-left);-webkit-mask-image:var(--bokeh-icon-caret-left);}.bk-tool-icon-caret-right{background-color:var(--icon-color);mask-image:var(--bokeh-icon-caret-right);-webkit-mask-image:var(--bokeh-icon-caret-right);}.bk-tool-icon-see-on{background-color:var(--icon-color);mask-image:var(--bokeh-icon-see-on);-webkit-mask-image:var(--bokeh-icon-see-on);}.bk-tool-icon-see-off{background-color:var(--icon-color);mask-image:var(--bokeh-icon-see-off);-webkit-mask-image:var(--bokeh-icon-see-off);}.bk-tool-icon-x-grip{background-color:var(--icon-color);mask-image:var(--bokeh-icon-x-grip);-webkit-mask-image:var(--bokeh-icon-x-grip);}.bk-tool-icon-y-grip{background-color:var(--icon-color);mask-image:var(--bokeh-icon-y-grip);-webkit-mask-image:var(--bokeh-icon-y-grip);}.bk-tool-icon-arrow-down-to-bar{background-color:var(--icon-color);mask-image:var(--bokeh-icon-arrow-down-to-bar);-webkit-mask-image:var(--bokeh-icon-arrow-down-to-bar);}.bk-tool-icon-arrow-up-from-bar{background-color:var(--icon-color);mask-image:var(--bokeh-icon-arrow-up-from-bar);-webkit-mask-image:var(--bokeh-icon-arrow-up-from-bar);}.bk-tool-icon-minimize{background-color:var(--icon-color);mask-image:var(--bokeh-icon-minimize);-webkit-mask-image:var(--bokeh-icon-minimize);}.bk-tool-icon-maximize{background-color:var(--icon-color);mask-image:var(--bokeh-icon-maximize);-webkit-mask-image:var(--bokeh-icon-maximize);}.bk-tool-icon-pin{background-color:var(--icon-color);mask-image:var(--bokeh-icon-pin);-webkit-mask-image:var(--bokeh-icon-pin);}.bk-tool-icon-unpin{background-color:var(--icon-color);mask-image:var(--bokeh-icon-unpin);-webkit-mask-image:var(--bokeh-icon-unpin);}.bk-tool-icon-pointer{background-color:var(--icon-color);mask-image:var(--bokeh-icon-hand-pointing);-webkit-mask-image:var(--bokeh-icon-hand-pointing);}.bk-tool-icon-delete{background-color:var(--icon-color);mask-image:var(--bokeh-icon-trash);-webkit-mask-image:var(--bokeh-icon-trash);}.bk-tool-icon-bold{background-color:var(--icon-color);mask-image:var(--bokeh-icon-bold);-webkit-mask-image:var(--bokeh-icon-bold);}.bk-tool-icon-italic{background-color:var(--icon-color);mask-image:var(--bokeh-icon-italic);-webkit-mask-image:var(--bokeh-icon-italic);}.bk-tool-icon-text-align-left{background-color:var(--icon-color);mask-image:var(--bokeh-icon-text-align-left);-webkit-mask-image:var(--bokeh-icon-text-align-left);}.bk-tool-icon-text-align-center{background-color:var(--icon-color);mask-image:var(--bokeh-icon-text-align-center);-webkit-mask-image:var(--bokeh-icon-text-align-center);}.bk-tool-icon-text-align-right{background-color:var(--icon-color);mask-image:var(--bokeh-icon-text-align-right);-webkit-mask-image:var(--bokeh-icon-text-align-right);}.bk-tool-icon-check{background-color:var(--icon-color);mask-image:var(--bokeh-icon-check);-webkit-mask-image:var(--bokeh-icon-check);}.bk-tool-icon-square{background-color:var(--icon-color);mask-image:var(--bokeh-icon-square);-webkit-mask-image:var(--bokeh-icon-square);}.bk-tool-icon-square-check{background-color:var(--icon-color);mask-image:var(--bokeh-icon-square-check);-webkit-mask-image:var(--bokeh-icon-square-check);}.bk-tool-icon-list{background-color:var(--icon-color);mask-image:var(--bokeh-icon-list);-webkit-mask-image:var(--bokeh-icon-list);}.bk-tool-icon-light-theme{background-color:var(--icon-color);mask-image:var(--bokeh-icon-light-theme);-webkit-mask-image:var(--bokeh-icon-light-theme);}.bk-tool-icon-dark-theme{background-color:var(--icon-color);mask-image:var(--bokeh-icon-dark-theme);-webkit-mask-image:var(--bokeh-icon-dark-theme);}:host{--bokeh-icon-question-mark:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M8%208a3.5%203%200%200%201%203.5%20-3h1a3.5%203%200%200%201%203.5%203a3%203%200%200%201%20-2%203a3%204%200%200%200%20-2%204%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2212%22%20y1%3D%2219%22%20x2%3D%2212%22%20y2%3D%2219.01%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-help:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Ccircle%20cx%3D%2212%22%20cy%3D%2212%22%20r%3D%229%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2212%22%20y1%3D%2217%22%20x2%3D%2212%22%20y2%3D%2217.01%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2013.5a1.5%201.5%200%200%201%201%20-1.5a2.6%202.6%200%201%200%20-3%20-4%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-x:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M18%206l-12%2012%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%206l12%2012%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-settings:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M10.325%204.317c.426%20-1.756%202.924%20-1.756%203.35%200a1.724%201.724%200%200%200%202.573%201.066c1.543%20-.94%203.31%20.826%202.37%202.37a1.724%201.724%200%200%200%201.065%202.572c1.756%20.426%201.756%202.924%200%203.35a1.724%201.724%200%200%200%20-1.066%202.573c.94%201.543%20-.826%203.31%20-2.37%202.37a1.724%201.724%200%200%200%20-2.572%201.065c-.426%201.756%20-2.924%201.756%20-3.35%200a1.724%201.724%200%200%200%20-2.573%20-1.066c-1.543%20.94%20-3.31%20-.826%20-2.37%20-2.37a1.724%201.724%200%200%200%20-1.065%20-2.572c-1.756%20-.426%20-1.756%20-2.924%200%20-3.35a1.724%201.724%200%200%200%201.066%20-2.573c-.94%20-1.543%20.826%20-3.31%202.37%20-2.37c1%20.608%202.296%20.07%202.572%20-1.065z%22%3E%3C%2Fpath%3E%0A%20%20%3Ccircle%20cx%3D%2212%22%20cy%3D%2212%22%20r%3D%223%22%3E%3C%2Fcircle%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-unknown:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M14%203v4a1%201%200%200%200%201%201h4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M17%2021h-10a2%202%200%200%201%20-2%20-2v-14a2%202%200%200%201%202%20-2h7l5%205v11a2%202%200%200%201%20-2%202z%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2017v.01%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2014a1.5%201.5%200%201%200%20-1.14%20-2.474%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-fullscreen:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Crect%20x%3D%223%22%20y%3D%2216%22%20width%3D%225%22%20height%3D%225%22%20rx%3D%221%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M4%2012v-6a2%202%200%200%201%202%20-2h12a2%202%200%200%201%202%202v12a2%202%200%200%201%20-2%202h-6%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%208h4v4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M16%208l-5%205%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-save:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4%2017v2a2%202%200%200%200%202%202h12a2%202%200%200%200%202%20-2v-2%22%20%2F%3E%0A%20%20%3Cpolyline%20points%3D%227%2011%2012%2016%2017%2011%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2212%22%20y1%3D%224%22%20x2%3D%2212%22%20y2%3D%2216%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-copy:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Crect%20x%3D%228%22%20y%3D%228%22%20width%3D%2212%22%20height%3D%2212%22%20rx%3D%222%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M16%208v-2a2%202%200%200%200%20-2%20-2h-8a2%202%200%200%200%20-2%202v8a2%202%200%200%200%202%202h2%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-open:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22currentColor%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M9%204h3l2%202h5a2%202%200%200%201%202%202v7a2%202%200%200%201%20-2%202h-10a2%202%200%200%201%20-2%20-2v-9a2%202%200%200%201%202%20-2%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M17%2017v2a2%202%200%200%201%20-2%202h-10a2%202%200%200%201%20-2%20-2v-9a2%202%200%200%201%202%20-2h2%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-tap-select:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cline%20x1%3D%223%22%20y1%3D%2212%22%20x2%3D%226%22%20y2%3D%2212%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2212%22%20y1%3D%223%22%20x2%3D%2212%22%20y2%3D%226%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%227.8%22%20y1%3D%227.8%22%20x2%3D%225.6%22%20y2%3D%225.6%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2216.2%22%20y1%3D%227.8%22%20x2%3D%2218.4%22%20y2%3D%225.6%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%227.8%22%20y1%3D%2216.2%22%20x2%3D%225.6%22%20y2%3D%2218.4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2012l9%203l-4%202l-2%204l-3%20-9%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-lasso-select:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4.028%2013.252c-.657%20-.972%20-1.028%20-2.078%20-1.028%20-3.252c0%20-3.866%204.03%20-7%209%20-7s9%203.134%209%207s-4.03%207%20-9%207c-1.913%200%20-3.686%20-.464%20-5.144%20-1.255%22%20%2F%3E%0A%20%20%3Ccircle%20cx%3D%225%22%20cy%3D%2215%22%20r%3D%222%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M5%2017c0%201.42%20.316%202.805%201%204%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-polygon-select:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M21.0003%2011.341L18.6863%204.27072L5.18848%205.42767L4.03152%2019.6968L12.664%2018.2014%22%20stroke-dasharray%3D%220.01%203.5%22%2F%3E%0A%20%20%3Cpath%20d%3D%22M14.7174%2018.8084C14.7166%2018.9614%2014.7627%2019.111%2014.8494%2019.2371C14.936%2019.3631%2015.0592%2019.4597%2015.2023%2019.5138C15.3455%2019.5679%2015.5017%2019.5769%2015.6501%2019.5396C15.7985%2019.5024%2015.9319%2019.4207%2016.0326%2019.3054L17.7357%2017.7103L20.0454%2021.3822C20.092%2021.4564%2020.1528%2021.5206%2020.2243%2021.5713C20.2957%2021.6219%2020.3765%2021.658%2020.4619%2021.6774C20.5473%2021.6969%2020.6357%2021.6993%2020.722%2021.6846C20.8084%2021.6699%2020.891%2021.6383%2020.9651%2021.5917L21.7486%2021.0989C21.8227%2021.0522%2021.8869%2020.9914%2021.9376%2020.92C21.9883%2020.8485%2022.0243%2020.7678%2022.0438%2020.6824C22.0632%2020.597%2022.0657%2020.5086%2022.051%2020.4222C22.0362%2020.3359%2022.0047%2020.2533%2021.958%2020.1791L19.6484%2016.5073L21.8358%2015.6655C21.9833%2015.6247%2022.1147%2015.5397%2022.2125%2015.422C22.3103%2015.3044%2022.3698%2015.1596%2022.383%2015.0071C22.3961%2014.8547%2022.3624%2014.7018%2022.2862%2014.5691C22.21%2014.4364%2022.095%2014.3302%2021.9567%2014.2647L14.2205%2010L14.7174%2018.8084Z%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-pan:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M18%209l3%203l-3%203%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%209l-3%203l3%203%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M9%2018l3%203l3%20-3%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%206l-3%20-3l-3%203%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2012h9%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%2012h9%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2012v9%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%203v9%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-x-pan:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M18%209l3%203l-3%203%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%209l-3%203l3%203%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2012h9%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%2012h9%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-y-pan:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M9%2018l3%203l3%20-3%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%206l-3%20-3l-3%203%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2012v9%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%203v9%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-pan-left:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22currentColor%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M20%2015h-8v3.586a1%201%200%200%201%20-1.707%20.707l-6.586%20-6.586a1%201%200%200%201%200%20-1.414l6.586%20-6.586a1%201%200%200%201%201.707%20.707v3.586h8a1%201%200%200%201%201%201v4a1%201%200%200%201%20-1%201z%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-pan-right:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22currentColor%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4%209h8v-3.586a1%201%200%200%201%201.707%20-.707l6.586%206.586a1%201%200%200%201%200%201.414l-6.586%206.586a1%201%200%200%201%20-1.707%20-.707v-3.586h-8a1%201%200%200%201%20-1%20-1v-4a1%201%200%200%201%201%20-1z%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-pan-up:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22currentColor%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M9%2020v-8h-3.586a1%201%200%200%201%20-.707%20-1.707l6.586%20-6.586a1%201%200%200%201%201.414%200l6.586%206.586a1%201%200%200%201%20-.707%201.707h-3.586v8a1%201%200%200%201%20-1%201h-4a1%201%200%200%201%20-1%20-1z%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-pan-down:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22currentColor%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M15%204v8h3.586a1%201%200%200%201%20.707%201.707l-6.586%206.586a1%201%200%200%201%20-1.414%200l-6.586%20-6.586a1%201%200%200%201%20.707%20-1.707h3.586v-8a1%201%200%200%201%201%20-1h4a1%201%200%200%201%201%201z%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-wheel-pan:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M14.5%207L17%209.5M17%209.5L14.5%2012M17%209.5H12M4.5%207L2%209.5M2%209.5L4.5%2012M2%209.5H7M7%2014.5L9.5%2017M9.5%2017L12%2014.5M9.5%2017V12M12%204.5L9.5%202M9.5%202L7%204.5M9.5%202V7%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15.5%2015.1519C15.5%2014.5812%2015.7267%2014.0338%2016.1303%2013.6303C16.5338%2013.2267%2017.0812%2013%2017.6519%2013H19.8037C20.3744%2013%2020.9218%2013.2267%2021.3253%2013.6303C21.7289%2014.0338%2021.9556%2014.5812%2021.9556%2015.1519V20.5315C21.9556%2021.1022%2021.7289%2021.6496%2021.3253%2022.0531C20.9218%2022.4567%2020.3744%2022.6834%2019.8037%2022.6834H17.6519C17.0812%2022.6834%2016.5338%2022.4567%2016.1303%2022.0531C15.7267%2021.6496%2015.5%2021.1022%2015.5%2020.5315V15.1519Z%22%20fill%3D%22currentColor%22%20fill-opacity%3D%220.4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M18.7278%2016V18.0541Z%22%20fill%3D%22currentColor%22%20fill-opacity%3D%220.4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M18.7278%2016V18.0541M15.5%2015.1519C15.5%2014.5812%2015.7267%2014.0338%2016.1303%2013.6303C16.5338%2013.2267%2017.0812%2013%2017.6519%2013H19.8037C20.3744%2013%2020.9218%2013.2267%2021.3253%2013.6303C21.7289%2014.0338%2021.9556%2014.5812%2021.9556%2015.1519V20.5315C21.9556%2021.1022%2021.7289%2021.6496%2021.3253%2022.0531C20.9218%2022.4567%2020.3744%2022.6834%2019.8037%2022.6834H17.6519C17.0812%2022.6834%2016.5338%2022.4567%2016.1303%2022.0531C15.7267%2021.6496%2015.5%2021.1022%2015.5%2020.5315V15.1519Z%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-box-select:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4%206v-1a1%201%200%200%201%201%20-1h1m5%200h2m5%200h1a1%201%200%200%201%201%201v1m0%205v2m0%205v1a1%201%200%200%201%20-1%201h-1m-5%200h-2m-5%200h-1a1%201%200%200%201%20-1%20-1v-1m0%20-5v-2%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-x-box-select:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M17%2013l-4%204%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M13%2013l4%204%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M4%206v-1a1%201%200%200%201%201%20-1h1m5%200h2m5%200h1a1%201%200%200%201%201%201v1m0%205v2m0%205v1a1%201%200%200%201%20-1%201h-1m-5%200h-2m-5%200h-1a1%201%200%200%201%20-1%20-1v-1m0%20-5v-2%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-y-box-select:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M13%2013l2%202l2%20-2%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%2015v2.5%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M4%206v-1a1%201%200%200%201%201%20-1h1m5%200h2m5%200h1a1%201%200%200%201%201%201v1m0%205v2m0%205v1a1%201%200%200%201%20-1%201h-1m-5%200h-2m-5%200h-1a1%201%200%200%201%20-1%20-1v-1m0%20-5v-2%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-box-zoom:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Ccircle%20cx%3D%2215%22%20cy%3D%2215%22%20r%3D%225%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M22%2022l-3%20-3%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%2018h-1a2%202%200%200%201%20-2%20-2v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%2011v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%206v-1a2%202%200%200%201%202%20-2h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M10%203h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%203h1a2%202%200%200%201%202%202v1%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-x-box-zoom:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M17%2013l-4%204%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M13%2013l4%204%22%20%2F%3E%0A%20%20%3Ccircle%20cx%3D%2215%22%20cy%3D%2215%22%20r%3D%225%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M22%2022l-3%20-3%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%2018h-1a2%202%200%200%201%20-2%20-2v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%2011v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%206v-1a2%202%200%200%201%202%20-2h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M10%203h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%203h1a2%202%200%200%201%202%202v1%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-y-box-zoom:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M13%2013l2%202l2%20-2%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%2015v2.5%22%20%2F%3E%0A%20%20%3Ccircle%20cx%3D%2215%22%20cy%3D%2215%22%20r%3D%225%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M22%2022l-3%20-3%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%2018h-1a2%202%200%200%201%20-2%20-2v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%2011v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%206v-1a2%202%200%200%201%202%20-2h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M10%203h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%203h1a2%202%200%200%201%202%202v1%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-auto-box-zoom:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Ccircle%20cx%3D%2215%22%20cy%3D%2215%22%20r%3D%225%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M22%2022l-3%20-3%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%2018h-1a2%202%200%200%201%20-2%20-2v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%2011v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%206v-1a2%202%200%200%201%202%20-2h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M10%203h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%203h1a2%202%200%200%201%202%202v1%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-wheel-zoom:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M8.681%2020.8339V14.1905M4.80569%204.77905C4.29678%205.28797%203.89309%205.89213%203.61767%206.55706C3.34225%207.22199%203.20049%207.93465%203.20049%208.65436C3.20049%209.37407%203.34225%2010.0867%203.61767%2010.7517C3.89309%2011.4166%204.29678%2012.0208%204.80569%2012.5297C5.31461%2013.0386%205.91877%2013.4423%206.5837%2013.7177C7.24863%2013.9931%207.96129%2014.1349%208.681%2014.1349C9.40071%2014.1349%2010.1134%2013.9931%2010.7783%2013.7177C11.4432%2013.4423%2012.0474%2013.0386%2012.5563%2012.5297C13.0652%2012.0208%2013.4689%2011.4166%2013.7443%2010.7517C14.0198%2010.0867%2014.1615%209.37407%2014.1615%208.65436C14.1615%207.93465%2014.0198%207.22199%2013.7443%206.55706C13.4689%205.89213%2013.0652%205.28797%2012.5563%204.77905C12.0474%204.27014%2011.4432%203.86645%2010.7783%203.59103C10.1134%203.31561%209.40071%203.17385%208.681%203.17385C7.96129%203.17385%207.24863%203.31561%206.5837%203.59103C5.91877%203.86645%205.31461%204.27014%204.80569%204.77905Z%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15.1824%2013.8968C15.1824%2013.3711%2015.3912%2012.867%2015.7629%2012.4953C16.1346%2012.1236%2016.6388%2011.9147%2017.1644%2011.9147H19.1465C19.6721%2011.9147%2020.1763%2012.1236%2020.548%2012.4953C20.9197%2012.867%2021.1285%2013.3711%2021.1285%2013.8968V18.8519C21.1285%2019.3775%2020.9197%2019.8817%2020.548%2020.2534C20.1763%2020.6251%2019.6721%2020.8339%2019.1465%2020.8339H17.1644C16.6388%2020.8339%2016.1346%2020.6251%2015.7629%2020.2534C15.3912%2019.8817%2015.1824%2019.3775%2015.1824%2018.8519V13.8968Z%22%20fill%3D%22currentColor%22%20fill-opacity%3D%220.4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M18.1555%2013.8968V16.6519Z%22%20fill%3D%22currentColor%22%20fill-opacity%3D%220.4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M18.1555%2013.8968V16.6519M15.1824%2013.8968C15.1824%2013.3711%2015.3912%2012.867%2015.7629%2012.4953C16.1346%2012.1236%2016.6388%2011.9147%2017.1644%2011.9147H19.1465C19.6721%2011.9147%2020.1763%2012.1236%2020.548%2012.4953C20.9197%2012.867%2021.1285%2013.3711%2021.1285%2013.8968V18.8519C21.1285%2019.3775%2020.9197%2019.8817%2020.548%2020.2534C20.1763%2020.6251%2019.6721%2020.8339%2019.1465%2020.8339H17.1644C16.6388%2020.8339%2016.1346%2020.6251%2015.7629%2020.2534C15.3912%2019.8817%2015.1824%2019.3775%2015.1824%2018.8519V13.8968Z%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M5.90637%208.8085H11.4556M8.681%206.03387V11.5831%22%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-box-edit:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M5%205V5.00874M8.5%205V5.00874M12%205V5.00874M15.5%205V5.00874M19%205V5.00874M5%2018.9913V19M8.5%2018.9913V19M12%2018.9913V19M19%2011.9956V12.0044M19%208.49781V8.50656M5%2015.4934V15.5022M5%2011.9956V12.0044M5%208.49781V8.50656%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M18.42%2015.6151C18.615%2015.4201%2018.8465%2015.2654%2019.1013%2015.1599C19.3561%2015.0543%2019.6292%2015%2019.905%2015C20.1808%2015%2020.4539%2015.0543%2020.7087%2015.1599C20.9635%2015.2654%2021.195%2015.4201%2021.39%2015.6151C21.585%2015.8101%2021.7397%2016.0416%2021.8452%2016.2964C21.9508%2016.5512%2022.0051%2016.8243%2022.0051%2017.1001C22.0051%2017.3759%2021.9508%2017.649%2021.8452%2017.9038C21.7397%2018.1586%2021.585%2018.3901%2021.39%2018.5851L18%2022.0051H15V19.0051L18.42%2015.6151Z%22%20fill%3D%22currentColor%22%20fill-opacity%3D%220.4%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-poly-edit:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M17.6568%2014.1213L17.3033%209.52513M15.182%205.98959L12%204.92893M8.818%205.98959L5.63602%2012.7071M7.05024%2014.8284L15.5355%2016.2426M18.3639%208.46447C17.9889%208.83954%2017.4802%209.05025%2016.9497%209.05025C16.4193%209.05025%2015.9106%208.83954%2015.5355%208.46447C15.1604%208.08939%2014.9497%207.58069%2014.9497%207.05025C14.9497%206.51982%2015.1604%206.01111%2015.5355%205.63604C15.9106%205.26097%2016.4193%205.05025%2016.9497%205.05025C17.4802%205.05025%2017.9889%205.26097%2018.3639%205.63604C18.739%206.01111%2018.9497%206.51982%2018.9497%207.05025C18.9497%207.58069%2018.739%208.08939%2018.3639%208.46447ZM11.2929%205.63604C10.9178%206.01111%2010.4091%206.22183%209.87866%206.22183C9.34823%206.22183%208.83952%206.01111%208.46445%205.63604C8.08938%205.26097%207.87866%204.75226%207.87866%204.22183C7.87866%203.69139%208.08938%203.18269%208.46445%202.80761C8.83952%202.43254%209.34823%202.22183%209.87866%202.22183C10.4091%202.22183%2010.9178%202.43254%2011.2929%202.80761C11.6679%203.18269%2011.8787%203.69139%2011.8787%204.22183C11.8787%204.75226%2011.6679%205.26097%2011.2929%205.63604ZM19.0711%2017.6569C18.696%2018.0319%2018.1873%2018.2426%2017.6568%2018.2426C17.1264%2018.2426%2016.6177%2018.0319%2016.2426%2017.6569C15.8676%2017.2818%2015.6568%2016.7731%2015.6568%2016.2426C15.6568%2015.7122%2015.8676%2015.2035%2016.2426%2014.8284C16.6177%2014.4534%2017.1264%2014.2426%2017.6568%2014.2426C18.1873%2014.2426%2018.696%2014.4534%2019.0711%2014.8284C19.4461%2015.2035%2019.6568%2015.7122%2019.6568%2016.2426C19.6568%2016.7731%2019.4461%2017.2818%2019.0711%2017.6569ZM6.34313%2016.2426C5.96806%2016.6177%205.45935%2016.8284%204.92892%2016.8284C4.39848%2016.8284%203.88978%2016.6177%203.5147%2016.2426C3.13963%2015.8676%202.92892%2015.3589%202.92892%2014.8284C2.92892%2014.298%203.13963%2013.7893%203.5147%2013.4142C3.88978%2013.0391%204.39848%2012.8284%204.92892%2012.8284C5.45935%2012.8284%205.96806%2013.0391%206.34313%2013.4142C6.7182%2013.7893%206.92892%2014.298%206.92892%2014.8284C6.92892%2015.3589%206.7182%2015.8676%206.34313%2016.2426Z%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M17.4057%2012.7025C17.6284%2012.4798%2017.8928%2012.3031%2018.1838%2012.1826C18.4748%2012.062%2018.7867%2012%2019.1016%2012C19.4166%2012%2019.7285%2012.062%2020.0194%2012.1826C20.3104%2012.3031%2020.5748%2012.4798%2020.7975%2012.7025C21.0202%2012.9252%2021.1969%2013.1896%2021.3174%2013.4806C21.438%2013.7715%2021.5%2014.0834%2021.5%2014.3984C21.5%2014.7133%2021.438%2015.0252%2021.3174%2015.3162C21.1969%2015.6072%2021.0202%2015.8716%2020.7975%2016.0943L18.8618%2018.0471L16.9261%2020H13.5V16.5739L17.4057%2012.7025Z%22%20fill%3D%22currentColor%22%20fill-opacity%3D%220.4%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-line-edit:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Ccircle%20cx%3D%2213.9036%22%20cy%3D%224.82583%22%20r%3D%222%22%20transform%3D%22rotate(47.4551%2013.9036%204.82583)%22%20%2F%3E%0A%20%20%3Ccircle%20cx%3D%224.32583%22%20cy%3D%2213.616%22%20r%3D%222%22%20transform%3D%22rotate(47.4551%204.32583%2013.616)%22%20%2F%3E%0A%20%20%3Crect%20x%3D%2212.4301%22%20y%3D%226.17816%22%20width%3D%220%22%20height%3D%229%22%20transform%3D%22rotate(47.4551%2012.4301%206.17816)%22%20fill%3D%22currentColor%22%20fill-opacity%3D%220.4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M13.9404%2020.4782C13.9736%2020.6275%2014.0517%2020.7631%2014.1643%2020.8668C14.2768%2020.9705%2014.4183%2021.0373%2014.5699%2021.0582C14.7214%2021.0792%2014.8758%2021.0533%2015.0122%2020.984C15.1486%2020.9148%2015.2606%2020.8054%2015.3331%2020.6707L16.6395%2018.7373L19.7069%2021.8046C19.7688%2021.8666%2019.8424%2021.9157%2019.9233%2021.9492C20.0042%2021.9827%2020.0909%2022%2020.1785%2022C20.2661%2022%2020.3528%2021.9827%2020.4338%2021.9492C20.5147%2021.9157%2020.5882%2021.8666%2020.6502%2021.8046L21.3046%2021.1502C21.3666%2021.0882%2021.4157%2021.0147%2021.4492%2020.9338C21.4827%2020.8528%2021.5%2020.7661%2021.5%2020.6785C21.5%2020.5909%2021.4827%2020.5042%2021.4492%2020.4233C21.4157%2020.3424%2021.3666%2020.2688%2021.3046%2020.2069L18.2373%2017.1395L20.1832%2015.8331C20.3179%2015.7605%2020.4272%2015.6485%2020.4965%2015.512C20.5657%2015.3756%2020.5915%2015.2212%2020.5705%2015.0696C20.5495%2014.9181%2020.4826%2014.7765%2020.3789%2014.6641C20.2751%2014.5516%2020.1394%2014.4735%2019.9901%2014.4404L11.5%2012L13.9404%2020.4782Z%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-clear-selection:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M5%205V5.00874M8.5%205V5.00874M12%205V5.00874M15.5%205V5.00874M19%205V5.00874M5%2018.9913V19M8.5%2018.9913V19M12%2018.9913V19M19%2011.9956V12.0044M19%208.49781V8.50656M5%2015.4934V15.5022M5%2011.9956V12.0044M5%208.49781V8.50656%22%20stroke-width%3D%223%22%20stroke-dasharray%3D%224%204%22%2F%3E%0A%20%20%3Cpath%20d%3D%22M15.5%2015L21.5%2021Z%22%20fill%3D%22currentColor%22%20fill-opacity%3D%220.4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M21.5%2015L15.5%2021Z%22%20fill%3D%22currentColor%22%20fill-opacity%3D%220.4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15.5%2015L21.5%2021M21.5%2015L15.5%2021%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-invert-selection:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M5%204.5V19L8.46484%2015.5352C7.56002%2014.6303%207%2013.3807%207%2012C7%209.23858%209.23858%207%2012%207C13.3807%207%2014.6303%207.56002%2015.5352%208.46484L19.5%204.5H5Z%22%20fill%3D%22currentColor%22%20fill-opacity%3D%220.4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M8.46484%2015.5352C9.36967%2016.44%2010.6193%2017%2012%2017C14.7614%2017%2017%2014.7614%2017%2012C17%2010.6193%2016.44%209.36967%2015.5352%208.46484L8.46484%2015.5352Z%22%20fill%3D%22currentColor%22%20fill-opacity%3D%220.4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3.99997%205.77778C3.99997%205.30628%204.18727%204.8541%204.52067%204.5207C4.85407%204.1873%205.30625%204%205.77775%204H18.2222C18.6937%204%2019.1459%204.1873%2019.4793%204.5207C19.8127%204.8541%2020%205.30628%2020%205.77778V18.2222C20%2018.6937%2019.8127%2019.1459%2019.4793%2019.4793C19.1459%2019.8127%2018.6937%2020%2018.2222%2020H5.77775C5.30625%2020%204.85407%2019.8127%204.52067%2019.4793C4.18727%2019.1459%203.99997%2018.6937%203.99997%2018.2222V5.77778Z%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M4.29477%2019.6812L19.7451%204.23096%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-point-draw:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Ccircle%20cx%3D%223.73807%22%20cy%3D%2217.2381%22%20r%3D%222%22%20transform%3D%22rotate(7.30509%203.73807%2017.2381)%22%20%2F%3E%0A%20%20%3Ccircle%20cx%3D%2219.7381%22%20cy%3D%228.23807%22%20r%3D%222%22%20transform%3D%22rotate(7.30509%2019.7381%208.23807)%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M11.3341%209.83406C11.9487%209.21945%2012.3268%208.40774%2012.4019%207.5418C12.477%206.67586%2012.2443%205.81118%2011.7447%205.09993C11.245%204.38868%2010.5106%203.87645%209.67048%203.65338C8.83039%203.43031%207.93855%203.51071%207.15191%203.88042C6.36526%204.25013%205.73423%204.88545%205.36986%205.67459C5.00549%206.46372%204.93114%207.35609%205.1599%208.19464C5.38865%209.03319%205.90585%209.76418%206.62047%2010.259C7.33509%2010.7538%208.20133%2010.9806%209.06675%2010.8997V8.30035L11.3341%209.83406Z%22%20fill%3D%22currentColor%22%20fill-opacity%3D%220.4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M11.3341%209.83406C11.9382%209.22991%2012.3142%208.43497%2012.3979%207.58468C12.4817%206.7344%2012.268%205.88138%2011.7933%205.17098C11.3187%204.46057%2010.6123%203.93673%209.79474%203.68872C8.97713%203.4407%208.09882%203.48385%207.30946%203.81081C6.5201%204.13777%205.86853%204.72832%205.46577%205.48183C5.06301%206.23534%204.93398%207.1052%205.10067%207.94318C5.26735%208.78116%205.71944%209.53542%206.3799%2010.0774C7.04035%2010.6195%207.86832%2010.9157%208.72272%2010.9157%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M9.30866%2018.2265C9.30141%2018.3958%209.34612%2018.5633%209.4368%2018.7065C9.52748%2018.8498%209.65978%2018.9618%209.81596%2019.0277C9.97215%2019.0936%2010.1447%2019.1101%2010.3106%2019.0751C10.4765%2019.0401%2010.6276%2018.9552%2010.7439%2018.8318L12.6964%2017.1374L15.0994%2021.2995C15.1479%2021.3835%2015.2125%2021.4572%2015.2895%2021.5163C15.3664%2021.5753%2015.4543%2021.6187%2015.5481%2021.6438C15.6418%2021.6689%2015.7396%2021.6753%2015.8358%2021.6627C15.932%2021.65%2016.0248%2021.6185%2016.1088%2021.57L16.9969%2021.0572C17.0809%2021.0087%2017.1546%2020.9441%2017.2136%2020.8671C17.2727%2020.7902%2017.316%2020.7023%2017.3412%2020.6085C17.3663%2020.5148%2017.3727%2020.417%2017.36%2020.3208C17.3474%2020.2246%2017.3159%2020.1318%2017.2673%2020.0478L14.8644%2015.8857L17.3214%2015.0456C17.4864%2015.0066%2017.6355%2014.918%2017.7487%2014.7919C17.8619%2014.6657%2017.9338%2014.5079%2017.9548%2014.3396C17.9758%2014.1714%2017.9448%2014.0008%2017.866%2013.8507C17.7872%2013.7006%2017.6644%2013.5781%2017.5141%2013.4998L9.12817%208.45374L9.30866%2018.2265Z%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-poly-draw:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M8.41421%2010.4142C8.03914%2010.7893%207.53043%2011%207%2011C6.46957%2011%205.96086%2010.7893%205.58579%2010.4142C5.21071%2010.0391%205%209.53043%205%209C5%208.46957%205.21071%207.96086%205.58579%207.58579C5.96086%207.21071%206.46957%207%207%207C7.53043%207%208.03914%207.21071%208.41421%207.58579C8.78929%207.96086%209%208.46957%209%209C9%209.53043%208.78929%2010.0391%208.41421%2010.4142ZM8.41421%2010.4142L10%2012M15.5858%2015.5858C15.9609%2015.2107%2016.4696%2015%2017%2015C17.5304%2015%2018.0391%2015.2107%2018.4142%2015.5858C18.7893%2015.9609%2019%2016.4696%2019%2017C19%2017.5304%2018.7893%2018.0391%2018.4142%2018.4142C18.0391%2018.7893%2017.5304%2019%2017%2019C16.4696%2019%2015.9609%2018.7893%2015.5858%2018.4142C15.2107%2018.0391%2015%2017.5304%2015%2017C15%2016.4696%2015.2107%2015.9609%2015.5858%2015.5858ZM15.5858%2015.5858L13.2431%2014.3522M8.5%207.5L10.25%206L11.2679%205M15%204.5L18%206M19.5%209L18%2015M11%204C11%204.53043%2011.2107%205.03914%2011.5858%205.41421C11.9609%205.78929%2012.4696%206%2013%206C13.5304%206%2014.0391%205.78929%2014.4142%205.41421C14.7893%205.03914%2015%204.53043%2015%204C15%203.46957%2014.7893%202.96086%2014.4142%202.58579C14.0391%202.21071%2013.5304%202%2013%202C12.4696%202%2011.9609%202.21071%2011.5858%202.58579C11.2107%202.96086%2011%203.46957%2011%204ZM18%207C18%207.53043%2018.2107%208.03914%2018.5858%208.41421C18.9609%208.78929%2019.4696%209%2020%209C20.5304%209%2021.0391%208.78929%2021.4142%208.41421C21.7893%208.03914%2022%207.53043%2022%207C22%206.46957%2021.7893%205.96086%2021.4142%205.58579C21.0391%205.21071%2020.5304%205%2020%205C19.4696%205%2018.9609%205.21071%2018.5858%205.58579C18.2107%205.96086%2018%206.46957%2018%207Z%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M10.6386%2020.3576C10.6105%2020.5046%2010.5382%2020.6394%2010.4313%2020.7441C10.3244%2020.8487%2010.1881%2020.9182%2010.0406%2020.9431C9.89312%2020.9681%209.74152%2020.9474%209.60615%2020.8837C9.47077%2020.82%209.35811%2020.7165%209.28326%2020.587L7.9493%2018.7362L5.04245%2021.8246C4.98375%2021.8869%204.91335%2021.9371%204.83526%2021.9723C4.75717%2022.0074%204.67292%2022.0268%204.58732%2022.0294C4.50172%2022.032%204.41644%2022.0177%204.33637%2021.9874C4.25629%2021.957%204.18298%2021.9112%204.12062%2021.8525L3.46166%2021.2322C3.3993%2021.1735%203.34911%2021.1031%203.31395%2021.0251C3.2788%2020.947%203.25937%2020.8627%203.25678%2020.7771C3.25419%2020.6915%203.26848%2020.6062%203.29885%2020.5262C3.32921%2020.4461%203.37505%2020.3728%203.43375%2020.3104L6.3406%2017.222L4.40026%2016.0029C4.26645%2015.9359%204.15631%2015.8297%204.08462%2015.6984C4.01293%2015.5671%203.98311%2015.417%203.99917%2015.2682C4.01522%2015.1195%204.07639%2014.9792%204.17446%2014.8662C4.27253%2014.7532%204.40281%2014.6729%204.54781%2014.6361L12.7726%2012L10.6386%2020.3576Z%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-freehand-draw:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4.5%2018C4.5%2019.6667%204.5%2022%208.5%2020C13.5%2017.5%2013.5%2020%2013.5%2021%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M5.20734%2016.0852H4.20734V17.0852H5.20734V16.0852ZM8.62197%2016.0852V17.0852H9.0362L9.32909%2016.7923L8.62197%2016.0852ZM17.5854%207.12183L18.2925%207.82893L18.2925%207.82893L17.5854%207.12183ZM15.8781%203V2V3ZM14.1708%203.70719L13.4636%203.00009L13.4636%203.00009L14.1708%203.70719ZM5.20734%2012.6706L4.50023%2011.9635L4.20734%2012.2564V12.6706H5.20734ZM14.0242%203.8537C13.6337%203.46317%2013.0005%203.46317%2012.61%203.8537C12.2195%204.24422%2012.2195%204.87739%2012.61%205.26791L14.0242%203.8537ZM16.0246%208.68254C16.4151%209.07307%2017.0483%209.07307%2017.4388%208.68254C17.8294%208.29202%2017.8294%207.65885%2017.4388%207.26833L16.0246%208.68254ZM7.19493%2010.683C6.80441%2010.2924%206.17124%2010.2924%205.78072%2010.683C5.39019%2011.0735%205.39019%2011.7067%205.78072%2012.0972L7.19493%2010.683ZM13.7439%2010.9633L14.451%2011.6704L14.451%2011.6704L13.7439%2010.9633ZM5.20734%2016.0852V17.0852H8.62197V16.0852V15.0852H5.20734V16.0852ZM17.5854%207.12183L18.2925%207.82893C18.9328%207.18859%2019.2926%206.32009%2019.2926%205.41451H18.2926H17.2926C17.2926%205.78966%2017.1436%206.14945%2016.8783%206.41472L17.5854%207.12183ZM18.2926%205.41451H19.2926C19.2926%204.50893%2018.9328%203.64043%2018.2925%203.00009L17.5854%203.70719L16.8783%204.4143C17.1436%204.67957%2017.2926%205.03936%2017.2926%205.41451H18.2926ZM17.5854%203.70719L18.2925%203.00009C17.6521%202.35974%2016.7837%202%2015.8781%202L15.8781%203L15.8781%204C16.2532%204%2016.613%204.14903%2016.8783%204.4143L17.5854%203.70719ZM15.8781%203V2C14.9725%202%2014.104%202.35974%2013.4636%203.00009L14.1708%203.70719L14.8779%204.4143C15.1431%204.14903%2015.5029%204%2015.8781%204V3ZM14.1708%203.70719L13.4636%203.00009L4.50023%2011.9635L5.20734%2012.6706L5.91444%2013.3777L14.8779%204.4143L14.1708%203.70719ZM5.20734%2012.6706H4.20734V16.0852H5.20734H6.20734V12.6706H5.20734ZM13.3171%204.5608L12.61%205.26791L16.0246%208.68254L16.7317%207.97544L17.4388%207.26833L14.0242%203.8537L13.3171%204.5608ZM13.7439%2010.9633L14.451%2011.6704L18.2925%207.82893L17.5854%207.12183L16.8783%206.41472L13.0368%2010.2562L13.7439%2010.9633ZM8.62197%2016.0852L9.32909%2016.7923L10.6096%2015.5118L9.90246%2014.8047L9.19534%2014.0976L7.91485%2015.3782L8.62197%2016.0852ZM6.48782%2011.3901L5.78072%2012.0972L9.19535%2015.5118L9.90246%2014.8047L10.6096%2014.0976L7.19493%2010.683L6.48782%2011.3901ZM13.7439%2010.9633L13.0368%2010.2562L9.19536%2014.0976L9.90246%2014.8047L10.6096%2015.5118L14.451%2011.6704L13.7439%2010.9633Z%22%20fill%3D%22currentColor%22%20fill-opacity%3D%220.4%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-append-mode:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M8%206C8%205.46957%208.21071%204.96086%208.58579%204.58579C8.96086%204.21071%209.46957%204%2010%204H18C18.5304%204%2019.0391%204.21071%2019.4142%204.58579C19.7893%204.96086%2020%205.46957%2020%206V14C20%2014.5304%2019.7893%2015.0391%2019.4142%2015.4142C19.0391%2015.7893%2018.5304%2016%2018%2016H10C9.46957%2016%208.96086%2015.7893%208.58579%2015.4142C8.21071%2015.0391%208%2014.5304%208%2014V6Z%22%20fill%3D%22currentColor%22%20fill-opacity%3D%220.4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M4%2010C4%209.46957%204.21071%208.96086%204.58579%208.58579C4.96086%208.21071%205.46957%208%206%208H14C14.5304%208%2015.0391%208.21071%2015.4142%208.58579C15.7893%208.96086%2016%209.46957%2016%2010V18C16%2018.5304%2015.7893%2019.0391%2015.4142%2019.4142C15.0391%2019.7893%2014.5304%2020%2014%2020H6C5.46957%2020%204.96086%2019.7893%204.58579%2019.4142C4.21071%2019.0391%204%2018.5304%204%2018V10Z%22%20fill%3D%22currentColor%22%20fill-opacity%3D%220.4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M8%206C8%205.46957%208.21071%204.96086%208.58579%204.58579C8.96086%204.21071%209.46957%204%2010%204H18C18.5304%204%2019.0391%204.21071%2019.4142%204.58579C19.7893%204.96086%2020%205.46957%2020%206V14C20%2014.5304%2019.7893%2015.0391%2019.4142%2015.4142C19.0391%2015.7893%2018.5304%2016%2018%2016H10C9.46957%2016%208.96086%2015.7893%208.58579%2015.4142C8.21071%2015.0391%208%2014.5304%208%2014V6Z%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M4%2010C4%209.46957%204.21071%208.96086%204.58579%208.58579C4.96086%208.21071%205.46957%208%206%208H14C14.5304%208%2015.0391%208.21071%2015.4142%208.58579C15.7893%208.96086%2016%209.46957%2016%2010V18C16%2018.5304%2015.7893%2019.0391%2015.4142%2019.4142C15.0391%2019.7893%2014.5304%2020%2014%2020H6C5.46957%2020%204.96086%2019.7893%204.58579%2019.4142C4.21071%2019.0391%204%2018.5304%204%2018V10Z%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-intersect-mode:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Crect%20x%3D%228.08807%22%20y%3D%228.02829%22%20width%3D%227.93701%22%20height%3D%227.93702%22%20fill%3D%22currentColor%22%20fill-opacity%3D%220.4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M9%2015L15%209M8%206C8%205.46957%208.21071%204.96086%208.58579%204.58579C8.96086%204.21071%209.46957%204%2010%204H18C18.5304%204%2019.0391%204.21071%2019.4142%204.58579C19.7893%204.96086%2020%205.46957%2020%206V14C20%2014.5304%2019.7893%2015.0391%2019.4142%2015.4142C19.0391%2015.7893%2018.5304%2016%2018%2016H10C9.46957%2016%208.96086%2015.7893%208.58579%2015.4142C8.21071%2015.0391%208%2014.5304%208%2014V6ZM4%2010C4%209.46957%204.21071%208.96086%204.58579%208.58579C4.96086%208.21071%205.46957%208%206%208H14C14.5304%208%2015.0391%208.21071%2015.4142%208.58579C15.7893%208.96086%2016%209.46957%2016%2010V18C16%2018.5304%2015.7893%2019.0391%2015.4142%2019.4142C15.0391%2019.7893%2014.5304%2020%2014%2020H6C5.46957%2020%204.96086%2019.7893%204.58579%2019.4142C4.21071%2019.0391%204%2018.5304%204%2018V10Z%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-subtract-mode:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4.26016%2019.6422V9.19123L7.92544%208.39874L8.91606%2015.9274L16.0485%2016.1751L15.5532%2019.9394L4.26016%2019.6422Z%22%20fill%3D%22currentColor%22%20fill-opacity%3D%220.4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M16%2016V18C16%2018.5304%2015.7893%2019.0391%2015.4142%2019.4142C15.0391%2019.7893%2014.5304%2020%2014%2020H6C5.46957%2020%204.96086%2019.7893%204.58579%2019.4142C4.21071%2019.0391%204%2018.5304%204%2018V10C4%209.46957%204.21071%208.96086%204.58579%208.58579C4.96086%208.21071%205.46957%208%206%208H8M8%206C8%205.46957%208.21071%204.96086%208.58579%204.58579C8.96086%204.21071%209.46957%204%2010%204H18C18.5304%204%2019.0391%204.21071%2019.4142%204.58579C19.7893%204.96086%2020%205.46957%2020%206V14C20%2014.5304%2019.7893%2015.0391%2019.4142%2015.4142C19.0391%2015.7893%2018.5304%2016%2018%2016H10C9.46957%2016%208.96086%2015.7893%208.58579%2015.4142C8.21071%2015.0391%208%2014.5304%208%2014V6Z%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-xor-mode:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M15.9778%208.01522H8.10718V4.50302H19.7862V15.8436H15.9778V8.01522Z%22%20fill%3D%22currentColor%22%20fill-opacity%3D%220.4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M8.06036%2016.03H15.931V19.5422H4.25198V8.20167H8.06036V16.03Z%22%20fill%3D%22currentColor%22%20fill-opacity%3D%220.4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M16%2016V18C16%2018.5304%2015.7893%2019.0391%2015.4142%2019.4142C15.0391%2019.7893%2014.5304%2020%2014%2020H6C5.46957%2020%204.96086%2019.7893%204.58579%2019.4142C4.21071%2019.0391%204%2018.5304%204%2018V10C4%209.46957%204.21071%208.96086%204.58579%208.58579C4.96086%208.21071%205.46957%208%206%208H8M16%2016H18C18.5304%2016%2019.0391%2015.7893%2019.4142%2015.4142C19.7893%2015.0391%2020%2014.5304%2020%2014V6C20%205.46957%2019.7893%204.96086%2019.4142%204.58579C19.0391%204.21071%2018.5304%204%2018%204H10C9.46957%204%208.96086%204.21071%208.58579%204.58579C8.21071%204.96086%208%205.46957%208%206V8M16%2016V14M16%2016H14M8%208H10M8%208V10M8%2014V16H10M14%208H16V10%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-replace-mode:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M21%2011V8C21%207.46957%2020.7893%206.96086%2020.4142%206.58579C20.0391%206.21071%2019.5304%206%2019%206H13M13%206L16%209M13%206L16%203M3%2013V16C3%2016.5304%203.21071%2017.0391%203.58579%2017.4142C3.96086%2017.7893%204.46957%2018%205%2018H11M11%2018L8%2015M11%2018L8%2021M3%204C3%203.73478%203.10536%203.48043%203.29289%203.29289C3.48043%203.10536%203.73478%203%204%203H8C8.26522%203%208.51957%203.10536%208.70711%203.29289C8.89464%203.48043%209%203.73478%209%204V8C9%208.26522%208.89464%208.51957%208.70711%208.70711C8.51957%208.89464%208.26522%209%208%209H4C3.73478%209%203.48043%208.89464%203.29289%208.70711C3.10536%208.51957%203%208.26522%203%208V4ZM15%2016C15%2015.7348%2015.1054%2015.4804%2015.2929%2015.2929C15.4804%2015.1054%2015.7348%2015%2016%2015H20C20.2652%2015%2020.5196%2015.1054%2020.7071%2015.2929C20.8946%2015.4804%2021%2015.7348%2021%2016V20C21%2020.2652%2020.8946%2020.5196%2020.7071%2020.7071C20.5196%2020.8946%2020.2652%2021%2020%2021H16C15.7348%2021%2015.4804%2020.8946%2015.2929%2020.7071C15.1054%2020.5196%2015%2020.2652%2015%2020V16Z%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-toggle-mode:url("data:image/svg+xml,%3Csvg%20width%3D%2233%22%20height%3D%2232%22%20viewBox%3D%220%200%2033%2032%22%20fill%3D%22none%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%3E%0A%3Crect%20x%3D%220.5%22%20width%3D%2232%22%20height%3D%2232%22%20fill%3D%22url(%23pattern0_195_301)%22%2F%3E%0A%3Cdefs%3E%0A%3Cpattern%20id%3D%22pattern0_195_301%22%20patternContentUnits%3D%22objectBoundingBox%22%20width%3D%221%22%20height%3D%221%22%3E%0A%3Cuse%20xlink%3Ahref%3D%22%23image0_195_301%22%20transform%3D%22scale(0.03125)%22%2F%3E%0A%3C%2Fpattern%3E%0A%3Cimage%20id%3D%22image0_195_301%22%20width%3D%2232%22%20height%3D%2232%22%20preserveAspectRatio%3D%22none%22%20xlink%3Ahref%3D%22data%3Aimage%2Fpng%3Bbase64%2CiVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADP3pUWHRSYXcgcHJvZmlsZSB0eXBlIGV4aWYAAHja7ZZbsiMnDIbfWUWWgCRAYjlcq2YHWX5%2B6HYf2%2BOpiieepxyoRrRQC6EPsN34%2B8d0f6GwZ3YhqqWckkcJOWQu6Jg%2FStkt%2BbDbXfgcwvuD3l0DDJVAyvFq6bS%2F6elycIiCXrxzZO0cqI8DOZz%2B7cnROZGsiFYU%2FXSUT0fCxwCdDsqxLJ%2By6f0S6jhkv63EjsetRvRY%2Bs3J83tQZK9HKIV5CIlHK3IGIOsJTgo6abfCh7rAVNEGuUWChLzK01UyIpor1PDS6IHK1aPXevdMK%2FBpIk9JTpd8qXcUX1PZqb%2BbOdjZ40d9tsOV80%2FZX8%2Bc3eZeM1ZRQkKq07mo21J2D3YVU6ypzcFf8oonwoXumlENu7qBWvfNV9RGmRi4JgXqVGjS2LJRQ4iBh2NdJ4Uby1aaKGduYEeLmgSarJKli4Fo29iD8BUL7Wmzb27PZpi5E0yZ4IzwydvVvfvBnOsoEHm7coW4cPoXB1pplNXCDERonkmNO8G3%2BlwWVwHBuLK8jkhGYuvhokb6uglkgxYYRsjjuJD20wFShKkjgiEBAVAjiZTIK7MSIZEGQAWh4wBxBQGKkTuC5CCSwMZ4TY1PlLYpR4baQY%2FLDCQiTpyCTZYCWCFE7B8Nhj1UosQQY0xRo8UcS5IUUkwpaVqXYlHR4DRqUlXTrMXEgkVLpmaWrWTOgksz5pQ1W865FMxZ4Lng6wKDUipXqaFGV1PVajXX0rB9WmixpabNWm6lc5eO%2B6Onrt167mXQwFYaYcSRhg4beZSJrTbFzTDjTFOnzTzLRe3E%2BlN9gxqd1HiTWoZ6UYNW9eaC1nUSFzMAw68IgbguBNjQvJh5oxB4kVvMfGacisgIMi5mnRYxEAyDOE66sXN8EF3k%2FhM3p%2BGBG%2F8uObfQvUnuZ26vqPX1M9Q2seMUrqR6wekbOVlhQ0T4sVsdfy%2Fds%2BJ35bejb0ffjv5vjkYtqzdcSF8vL%2Fo10x%2BNqJZRMNcSp9aVxL7srv%2BSpw0E%2FkL9O%2B%2FuI%2BEgGveRcCDdR8JBFO4j4dh29H44e3%2BsbXLXd78YWPvnrTW7D5yOb0fvOsL%2FkOz%2BAVNjw%2BbixfXWAAABhGlDQ1BJQ0MgcHJvZmlsZQAAeJx9kT1Iw0AcxV9TtSIVRTuIOGSoThZERRy1CkWoEGqFVh1MLv0QmjQkKS6OgmvBwY%2FFqoOLs64OroIg%2BAHi7OCk6CIl%2Fi8ptIjx4Lgf7%2B497t4BQq3ENKttDNB020wl4mImuyKGXtGBIPoQRq%2FMLGNWkpLwHV%2F3CPD1Lsaz%2FM%2F9ObrVnMWAgEg8wwzTJl4nntq0Dc77xBFWlFXic%2BJRky5I%2FMh1xeM3zgWXBZ4ZMdOpOeIIsVhoYaWFWdHUiCeJo6qmU76Q8VjlvMVZK1VY4578heGcvrzEdZpDSGABi5AgQkEFGyjBRoxWnRQLKdqP%2B%2FgHXb9ELoVcG2DkmEcZGmTXD%2F4Hv7u18hPjXlI4DrS%2FOM7HMBDaBepVx%2Fk%2Bdpz6CRB8Bq70pr9cA6Y%2FSa82tegR0LMNXFw3NWUPuNwBBp4M2ZRdKUhTyOeB9zP6pizQfwt0rXq9NfZx%2BgCkqavkDXBwCIwUKHvN592drb39e6bR3w%2F9qXJ4zBnVPwAADRppVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw%2FeHBhY2tldCBiZWdpbj0i77u%2FIiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8%2BCjx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IlhNUCBDb3JlIDQuNC4wLUV4aXYyIj4KIDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI%2BCiAgPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIKICAgIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIgogICAgeG1sbnM6c3RFdnQ9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZUV2ZW50IyIKICAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIKICAgIHhtbG5zOkdJTVA9Imh0dHA6Ly93d3cuZ2ltcC5vcmcveG1wLyIKICAgIHhtbG5zOnRpZmY9Imh0dHA6Ly9ucy5hZG9iZS5jb20vdGlmZi8xLjAvIgogICAgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIgogICB4bXBNTTpEb2N1bWVudElEPSJnaW1wOmRvY2lkOmdpbXA6MjFjNTkwNzMtOTc1Zi00ZjAxLTljMDktYzY2NWY3NTBhMDA2IgogICB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjdhODY1NGM1LTZiYTktNDkwMi1iZWNmLTAyMGE3Y2I1MTI5NCIKICAgeG1wTU06T3JpZ2luYWxEb2N1bWVudElEPSJ4bXAuZGlkOmNmNDY3MmE2LTRjN2ItNDAwYi04N2U4LWExMjFjY2ZlZjI1YSIKICAgZGM6Rm9ybWF0PSJpbWFnZS9wbmciCiAgIEdJTVA6QVBJPSIyLjAiCiAgIEdJTVA6UGxhdGZvcm09IkxpbnV4IgogICBHSU1QOlRpbWVTdGFtcD0iMTcxNzQzODY2NDU5OTYwMiIKICAgR0lNUDpWZXJzaW9uPSIyLjEwLjMwIgogICB0aWZmOk9yaWVudGF0aW9uPSIxIgogICB4bXA6Q3JlYXRvclRvb2w9IkdJTVAgMi4xMCI%2BCiAgIDx4bXBNTTpIaXN0b3J5PgogICAgPHJkZjpTZXE%2BCiAgICAgPHJkZjpsaQogICAgICBzdEV2dDphY3Rpb249InNhdmVkIgogICAgICBzdEV2dDpjaGFuZ2VkPSIvIgogICAgICBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjAyOTk4NWE4LThlMjItNGI2NS1hNTQwLTE3MWI2NjU3YTYxOCIKICAgICAgc3RFdnQ6c29mdHdhcmVBZ2VudD0iR2ltcCAyLjEwIChMaW51eCkiCiAgICAgIHN0RXZ0OndoZW49IjIwMjQtMDYtMDNUMjA6MTc6NDQrMDI6MDAiLz4KICAgIDwvcmRmOlNlcT4KICAgPC94bXBNTTpIaXN0b3J5PgogIDwvcmRmOkRlc2NyaXB0aW9uPgogPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgIAo8P3hwYWNrZXQgZW5kPSJ3Ij8%2BrdIyIAAAAAZiS0dEAP8A%2FwD%2FoL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB%2BgGAxIRLNWVUewAAAB9SURBVFjDY2AYBaNggAEjNsGFy1b%2BR%2BbHR4UzUlMcGTANymBZuGzlf3TX08o8ptFUOJoGBtrxTNS2HFd%2Bp7kDyLF80KYZkiyhieXEWkas5VTLBciVDLXinOREiGwhNRIcCzmaBiSlj9YFw7Y9wEJK8Uppm3C0RTQKRgE2AAByVIRiIg%2Bg0AAAAABJRU5ErkJggg%3D%3D%22%2F%3E%0A%3C%2Fdefs%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-zoom-in:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Ccircle%20cx%3D%2210%22%20cy%3D%2210%22%20r%3D%227%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%227%22%20y1%3D%2210%22%20x2%3D%2213%22%20y2%3D%2210%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2210%22%20y1%3D%227%22%20x2%3D%2210%22%20y2%3D%2213%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2221%22%20y1%3D%2221%22%20x2%3D%2215%22%20y2%3D%2215%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-zoom-out:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Ccircle%20cx%3D%2210%22%20cy%3D%2210%22%20r%3D%227%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%227%22%20y1%3D%2210%22%20x2%3D%2213%22%20y2%3D%2210%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2221%22%20y1%3D%2221%22%20x2%3D%2215%22%20y2%3D%2215%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-undo:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M9%2014L5%2010M5%2010L9%206M5%2010H16C17.0609%2010%2018.0783%2010.4214%2018.8284%2011.1716C19.5786%2011.9217%2020%2012.9391%2020%2014C20%2015.0609%2019.5786%2016.0783%2018.8284%2016.8284C18.0783%2017.5786%2017.0609%2018%2016%2018H15%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-redo:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M15%2013L19%209M19%209L15%205M19%209L8%209C6.93913%209%205.92172%209.42143%205.17157%2010.1716C4.42143%2010.9217%204%2011.9391%204%2013C4%2014.0609%204.42143%2015.0783%205.17157%2015.8284C5.92172%2016.5786%206.93913%2017%208%2017H9%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-reset:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M3.06006%2013.0001C3.30547%2015.1939%204.34865%2017.2211%205.9912%2018.696C7.63374%2020.1709%209.76108%2020.9907%2011.9686%2020.9995C14.1762%2021.0082%2016.3099%2020.2053%2017.9641%2018.7434C19.6183%2017.2816%2020.6775%2015.2628%2020.9403%2013.0709C21.2031%2010.879%2020.6511%208.66702%2019.3894%206.85557C18.1276%205.04412%2016.2441%203.75958%2014.0971%203.24624C11.95%202.7329%209.68922%203.02658%207.74457%204.07141C5.79993%205.11625%204.30712%206.83937%203.55006%208.91306M3%204.00098V9.00098H8M11%2012C11%2012.2652%2011.1054%2012.5196%2011.2929%2012.7071C11.4804%2012.8946%2011.7348%2013%2012%2013C12.2652%2013%2012.5196%2012.8946%2012.7071%2012.7071C12.8946%2012.5196%2013%2012.2652%2013%2012C13%2011.7348%2012.8946%2011.4804%2012.7071%2011.2929C12.5196%2011.1054%2012.2652%2011%2012%2011C11.7348%2011%2011.4804%2011.1054%2011.2929%2011.2929C11.1054%2011.4804%2011%2011.7348%2011%2012Z%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-hover:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M12%2020l-3%20-3h-2a3%203%200%200%201%20-3%20-3v-6a3%203%200%200%201%203%20-3h10a3%203%200%200%201%203%203v6a3%203%200%200%201%20-3%203h-2l-3%203%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%228%22%20y1%3D%229%22%20x2%3D%2216%22%20y2%3D%229%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%228%22%20y1%3D%2213%22%20x2%3D%2214%22%20y2%3D%2213%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-crosshair:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Ccircle%20cx%3D%2212%22%20cy%3D%2212%22%20r%3D%229%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M20%2012h-4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M4%2012h4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2020v-4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%204v4%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-chevron-up:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpolyline%20points%3D%226%2015%2012%209%2018%2015%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-chevron-down:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpolyline%20points%3D%226%209%2012%2015%2018%209%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-chevron-left:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpolyline%20points%3D%2215%206%209%2012%2015%2018%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-chevron-right:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpolyline%20points%3D%229%206%2015%2012%209%2018%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-caret-up:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22currentColor%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M18%2015l-6%20-6l-6%206h12%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-caret-down:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22currentColor%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M18%2015l-6%20-6l-6%206h12%22%20transform%3D%22rotate(180%2012%2012)%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-caret-left:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22currentColor%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M18%2015l-6%20-6l-6%206h12%22%20transform%3D%22rotate(270%2012%2012)%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-caret-right:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22currentColor%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M18%2015l-6%20-6l-6%206h12%22%20transform%3D%22rotate(90%2012%2012)%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-see-on:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Ccircle%20cx%3D%2212%22%20cy%3D%2212%22%20r%3D%222%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M22%2012c-2.667%204.667%20-6%207%20-10%207s-7.333%20-2.333%20-10%20-7c2.667%20-4.667%206%20-7%2010%20-7s7.333%202.333%2010%207%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-see-off:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cline%20x1%3D%223%22%20y1%3D%223%22%20x2%3D%2221%22%20y2%3D%2221%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M10.584%2010.587a2%202%200%200%200%202.828%202.83%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M9.363%205.365a9.466%209.466%200%200%201%202.637%20-.365c4%200%207.333%202.333%2010%207c-.778%201.361%20-1.612%202.524%20-2.503%203.488m-2.14%201.861c-1.631%201.1%20-3.415%201.651%20-5.357%201.651c-4%200%20-7.333%20-2.333%20-10%20-7c1.369%20-2.395%202.913%20-4.175%204.632%20-5.341%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-cursor-rotate:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%3E%0A%20%20%3Cg%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%20%20%3Cg%20stroke-width%3D%224%22%20stroke%3D%22white%22%3E%0A%20%20%20%20%20%20%3Cpath%20d%3D%22M9%204.55a8%208%200%200%201%206%2014.9m0%20-4.45v5h5%22%20%2F%3E%0A%20%20%20%20%3C%2Fg%3E%0A%20%20%20%20%3Cg%20stroke-width%3D%222%22%20stroke%3D%22black%22%3E%0A%20%20%20%20%20%20%3Cpath%20d%3D%22M9%204.55a8%208%200%200%201%206%2014.9m0%20-4.45v5h5%22%20%2F%3E%0A%20%20%20%20%3C%2Fg%3E%0A%20%20%3C%2Fg%3E%0A%3C%2Fsvg%3E%0A") 12 12, auto;--bokeh-icon-x-grip:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M5%209m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M5%2015m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M12%209m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M12%2015m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M19%209m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M19%2015m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-y-grip:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M9%205m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M9%2012m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M9%2019m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M15%205m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M15%2012m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M15%2019m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-arrow-down-to-bar:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4%2020l16%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M12%2014l0%20-10%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M12%2014l4%20-4%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M12%2014l-4%20-4%22%3E%3C%2Fpath%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-arrow-up-from-bar:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M12%204l0%2010%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M12%204l4%204%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M12%204l-4%204%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M4%2020l16%200%22%3E%3C%2Fpath%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-minimize:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M15%2019v-2a2%202%200%200%201%202%20-2h2%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M15%205v2a2%202%200%200%200%202%202h2%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M5%2015h2a2%202%200%200%201%202%202v2%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M5%209h2a2%202%200%200%200%202%20-2v-2%22%3E%3C%2Fpath%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-maximize:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4%208v-2a2%202%200%200%201%202%20-2h2%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M4%2016v2a2%202%200%200%200%202%202h2%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M16%204h2a2%202%200%200%201%202%202v2%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M16%2020h2a2%202%200%200%200%202%20-2v-2%22%3E%3C%2Fpath%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-pin:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M15%204.5l-4%204l-4%201.5l-1.5%201.5l7%207l1.5%20-1.5l1.5%20-4l4%20-4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M9%2015l-4.5%204.5%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M14.5%204l5.5%205.5%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-unpin:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M3%203l18%2018%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%204.5l-3.249%203.249m-2.57%201.433l-2.181%20.818l-1.5%201.5l7%207l1.5%20-1.5l.82%20-2.186m1.43%20-2.563l3.25%20-3.251%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M9%2015l-4.5%204.5%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M14.5%204l5.5%205.5%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-hand-pointing:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M8%2013v-8.5a1.5%201.5%200%200%201%203%200v7.5%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M11%2011.5v-2a1.5%201.5%200%201%201%203%200v2.5%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M14%2010.5a1.5%201.5%200%200%201%203%200v1.5%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M17%2011.5a1.5%201.5%200%200%201%203%200v4.5a6%206%200%200%201%20-6%206h-2h.208a6%206%200%200%201%20-5.012%20-2.7a69.74%2069.74%200%200%201%20-.196%20-.3c-.312%20-.479%20-1.407%20-2.388%20-3.286%20-5.728a1.5%201.5%200%200%201%20.536%20-2.022a1.867%201.867%200%200%201%202.28%20.28l1.47%201.47%22%3E%3C%2Fpath%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-trash:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4%207l16%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M10%2011l0%206%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M14%2011l0%206%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M5%207l1%2012a2%202%200%200%200%202%202h8a2%202%200%200%200%202%20-2l1%20-12%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M9%207v-3a1%201%200%200%201%201%20-1h4a1%201%200%200%201%201%201v3%22%3E%3C%2Fpath%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-bold:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M7%205h6a3.5%203.5%200%200%201%200%207h-6z%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M13%2012h1a3.5%203.5%200%200%201%200%207h-7v-7%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-italic:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M11%205l6%200%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M7%2019l6%200%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M14%205l-4%2014%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-text-align-left:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4%206l16%200%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M4%2012l10%200%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M4%2018l14%200%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-text-align-center:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4%206l16%200%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M8%2012l8%200%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%2018l12%200%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-text-align-right:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4%206l16%200%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M10%2012l10%200%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%2018l14%200%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-check:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M5%2012l5%205l10%20-10%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-square:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M3%203m0%202a2%202%200%200%201%202%20-2h14a2%202%200%200%201%202%202v14a2%202%200%200%201%20-2%202h-14a2%202%200%200%201%20-2%20-2z%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-square-check:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M3%203m0%202a2%202%200%200%201%202%20-2h14a2%202%200%200%201%202%202v14a2%202%200%200%201%20-2%202h-14a2%202%200%200%201%20-2%20-2z%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M9%2012l2%202l4%20-4%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-list:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22currentColor%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M9%206l11%200%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M9%2012l11%200%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M9%2018l11%200%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M5%206l0%20.01%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M5%2012l0%20.01%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M5%2018l0%20.01%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-range:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M16.375%2014.625L19%2012M19%2012L16.375%209.375M19%2012H12H5M5%2012L7.625%209.375M5%2012L7.625%2014.625%22%20%2F%3E%0A%20%20%3Crect%20x%3D%222%22%20y%3D%226%22%20width%3D%220%22%20height%3D%2212%22%20stroke-width%3D%223%22%20stroke-dasharray%3D%220.01%203.5%22%2F%3E%0A%20%20%3Crect%20x%3D%2222%22%20y%3D%226%22%20width%3D%220%22%20height%3D%2212%22%20stroke-width%3D%223%22%20stroke-dasharray%3D%220.01%203.5%22%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-light-theme:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22currentColor%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M12%2012m-4%200a4%204%200%201%200%208%200a4%204%200%201%200%20-8%200%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%2012h1m8%20-9v1m8%208h1m-9%208v1m-6.4%20-15.4l.7%20.7m12.1%20-.7l-.7%20.7m0%2011.4l.7%20.7m-12.1%20-.7l-.7%20.7%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-dark-theme:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22currentColor%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M12%203c.132%200%20.263%200%20.393%200a7.5%207.5%200%200%200%207.92%2012.446a9%209%200%201%201%20-8.313%20-12.454z%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-pencil:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22currentColor%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4%2020h4l10.5%20-10.5a2.828%202.828%200%201%200%20-4%20-4l-10.5%2010.5v4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M13.5%206.5l4%204%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");}`;
},
/* styles/buttons.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.btn = "bk-btn";
    exports.active = "bk-active";
    exports.btn_default = "bk-btn-default";
    exports.btn_primary = "bk-btn-primary";
    exports.btn_success = "bk-btn-success";
    exports.btn_warning = "bk-btn-warning";
    exports.btn_danger = "bk-btn-danger";
    exports.btn_light = "bk-btn-light";
    exports.btn_group = "bk-btn-group";
    exports.vertical = "bk-vertical";
    exports.horizontal = "bk-horizontal";
    exports.dropdown_toggle = "bk-dropdown-toggle";
    exports.default = `:host{--file:#fff;--file-border:#ccc;--file-hover:#f5f5f5;--file-hover-border:#b8b8b8;--file-active:#ebebeb;--file-active-border:#adadad;--file-disabled:#e6e6e6;--file-disabled-border:#ccc;--default:#fff;--default-border:#ccc;--default-hover:#f5f5f5;--default-hover-border:#b8b8b8;--default-active:#ebebeb;--default-active-border:#adadad;--default-disabled:#e6e6e6;--default-disabled-border:#ccc;--primary:#428bca;--primary-border:#357ebd;--primary-hover:#3681c1;--primary-hover-border:#2c699e;--primary-active:#3276b1;--primary-active-border:#285e8e;--primary-disabled:#506f89;--primary-disabled-border:#357ebd;--success:#5cb85c;--success-border:#4cae4c;--success-hover:#4eb24e;--success-hover-border:#409240;--success-active:#47a447;--success-active-border:#398439;--success-disabled:#667b66;--success-disabled-border:#4cae4c;--warning:#f0ad4e;--warning-border:#eea236;--warning-hover:#eea43b;--warning-hover-border:#e89014;--warning-active:#ed9c28;--warning-active-border:#d58512;--warning-disabled:#c89143;--warning-disabled-border:#eea236;--danger:#d9534f;--danger-border:#d43f3a;--danger-hover:#d5433e;--danger-hover-border:#bd2d29;--danger-active:#d2322d;--danger-active-border:#ac2925;--danger-disabled:#a55350;--danger-disabled-border:#d43f3a;--light:#fff;--light-border:#ccc;--light-hover:#f5f5f5;--light-hover-border:#b8b8b8;--light-active:#ebebeb;--light-active-border:#adadad;--light-disabled:#e6e6e6;--light-disabled-border:#ccc;}.bk-btn,::file-selector-button{height:100%;display:inline-block;text-align:center;vertical-align:middle;white-space:nowrap;cursor:pointer;padding:var(--padding-vertical) var(--padding-horizontal);font-size:var(--font-size);border:var(--border-width) var(--border-style) transparent;border-radius:var(--border-radius);outline:0;outline-offset:-5px;user-select:none;-webkit-user-select:none;}.bk-btn:hover,::file-selector-button:hover,.bk-btn:focus,::file-selector-button:focus{text-decoration:none;}.bk-btn:active,::file-selector-button:active,.bk-active.bk-btn,.bk-active::file-selector-button{background-image:none;box-shadow:var(--box-shadow-inset);}.bk-btn[disabled]{cursor:not-allowed;pointer-events:none;opacity:0.65;box-shadow:none;}::file-selector-button{color:var(--color);background-color:var(--file);border-color:var(--file-border);}::file-selector-button:hover{background-color:var(--file-hover);border-color:var(--file-hover-border);}.bk-active::file-selector-button{background-color:var(--file-active);border-color:var(--file-active-border);}::file-selector-button[disabled],::file-selector-button[disabled]:hover,::file-selector-button[disabled]:focus,::file-selector-button[disabled]:active,.bk-active::file-selector-button[disabled]{background-color:var(--file-disabled);border-color:var(--file-disabled-border);}::file-selector-button:focus,::file-selector-button:active{outline:var(--outline);}.bk-btn-default{color:var(--color);background-color:var(--default);border-color:var(--default-border);}.bk-btn-default:hover{background-color:var(--default-hover);border-color:var(--default-hover-border);}.bk-active.bk-btn-default{background-color:var(--default-active);border-color:var(--default-active-border);}.bk-btn-default[disabled],.bk-btn-default[disabled]:hover,.bk-btn-default[disabled]:focus,.bk-btn-default[disabled]:active,.bk-active.bk-btn-default[disabled]{background-color:var(--default-disabled);border-color:var(--default-disabled-border);}.bk-btn-default:focus,.bk-btn-default:active{outline:var(--outline);}.bk-btn-primary{color:var(--inverted-color);background-color:var(--primary);border-color:var(--primary-border);}.bk-btn-primary:hover{background-color:var(--primary-hover);border-color:var(--primary-hover-border);}.bk-active.bk-btn-primary{background-color:var(--primary-active);border-color:var(--primary-active-border);}.bk-btn-primary[disabled],.bk-btn-primary[disabled]:hover,.bk-btn-primary[disabled]:focus,.bk-btn-primary[disabled]:active,.bk-active.bk-btn-primary[disabled]{background-color:var(--primary-disabled);border-color:var(--primary-disabled-border);}.bk-btn-primary:focus,.bk-btn-primary:active{outline:var(--outline);}.bk-btn-success{color:var(--inverted-color);background-color:var(--success);border-color:var(--success-border);}.bk-btn-success:hover{background-color:var(--success-hover);border-color:var(--success-hover-border);}.bk-active.bk-btn-success{background-color:var(--success-active);border-color:var(--success-active-border);}.bk-btn-success[disabled],.bk-btn-success[disabled]:hover,.bk-btn-success[disabled]:focus,.bk-btn-success[disabled]:active,.bk-active.bk-btn-success[disabled]{background-color:var(--success-disabled);border-color:var(--success-disabled-border);}.bk-btn-success:focus,.bk-btn-success:active{outline:var(--outline);}.bk-btn-warning{color:var(--inverted-color);background-color:var(--warning);border-color:var(--warning-border);}.bk-btn-warning:hover{background-color:var(--warning-hover);border-color:var(--warning-hover-border);}.bk-active.bk-btn-warning{background-color:var(--warning-active);border-color:var(--warning-active-border);}.bk-btn-warning[disabled],.bk-btn-warning[disabled]:hover,.bk-btn-warning[disabled]:focus,.bk-btn-warning[disabled]:active,.bk-active.bk-btn-warning[disabled]{background-color:var(--warning-disabled);border-color:var(--warning-disabled-border);}.bk-btn-warning:focus,.bk-btn-warning:active{outline:var(--outline);}.bk-btn-danger{color:var(--inverted-color);background-color:var(--danger);border-color:var(--danger-border);}.bk-btn-danger:hover{background-color:var(--danger-hover);border-color:var(--danger-hover-border);}.bk-active.bk-btn-danger{background-color:var(--danger-active);border-color:var(--danger-active-border);}.bk-btn-danger[disabled],.bk-btn-danger[disabled]:hover,.bk-btn-danger[disabled]:focus,.bk-btn-danger[disabled]:active,.bk-active.bk-btn-danger[disabled]{background-color:var(--danger-disabled);border-color:var(--danger-disabled-border);}.bk-btn-danger:focus,.bk-btn-danger:active{outline:var(--outline);}.bk-btn-light{color:var(--color);background-color:var(--light);border-color:var(--light-border);border-color:transparent;}.bk-btn-light:hover{background-color:var(--light-hover);border-color:var(--light-hover-border);}.bk-active.bk-btn-light{background-color:var(--light-active);border-color:var(--light-active-border);}.bk-btn-light[disabled],.bk-btn-light[disabled]:hover,.bk-btn-light[disabled]:focus,.bk-btn-light[disabled]:active,.bk-active.bk-btn-light[disabled]{background-color:var(--light-disabled);border-color:var(--light-disabled-border);}.bk-btn-light:focus,.bk-btn-light:active{outline:var(--outline);}.bk-btn-group{height:100%;display:flex;flex-wrap:nowrap;align-items:center;}.bk-btn-group:not(.bk-vertical),.bk-btn-group.bk-horizontal{flex-direction:row;}.bk-btn-group.bk-vertical{flex-direction:column;}.bk-btn-group > .bk-btn{flex-grow:1;}.bk-btn-group:not(.bk-vertical) > .bk-btn + .bk-btn{margin-left:-1px;}.bk-btn-group.bk-vertical > .bk-btn + .bk-btn{margin-top:-1px;}.bk-btn-group:not(.bk-vertical) > .bk-btn:first-child:not(:last-child){border-bottom-right-radius:0;border-top-right-radius:0;}.bk-btn-group.bk-vertical > .bk-btn:first-child:not(:last-child){border-bottom-left-radius:0;border-bottom-right-radius:0;}.bk-btn-group:not(.bk-vertical) > .bk-btn:not(:first-child):last-child{border-bottom-left-radius:0;border-top-left-radius:0;}.bk-btn-group.bk-vertical > .bk-btn:not(:first-child):last-child{border-top-left-radius:0;border-top-right-radius:0;}.bk-btn-group > .bk-btn:not(:first-child):not(:last-child){border-radius:0;}.bk-btn-group.bk-vertical > .bk-btn{width:100%;}.bk-btn-group .bk-dropdown-toggle{flex:0 0 0;padding:var(--padding-vertical) calc(var(--padding-horizontal)/2);}`;
},
/* styles/notifications.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = `:host{position:fixed;left:50%;top:0.5em;transform:translate(-50%, 0);width:max-content;height:max-content;max-width:50%;}:host > .entries:empty{display:none;}.entries{display:flex;flex-direction:column;flex-wrap:nowrap;gap:0.5em;}.entries > *{padding:0.5em;border:1px solid gray;border-radius:0.5em;}.error{background-color:var(--danger);border-color:var(--danger-border);}.success{background-color:var(--success);border-color:var(--success-border);}.try{font-weight:bold;cursor:pointer;}.try:hover{text-decoration:underline;}.close{display:inline-block;vertical-align:middle;margin-left:1em;width:1em;height:1em;cursor:pointer;mask-image:var(--bokeh-icon-x);-webkit-mask-image:var(--bokeh-icon-x);mask-size:contain;-webkit-mask-size:contain;mask-position:center center;-webkit-mask-position:center center;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat;background-color:black;}.close:hover{background-color:var(--hover-color);}`;
},
/* document/defs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.decode_def = decode_def;
    const tslib_1 = require(1) /* tslib */;
    const model_1 = require(52) /* ../model */;
    const kinds = tslib_1.__importStar(require(22) /* ../core/kinds */);
    const types_1 = require(8) /* ../core/util/types */;
    const object_1 = require(9) /* ../core/util/object */;
    function decode_def(def, deserializer) {
        function kind_of(ref) {
            if ((0, types_1.isString)(ref)) {
                switch (ref) {
                    case "Any": return kinds.Any;
                    case "Unknown": return kinds.Unknown;
                    case "Bool": return kinds.Bool;
                    case "Float": return kinds.Float;
                    case "Int": return kinds.Int;
                    case "Bytes": return kinds.Bytes;
                    case "Str": return kinds.Str;
                    case "Null": return kinds.Null;
                }
            }
            else {
                switch (ref[0]) {
                    case "Regex": {
                        const [, regex, flags] = ref;
                        return kinds.Regex(new RegExp(regex, flags));
                    }
                    case "Nullable": {
                        const [, sub_ref] = ref;
                        return kinds.Nullable(kind_of(sub_ref));
                    }
                    case "Or": {
                        const [, sub_ref, ...sub_refs] = ref;
                        return kinds.Or(kind_of(sub_ref), ...sub_refs.map(kind_of));
                    }
                    case "Tuple": {
                        const [, sub_ref, ...sub_refs] = ref;
                        return kinds.Tuple(kind_of(sub_ref), ...sub_refs.map(kind_of));
                    }
                    case "List": {
                        const [, sub_ref] = ref;
                        return kinds.List(kind_of(sub_ref));
                    }
                    case "Struct": {
                        const [, ...entry_refs] = ref;
                        const entries = entry_refs.map(([key, val_ref]) => [key, kind_of(val_ref)]);
                        return kinds.Struct((0, object_1.to_object)(entries));
                    }
                    case "Dict": {
                        const [, val_ref] = ref;
                        return kinds.Dict(kind_of(val_ref));
                    }
                    case "Mapping": {
                        const [, key_ref, val_ref] = ref;
                        return kinds.Mapping(kind_of(key_ref), kind_of(val_ref));
                    }
                    case "Enum": {
                        const [, ...items] = ref;
                        return kinds.Enum(...items);
                    }
                    case "Ref": {
                        const [, model_ref] = ref;
                        const model = deserializer.resolver.get(model_ref.id);
                        if (model != null) {
                            return kinds.Ref(model);
                        }
                        else {
                            throw new Error(`${model_ref.id} wasn't defined before referencing it`);
                        }
                    }
                    case "AnyRef": {
                        return kinds.AnyRef();
                    }
                }
            }
        }
        const base = (() => {
            const name = def.extends?.id ?? "Model";
            if (name == "Model") {
                // TODO: support base classes in general
                return model_1.Model;
            }
            const base = deserializer.resolver.get(name);
            if (base != null) {
                return base;
            }
            else {
                throw new Error(`base model ${name} of ${def.name} is not defined`);
            }
        })();
        const model = class extends base {
            static __qualified__ = def.name;
        };
        function decode(value) {
            if (value === undefined) {
                return value;
            }
            else {
                return deserializer.decode(value);
            }
        }
        for (const prop of def.properties ?? []) {
            const kind = kind_of(prop.kind);
            model.define({ [prop.name]: [kind, decode(prop.default)] });
        }
        for (const prop of def.overrides ?? []) {
            model.override({ [prop.name]: decode(prop.default) });
        }
        deserializer.resolver.register(model);
        return model;
    }
},
/* core/bokeh_events.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.event = event;
    exports.server_event = server_event;
    var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
        if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
            r = Reflect.decorate(decorators, target, key, desc);
        else
            for (var i = decorators.length - 1; i >= 0; i--)
                if (d = decorators[i])
                    r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
        return c > 3 && r && Object.defineProperty(target, key, r), r;
    };
    const model_1 = require(52) /* ../model */;
    const types_1 = require(8) /* ./util/types */;
    const assert_1 = require(13) /* ./util/assert */;
    const serialization_1 = require(33) /* ./serialization */;
    const deserializer_1 = require(48) /* ./serialization/deserializer */;
    const eq_1 = require(27) /* ./util/eq */;
    deserializer_1.Deserializer.register("event", (rep, deserializer) => {
        const cls = deserializable_events.get(rep.name);
        if (cls !== undefined && cls.from_values != null) {
            const values = deserializer.decode(rep.values);
            (0, assert_1.assert)((0, types_1.isPlainObject)(values));
            return cls.from_values(values);
        }
        else {
            deserializer.error(`deserialization of '${rep.name}' event is not supported`);
        }
    });
    function event(event_name) {
        return (cls) => {
            cls.prototype.event_name = event_name;
        };
    }
    const deserializable_events = new Map();
    /**
     * Marks and registers a class as a one way (server -> client) event.
     */
    function server_event(event_name) {
        return (cls) => {
            if (deserializable_events.has(event_name)) {
                throw new Error(`'${event_name}' event is already registered`);
            }
            deserializable_events.set(event_name, cls);
            cls.prototype.event_name = event_name;
            cls.prototype.publish = false;
        };
    }
    class BokehEvent {
        [serialization_1.serialize](serializer) {
            const { event_name: name, event_values } = this;
            const values = serializer.encode(event_values);
            return { type: "event", name, values };
        }
        [eq_1.equals](that, cmp) {
            return this.event_name == that.event_name && cmp.eq(this.event_values, that.event_values);
        }
        static {
            this.prototype.publish = true;
        }
    }
    exports.BokehEvent = BokehEvent;
    class ModelEvent extends BokehEvent {
        origin = null;
        get event_values() {
            return { model: this.origin };
        }
    }
    exports.ModelEvent = ModelEvent;
    class UserEvent extends ModelEvent {
        values;
        constructor(values) {
            super();
            this.values = values;
        }
        get event_values() {
            return { ...super.event_values, ...this.values };
        }
        static from_values(values) {
            const origin = (() => {
                if ("model" in values) {
                    const { model } = values;
                    (0, assert_1.assert)(model === null || model instanceof model_1.Model);
                    delete values.model;
                    return model;
                }
                else {
                    return null;
                }
            })();
            const event = new this(values);
            event.origin = origin;
            return event;
        }
    }
    exports.UserEvent = UserEvent;
    class PropertyBundleEvent extends ModelEvent {
        values;
        constructor(values) {
            super();
            this.values = values;
        }
        get event_values() {
            return { ...super.event_values, ...this.values };
        }
    }
    exports.PropertyBundleEvent = PropertyBundleEvent;
    class DocumentEvent extends BokehEvent {
    }
    exports.DocumentEvent = DocumentEvent;
    let DocumentReady = class DocumentReady extends DocumentEvent {
        get event_values() {
            return {};
        }
    };
    exports.DocumentReady = DocumentReady;
    exports.DocumentReady = DocumentReady = __decorate([
        event("document_ready")
    ], DocumentReady);
    class ConnectionEvent extends DocumentEvent {
    }
    exports.ConnectionEvent = ConnectionEvent;
    /**
     * Announce when a WebSocket connection was disconnected.
     *
     * @member timestamp when the last connection attempt was made
     * @member attempts  the number of times reconnection was attempted
     * @member timeout   milliseconds till next reconnection attempt or `null`
     *                   indicating that no further attempts will be made
     */
    class ConnectionLost extends ConnectionEvent {
        connection;
        attempts;
        timeout;
        timestamp = Date.now();
        constructor(connection, attempts, timeout) {
            super();
            this.connection = connection;
            this.attempts = attempts;
            this.timeout = timeout;
        }
        get event_values() {
            const { timestamp, attempts, timeout } = this;
            return { timestamp, attempts, timeout };
        }
        static {
            this.prototype.event_name = "connection_lost";
            this.prototype.publish = false;
        }
        reconnect() {
            void this.connection.deref()?.reconnect();
        }
    }
    exports.ConnectionLost = ConnectionLost;
    /**
     * Announce when a connection to the client has been reconnected.
     */
    class ClientReconnected extends ConnectionEvent {
        get event_values() {
            return {};
        }
        static {
            this.prototype.event_name = "client_reconnected";
        }
    }
    exports.ClientReconnected = ClientReconnected;
    let AxisClick = class AxisClick extends ModelEvent {
        model;
        value;
        constructor(model, value) {
            super();
            this.model = model;
            this.value = value;
        }
        get event_values() {
            const { value } = this;
            return { ...super.event_values, value };
        }
    };
    exports.AxisClick = AxisClick;
    exports.AxisClick = AxisClick = __decorate([
        event("axis_click")
    ], AxisClick);
    let ButtonClick = class ButtonClick extends ModelEvent {
    };
    exports.ButtonClick = ButtonClick;
    exports.ButtonClick = ButtonClick = __decorate([
        event("button_click")
    ], ButtonClick);
    let LegendItemClick = class LegendItemClick extends ModelEvent {
        model;
        item;
        constructor(model, item) {
            super();
            this.model = model;
            this.item = item;
        }
        get event_values() {
            const { item } = this;
            return { ...super.event_values, item };
        }
    };
    exports.LegendItemClick = LegendItemClick;
    exports.LegendItemClick = LegendItemClick = __decorate([
        event("legend_item_click")
    ], LegendItemClick);
    let MenuItemClick = class MenuItemClick extends ModelEvent {
        item;
        constructor(item) {
            super();
            this.item = item;
        }
        get event_values() {
            const { item } = this;
            return { ...super.event_values, item };
        }
    };
    exports.MenuItemClick = MenuItemClick;
    exports.MenuItemClick = MenuItemClick = __decorate([
        event("menu_item_click")
    ], MenuItemClick);
    let ValueSubmit = class ValueSubmit extends ModelEvent {
        value;
        constructor(value) {
            super();
            this.value = value;
        }
        get event_values() {
            const { value } = this;
            return { ...super.event_values, value };
        }
    };
    exports.ValueSubmit = ValueSubmit;
    exports.ValueSubmit = ValueSubmit = __decorate([
        event("value_submit")
    ], ValueSubmit);
    // A UIEvent is an event originating on a canvas this includes.
    // DOM events such as keystrokes as well as hammer, LOD, and range events.
    class UIEvent extends ModelEvent {
    }
    exports.UIEvent = UIEvent;
    let LODStart = class LODStart extends UIEvent {
    };
    exports.LODStart = LODStart;
    exports.LODStart = LODStart = __decorate([
        event("lodstart")
    ], LODStart);
    let LODEnd = class LODEnd extends UIEvent {
    };
    exports.LODEnd = LODEnd;
    exports.LODEnd = LODEnd = __decorate([
        event("lodend")
    ], LODEnd);
    let RangesUpdate = class RangesUpdate extends UIEvent {
        x0;
        x1;
        y0;
        y1;
        constructor(x0, x1, y0, y1) {
            super();
            this.x0 = x0;
            this.x1 = x1;
            this.y0 = y0;
            this.y1 = y1;
        }
        get event_values() {
            const { x0, x1, y0, y1 } = this;
            return { ...super.event_values, x0, x1, y0, y1 };
        }
    };
    exports.RangesUpdate = RangesUpdate;
    exports.RangesUpdate = RangesUpdate = __decorate([
        event("rangesupdate")
    ], RangesUpdate);
    let SelectionGeometry = class SelectionGeometry extends UIEvent {
        geometry;
        final;
        constructor(geometry, final) {
            super();
            this.geometry = geometry;
            this.final = final;
        }
        get event_values() {
            const { geometry, final } = this;
            return { ...super.event_values, geometry, final };
        }
    };
    exports.SelectionGeometry = SelectionGeometry;
    exports.SelectionGeometry = SelectionGeometry = __decorate([
        event("selectiongeometry")
    ], SelectionGeometry);
    let Reset = class Reset extends UIEvent {
    };
    exports.Reset = Reset;
    exports.Reset = Reset = __decorate([
        event("reset")
    ], Reset);
    class PointEvent extends UIEvent {
        sx;
        sy;
        x;
        y;
        modifiers;
        constructor(sx, sy, x, y, modifiers) {
            super();
            this.sx = sx;
            this.sy = sy;
            this.x = x;
            this.y = y;
            this.modifiers = modifiers;
        }
        get event_values() {
            const { sx, sy, x, y, modifiers } = this;
            return { ...super.event_values, sx, sy, x, y, modifiers };
        }
    }
    exports.PointEvent = PointEvent;
    let Pan = class Pan extends PointEvent {
        delta_x;
        delta_y;
        /* TODO: direction: -1 | 1 */
        constructor(sx, sy, x, y, delta_x, delta_y, modifiers) {
            super(sx, sy, x, y, modifiers);
            this.delta_x = delta_x;
            this.delta_y = delta_y;
        }
        get event_values() {
            const { delta_x, delta_y /*, direction*/ } = this;
            return { ...super.event_values, delta_x, delta_y /*, direction*/ };
        }
    };
    exports.Pan = Pan;
    exports.Pan = Pan = __decorate([
        event("pan")
    ], Pan);
    let Pinch = class Pinch extends PointEvent {
        scale;
        constructor(sx, sy, x, y, scale, modifiers) {
            super(sx, sy, x, y, modifiers);
            this.scale = scale;
        }
        get event_values() {
            const { scale } = this;
            return { ...super.event_values, scale };
        }
    };
    exports.Pinch = Pinch;
    exports.Pinch = Pinch = __decorate([
        event("pinch")
    ], Pinch);
    let Rotate = class Rotate extends PointEvent {
        rotation;
        constructor(sx, sy, x, y, rotation, modifiers) {
            super(sx, sy, x, y, modifiers);
            this.rotation = rotation;
        }
        get event_values() {
            const { rotation } = this;
            return { ...super.event_values, rotation };
        }
    };
    exports.Rotate = Rotate;
    exports.Rotate = Rotate = __decorate([
        event("rotate")
    ], Rotate);
    let MouseWheel = class MouseWheel extends PointEvent {
        delta;
        constructor(sx, sy, x, y, delta, modifiers) {
            super(sx, sy, x, y, modifiers);
            this.delta = delta;
        }
        get event_values() {
            const { delta } = this;
            return { ...super.event_values, delta };
        }
    };
    exports.MouseWheel = MouseWheel;
    exports.MouseWheel = MouseWheel = __decorate([
        event("wheel")
    ], MouseWheel);
    let MouseMove = class MouseMove extends PointEvent {
    };
    exports.MouseMove = MouseMove;
    exports.MouseMove = MouseMove = __decorate([
        event("mousemove")
    ], MouseMove);
    let MouseEnter = class MouseEnter extends PointEvent {
    };
    exports.MouseEnter = MouseEnter;
    exports.MouseEnter = MouseEnter = __decorate([
        event("mouseenter")
    ], MouseEnter);
    let MouseLeave = class MouseLeave extends PointEvent {
    };
    exports.MouseLeave = MouseLeave;
    exports.MouseLeave = MouseLeave = __decorate([
        event("mouseleave")
    ], MouseLeave);
    let Tap = class Tap extends PointEvent {
    };
    exports.Tap = Tap;
    exports.Tap = Tap = __decorate([
        event("tap")
    ], Tap);
    let DoubleTap = class DoubleTap extends PointEvent {
    };
    exports.DoubleTap = DoubleTap;
    exports.DoubleTap = DoubleTap = __decorate([
        event("doubletap")
    ], DoubleTap);
    let Press = class Press extends PointEvent {
    };
    exports.Press = Press;
    exports.Press = Press = __decorate([
        event("press")
    ], Press);
    let PressUp = class PressUp extends PointEvent {
    };
    exports.PressUp = PressUp;
    exports.PressUp = PressUp = __decorate([
        event("pressup")
    ], PressUp);
    let PanStart = class PanStart extends PointEvent {
    };
    exports.PanStart = PanStart;
    exports.PanStart = PanStart = __decorate([
        event("panstart")
    ], PanStart);
    let PanEnd = class PanEnd extends PointEvent {
    };
    exports.PanEnd = PanEnd;
    exports.PanEnd = PanEnd = __decorate([
        event("panend")
    ], PanEnd);
    let PinchStart = class PinchStart extends PointEvent {
    };
    exports.PinchStart = PinchStart;
    exports.PinchStart = PinchStart = __decorate([
        event("pinchstart")
    ], PinchStart);
    let PinchEnd = class PinchEnd extends PointEvent {
    };
    exports.PinchEnd = PinchEnd;
    exports.PinchEnd = PinchEnd = __decorate([
        event("pinchend")
    ], PinchEnd);
    let RotateStart = class RotateStart extends PointEvent {
    };
    exports.RotateStart = RotateStart;
    exports.RotateStart = RotateStart = __decorate([
        event("rotatestart")
    ], RotateStart);
    let RotateEnd = class RotateEnd extends PointEvent {
    };
    exports.RotateEnd = RotateEnd;
    exports.RotateEnd = RotateEnd = __decorate([
        event("rotateend")
    ], RotateEnd);
},
/* embed/standalone.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.add_document_standalone = add_document_standalone;
    const document_1 = require(5) /* ../document */;
    const view_manager_1 = require(68) /* ../core/view_manager */;
    const dom_view_1 = require(64) /* ../core/dom_view */;
    const types_1 = require(8) /* ../core/util/types */;
    const assert_1 = require(13) /* ../core/util/assert */;
    // A map from the root model IDs to their views.
    exports.index = new Proxy(new view_manager_1.ViewManager(), {
        get(manager, property) {
            if ((0, types_1.isString)(property)) {
                const view = manager.get_by_id(property);
                if (view != null) {
                    return view;
                }
            }
            return Reflect.get(manager, property);
        },
        has(manager, property) {
            if ((0, types_1.isString)(property)) {
                const view = manager.get_by_id(property);
                if (view != null) {
                    return true;
                }
            }
            return Reflect.has(manager, property);
        },
        ownKeys(manager) {
            return manager.roots.map((root) => root.model.id);
        },
        getOwnPropertyDescriptor(manager, property) {
            if ((0, types_1.isString)(property)) {
                const view = manager.get_by_id(property);
                if (view != null) {
                    return { configurable: true, enumerable: true, writable: false, value: view };
                }
            }
            return Reflect.getOwnPropertyDescriptor(manager, property);
        },
    });
    async function add_document_standalone(document, element, roots = [], use_for_title = false) {
        // this is a LOCAL index of views used only by this particular rendering
        // call, so we can remove the views we create.
        (0, assert_1.assert)(document.views_manager == null);
        const views = new view_manager_1.ViewManager([], exports.index);
        document.views_manager = views;
        async function render_view(model) {
            const view = await views.build_view(model);
            if (view instanceof dom_view_1.DOMView) {
                const i = document.all_roots.indexOf(model);
                const root_el = roots[i] ?? element;
                view.build(root_el);
            }
            return view;
        }
        async function render_model(model) {
            if (model.default_view != null) {
                const view = await render_view(model);
                exports.index.add(view);
            }
            else {
                document.notify_idle(model);
            }
        }
        function unrender_model(model) {
            const view = views.get(model);
            view?.remove();
        }
        for (const model of document.all_roots) {
            await render_model(model);
        }
        const { notifications } = document.config;
        if (notifications != null) {
            await render_view(notifications);
        }
        if (use_for_title) {
            window.document.title = document.title();
        }
        document.on_change((event) => {
            if (event instanceof document_1.RootAddedEvent) {
                void render_model(event.model);
            }
            else if (event instanceof document_1.RootRemovedEvent) {
                unrender_model(event.model);
            }
            else if (use_for_title && event instanceof document_1.TitleChangedEvent) {
                window.document.title = event.title;
            }
        });
        return views;
    }
},
/* embed/server.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports._get_ws_url = _get_ws_url;
    exports.add_document_from_session = add_document_from_session;
    const connection_1 = require(83) /* ../client/connection */;
    const logging_1 = require(11) /* ../core/logging */;
    const standalone_1 = require(81) /* ./standalone */;
    // @internal
    function _get_ws_url(app_path, absolute_url) {
        // if in an `srcdoc` iframe, try to get the absolute URL
        // from the `data-absolute-url` attribute if not passed explicitly
        if (absolute_url === undefined && _is_frame_HTMLElement(frameElement) && frameElement.dataset.absoluteUrl !== undefined) {
            absolute_url = frameElement.dataset.absoluteUrl;
        }
        let loc;
        if (absolute_url != null) {
            loc = document.createElement("a");
            loc.href = absolute_url;
        }
        else {
            loc = window.location;
        }
        const protocol = loc.protocol == "https:" ? "wss:" : "ws:";
        if (app_path != null) {
            if (app_path == "/") {
                app_path = "";
            }
        }
        else {
            app_path = loc.pathname.replace(/\/+$/, "");
        }
        return `${protocol}//${loc.host}${app_path}/ws`;
    }
    function _is_frame_HTMLElement(frame) {
        // `frameElement` is a delicate construct; it allows the document inside the frame to access
        // some (but not all) properties of the parent element in which the frame document is embedded.
        // Because it lives in a different DOM context than the frame's `window`, we cannot just use
        // `frameElement instanceof HTMLIFrameElement`; we could use `window.parent.HTMLIFrameElement`
        // but this can be blocked by CORS policy and throw an exception.
        if (frame === null) {
            return false;
        }
        if (frame.tagName.toUpperCase() === "IFRAME") {
            return true;
        }
        return false;
    }
    const _sessions = new Map();
    function _get_session(websocket_url, token, args_string) {
        const session_id = (0, connection_1.parse_token)(token).session_id;
        if (!_sessions.has(websocket_url)) {
            _sessions.set(websocket_url, new Map());
        }
        const subsessions = _sessions.get(websocket_url);
        if (!subsessions.has(session_id)) {
            subsessions.set(session_id, (0, connection_1.pull_session)(websocket_url, token, args_string));
        }
        return subsessions.get(session_id);
    }
    // Fill element with the roots from token
    async function add_document_from_session(websocket_url, token, element, roots = [], use_for_title = false) {
        const args_string = window.location.search.substring(1);
        let session;
        try {
            session = await _get_session(websocket_url, token, args_string);
        }
        catch (error) {
            const session_id = (0, connection_1.parse_token)(token).session_id;
            logging_1.logger.error(`Failed to load Bokeh session ${session_id}: ${error}`);
            throw error;
        }
        return (0, standalone_1.add_document_standalone)(session.document, element, roots, use_for_title);
    }
},
/* client/connection.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.parse_token = parse_token;
    exports.pull_session = pull_session;
    const bokeh_events_1 = require(80) /* ../core/bokeh_events */;
    const logging_1 = require(11) /* ../core/logging */;
    const document_1 = require(5) /* ../document */;
    const message_1 = require(84) /* ../protocol/message */;
    const receiver_1 = require(85) /* ../protocol/receiver */;
    const session_1 = require(86) /* ./session */;
    const assert_1 = require(13) /* ../core/util/assert */;
    exports.DEFAULT_SERVER_WEBSOCKET_URL = "ws://localhost:5006/ws";
    exports.DEFAULT_TOKEN = "eyJzZXNzaW9uX2lkIjogImRlZmF1bHQifQ";
    const MAX_RECONNECTION_ATTEMPTS = 5;
    const RECONNECT_BASE_DELAY = 1000;
    let _connection_count = 0;
    function parse_token(token) {
        let payload = token.split(".")[0];
        const mod = payload.length % 4;
        if (mod != 0) {
            payload = payload + "=".repeat(4 - mod);
        }
        return JSON.parse(atob(payload.replace(/_/g, "/").replace(/-/g, "+")));
    }
    // WebSocket close event is emitted before page is destroyed, resulting in an
    // unnecessary reconnect attempt and a UI notification just before page reloads.
    let _prevent_reconnect = false;
    addEventListener("beforeunload", () => {
        _prevent_reconnect = true;
    });
    class ClientConnection {
        url;
        token;
        args_string;
        _number = _connection_count++;
        socket = null;
        session = null;
        closed_permanently = false;
        id;
        _reconnection_attempts_left = MAX_RECONNECTION_ATTEMPTS;
        get reconnection_attempts() {
            return MAX_RECONNECTION_ATTEMPTS - this._reconnection_attempts_left;
        }
        _current_handler = null;
        _pending_replies = new Map();
        _pending_messages = [];
        _receiver = new receiver_1.Receiver();
        constructor(url = exports.DEFAULT_SERVER_WEBSOCKET_URL, token = exports.DEFAULT_TOKEN, args_string = null) {
            this.url = url;
            this.token = token;
            this.args_string = args_string;
            this.id = parse_token(token).session_id.split(".")[0];
            logging_1.logger.debug(`Creating websocket ${this._number} to '${this.url}' session '${this.id}'`);
        }
        async reconnect() {
            this._try_reconnect(true);
        }
        async connect() {
            if (this.closed_permanently) {
                throw new Error("Cannot connect() a closed ClientConnection");
            }
            if (this.socket != null) {
                throw new Error("Already connected");
            }
            this._current_handler = null;
            this._pending_replies.clear();
            this._pending_messages = [];
            try {
                let versioned_url = `${this.url}`;
                if (this.args_string != null && this.args_string.length > 0) {
                    versioned_url += `?${this.args_string}`;
                }
                this.socket = new WebSocket(versioned_url, ["bokeh", this.token]);
                return new Promise((resolve, reject) => {
                    (0, assert_1.assert)(this.socket != null);
                    // "arraybuffer" gives us binary data we can look at;
                    // if we just needed an opaque blob we could use "blob"
                    this.socket.binaryType = "arraybuffer";
                    this.socket.onopen = () => this._on_open(resolve, reject);
                    this.socket.onmessage = (event) => this._on_message(event);
                    this.socket.onclose = (event) => this._on_close(event, reject);
                    this.socket.onerror = () => this._on_error(reject);
                });
            }
            catch (error) {
                logging_1.logger.error(`websocket creation failed to url: ${this.url}`);
                logging_1.logger.error(` - ${error}`);
                throw error;
            }
        }
        close() {
            if (!this.closed_permanently) {
                logging_1.logger.debug(`Permanently closing websocket connection ${this._number}`);
                this.closed_permanently = true;
                if (this.socket != null) {
                    this.socket.close(1000, `close method called on ClientConnection ${this._number}`);
                }
                this.session._connection_closed();
            }
        }
        _try_reconnect(force = false) {
            if (this.closed_permanently) {
                logging_1.logger.info(`Websocket connection ${this._number} permanently disconnected, will not attempt to reconnect`);
            }
            else if (!force && this._reconnection_attempts_left <= 0) {
                logging_1.logger.info(`Websocket connection ${this._number} disconnected, will not attempt to automatically reconnect`);
            }
            else {
                if (this.socket?.readyState !== WebSocket.OPEN && this.socket?.readyState !== WebSocket.CONNECTING) {
                    this._reconnection_attempts_left -= 1;
                    logging_1.logger.debug(`Attempting to reconnect websocket ${this._number}, ${this._reconnection_attempts_left} attempts left`);
                    this.connect().then(() => {
                        logging_1.logger.info(`Reconnected websocket ${this._number}`);
                        this._reconnection_attempts_left = MAX_RECONNECTION_ATTEMPTS;
                        this.session?.document.event_manager.send_event(new bokeh_events_1.ClientReconnected());
                    }).catch(err => {
                        logging_1.logger.debug(`Could not reconnect ${this._number}, ${err}`);
                    });
                }
            }
        }
        _schedule_reconnect(milliseconds) {
            if (this.session == null) {
                return;
            }
            const { document } = this.session;
            const should_reconnect = document.config.reconnect_session && this._reconnection_attempts_left > 0;
            const timeout = should_reconnect ? milliseconds : null;
            const event = new bokeh_events_1.ConnectionLost(new WeakRef(this), this.reconnection_attempts, timeout);
            document.event_manager.send_event(event);
            if (should_reconnect) {
                setTimeout(() => this._try_reconnect(), milliseconds);
            }
        }
        send(message) {
            if (this.socket != null) {
                message.send(this.socket);
            }
            else {
                logging_1.logger.error("not connected so cannot send", message);
            }
        }
        async send_with_reply(message) {
            const reply = await new Promise((resolve, reject) => {
                this._pending_replies.set(message.msgid(), { resolve, reject });
                this.send(message);
            });
            if (reply.msgtype() == "ERROR") {
                throw new Error(`Error reply ${reply.content.text}`);
            }
            else {
                return reply;
            }
        }
        async _pull_doc_json() {
            const message = message_1.Message.create("PULL-DOC-REQ", {}, {});
            const reply = await this.send_with_reply(message);
            if (!("doc" in reply.content)) {
                throw new Error("No 'doc' field in PULL-DOC-REPLY");
            }
            return { doc_json: reply.content.doc, buffers: reply.buffers };
        }
        async _repull_session_doc(resolve, reject) {
            logging_1.logger.debug(this.session != null ? "Repulling session" : "Pulling session for first time");
            try {
                const { doc_json, buffers } = await this._pull_doc_json();
                if (this.session == null) {
                    if (this.closed_permanently) {
                        logging_1.logger.debug("Got new document after connection was already closed");
                        reject(new Error("The connection has been closed"));
                    }
                    else {
                        const events = [];
                        const document = document_1.Document.from_json(doc_json, events, buffers);
                        this.session = new session_1.ClientSession(this, document);
                        // Send back change events that happened during model initialization.
                        for (const event of events) {
                            document._trigger_on_change(event);
                        }
                        for (const msg of this._pending_messages) {
                            this.session.handle(msg);
                        }
                        this._pending_messages = [];
                        logging_1.logger.debug("Created a new session from new pulled doc");
                        resolve(this.session);
                    }
                }
                else {
                    this.session.document.replace_with_json(doc_json, buffers);
                    logging_1.logger.debug("Updated existing session with new pulled doc");
                    resolve(this.session);
                }
            }
            catch (error) {
                console.trace(error);
                logging_1.logger.error(`Failed to repull session ${error}`);
                reject(error instanceof Error ? error : `${error}`);
            }
        }
        _on_open(resolve, reject) {
            logging_1.logger.info(`Websocket connection ${this._number} is now open`);
            this._current_handler = (message) => {
                this._awaiting_ack_handler(message, resolve, reject);
            };
        }
        _on_message(event) {
            if (this._current_handler == null) {
                logging_1.logger.error("Got a message with no current handler set");
            }
            try {
                this._receiver.consume(event.data);
            }
            catch (e) {
                this._close_bad_protocol(`${e}`);
            }
            const msg = this._receiver.message;
            if (msg != null) {
                const problem = msg.problem();
                if (problem != null) {
                    this._close_bad_protocol(problem);
                }
                this._current_handler(msg);
            }
        }
        /**
         * The reconnect delay exponentially increases after each attempt. The
         * first attempt is done immediately.
         */
        _reconnect_delay() {
            const retries = MAX_RECONNECTION_ATTEMPTS - this._reconnection_attempts_left;
            return retries == 0 ? 0 : RECONNECT_BASE_DELAY * 2 ** retries;
        }
        _on_close(event, reject) {
            logging_1.logger.info(`Lost websocket ${this._number} connection, ${event.code} (${event.reason})`);
            this.socket = null;
            this._pending_replies.forEach((pr) => pr.reject("Disconnected"));
            this._pending_replies.clear();
            if (!this.closed_permanently && !_prevent_reconnect) {
                logging_1.logger.debug(`Pending schedule_reconnect for ${this._number}`);
                this._schedule_reconnect(this._reconnect_delay());
            }
            reject(new Error(`Lost websocket connection, ${event.code} (${event.reason})`));
        }
        _on_error(reject) {
            logging_1.logger.debug(`Websocket error on socket ${this._number}`);
            const msg = "Could not open websocket";
            logging_1.logger.error(`Failed to connect to Bokeh server: ${msg}`);
            reject(new Error(msg));
        }
        _close_bad_protocol(detail) {
            logging_1.logger.error(`Closing connection: ${detail}`);
            if (this.socket != null) {
                this.socket.close(1002, detail);
            } // 1002 = protocol error
        }
        _awaiting_ack_handler(message, resolve, reject) {
            if (message.msgtype() === "ACK") {
                this._current_handler = (message) => this._steady_state_handler(message);
                // Reload any sessions
                void this._repull_session_doc(resolve, reject);
            }
            else {
                this._close_bad_protocol("First message was not an ACK");
            }
        }
        _steady_state_handler(message) {
            const reqid = message.reqid();
            const pr = this._pending_replies.get(reqid);
            if (pr != null) {
                this._pending_replies.delete(reqid);
                pr.resolve(message);
            }
            else if (this.session != null) {
                this.session.handle(message);
            }
            else if (message.msgtype() != "PATCH-DOC") {
                // This branch can be executed only before we get the document.
                // When we get the document, all of the patches will already be incorporated.
                // In general, it's not possible to apply patches received before the document,
                // since they may change some models that were removed before serving the document.
                this._pending_messages.push(message);
            }
        }
    }
    exports.ClientConnection = ClientConnection;
    function pull_session(url, token, args_string) {
        const connection = new ClientConnection(url, token, args_string);
        return connection.connect();
    }
},
/* protocol/message.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const serialization_1 = require(33) /* ../core/serialization */;
    const string_1 = require(41) /* ../core/util/string */;
    const assert_1 = require(13) /* ../core/util/assert */;
    class Message {
        header;
        metadata;
        content;
        _buffers = new Map();
        get buffers() {
            return this._buffers;
        }
        constructor(header, metadata, content) {
            this.header = header;
            this.metadata = metadata;
            this.content = content;
        }
        static assemble(header_json, metadata_json, content_json) {
            const header = JSON.parse(header_json);
            const metadata = JSON.parse(metadata_json);
            const content = JSON.parse(content_json);
            return new Message(header, metadata, content);
        }
        assemble_buffer(buf_header, buf_payload) {
            const nb = this.header.num_buffers ?? 0;
            if (nb <= this._buffers.size) {
                throw new Error(`too many buffers received, expecting ${nb}`);
            }
            const { id } = JSON.parse(buf_header);
            this._buffers.set(id, buf_payload);
        }
        static create(msgtype, metadata, content) {
            const header = Message.create_header(msgtype);
            return new Message(header, metadata, content);
        }
        static create_header(msgtype) {
            return {
                msgid: (0, string_1.unique_id)(),
                msgtype,
            };
        }
        complete() {
            const { num_buffers } = this.header;
            return num_buffers == null || this._buffers.size == num_buffers;
        }
        send(socket) {
            (0, assert_1.assert)(this.header.num_buffers == null);
            const buffers = [];
            const content_json = JSON.stringify(this.content, (_, val) => {
                if (val instanceof serialization_1.Buffer) {
                    const ref = { id: `${buffers.length}` };
                    buffers.push([ref, val.buffer]);
                    return ref;
                }
                else {
                    return val;
                }
            });
            const num_buffers = buffers.length;
            if (num_buffers > 0) {
                this.header.num_buffers = num_buffers;
            }
            const header_json = JSON.stringify(this.header);
            const metadata_json = JSON.stringify(this.metadata);
            socket.send(header_json);
            socket.send(metadata_json);
            socket.send(content_json);
            for (const [ref, buffer] of buffers) {
                socket.send(JSON.stringify(ref));
                socket.send(buffer);
            }
        }
        msgid() {
            return this.header.msgid;
        }
        msgtype() {
            return this.header.msgtype;
        }
        reqid() {
            return this.header.reqid;
        }
        // return the reason we should close on bad protocol, if there is one
        problem() {
            if (!("msgid" in this.header)) {
                return "No msgid in header";
            }
            else if (!("msgtype" in this.header)) {
                return "No msgtype in header";
            }
            else {
                return null;
            }
        }
    }
    exports.Message = Message;
},
/* protocol/receiver.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const message_1 = require(84) /* ./message */;
    const types_1 = require(8) /* ../core/util/types */;
    const assert_1 = require(13) /* ../core/util/assert */;
    class Receiver {
        message = null;
        _partial = null;
        _fragments = [];
        _buf_header = null;
        _current_consumer = this._HEADER;
        consume(fragment) {
            this._current_consumer(fragment);
        }
        _HEADER(fragment) {
            this._assume_text(fragment);
            this.message = null;
            this._partial = null;
            this._fragments = [fragment];
            this._buf_header = null;
            this._current_consumer = this._METADATA;
        }
        _METADATA(fragment) {
            this._assume_text(fragment);
            this._fragments.push(fragment);
            this._current_consumer = this._CONTENT;
        }
        _CONTENT(fragment) {
            this._assume_text(fragment);
            this._fragments.push(fragment);
            const [header_json, metadata_json, content_json] = this._fragments;
            (0, assert_1.assert)(header_json != null && metadata_json != null && content_json != null);
            this._partial = message_1.Message.assemble(header_json, metadata_json, content_json);
            this._check_complete();
        }
        _BUFFER_HEADER(fragment) {
            this._assume_text(fragment);
            this._buf_header = fragment;
            this._current_consumer = this._BUFFER_PAYLOAD;
        }
        _BUFFER_PAYLOAD(fragment) {
            this._assume_binary(fragment);
            (0, assert_1.assert)(this._partial != null && this._buf_header != null);
            this._partial.assemble_buffer(this._buf_header, fragment);
            this._check_complete();
        }
        _assume_text(fragment) {
            if (!(0, types_1.isString)(fragment)) {
                throw new Error("Expected text fragment but received binary fragment");
            }
        }
        _assume_binary(fragment) {
            if (!(fragment instanceof ArrayBuffer)) {
                throw new Error("Expected binary fragment but received text fragment");
            }
        }
        _check_complete() {
            if (this._partial.complete()) {
                this.message = this._partial;
                this._current_consumer = this._HEADER;
            }
            else {
                this._current_consumer = this._BUFFER_HEADER;
            }
        }
    }
    exports.Receiver = Receiver;
},
/* client/session.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const document_1 = require(5) /* ../document */;
    const message_1 = require(84) /* ../protocol/message */;
    const logging_1 = require(11) /* ../core/logging */;
    class ClientSession {
        _connection;
        document;
        _document_listener = (event) => {
            this._document_changed(event);
        };
        constructor(_connection, document) {
            this._connection = _connection;
            this.document = document;
            this.document.on_change(this._document_listener, true);
        }
        // XXX: this is only needed in tests
        get id() {
            return this._connection.id;
        }
        handle(message) {
            const msgtype = message.msgtype();
            switch (msgtype) {
                case "PATCH-DOC": {
                    this._handle_patch(message);
                    break;
                }
                case "OK": {
                    this._handle_ok(message);
                    break;
                }
                case "ERROR": {
                    this._handle_error(message);
                    break;
                }
                default:
                    logging_1.logger.debug(`Doing nothing with message '${msgtype}'`);
            }
        }
        // TODO: notify_connection_retry ?
        // data: time (ms) to next retry, connection attempt number
        close() {
            this._connection.close();
        }
        /*protected*/ _connection_closed() {
            this.document.remove_on_change(this._document_listener);
        }
        // Sends a request to the server for info about the server, such as its Bokeh
        // version. Returns a promise, the value of the promise is a free-form dictionary
        // of server details.
        async request_server_info() {
            const message = message_1.Message.create("SERVER-INFO-REQ", {}, {});
            const reply = await this._connection.send_with_reply(message);
            return reply.content;
        }
        // Sends some request to the server (no guarantee about which one) and returns
        // a promise which is completed when the server replies. The purpose of this
        // is that if you wait for the promise to be completed, you know the server
        // has processed the request. This is useful when writing tests because once
        // the server has processed this request it should also have processed any
        // events or requests you sent previously, which means you can check for the
        // results of that processing without a race condition. (This assumes the
        // server processes events in sequence, which it mostly has to semantically,
        // since reordering events might change the final state.)
        async force_roundtrip() {
            await this.request_server_info();
        }
        _document_changed(event) {
            const events = (() => {
                const events = event instanceof document_1.DocumentEventBatch ? (event.sync ? event.events : []) : [event];
                return events.filter((event) => event.sync);
            })();
            if (events.length == 0) {
                return;
            }
            const patch = this.document.create_json_patch(events);
            // TODO (havocp) the connection may be closed here, which will
            // cause this send to throw an error - need to deal with it more cleanly.
            const message = message_1.Message.create("PATCH-DOC", {}, patch);
            this._connection.send(message);
        }
        _handle_patch(message) {
            this.document.apply_json_patch(message.content, message.buffers);
        }
        _handle_ok(message) {
            logging_1.logger.trace(`Unhandled OK reply to ${message.reqid()}`);
        }
        _handle_error(message) {
            logging_1.logger.error(`Unhandled ERROR reply to ${message.reqid()}: ${message.content.text}`);
        }
    }
    exports.ClientSession = ClientSession;
},
/* embed/dom.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports._resolve_element = _resolve_element;
    exports._resolve_root_elements = _resolve_root_elements;
    const dom_1 = require(61) /* ../core/dom */;
    const types_1 = require(8) /* ../core/util/types */;
    function _get_element(target) {
        let element = (0, types_1.isString)(target) ? document.getElementById(target) : target;
        if (element == null) {
            throw new Error(`Error rendering Bokeh model: could not find ${(0, types_1.isString)(target) ? `#${target}` : target} HTML tag`);
        }
        if (!(0, dom_1.contains)(document.body, element)) {
            throw new Error(`Error rendering Bokeh model: element ${(0, types_1.isString)(target) ? `#${target}` : target} must be under <body>`);
        }
        // If autoload script, replace script tag with div for embedding.
        if (element instanceof HTMLElement && element.tagName == "SCRIPT") {
            const root_el = (0, dom_1.div)();
            element.replaceWith(root_el);
            element = root_el;
        }
        return element;
    }
    function _resolve_element(item) {
        const { elementid } = item;
        if (elementid != null) {
            return _get_element(elementid);
        }
        else {
            return document.body;
        }
    }
    function _resolve_root_elements(item) {
        const roots = [];
        if (item.root_ids != null && item.roots != null) {
            for (const root_id of item.root_ids) {
                roots.push(_get_element(item.roots[root_id]));
            }
        }
        return roots;
    }
},
/* embed/notebook.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.embed_items_notebook = embed_items_notebook;
    const document_1 = require(5) /* ../document */;
    const receiver_1 = require(85) /* ../protocol/receiver */;
    const logging_1 = require(11) /* ../core/logging */;
    const object_1 = require(9) /* ../core/util/object */;
    const standalone_1 = require(81) /* ./standalone */;
    const dom_1 = require(87) /* ./dom */;
    // This exists to allow the @bokeh/jupyter_bokeh extension to store the
    // notebook kernel so that _init_comms can register the comms target.
    // This has to be available at Bokeh.embed.kernels in JupyterLab.
    exports.kernels = {};
    function _handle_notebook_comms(receiver, comm_msg) {
        if (comm_msg.buffers.length > 0) {
            receiver.consume(comm_msg.buffers[0].buffer);
        }
        else {
            receiver.consume(comm_msg.content.data);
        }
        const msg = receiver.message;
        if (msg != null) {
            this.apply_json_patch(msg.content, msg.buffers);
        }
    }
    function _init_comms(target, doc) {
        if (typeof Jupyter !== "undefined" && Jupyter.notebook.kernel != null) {
            logging_1.logger.info(`Registering Jupyter comms for target ${target}`);
            const comm_manager = Jupyter.notebook.kernel.comm_manager;
            try {
                comm_manager.register_target(target, (comm) => {
                    logging_1.logger.info(`Registering Jupyter comms for target ${target}`);
                    const r = new receiver_1.Receiver();
                    comm.on_msg(_handle_notebook_comms.bind(doc, r));
                });
            }
            catch (e) {
                logging_1.logger.warn(`Jupyter comms failed to register. push_notebook() will not function. (exception reported: ${e})`);
            }
        }
        else if (doc.roots()[0].id in exports.kernels) {
            logging_1.logger.info(`Registering JupyterLab comms for target ${target}`);
            const kernel = exports.kernels[doc.roots()[0].id];
            try {
                kernel.registerCommTarget(target, (comm) => {
                    logging_1.logger.info(`Registering JupyterLab comms for target ${target}`);
                    const r = new receiver_1.Receiver();
                    comm.onMsg = _handle_notebook_comms.bind(doc, r);
                });
            }
            catch (e) {
                logging_1.logger.warn(`Jupyter comms failed to register. push_notebook() will not function. (exception reported: ${e})`);
            }
        }
        else if (typeof google != "undefined" && google.colab.kernel != null) {
            logging_1.logger.info(`Registering Google Colab comms for target ${target}`);
            const comm_manager = google.colab.kernel.comms;
            try {
                comm_manager.registerTarget(target, async (comm) => {
                    logging_1.logger.info(`Registering Google Colab comms for target ${target}`);
                    const r = new receiver_1.Receiver();
                    for await (const message of comm.messages) {
                        const content = { data: message.data };
                        const buffers = [];
                        for (const buffer of message.buffers ?? []) {
                            buffers.push(new DataView(buffer));
                        }
                        const msg = { content, buffers };
                        _handle_notebook_comms.bind(doc)(r, msg);
                    }
                });
            }
            catch (e) {
                logging_1.logger.warn(`Google Colab comms failed to register. push_notebook() will not function. (exception reported: ${e})`);
            }
        }
        else {
            console.warn("Jupyter notebooks comms not available. push_notebook() will not function. If running JupyterLab ensure the latest @bokeh/jupyter_bokeh extension is installed. In an exported notebook this warning is expected.");
        }
    }
    async function embed_items_notebook(docs_json, render_items) {
        if ((0, object_1.size)(docs_json) != 1) {
            throw new Error("embed_items_notebook expects exactly one document in docs_json");
        }
        const document = document_1.Document.from_json((0, object_1.values)(docs_json)[0]);
        for (const item of render_items) {
            if (item.notebook_comms_target != null) {
                _init_comms(item.notebook_comms_target, document);
            }
            const element = (0, dom_1._resolve_element)(item);
            const roots = (0, dom_1._resolve_root_elements)(item);
            await (0, standalone_1.add_document_standalone)(document, element, roots);
            for (const root of roots) {
                if (root instanceof HTMLElement) {
                    root.removeAttribute("id");
                }
            }
        }
    }
},
/* protocol/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(84) /* ./message */, exports);
    tslib_1.__exportStar(require(85) /* ./receiver */, exports);
},
/* safely.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.safely = safely;
    // Keep this code as terse and as close to vanila JS as possible. If we
    // arrived here, it means we should trust no one and need to act properly.
    function _burst_into_flames(error) {
        // Make box
        const box = document.createElement("div");
        box.style.backgroundColor = "#f2dede";
        box.style.border = "1px solid #a94442";
        box.style.borderRadius = "4px";
        box.style.display = "inline-block";
        box.style.fontFamily = "sans-serif";
        box.style.marginTop = "5px";
        box.style.minWidth = "200px";
        box.style.padding = "5px 5px 5px 10px";
        box.classList.add("bokeh-error-box-into-flames");
        // Make button
        const button = document.createElement("span");
        button.style.backgroundColor = "#a94442";
        button.style.borderRadius = "0px 4px 0px 0px";
        button.style.color = "white";
        button.style.cursor = "pointer";
        button.style.cssFloat = "right";
        button.style.fontSize = "0.8em";
        button.style.margin = "-6px -6px 0px 0px";
        button.style.padding = "2px 5px 4px 5px";
        button.title = "close";
        button.setAttribute("aria-label", "close");
        button.appendChild(document.createTextNode("x"));
        button.addEventListener("click", () => body.removeChild(box));
        // Make title
        const title = document.createElement("h3");
        title.style.color = "#a94442";
        title.style.margin = "8px 0px 0px 0px";
        title.style.padding = "0px";
        title.appendChild(document.createTextNode("Bokeh Error"));
        // Make message
        const message = document.createElement("pre");
        message.style.whiteSpace = "unset";
        message.style.overflowX = "auto";
        message.appendChild(document.createTextNode(error));
        // Add pieces to box
        box.appendChild(button);
        box.appendChild(title);
        box.appendChild(message);
        // Put box in doc
        const body = document.getElementsByTagName("body")[0];
        body.insertBefore(box, body.firstChild);
    }
    function safely(fn, silent = false) {
        try {
            return fn();
        }
        catch (error) {
            const text = error instanceof Error && error.stack != null ? error.stack : `${error}`;
            _burst_into_flames(text);
            if (!silent) {
                throw error;
            }
            else {
                return;
            }
        }
    }
},
/* models/main.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const base_1 = require(7) /* ../base */;
    const AllModels = tslib_1.__importStar(require(92) /* ./ */);
    (0, base_1.register_models)(AllModels);
    const DOMModels = tslib_1.__importStar(require(634) /* ./dom */);
    (0, base_1.register_models)(DOMModels);
},
/* models/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(93) /* ./annotations */, exports);
    tslib_1.__exportStar(require(348) /* ./axes */, exports);
    tslib_1.__exportStar(require(422) /* ./callbacks */, exports);
    tslib_1.__exportStar(require(432) /* ./canvas */, exports);
    tslib_1.__exportStar(require(433) /* ./comparisons */, exports);
    tslib_1.__exportStar(require(437) /* ./coordinates */, exports);
    tslib_1.__exportStar(require(438) /* ./expressions */, exports);
    tslib_1.__exportStar(require(447) /* ./filters */, exports);
    tslib_1.__exportStar(require(326) /* ./formatters */, exports);
    tslib_1.__exportStar(require(456) /* ./glyphs */, exports);
    tslib_1.__exportStar(require(497) /* ./graphics */, exports);
    tslib_1.__exportStar(require(498) /* ./graphs */, exports);
    tslib_1.__exportStar(require(502) /* ./grids */, exports);
    tslib_1.__exportStar(require(503) /* ./layouts */, exports);
    tslib_1.__exportStar(require(354) /* ./mappers */, exports);
    tslib_1.__exportStar(require(522) /* ./misc */, exports);
    tslib_1.__exportStar(require(524) /* ./text */, exports);
    tslib_1.__exportStar(require(525) /* ./transforms */, exports);
    tslib_1.__exportStar(require(534) /* ./plots */, exports);
    tslib_1.__exportStar(require(540) /* ./policies */, exports);
    tslib_1.__exportStar(require(541) /* ./random */, exports);
    tslib_1.__exportStar(require(341) /* ./ranges */, exports);
    tslib_1.__exportStar(require(543) /* ./renderers */, exports);
    tslib_1.__exportStar(require(339) /* ./scales */, exports);
    tslib_1.__exportStar(require(546) /* ./selections */, exports);
    tslib_1.__exportStar(require(547) /* ./selectors */, exports);
    tslib_1.__exportStar(require(552) /* ./sources */, exports);
    tslib_1.__exportStar(require(283) /* ./tickers */, exports);
    tslib_1.__exportStar(require(557) /* ./tiles */, exports);
    tslib_1.__exportStar(require(566) /* ./textures */, exports);
    tslib_1.__exportStar(require(570) /* ./ui */, exports);
    tslib_1.__exportStar(require(587) /* ./tools */, exports);
},
/* models/annotations/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    var area_visuals_1 = require(94) /* ./area_visuals */;
    __esExport("AreaVisuals", area_visuals_1.AreaVisuals);
    var annotation_1 = require(96) /* ./annotation */;
    __esExport("Annotation", annotation_1.Annotation);
    var arrow_1 = require(140) /* ./arrow */;
    __esExport("Arrow", arrow_1.Arrow);
    var arrow_head_1 = require(252) /* ./arrow_head */;
    __esExport("ArrowHead", arrow_head_1.ArrowHead);
    var arrow_head_2 = require(252) /* ./arrow_head */;
    __esExport("OpenHead", arrow_head_2.OpenHead);
    var arrow_head_3 = require(252) /* ./arrow_head */;
    __esExport("NormalHead", arrow_head_3.NormalHead);
    var arrow_head_4 = require(252) /* ./arrow_head */;
    __esExport("TeeHead", arrow_head_4.TeeHead);
    var arrow_head_5 = require(252) /* ./arrow_head */;
    __esExport("VeeHead", arrow_head_5.VeeHead);
    var base_color_bar_1 = require(254) /* ./base_color_bar */;
    __esExport("BaseColorBar", base_color_bar_1.BaseColorBar);
    var band_1 = require(343) /* ./band */;
    __esExport("Band", band_1.Band);
    var box_annotation_1 = require(345) /* ./box_annotation */;
    __esExport("BoxAnnotation", box_annotation_1.BoxAnnotation);
    __esExport("BoxInteractionHandles", box_annotation_1.BoxInteractionHandles);
    var color_bar_1 = require(347) /* ./color_bar */;
    __esExport("ColorBar", color_bar_1.ColorBar);
    var contour_color_bar_1 = require(364) /* ./contour_color_bar */;
    __esExport("ContourColorBar", contour_color_bar_1.ContourColorBar);
    var label_1 = require(365) /* ./label */;
    __esExport("Label", label_1.Label);
    var label_set_1 = require(366) /* ./label_set */;
    __esExport("LabelSet", label_set_1.LabelSet);
    var legend_1 = require(367) /* ./legend */;
    __esExport("Legend", legend_1.Legend);
    var legend_item_1 = require(368) /* ./legend_item */;
    __esExport("LegendItem", legend_item_1.LegendItem);
    var poly_annotation_1 = require(370) /* ./poly_annotation */;
    __esExport("PolyAnnotation", poly_annotation_1.PolyAnnotation);
    var scale_bar_1 = require(371) /* ./scale_bar */;
    __esExport("ScaleBar", scale_bar_1.ScaleBar);
    var dimensional_1 = require(372) /* ./dimensional */;
    __esExport("Metric", dimensional_1.Metric);
    __esExport("ReciprocalMetric", dimensional_1.ReciprocalMetric);
    __esExport("MetricLength", dimensional_1.MetricLength);
    __esExport("ReciprocalMetricLength", dimensional_1.ReciprocalMetricLength);
    __esExport("ImperialLength", dimensional_1.ImperialLength);
    __esExport("Angular", dimensional_1.Angular);
    var size_bar_1 = require(373) /* ./size_bar */;
    __esExport("SizeBar", size_bar_1.SizeBar);
    var slope_1 = require(414) /* ./slope */;
    __esExport("Slope", slope_1.Slope);
    var span_1 = require(415) /* ./span */;
    __esExport("Span", span_1.Span);
    var text_annotation_1 = require(256) /* ./text_annotation */;
    __esExport("TextAnnotation", text_annotation_1.TextAnnotation);
    var title_1 = require(255) /* ./title */;
    __esExport("Title", title_1.Title);
    var toolbar_panel_1 = require(404) /* ./toolbar_panel */;
    __esExport("ToolbarPanel", toolbar_panel_1.ToolbarPanel);
    var whisker_1 = require(416) /* ./whisker */;
    __esExport("Whisker", whisker_1.Whisker);
    tslib_1.__exportStar(require(417) /* ./html */, exports);
},
/* models/annotations/area_visuals.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const model_1 = require(52) /* ../../model */;
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    class AreaVisuals extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        clone(attrs) {
            return super.clone(attrs);
        }
        static {
            this.mixins([
                mixins.Line,
                mixins.Fill,
                mixins.Hatch,
                ["hover_", mixins.Line],
                ["hover_", mixins.Fill],
                ["hover_", mixins.Hatch],
            ]);
        }
    }
    exports.AreaVisuals = AreaVisuals;
},
/* core/property_mixins.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.attrs_of = attrs_of;
    const tslib_1 = require(1) /* tslib */;
    const p = tslib_1.__importStar(require(20) /* ./properties */);
    const enums_1 = require(21) /* ./enums */;
    const k = tslib_1.__importStar(require(22) /* ./kinds */);
    const object_1 = require(9) /* ./util/object */;
    const types_1 = require(8) /* ./util/types */;
    exports.Line = {
        line_color: [k.Nullable(k.Color), "black"],
        line_alpha: [k.Alpha, 1.0],
        line_width: [k.Float, 1],
        line_join: [enums_1.LineJoin, "bevel"],
        line_cap: [enums_1.LineCap, "butt"],
        line_dash: [k.Or(enums_1.LineDash, k.Array(k.Float)), []],
        line_dash_offset: [k.Float, 0],
    };
    exports.Fill = {
        fill_color: [k.Nullable(k.Color), "gray"],
        fill_alpha: [k.Alpha, 1.0],
    };
    exports.Image = {
        global_alpha: [k.Alpha, 1.0],
    };
    exports.Hatch = {
        hatch_color: [k.Nullable(k.Color), "black"],
        hatch_alpha: [k.Alpha, 1.0],
        hatch_scale: [k.Float, 12.0],
        hatch_pattern: [k.Nullable(k.Or(enums_1.HatchPatternType, k.Str)), null],
        hatch_weight: [k.Float, 1.0],
        hatch_extra: [k.Dict(k.AnyRef()), {}], // XXX: recursive imports
    };
    exports.Text = {
        text_color: [k.Nullable(k.Color), "#444444"],
        text_outline_color: [k.Nullable(k.Color), null],
        text_outline_width: [k.Float, 1.0],
        text_alpha: [k.Alpha, 1.0],
        text_font: [p.Font, "helvetica"],
        text_font_size: [k.FontSize, "16px"],
        text_font_style: [enums_1.FontStyle, "normal"],
        text_align: [enums_1.TextAlign, "left"],
        text_baseline: [enums_1.TextBaseline, "bottom"],
        text_line_height: [k.Float, 1.2],
    };
    exports.LineScalar = {
        line_color: [p.ColorScalar, "black"],
        line_alpha: [p.NumberScalar, 1.0],
        line_width: [p.NumberScalar, 1],
        line_join: [p.LineJoinScalar, "bevel"],
        line_cap: [p.LineCapScalar, "butt"],
        line_dash: [p.LineDashScalar, []],
        line_dash_offset: [p.NumberScalar, 0],
    };
    exports.FillScalar = {
        fill_color: [p.ColorScalar, "gray"],
        fill_alpha: [p.NumberScalar, 1.0],
    };
    exports.ImageScalar = {
        global_alpha: [p.NumberScalar, 1.0],
    };
    exports.HatchScalar = {
        hatch_color: [p.ColorScalar, "black"],
        hatch_alpha: [p.NumberScalar, 1.0],
        hatch_scale: [p.NumberScalar, 12.0],
        hatch_pattern: [p.NullStringScalar, null],
        hatch_weight: [p.NumberScalar, 1.0],
        hatch_extra: [p.DictScalar, {}],
    };
    exports.TextScalar = {
        text_color: [p.ColorScalar, "#444444"],
        text_outline_color: [p.ColorScalar, null],
        text_outline_width: [p.NumberScalar, 1.0],
        text_alpha: [p.NumberScalar, 1.0],
        text_font: [p.FontScalar, "helvetica"],
        text_font_size: [p.FontSizeScalar, "16px"],
        text_font_style: [p.FontStyleScalar, "normal"],
        text_align: [p.TextAlignScalar, "left"],
        text_baseline: [p.TextBaselineScalar, "bottom"],
        text_line_height: [p.NumberScalar, 1.2],
    };
    exports.LineVector = {
        line_color: [p.ColorSpec, "black"],
        line_alpha: [p.NumberSpec, 1.0],
        line_width: [p.NumberSpec, 1],
        line_join: [p.LineJoinSpec, "bevel"],
        line_cap: [p.LineCapSpec, "butt"],
        line_dash: [p.LineDashSpec, []],
        line_dash_offset: [p.NumberSpec, 0],
    };
    exports.FillVector = {
        fill_color: [p.ColorSpec, "gray"],
        fill_alpha: [p.NumberSpec, 1.0],
    };
    exports.ImageVector = {
        global_alpha: [p.NumberSpec, 1.0],
    };
    exports.HatchVector = {
        hatch_color: [p.ColorSpec, "black"],
        hatch_alpha: [p.NumberSpec, 1.0],
        hatch_scale: [p.NumberSpec, 12.0],
        hatch_pattern: [p.NullStringSpec, null],
        hatch_weight: [p.NumberSpec, 1.0],
        hatch_extra: [p.DictScalar, {}],
    };
    exports.TextVector = {
        text_color: [p.ColorSpec, "#444444"],
        text_outline_color: [p.ColorSpec, null],
        text_outline_width: [p.NumberSpec, 1.0],
        text_alpha: [p.NumberSpec, 1.0],
        text_font: [p.FontSpec, "helvetica"],
        text_font_size: [p.FontSizeSpec, "16px"],
        text_font_style: [p.FontStyleSpec, "normal"],
        text_align: [p.TextAlignSpec, "left"],
        text_baseline: [p.TextBaselineSpec, "bottom"],
        text_line_height: [p.NumberSpec, 1.2],
    };
    function attrs_of(model, prefix, mixin, new_prefix = false) {
        const attrs = {};
        for (const attr of (0, object_1.keys)(mixin)) {
            const prefixed_attr = `${prefix}${attr}`;
            const value = model[prefixed_attr];
            const new_attr = (() => {
                if ((0, types_1.isString)(new_prefix)) {
                    return `${new_prefix}${attr}`;
                }
                else if (new_prefix) {
                    return prefixed_attr;
                }
                else {
                    return attr;
                }
            })();
            attrs[new_attr] = value;
        }
        return attrs;
    }
},
/* models/annotations/annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const composite_renderer_1 = require(97) /* ../renderers/composite_renderer */;
    class AnnotationView extends composite_renderer_1.CompositeRendererView {
        get bbox() {
            return super.bbox ?? this.layout?.bbox;
        }
        get_size() {
            if (this.displayed) {
                const { width, height } = this._get_size();
                return { width: Math.round(width), height: Math.round(height) };
            }
            else {
                return { width: 0, height: 0 };
            }
        }
        _get_size() {
            throw new Error("not implemented");
        }
        connect_signals() {
            super.connect_signals();
            const p = this.model.properties;
            this.on_change(p.visible, () => {
                if (this.layout != null) {
                    this.layout.visible = this.model.visible;
                    this.plot_view.request_layout();
                }
            });
        }
        get needs_clip() {
            return this.layout == null; // TODO: change this, when center layout is fully implemented
        }
    }
    exports.AnnotationView = AnnotationView;
    class Annotation extends composite_renderer_1.CompositeRenderer {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.override({
                level: "annotation",
            });
        }
    }
    exports.Annotation = Annotation;
},
/* models/renderers/composite_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const renderer_1 = require(98) /* ./renderer */;
    const ui_element_1 = require(55) /* ../ui/ui_element */;
    const dom_node_1 = require(130) /* ../dom/dom_node */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const kinds_1 = require(22) /* ../../core/kinds */;
    const layout_dom_1 = require(131) /* ../layouts/layout_dom */;
    // TODO UIElement needs to inherit from DOMNode
    exports.ElementLike = (0, kinds_1.Or)((0, kinds_1.Ref)(ui_element_1.UIElement), (0, kinds_1.Ref)(dom_node_1.DOMNode));
    class CompositeRendererView extends renderer_1.RendererView {
        _renderer_views = new Map();
        get renderer_views() {
            return this.computed_renderer_views;
        }
        _computed_renderer_views = [];
        _element_views = new Map();
        get element_views() {
            return this.computed_element_views;
        }
        _computed_element_views = [];
        children_views() {
            return [...super.children_views(), ...this.renderer_views, ...this.element_views];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._build_renderers();
            await this._build_elements();
        }
        _computed_renderers = [];
        get computed_renderers() {
            return [...this.model.renderers, ...this._computed_renderers];
        }
        get computed_renderer_views() {
            return this._computed_renderer_views;
        }
        async _build_renderers() {
            const renderers = this.computed_renderers;
            const result = await (0, build_views_1.build_views)(this._renderer_views, renderers, { parent: this.plot_view });
            this._computed_renderer_views = renderers.map((item) => this._renderer_views.get(item)).filter((rv) => rv != null);
            return result;
        }
        _computed_elements = [];
        get computed_elements() {
            return [...this.model.elements, ...this._computed_elements];
        }
        get computed_element_views() {
            return this._computed_element_views;
        }
        async _build_elements() {
            const elements = this.computed_elements;
            const result = await (0, build_views_1.build_views)(this._element_views, elements, { parent: (model) => model instanceof layout_dom_1.LayoutDOM ? null : this.plot_view });
            this._computed_element_views = elements.map((item) => this._element_views.get(item)).filter((ev) => ev != null);
            return result;
        }
        async _update_renderers() {
            await this._build_renderers();
        }
        async _update_elements() {
            const { created } = await this._build_elements();
            const created_views = new Set(created);
            // Since appending to a DOM node will move the node to the end if it has
            // already been added appending all the children in order will result in
            // correct ordering.
            for (const view of this.element_views) {
                const is_new = created_views.has(view);
                const target = view.rendering_target() ?? this.self_target;
                if (is_new) {
                    view.render_to(target);
                }
                else {
                    target.append(view.el);
                }
            }
            this.r_after_render();
        }
        render() {
            super.render();
            for (const element_view of this.element_views) {
                const target = element_view.rendering_target() ?? this.self_target;
                element_view.render_to(target);
            }
        }
        connect_signals() {
            super.connect_signals();
            const { renderers, elements } = this.model.properties;
            this.on_change(renderers, async () => {
                await this._update_renderers();
            });
            this.on_change(elements, async () => {
                await this._update_elements();
            });
        }
        paint(ctx) {
            super.paint(ctx);
            if (this.displayed && this.is_renderable) {
                for (const renderer of this.computed_renderer_views) {
                    renderer.paint(ctx);
                }
            }
            const { displayed } = this;
            for (const element_view of this.element_views) {
                element_view.reposition(displayed);
            }
        }
        has_finished() {
            if (!super.has_finished()) {
                return false;
            }
            for (const renderer_view of this.renderer_views) {
                if (!renderer_view.has_finished()) {
                    return false;
                }
            }
            for (const element_view of this.element_views) {
                if (!element_view.has_finished()) {
                    return false;
                }
            }
            return true;
        }
    }
    exports.CompositeRendererView = CompositeRendererView;
    class CompositeRenderer extends renderer_1.Renderer {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ List, Ref }) => ({
                renderers: [List(Ref(renderer_1.Renderer)), []],
                elements: [List(exports.ElementLike), []],
            }));
        }
    }
    exports.CompositeRenderer = CompositeRenderer;
},
/* models/renderers/renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const styled_element_1 = require(56) /* ../ui/styled_element */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const visuals = tslib_1.__importStar(require(99) /* ../../core/visuals */);
    const enums_1 = require(21) /* ../../core/enums */;
    const types_1 = require(8) /* ../../core/util/types */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    const coordinate_mapping_1 = require(107) /* ../coordinates/coordinate_mapping */;
    const menu_1 = require(122) /* ../ui/menus/menu */;
    const renderer_group_1 = require(129) /* ./renderer_group */;
    const dom_1 = require(61) /* ../../core/dom */;
    class RendererView extends styled_element_1.StyledElementView {
        visuals;
        layout;
        _panel = null;
        get panel() {
            return this._panel;
        }
        set panel(panel) {
            this._panel = panel;
        }
        position = new dom_1.InlineStyleSheet("", "position");
        computed_stylesheets() {
            return [...super.computed_stylesheets(), this.position];
        }
        rendering_target() {
            return this.plot_view.canvas_view.underlays_el;
        }
        _context_menu = null;
        get context_menu() {
            return this._context_menu;
        }
        children_views() {
            return [...super.children_views(), this._context_menu];
        }
        _coordinates;
        get coordinates() {
            const { _coordinates } = this;
            if (_coordinates != null) {
                return _coordinates;
            }
            else {
                return this._coordinates = this._initialize_coordinates();
            }
        }
        _custom_coordinates = null;
        set coordinates(custom_coordinates) {
            this._custom_coordinates = custom_coordinates;
        }
        initialize() {
            super.initialize();
            this.visuals = new visuals.Visuals(this);
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const { context_menu } = this.model;
            if (context_menu != null) {
                this._context_menu = await (0, build_views_1.build_view)(context_menu, { parent: this.plot_view });
            }
        }
        connect_signals() {
            super.connect_signals();
            const { group } = this.model;
            if (group != null) {
                this.on_change(group.properties.visible, () => {
                    this.model.visible = group.visible;
                });
            }
            const { x_range_name, y_range_name } = this.model.properties;
            this.on_change([x_range_name, y_range_name], () => delete this._coordinates);
            this.connect(this.plot_view.frame.model.change, () => delete this._coordinates);
        }
        _initialize_coordinates() {
            if (this._custom_coordinates != null) {
                return this._custom_coordinates;
            }
            const { coordinates } = this.model;
            const { frame } = this.plot_view;
            if (coordinates != null) {
                return coordinates.get_transform(frame);
            }
            else {
                const { x_range_name, y_range_name } = this.model;
                const x_scale = frame.x_scales.get(x_range_name);
                const y_scale = frame.y_scales.get(y_range_name);
                (0, assert_1.assert)(x_scale != null, `missing '${x_range_name}' range`);
                (0, assert_1.assert)(y_scale != null, `missing '${y_range_name}' range`);
                return new coordinate_mapping_1.CoordinateTransform(x_scale, y_scale);
            }
        }
        get plot_view() {
            return this.parent;
        }
        get plot_model() {
            return this.parent.model;
        }
        get layer() {
            const { overlays, primary } = this.canvas;
            return this.model.level == "overlay" ? overlays : primary;
        }
        get canvas() {
            return this.plot_view.canvas_view;
        }
        request_paint() {
            this.plot_view.request_paint(this);
        }
        request_layout() {
            this.plot_view.request_layout();
        }
        notify_finished() {
            this.plot_view.notify_finished();
        }
        notify_finished_after_paint() {
            this.plot_view.notify_finished_after_paint();
        }
        get needs_clip() {
            return false;
        }
        get has_webgl() {
            return false;
        }
        /*
        get visible(): boolean {
          const {visible, group} = this.model
          return !visible ? false : (group?.visible ?? true)
        }
        */
        get displayed() {
            return this.model.visible;
        }
        get is_renderable() {
            return true;
        }
        get is_dual_renderer() {
            return false;
        }
        paint(ctx) {
            // It would be better to update geometry (the internal layout) only when
            // necessary, but conditions for that are not clear, so for now update
            // at every paint.
            this.update_geometry();
            this.compute_geometry();
            this.update_position();
            if (this.displayed && this.is_renderable) {
                this._paint(ctx);
            }
            this.mark_finished();
        }
        renderer_view(_renderer) {
            return undefined;
        }
        /**
         * Geometry setup that doesn't change between paints.
         */
        update_geometry() { }
        /**
         * Geometry setup that changes between paints.
         */
        compute_geometry() { }
        /**
         * Updates the position of the associated DOM element.
         */
        update_position() {
            const { bbox, position } = this;
            if (bbox != null && bbox.is_valid) {
                if (this.panel != null) {
                    position.replace(`
        :host {
          position: relative;
          width:    ${bbox.width}px;
          height:   ${bbox.height}px;
        }
        `);
                }
                else {
                    position.replace(`
        :host {
          position: absolute;
          left:     ${bbox.left}px;
          top:      ${bbox.top}px;
          width:    ${bbox.width}px;
          height:   ${bbox.height}px;
        }
        `);
                }
            }
            else {
                position.replace(`
      :host {
        display: none;
      }
      `);
            }
        }
        resolve_frame() {
            return this.plot_view.frame; // TODO CartesianFrameView (PR #13286)
        }
        resolve_canvas() {
            return this.plot_view.canvas;
        }
        resolve_plot() {
            return this.plot_view;
        }
        resolve_symbol(node) {
            const target = this;
            const { bbox } = target;
            if (bbox == null) {
                return { x: NaN, y: NaN };
            }
            else {
                const value = bbox.resolve(node.symbol);
                const { offset } = node;
                if ((0, types_1.isNumber)(value)) {
                    return value + offset;
                }
                else {
                    const { x, y } = value;
                    return { x: x + offset, y: y + offset };
                }
            }
        }
        get attribution() {
            return null;
        }
    }
    exports.RendererView = RendererView;
    class Renderer extends styled_element_1.StyledElement {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Bool, Str, Ref, Nullable }) => ({
                group: [Nullable(Ref(renderer_group_1.RendererGroup)), null],
                level: [enums_1.RenderLevel, "image"],
                visible: [Bool, true],
                x_range_name: [Str, "default"],
                y_range_name: [Str, "default"],
                coordinates: [Nullable(Ref(coordinate_mapping_1.CoordinateMapping)), null],
                propagate_hover: [Bool, false],
                context_menu: [Nullable(Ref(menu_1.Menu)), null],
            }));
        }
    }
    exports.Renderer = Renderer;
},
/* core/visuals/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const line_1 = require(100) /* ./line */;
    __esExport("Line", line_1.Line);
    __esExport("LineScalar", line_1.LineScalar);
    __esExport("LineVector", line_1.LineVector);
    const fill_1 = require(102) /* ./fill */;
    __esExport("Fill", fill_1.Fill);
    __esExport("FillScalar", fill_1.FillScalar);
    __esExport("FillVector", fill_1.FillVector);
    const text_1 = require(103) /* ./text */;
    __esExport("Text", text_1.Text);
    __esExport("TextScalar", text_1.TextScalar);
    __esExport("TextVector", text_1.TextVector);
    const hatch_1 = require(104) /* ./hatch */;
    __esExport("Hatch", hatch_1.Hatch);
    __esExport("HatchScalar", hatch_1.HatchScalar);
    __esExport("HatchVector", hatch_1.HatchVector);
    const image_1 = require(106) /* ./image */;
    __esExport("Image", image_1.Image);
    __esExport("ImageScalar", image_1.ImageScalar);
    __esExport("ImageVector", image_1.ImageVector);
    const mixins = tslib_1.__importStar(require(95) /* ../property_mixins */);
    const visual_1 = require(101) /* ./visual */;
    __esExport("VisualProperties", visual_1.VisualProperties);
    __esExport("VisualUniforms", visual_1.VisualUniforms);
    class Visuals {
        *[Symbol.iterator]() {
            yield* this._visuals;
        }
        _visuals = [];
        constructor(view) {
            for (const [prefix, mixin] of view.model._mixins) {
                const visual = (() => {
                    switch (mixin) {
                        case mixins.Line: return new line_1.Line(view, prefix);
                        case mixins.LineScalar: return new line_1.LineScalar(view, prefix);
                        case mixins.LineVector: return new line_1.LineVector(view, prefix);
                        case mixins.Fill: return new fill_1.Fill(view, prefix);
                        case mixins.FillScalar: return new fill_1.FillScalar(view, prefix);
                        case mixins.FillVector: return new fill_1.FillVector(view, prefix);
                        case mixins.Text: return new text_1.Text(view, prefix);
                        case mixins.TextScalar: return new text_1.TextScalar(view, prefix);
                        case mixins.TextVector: return new text_1.TextVector(view, prefix);
                        case mixins.Hatch: return new hatch_1.Hatch(view, prefix);
                        case mixins.HatchScalar: return new hatch_1.HatchScalar(view, prefix);
                        case mixins.HatchVector: return new hatch_1.HatchVector(view, prefix);
                        case mixins.Image: return new image_1.Image(view, prefix);
                        case mixins.ImageScalar: return new image_1.ImageScalar(view, prefix);
                        case mixins.ImageVector: return new image_1.ImageVector(view, prefix);
                        default:
                            throw new Error("unknown visual");
                    }
                })();
                if (visual instanceof visual_1.VisualProperties) {
                    visual.update();
                }
                this._visuals.push(visual);
                Object.defineProperty(this, prefix + visual.type, {
                    get() {
                        return visual;
                    },
                    configurable: false,
                    enumerable: true,
                });
            }
        }
    }
    exports.Visuals = Visuals;
},
/* core/visuals/line.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.resolve_line_dash = resolve_line_dash;
    const tslib_1 = require(1) /* tslib */;
    const visual_1 = require(101) /* ./visual */;
    const mixins = tslib_1.__importStar(require(95) /* ../property_mixins */);
    const enums_1 = require(21) /* ../enums */;
    const color_1 = require(23) /* ../util/color */;
    const types_1 = require(8) /* ../util/types */;
    function resolve_line_dash(line_dash) {
        if ((0, types_1.isArray)(line_dash)) {
            return line_dash;
        }
        else {
            switch (line_dash) {
                case "solid": return [];
                case "dashed": return [3, 2];
                case "dotted": return [2, 1];
                case "dotdash": return [2, 4, 6, 4];
                case "dashdot": return [6, 4, 2, 4];
                default:
                    return line_dash.split(" ").map(Number).filter(types_1.isInteger);
            }
        }
    }
    class Line extends visual_1.VisualProperties {
        get doit() {
            const color = this.get_line_color();
            const alpha = this.get_line_alpha();
            const width = this.get_line_width();
            return !(color == null || alpha == 0 || width == 0);
        }
        apply(ctx, path) {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
                if (path != null) {
                    ctx.stroke(path);
                }
                else {
                    ctx.stroke();
                }
            }
            return doit;
        }
        values() {
            return {
                color: this.get_line_color(),
                alpha: this.get_line_alpha(),
                width: this.get_line_width(),
                join: this.get_line_join(),
                cap: this.get_line_cap(),
                dash: this.get_line_dash(),
                offset: this.get_line_dash_offset(),
            };
        }
        computed_values() {
            const color = this.get_line_color();
            const alpha = this.get_line_alpha();
            return {
                color: (0, color_1.color2css)(color, alpha),
                width: this.get_line_width(),
                join: this.get_line_join(),
                cap: this.get_line_cap(),
                dash: this.get_line_dash(),
                offset: this.get_line_dash_offset(),
            };
        }
        set_value(ctx) {
            const { color, width, join, cap, dash, offset } = this.computed_values();
            ctx.strokeStyle = color;
            ctx.lineWidth = width;
            ctx.lineJoin = join;
            ctx.lineCap = cap;
            ctx.setLineDash(resolve_line_dash(dash));
            ctx.lineDashOffset = offset;
        }
        get_line_color() {
            const css_color = this._get_css_value("line-color");
            if (css_color != "") {
                return css_color;
            }
            return this.line_color.get_value();
        }
        get_line_alpha() {
            const css_alpha = this._get_css_value("line-alpha");
            if (css_alpha != "") {
                const alpha = Number(css_alpha);
                if (isFinite(alpha)) {
                    return alpha;
                }
            }
            return this.line_alpha.get_value();
        }
        get_line_width() {
            const css_width = this._get_css_value("line-width");
            if (css_width != "") {
                const width = Number(css_width);
                if (isFinite(width)) {
                    return width;
                }
            }
            return this.line_width.get_value();
        }
        get_line_join() {
            const css_join = this._get_css_value("line-join");
            if (enums_1.LineJoin.valid(css_join)) {
                return css_join;
            }
            return this.line_join.get_value();
        }
        get_line_cap() {
            const css_cap = this._get_css_value("line-cap");
            if (enums_1.LineCap.valid(css_cap)) {
                return css_cap;
            }
            return this.line_cap.get_value();
        }
        get_line_dash() {
            const css_dash = this._get_css_value("line-dash");
            if (enums_1.LineDash.valid(css_dash)) {
                return css_dash;
            }
            return this.line_dash.get_value();
        }
        get_line_dash_offset() {
            const css_dash_offset = this._get_css_value("line-dash-offset");
            if (css_dash_offset != "") {
                const dash_offset = Number(css_dash_offset);
                if (isFinite(dash_offset)) {
                    return dash_offset;
                }
            }
            return this.line_dash_offset.get_value();
        }
    }
    exports.Line = Line;
    class LineScalar extends visual_1.VisualUniforms {
        get doit() {
            const color = this.line_color.value;
            const alpha = this.line_alpha.value;
            const width = this.line_width.value;
            return !(color == 0 || alpha == 0 || width == 0);
        }
        apply(ctx, path) {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
                if (path != null) {
                    ctx.stroke(path);
                }
                else {
                    ctx.stroke();
                }
            }
            return doit;
        }
        values() {
            return {
                color: this.line_color.value,
                alpha: this.line_alpha.value,
                width: this.line_width.value,
                join: this.line_join.value,
                cap: this.line_cap.value,
                dash: this.line_dash.value,
                offset: this.line_dash_offset.value,
            };
        }
        set_value(ctx) {
            const color = this.line_color.value;
            const alpha = this.line_alpha.value;
            ctx.strokeStyle = (0, color_1.color2css)(color, alpha);
            ctx.lineWidth = this.line_width.value;
            ctx.lineJoin = this.line_join.value;
            ctx.lineCap = this.line_cap.value;
            ctx.setLineDash(resolve_line_dash(this.line_dash.value));
            ctx.lineDashOffset = this.line_dash_offset.value;
        }
    }
    exports.LineScalar = LineScalar;
    class LineVector extends visual_1.VisualUniforms {
        get doit() {
            const { line_color } = this;
            if (line_color.is_Scalar() && line_color.value == 0) {
                return false;
            }
            const { line_alpha } = this;
            if (line_alpha.is_Scalar() && line_alpha.value == 0) {
                return false;
            }
            const { line_width } = this;
            if (line_width.is_Scalar() && line_width.value == 0) {
                return false;
            }
            return true;
        }
        v_doit(i) {
            if (this.line_color.get(i) == 0) {
                return false;
            }
            if (this.line_alpha.get(i) == 0) {
                return false;
            }
            if (this.line_width.get(i) == 0) {
                return false;
            }
            return true;
        }
        apply(ctx, i, path) {
            const doit = this.v_doit(i);
            if (doit) {
                this.set_vectorize(ctx, i);
                if (path != null) {
                    ctx.stroke(path);
                }
                else {
                    ctx.stroke();
                }
            }
            return doit;
        }
        values(i) {
            return {
                color: this.line_color.get(i),
                alpha: this.line_alpha.get(i),
                width: this.line_width.get(i),
                join: this.line_join.get(i),
                cap: this.line_cap.get(i),
                dash: this.line_dash.get(i),
                offset: this.line_dash_offset.get(i),
            };
        }
        set_vectorize(ctx, i) {
            const color = this.line_color.get(i);
            const alpha = this.line_alpha.get(i);
            const width = this.line_width.get(i);
            const join = this.line_join.get(i);
            const cap = this.line_cap.get(i);
            const dash = this.line_dash.get(i);
            const offset = this.line_dash_offset.get(i);
            ctx.strokeStyle = (0, color_1.color2css)(color, alpha);
            ctx.lineWidth = width;
            ctx.lineJoin = join;
            ctx.lineCap = cap;
            ctx.setLineDash(resolve_line_dash(dash));
            ctx.lineDashOffset = offset;
        }
    }
    exports.LineVector = LineVector;
    Line.prototype.type = "line";
    Line.prototype.attrs = Object.keys(mixins.Line);
    LineScalar.prototype.type = "line";
    LineScalar.prototype.attrs = Object.keys(mixins.LineScalar);
    LineVector.prototype.type = "line";
    LineVector.prototype.attrs = Object.keys(mixins.LineVector);
},
/* core/visuals/visual.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const global_css_prefix = "--bk-";
    class VisualProperties {
        obj;
        prefix;
        _props;
        *[Symbol.iterator]() {
            yield* this._props;
        }
        css_prefix;
        constructor(obj, prefix = "") {
            this.obj = obj;
            this.prefix = prefix;
            this.css_prefix = `${global_css_prefix}${prefix.replaceAll("_", "-")}`;
            const self = this;
            this._props = [];
            for (const attr of this.attrs) {
                const prop = obj.model.properties[prefix + attr];
                prop.change.connect(() => this.update());
                self[attr] = prop;
                this._props.push(prop);
            }
        }
        update() {
            this._css_cache = null;
        }
        _css_cache = null;
        _get_css_value(name) {
            const css_name = `${this.css_prefix}${name}`;
            const cached = this._css_cache?.get(css_name);
            if (cached != null) {
                return cached;
            }
            const value = getComputedStyle(this.obj.el).getPropertyValue(css_name);
            if (this._css_cache == null) {
                this._css_cache = new Map();
                // CSS can change independently of visual properties through stylesheets,
                // classes, or inheritance. Cache only within a synchronous render pass.
                queueMicrotask(() => this._css_cache = null);
            }
            this._css_cache.set(css_name, value);
            return value;
        }
    }
    exports.VisualProperties = VisualProperties;
    class VisualUniforms {
        obj;
        prefix;
        *[Symbol.iterator]() {
            for (const attr of this.attrs) {
                yield this.obj.model.properties[this.prefix + attr];
            }
        }
        constructor(obj, prefix = "") {
            this.obj = obj;
            this.prefix = prefix;
            for (const attr of this.attrs) {
                Object.defineProperty(this, attr, {
                    get() {
                        return obj[prefix + attr];
                    },
                });
            }
        }
        update() { }
    }
    exports.VisualUniforms = VisualUniforms;
},
/* core/visuals/fill.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const visual_1 = require(101) /* ./visual */;
    const mixins = tslib_1.__importStar(require(95) /* ../property_mixins */);
    const color_1 = require(23) /* ../util/color */;
    class Fill extends visual_1.VisualProperties {
        get doit() {
            const color = this.get_fill_color();
            const alpha = this.get_fill_alpha();
            return !(color == null || alpha == 0);
        }
        apply(ctx, path_or_rule, rule = "nonzero") {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
                if (path_or_rule instanceof Path2D) {
                    const path = path_or_rule;
                    ctx.fill(path, rule);
                }
                else {
                    ctx.fill(path_or_rule ?? rule);
                }
            }
            return doit;
        }
        values() {
            return {
                color: this.get_fill_color(),
                alpha: this.get_fill_alpha(),
            };
        }
        computed_values() {
            const color = this.get_fill_color();
            const alpha = this.get_fill_alpha();
            return {
                color: (0, color_1.color2css)(color, alpha),
            };
        }
        set_value(ctx) {
            const { color } = this.computed_values();
            ctx.fillStyle = color;
        }
        get_fill_color() {
            const css_color = this._get_css_value("fill-color");
            if (css_color != "") {
                return css_color;
            }
            return this.fill_color.get_value();
        }
        get_fill_alpha() {
            const css_alpha = this._get_css_value("fill-alpha");
            if (css_alpha != "") {
                const alpha = Number(css_alpha);
                if (isFinite(alpha)) {
                    return alpha;
                }
            }
            return this.fill_alpha.get_value();
        }
    }
    exports.Fill = Fill;
    class FillScalar extends visual_1.VisualUniforms {
        get doit() {
            const color = this.fill_color.value;
            const alpha = this.fill_alpha.value;
            return !(color == 0 || alpha == 0);
        }
        apply(ctx, path_or_rule, rule = "nonzero") {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
                if (path_or_rule instanceof Path2D) {
                    const path = path_or_rule;
                    ctx.fill(path, rule);
                }
                else {
                    ctx.fill(path_or_rule ?? rule);
                }
            }
            return doit;
        }
        Values;
        values() {
            return {
                color: this.fill_color.value,
                alpha: this.fill_alpha.value,
            };
        }
        set_value(ctx) {
            const color = this.fill_color.value;
            const alpha = this.fill_alpha.value;
            ctx.fillStyle = (0, color_1.color2css)(color, alpha);
        }
    }
    exports.FillScalar = FillScalar;
    class FillVector extends visual_1.VisualUniforms {
        get doit() {
            const { fill_color } = this;
            if (fill_color.is_Scalar() && fill_color.value == 0) {
                return false;
            }
            const { fill_alpha } = this;
            if (fill_alpha.is_Scalar() && fill_alpha.value == 0) {
                return false;
            }
            return true;
        }
        v_doit(i) {
            if (this.fill_color.get(i) == 0) {
                return false;
            }
            if (this.fill_alpha.get(i) == 0) {
                return false;
            }
            return true;
        }
        apply(ctx, i, path_or_rule, rule = "nonzero") {
            const doit = this.v_doit(i);
            if (doit) {
                this.set_vectorize(ctx, i);
                if (path_or_rule instanceof Path2D) {
                    const path = path_or_rule;
                    ctx.fill(path, rule);
                }
                else {
                    ctx.fill(path_or_rule ?? rule);
                }
            }
            return doit;
        }
        Values;
        values(i) {
            return {
                color: this.fill_color.get(i),
                alpha: this.fill_alpha.get(i),
            };
        }
        set_vectorize(ctx, i) {
            const color = this.fill_color.get(i);
            const alpha = this.fill_alpha.get(i);
            ctx.fillStyle = (0, color_1.color2css)(color, alpha);
        }
    }
    exports.FillVector = FillVector;
    Fill.prototype.type = "fill";
    Fill.prototype.attrs = Object.keys(mixins.Fill);
    FillScalar.prototype.type = "fill";
    FillScalar.prototype.attrs = Object.keys(mixins.FillScalar);
    FillVector.prototype.type = "fill";
    FillVector.prototype.attrs = Object.keys(mixins.FillVector);
},
/* core/visuals/text.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const visual_1 = require(101) /* ./visual */;
    const mixins = tslib_1.__importStar(require(95) /* ../property_mixins */);
    const enums_1 = require(21) /* ../enums */;
    const color_1 = require(23) /* ../util/color */;
    const _font_cache = new Map();
    function load_font(font, obj) {
        const objs = _font_cache.get(font);
        if (objs == null) {
            const objs = new WeakSet([obj]);
            _font_cache.set(font, objs);
        }
        else if (!objs.has(obj)) {
            objs.add(obj);
        }
        else {
            return;
        }
        const { fonts } = document;
        if (!fonts.check(font)) {
            void fonts.load(font).then(() => obj.request_paint());
        }
    }
    class Text extends visual_1.VisualProperties {
        get doit() {
            const color = this.get_text_color();
            const alpha = this.get_text_alpha();
            return !(color == null || alpha == 0);
        }
        update() {
            super.update();
            if (!this.doit) {
                return;
            }
            const font = this.font_value();
            load_font(font, this.obj);
        }
        values() {
            return {
                color: this.get_text_color(),
                outline_color: this.get_text_outline_color(),
                outline_width: this.get_text_outline_width(),
                alpha: this.get_text_alpha(),
                font: this.get_text_font(),
                font_size: this.get_text_font_size(),
                font_style: this.get_text_font_style(),
                align: this.get_text_align(),
                baseline: this.get_text_baseline(),
                line_height: this.get_text_line_height(),
            };
        }
        computed_values() {
            const color = this.get_text_color();
            const outline_color = this.get_text_outline_color();
            const outline_width = this.get_text_outline_width();
            const alpha = this.get_text_alpha();
            return {
                color: (0, color_1.color2css)(color, alpha),
                outline_color: (0, color_1.color2css)(outline_color, alpha),
                outline_width,
                font: this.font_value(),
                text_align: this.get_text_align(),
                text_baseline: this.get_text_baseline(),
                line_height: this.get_text_line_height(),
            };
        }
        set_value(ctx) {
            const { color, outline_color, font, text_align, text_baseline, } = this.computed_values();
            ctx.fillStyle = color;
            ctx.strokeStyle = outline_color;
            ctx.font = font;
            ctx.textAlign = text_align;
            ctx.textBaseline = text_baseline;
        }
        font_value() {
            const style = this.get_text_font_style();
            const size = this.get_text_font_size();
            const face = this.get_text_font();
            return `${style} ${size} ${face}`;
        }
        get_text_color() {
            const css_color = this._get_css_value("text-color");
            if (css_color != "") {
                return css_color;
            }
            return this.text_color.get_value();
        }
        get_text_outline_color() {
            const css_color = this._get_css_value("text-outline-color");
            if (css_color != "") {
                return css_color;
            }
            return this.text_outline_color.get_value();
        }
        get_text_outline_width() {
            const css_width = this._get_css_value("text-outline-width");
            if (css_width != "") {
                const width = Number(css_width);
                if (isFinite(width)) {
                    return width;
                }
            }
            return this.text_outline_width.get_value();
        }
        get_text_alpha() {
            const css_alpha = this._get_css_value("text-alpha");
            if (css_alpha != "") {
                const alpha = Number(css_alpha);
                if (isFinite(alpha)) {
                    return alpha;
                }
            }
            return this.text_alpha.get_value();
        }
        get_text_font() {
            const css_font = this._get_css_value("text-font");
            if (css_font != "") {
                return css_font;
            }
            return this.text_font.get_value();
        }
        get_text_font_size() {
            const css_font_size = this._get_css_value("text-font-size");
            if (css_font_size != "") {
                return css_font_size;
            }
            return this.text_font_size.get_value();
        }
        get_text_font_style() {
            const css_font_style = this._get_css_value("text-font-style");
            if (enums_1.FontStyle.valid(css_font_style)) {
                return css_font_style;
            }
            return this.text_font_style.get_value();
        }
        get_text_align() {
            const css_align = this._get_css_value("text-align");
            if (enums_1.TextAlign.valid(css_align)) {
                return css_align;
            }
            return this.text_align.get_value();
        }
        get_text_baseline() {
            const css_baseline = this._get_css_value("text-baseline");
            if (enums_1.TextBaseline.valid(css_baseline)) {
                return css_baseline;
            }
            return this.text_baseline.get_value();
        }
        get_text_line_height() {
            const css_line_height = this._get_css_value("line-height");
            if (css_line_height != "") {
                const line_height = Number(css_line_height);
                if (isFinite(line_height)) {
                    return line_height;
                }
            }
            return this.text_line_height.get_value();
        }
    }
    exports.Text = Text;
    class TextScalar extends visual_1.VisualUniforms {
        get doit() {
            const color = this.text_color.value;
            const alpha = this.text_alpha.value;
            return !(color == 0 || alpha == 0);
        }
        update() {
            if (!this.doit) {
                return;
            }
            const font = this.font_value();
            load_font(font, this.obj);
        }
        values() {
            return {
                color: this.text_color.value,
                outline_color: this.text_outline_color.value,
                outline_width: this.text_outline_width.value,
                alpha: this.text_alpha.value,
                font: this.text_font.value,
                font_size: this.text_font_size.value,
                font_style: this.text_font_style.value,
                align: this.text_align.value,
                baseline: this.text_baseline.value,
                line_height: this.text_line_height.value,
            };
        }
        set_value(ctx) {
            const color = this.text_color.value;
            const alpha = this.text_alpha.value;
            const outline_color = this.text_outline_color.value;
            const outline_width = this.text_outline_width.value;
            const font = this.font_value();
            const align = this.text_align.value;
            const baseline = this.text_baseline.value;
            ctx.fillStyle = (0, color_1.color2css)(color, alpha);
            ctx.strokeStyle = (0, color_1.color2css)(outline_color, alpha);
            ctx.lineWidth = outline_width;
            ctx.font = font;
            ctx.textAlign = align;
            ctx.textBaseline = baseline;
        }
        font_value() {
            const style = this.text_font_style.value;
            const size = this.text_font_size.value;
            const face = this.text_font.value;
            return `${style} ${size} ${face}`;
        }
    }
    exports.TextScalar = TextScalar;
    class TextVector extends visual_1.VisualUniforms {
        _assert_font(i) {
            const font = this.font_value(i);
            load_font(font, this.obj);
        }
        values(i) {
            this._assert_font(i);
            return {
                color: this.text_color.get(i),
                outline_color: this.text_outline_color.get(i),
                outline_width: this.text_outline_width.get(i),
                alpha: this.text_alpha.get(i),
                font: this.text_font.get(i),
                font_size: this.text_font_size.get(i),
                font_style: this.text_font_style.get(i),
                align: this.text_align.get(i),
                baseline: this.text_baseline.get(i),
                line_height: this.text_line_height.get(i),
            };
        }
        get doit() {
            const { text_color } = this;
            if (text_color.is_Scalar() && text_color.value == 0) {
                return false;
            }
            const { text_alpha } = this;
            if (text_alpha.is_Scalar() && text_alpha.value == 0) {
                return false;
            }
            return true;
        }
        v_doit(i) {
            if (this.text_color.get(i) == 0) {
                return false;
            }
            if (this.text_alpha.get(i) == 0) {
                return false;
            }
            return true;
        }
        apply(ctx, i) {
            const doit = this.v_doit(i);
            if (doit) {
                this.set_vectorize(ctx, i);
            }
            return doit;
        }
        set_vectorize(ctx, i) {
            this._assert_font(i);
            const color = this.text_color.get(i);
            const outline_color = this.text_outline_color.get(i);
            const outline_width = this.text_outline_width.get(i);
            const alpha = this.text_alpha.get(i);
            const font = this.font_value(i);
            const align = this.text_align.get(i);
            const baseline = this.text_baseline.get(i);
            ctx.fillStyle = (0, color_1.color2css)(color, alpha);
            ctx.strokeStyle = (0, color_1.color2css)(outline_color, alpha);
            ctx.lineWidth = outline_width;
            ctx.font = font;
            ctx.textAlign = align;
            ctx.textBaseline = baseline;
        }
        font_value(i) {
            const style = this.text_font_style.get(i);
            const size = this.text_font_size.get(i);
            const face = this.text_font.get(i);
            return `${style} ${size} ${face}`;
        }
    }
    exports.TextVector = TextVector;
    Text.prototype.type = "text";
    Text.prototype.attrs = Object.keys(mixins.Text);
    TextScalar.prototype.type = "text";
    TextScalar.prototype.attrs = Object.keys(mixins.TextScalar);
    TextVector.prototype.type = "text";
    TextVector.prototype.attrs = Object.keys(mixins.TextVector);
},
/* core/visuals/hatch.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const visual_1 = require(101) /* ./visual */;
    const patterns_1 = require(105) /* ./patterns */;
    const p = tslib_1.__importStar(require(20) /* ../properties */);
    const mixins = tslib_1.__importStar(require(95) /* ../property_mixins */);
    const object_1 = require(9) /* ../util/object */;
    class Hatch extends visual_1.VisualProperties {
        _hatch_image;
        _hatch_svg;
        _update_iteration = 0;
        update() {
            super.update();
            this._update_iteration++;
            this._hatch_image = null;
            this._hatch_svg = null;
            if (!this.doit) {
                return;
            }
            const color = this.get_hatch_color();
            const alpha = this.get_hatch_alpha();
            const scale = this.get_hatch_scale();
            const pattern = this.get_hatch_pattern();
            const weight = this.get_hatch_weight();
            const finalize = (image) => {
                this._hatch_image = image;
            };
            const finalize_svg = (image_svg) => {
                this._hatch_svg = image_svg;
            };
            const textures = (0, object_1.dict)(this.get_hatch_extra());
            const texture = textures.get(pattern);
            if (texture != null) {
                const image = texture.get_pattern(color, alpha, scale, weight);
                if (image instanceof Promise) {
                    const { _update_iteration } = this;
                    void image.then((image) => {
                        if (this._update_iteration == _update_iteration) {
                            finalize(image);
                            this.obj.request_paint();
                        }
                    });
                }
                else {
                    finalize(image);
                }
            }
            else {
                const layer = this.obj.canvas.create_layer();
                const image = (0, patterns_1.get_pattern)(layer, pattern, color, alpha, scale, weight);
                finalize(image);
                const svg_layer = this.obj.canvas.create_layer_svg();
                const image_svg = (0, patterns_1.get_pattern)(svg_layer, pattern, color, alpha, scale, weight);
                finalize_svg(image_svg);
            }
        }
        get doit() {
            const color = this.get_hatch_color();
            const alpha = this.get_hatch_alpha();
            const pattern = this.get_hatch_pattern();
            return !(color == null || alpha == 0 || pattern == " " || pattern == "blank" || pattern == null);
        }
        apply(ctx, path_or_rule, rule = "nonzero") {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
                ctx.layer.undo_transform(() => {
                    if (path_or_rule instanceof Path2D) {
                        const path = path_or_rule;
                        ctx.fill(path, rule);
                    }
                    else {
                        ctx.fill(path_or_rule ?? rule);
                    }
                });
            }
            return doit;
        }
        set_value(ctx) {
            const pattern = this.pattern(ctx);
            ctx.fillStyle = pattern ?? "transparent";
        }
        pattern(ctx) {
            const image = this._hatch_image;
            if (image == null) {
                return null;
            }
            else {
                return ctx.createPattern(image, this.repetition());
            }
        }
        repetition() {
            const pattern = this.get_hatch_pattern();
            const textures = (0, object_1.dict)(this.get_hatch_extra());
            const texture = textures.get(pattern);
            if (texture == null) {
                return "repeat";
            }
            else {
                switch (texture.repetition) {
                    case "repeat": return "repeat";
                    case "repeat_x": return "repeat-x";
                    case "repeat_y": return "repeat-y";
                    case "no_repeat": return "no-repeat";
                }
            }
        }
        computed_values() {
            let pattern = "";
            if (this._hatch_svg !== null && this._hatch_svg instanceof SVGElement) {
                pattern = `data:image/svg+xml;base64,${btoa(new XMLSerializer().serializeToString(this._hatch_svg))}`;
            }
            return {
                scale: this.get_hatch_scale(),
                pattern,
            };
        }
        get_hatch_color() {
            const css_color = this._get_css_value("hatch-color");
            if (css_color != "") {
                return css_color;
            }
            return this.hatch_color.get_value();
        }
        get_hatch_alpha() {
            const css_alpha = this._get_css_value("hatch-alpha");
            if (css_alpha != "") {
                const alpha = Number(css_alpha);
                if (isFinite(alpha)) {
                    return alpha;
                }
            }
            return this.hatch_alpha.get_value();
        }
        get_hatch_scale() {
            const css_scale = this._get_css_value("hatch-scale");
            if (css_scale != "") {
                const scale = Number(css_scale);
                if (isFinite(scale)) {
                    return scale;
                }
            }
            return this.hatch_scale.get_value();
        }
        get_hatch_pattern() {
            const css_pattern = this._get_css_value("hatch-pattern");
            if (css_pattern != "") {
                if (css_pattern == "none") {
                    return null;
                }
                else {
                    return css_pattern;
                }
            }
            return this.hatch_pattern.get_value();
        }
        get_hatch_weight() {
            const css_weight = this._get_css_value("hatch-weight");
            if (css_weight != "") {
                const weight = Number(css_weight);
                if (isFinite(weight)) {
                    return weight;
                }
            }
            return this.hatch_weight.get_value();
        }
        get_hatch_extra() {
            return this.hatch_extra.get_value();
        }
    }
    exports.Hatch = Hatch;
    class HatchScalar extends visual_1.VisualUniforms {
        _hatch_image;
        _static_doit = false;
        _compute_static_doit() {
            const color = this.hatch_color.value;
            const alpha = this.hatch_alpha.value;
            const pattern = this.hatch_pattern.value;
            return !(color == 0 || alpha == 0 || pattern == " " || pattern == "blank" || pattern == null);
        }
        _update_iteration = 0;
        update() {
            this._update_iteration++;
            const n = this.hatch_color.length;
            this._hatch_image = new p.UniformScalar(null, n);
            this._static_doit = this._compute_static_doit();
            if (!this._static_doit) {
                return;
            }
            const color = this.hatch_color.value;
            const alpha = this.hatch_alpha.value;
            const scale = this.hatch_scale.value;
            const pattern = this.hatch_pattern.value;
            const weight = this.hatch_weight.value;
            const finalize = (image) => {
                this._hatch_image = new p.UniformScalar(image, n);
            };
            const textures = (0, object_1.dict)(this.hatch_extra.value);
            const texture = textures.get(pattern);
            if (texture != null) {
                const image = texture.get_pattern(color, alpha, scale, weight);
                if (image instanceof Promise) {
                    const { _update_iteration } = this;
                    void image.then((image) => {
                        if (this._update_iteration == _update_iteration) {
                            finalize(image);
                            this.obj.request_paint();
                        }
                    });
                }
                else {
                    finalize(image);
                }
            }
            else {
                const layer = this.obj.canvas.create_layer();
                const image = (0, patterns_1.get_pattern)(layer, pattern, color, alpha, scale, weight);
                finalize(image);
            }
        }
        get doit() {
            return this._static_doit;
        }
        apply(ctx, path_or_rule, rule = "nonzero") {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
                ctx.layer.undo_transform(() => {
                    if (path_or_rule instanceof Path2D) {
                        const path = path_or_rule;
                        ctx.fill(path, rule);
                    }
                    else {
                        ctx.fill(path_or_rule ?? rule);
                    }
                });
            }
            return doit;
        }
        set_value(ctx) {
            ctx.fillStyle = this.pattern(ctx) ?? "transparent";
        }
        pattern(ctx) {
            const image = this._hatch_image.value;
            if (image == null) {
                return null;
            }
            else {
                return ctx.createPattern(image, this.repetition());
            }
        }
        repetition() {
            const pattern = this.hatch_pattern.value;
            if (pattern != null) {
                const textures = (0, object_1.dict)(this.hatch_extra.value);
                const texture = textures.get(pattern);
                if (texture != null) {
                    switch (texture.repetition) {
                        case "repeat": return "repeat";
                        case "repeat_x": return "repeat-x";
                        case "repeat_y": return "repeat-y";
                        case "no_repeat": return "no-repeat";
                    }
                }
            }
            return "repeat";
        }
    }
    exports.HatchScalar = HatchScalar;
    class HatchVector extends visual_1.VisualUniforms {
        _hatch_image;
        _static_doit = false;
        _compute_static_doit() {
            const { hatch_color } = this;
            if (hatch_color.is_Scalar() && hatch_color.value == 0) {
                return false;
            }
            const { hatch_alpha } = this;
            if (hatch_alpha.is_Scalar() && hatch_alpha.value == 0) {
                return false;
            }
            const { hatch_pattern } = this;
            if (hatch_pattern.is_Scalar()) {
                const pattern = hatch_pattern.value;
                if (pattern == " " || pattern == "blank" || pattern == null) {
                    return false;
                }
            }
            return true;
        }
        _update_iteration = 0;
        update() {
            this._update_iteration++;
            const n = this.hatch_color.length;
            this._hatch_image = new p.UniformScalar(null, n);
            this._static_doit = this._compute_static_doit();
            if (!this._static_doit) {
                return;
            }
            const resolve_image = (pattern, color, alpha, scale, weight, finalize) => {
                const textures = (0, object_1.dict)(this.hatch_extra.value);
                const texture = textures.get(pattern);
                if (texture != null) {
                    const image = texture.get_pattern(color, alpha, scale, weight);
                    if (image instanceof Promise) {
                        const { _update_iteration } = this;
                        void image.then((image) => {
                            if (this._update_iteration == _update_iteration) {
                                finalize(image);
                                this.obj.request_paint();
                            }
                        });
                    }
                    else {
                        finalize(image);
                    }
                }
                else {
                    const layer = this.obj.canvas.create_layer();
                    const image = (0, patterns_1.get_pattern)(layer, pattern, color, alpha, scale, weight);
                    finalize(image);
                }
            };
            if (this.hatch_color.is_Scalar() &&
                this.hatch_alpha.is_Scalar() &&
                this.hatch_scale.is_Scalar() &&
                this.hatch_pattern.is_Scalar() &&
                this.hatch_weight.is_Scalar()) {
                const color = this.hatch_color.value;
                const alpha = this.hatch_alpha.value;
                const scale = this.hatch_scale.value;
                const pattern = this.hatch_pattern.value;
                const weight = this.hatch_weight.value;
                resolve_image(pattern, color, alpha, scale, weight, (image) => {
                    this._hatch_image = new p.UniformScalar(image, n);
                });
            }
            else {
                const images = new Array(n);
                images.fill(null);
                this._hatch_image = new p.UniformVector(images);
                for (let i = 0; i < n; i++) {
                    const color = this.hatch_color.get(i);
                    const alpha = this.hatch_alpha.get(i);
                    const scale = this.hatch_scale.get(i);
                    const pattern = this.hatch_pattern.get(i);
                    const weight = this.hatch_weight.get(i);
                    resolve_image(pattern, color, alpha, scale, weight, (image) => {
                        images[i] = image;
                    });
                }
            }
        }
        get doit() {
            return this._static_doit;
        }
        v_doit(i) {
            if (!this.doit) {
                return false;
            }
            if (this.hatch_color.get(i) == 0) {
                return false;
            }
            if (this.hatch_alpha.get(i) == 0) {
                return false;
            }
            const pattern = this.hatch_pattern.get(i);
            if (pattern == " " || pattern == "blank" || pattern == null) {
                return false;
            }
            return true;
        }
        apply(ctx, i, path_or_rule, rule = "nonzero") {
            const doit = this.v_doit(i);
            if (doit) {
                this.set_vectorize(ctx, i);
                ctx.layer.undo_transform(() => {
                    if (path_or_rule instanceof Path2D) {
                        const path = path_or_rule;
                        ctx.fill(path, rule);
                    }
                    else {
                        ctx.fill(path_or_rule ?? rule);
                    }
                });
            }
            return doit;
        }
        set_vectorize(ctx, i) {
            ctx.fillStyle = this.pattern(ctx, i) ?? "transparent";
        }
        pattern(ctx, i) {
            const image = this._hatch_image.get(i);
            if (image == null) {
                return null;
            }
            else {
                return ctx.createPattern(image, this.repetition(i));
            }
        }
        repetition(i) {
            const pattern = this.hatch_pattern.get(i);
            if (pattern != null) {
                const textures = (0, object_1.dict)(this.hatch_extra.value);
                const texture = textures.get(pattern);
                if (texture != null) {
                    switch (texture.repetition) {
                        case "repeat": return "repeat";
                        case "repeat_x": return "repeat-x";
                        case "repeat_y": return "repeat-y";
                        case "no_repeat": return "no-repeat";
                    }
                }
            }
            return "repeat";
        }
    }
    exports.HatchVector = HatchVector;
    Hatch.prototype.type = "hatch";
    Hatch.prototype.attrs = Object.keys(mixins.Hatch);
    HatchScalar.prototype.type = "hatch";
    HatchScalar.prototype.attrs = Object.keys(mixins.HatchScalar);
    HatchVector.prototype.type = "hatch";
    HatchVector.prototype.attrs = Object.keys(mixins.HatchVector);
},
/* core/visuals/patterns.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.get_pattern = get_pattern;
    const logging_1 = require(11) /* ../logging */;
    const color_1 = require(23) /* ../util/color */;
    function _horz(ctx, h, h2) {
        ctx.moveTo(0, h2 + 0.5);
        ctx.lineTo(h, h2 + 0.5);
        ctx.stroke();
    }
    function _vert(ctx, h, h2) {
        ctx.moveTo(h2 + 0.5, 0);
        ctx.lineTo(h2 + 0.5, h);
        ctx.stroke();
    }
    function _x(ctx, h) {
        ctx.moveTo(0, h);
        ctx.lineTo(h, 0);
        ctx.stroke();
        ctx.moveTo(0, 0);
        ctx.lineTo(h, h);
        ctx.stroke();
    }
    exports.hatch_aliases = {
        " ": "blank",
        ".": "dot",
        o: "ring",
        "-": "horizontal_line",
        "|": "vertical_line",
        "+": "cross",
        "\"": "horizontal_dash",
        ":": "vertical_dash",
        "@": "spiral",
        "/": "right_diagonal_line",
        "\\": "left_diagonal_line",
        x: "diagonal_cross",
        ",": "right_diagonal_dash",
        "`": "left_diagonal_dash",
        v: "horizontal_wave",
        ">": "vertical_wave",
        "*": "criss_cross",
    };
    function get_pattern(layer, pattern, color, alpha, scale, weight) {
        layer.resize(scale, scale);
        layer.prepare();
        create_hatch_canvas(layer.ctx, pattern, color, alpha, scale, weight);
        return layer.canvas;
    }
    function create_hatch_canvas(ctx, hatch_pattern, hatch_color, hatch_alpha, hatch_scale, hatch_weight) {
        const h = hatch_scale;
        const h2 = h / 2;
        const h4 = h2 / 2;
        const color = (0, color_1.color2css)(hatch_color, hatch_alpha);
        ctx.strokeStyle = color;
        ctx.fillStyle = color;
        ctx.lineCap = "square";
        ctx.lineWidth = hatch_weight;
        switch (exports.hatch_aliases[hatch_pattern] ?? hatch_pattern) {
            // we should not need these if code conditions on hatch.doit, but
            // include them here just for completeness
            case "blank":
                break;
            case "dot":
                ctx.arc(h2, h2, h2 / 2, 0, 2 * Math.PI, true);
                ctx.fill();
                break;
            case "ring":
                ctx.arc(h2, h2, h2 / 2, 0, 2 * Math.PI, true);
                ctx.stroke();
                break;
            case "horizontal_line":
                _horz(ctx, h, h2);
                break;
            case "vertical_line":
                _vert(ctx, h, h2);
                break;
            case "cross":
                _horz(ctx, h, h2);
                _vert(ctx, h, h2);
                break;
            case "horizontal_dash":
                _horz(ctx, h2, h2);
                break;
            case "vertical_dash":
                _vert(ctx, h2, h2);
                break;
            case "spiral": {
                const h30 = h / 30;
                ctx.moveTo(h2, h2);
                for (let i = 0; i < 360; i++) {
                    const angle = 0.1 * i;
                    const x = h2 + (h30 * angle) * Math.cos(angle);
                    const y = h2 + (h30 * angle) * Math.sin(angle);
                    ctx.lineTo(x, y);
                }
                ctx.stroke();
                break;
            }
            case "right_diagonal_line":
                ctx.moveTo(-h4 + 0.5, h);
                ctx.lineTo(h4 + 0.5, 0);
                ctx.stroke();
                ctx.moveTo(h4 + 0.5, h);
                ctx.lineTo(3 * h4 + 0.5, 0);
                ctx.stroke();
                ctx.moveTo(3 * h4 + 0.5, h);
                ctx.lineTo(5 * h4 + 0.5, 0);
                ctx.stroke();
                break;
            case "left_diagonal_line":
                ctx.moveTo(h4 + 0.5, h);
                ctx.lineTo(-h4 + 0.5, 0);
                ctx.stroke();
                ctx.moveTo(3 * h4 + 0.5, h);
                ctx.lineTo(h4 + 0.5, 0);
                ctx.stroke();
                ctx.moveTo(5 * h4 + 0.5, h);
                ctx.lineTo(3 * h4 + 0.5, 0);
                ctx.stroke();
                break;
            case "diagonal_cross":
                _x(ctx, h);
                break;
            case "right_diagonal_dash":
                ctx.moveTo(h4 + 0.5, 3 * h4 + 0.5);
                ctx.lineTo(3 * h4 + 0.5, h4 + 0.5);
                ctx.stroke();
                break;
            case "left_diagonal_dash":
                ctx.moveTo(h4 + 0.5, h4 + 0.5);
                ctx.lineTo(3 * h4 + 0.5, 3 * h4 + 0.5);
                ctx.stroke();
                break;
            case "horizontal_wave":
                ctx.moveTo(0, h4);
                ctx.lineTo(h2, 3 * h4);
                ctx.lineTo(h, h4);
                ctx.stroke();
                break;
            case "vertical_wave":
                ctx.moveTo(h4, 0);
                ctx.lineTo(3 * h4, h2);
                ctx.lineTo(h4, h);
                ctx.stroke();
                break;
            case "criss_cross":
                _x(ctx, h);
                _horz(ctx, h, h2);
                _vert(ctx, h, h2);
                break;
            default:
                logging_1.logger.warn(`unknown hatch pattern: ${hatch_pattern}`);
        }
    }
},
/* core/visuals/image.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const visual_1 = require(101) /* ./visual */;
    const mixins = tslib_1.__importStar(require(95) /* ../property_mixins */);
    class Image extends visual_1.VisualProperties {
        get doit() {
            const alpha = this.global_alpha.get_value();
            return !(alpha == 0);
        }
        apply(ctx) {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
            }
            return doit;
        }
        values() {
            return {
                global_alpha: this.global_alpha.get_value(),
            };
        }
        set_value(ctx) {
            const alpha = this.global_alpha.get_value();
            ctx.globalAlpha = alpha;
        }
    }
    exports.Image = Image;
    class ImageScalar extends visual_1.VisualUniforms {
        get doit() {
            const alpha = this.global_alpha.value;
            return !(alpha == 0);
        }
        apply(ctx) {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
            }
            return doit;
        }
        values() {
            return {
                global_alpha: this.global_alpha.value,
            };
        }
        set_value(ctx) {
            const alpha = this.global_alpha.value;
            ctx.globalAlpha = alpha;
        }
    }
    exports.ImageScalar = ImageScalar;
    class ImageVector extends visual_1.VisualUniforms {
        get doit() {
            const { global_alpha } = this;
            if (global_alpha.is_Scalar() && global_alpha.value == 0) {
                return false;
            }
            return true;
        }
        v_doit(i) {
            if (this.global_alpha.get(i) == 0) {
                return false;
            }
            return true;
        }
        apply(ctx, i) {
            const doit = this.v_doit(i);
            if (doit) {
                this.set_vectorize(ctx, i);
            }
            return doit;
        }
        values(i) {
            return {
                alpha: this.global_alpha.get(i),
            };
        }
        set_vectorize(ctx, i) {
            const alpha = this.global_alpha.get(i);
            ctx.globalAlpha = alpha;
        }
    }
    exports.ImageVector = ImageVector;
    Image.prototype.type = "image";
    Image.prototype.attrs = Object.keys(mixins.Image);
    ImageScalar.prototype.type = "image";
    ImageScalar.prototype.attrs = Object.keys(mixins.ImageScalar);
    ImageVector.prototype.type = "image";
    ImageVector.prototype.attrs = Object.keys(mixins.ImageVector);
},
/* models/coordinates/coordinate_mapping.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    const scale_1 = require(108) /* ../scales/scale */;
    const linear_scale_1 = require(113) /* ../scales/linear_scale */;
    const log_scale_1 = require(115) /* ../scales/log_scale */;
    const categorical_scale_1 = require(116) /* ../scales/categorical_scale */;
    const composite_scale_1 = require(117) /* ../scales/composite_scale */;
    const range_1 = require(110) /* ../ranges/range */;
    const data_range1d_1 = require(118) /* ../ranges/data_range1d */;
    const factor_range_1 = require(121) /* ../ranges/factor_range */;
    class CoordinateTransform {
        x_scale;
        y_scale;
        x_source;
        y_source;
        ranges;
        scales;
        constructor(x_scale, y_scale) {
            this.x_scale = x_scale;
            this.y_scale = y_scale;
            this.x_source = this.x_scale.source_range;
            this.y_source = this.y_scale.source_range;
            this.ranges = [this.x_source, this.y_source];
            this.scales = [this.x_scale, this.y_scale];
        }
        map_to_screen(xs, ys) {
            const sxs = this.x_scale.v_compute(xs);
            const sys = this.y_scale.v_compute(ys);
            return [sxs, sys];
        }
        map_from_screen(sxs, sys) {
            const xs = this.x_scale.v_invert(sxs);
            const ys = this.y_scale.v_invert(sys);
            return [xs, ys];
        }
    }
    exports.CoordinateTransform = CoordinateTransform;
    class CoordinateMapping extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Ref }) => ({
                x_source: [Ref(range_1.Range), () => new data_range1d_1.DataRange1d()],
                y_source: [Ref(range_1.Range), () => new data_range1d_1.DataRange1d()],
                x_scale: [Ref(scale_1.Scale), () => new linear_scale_1.LinearScale()],
                y_scale: [Ref(scale_1.Scale), () => new linear_scale_1.LinearScale()],
                x_target: [Ref(range_1.Range)],
                y_target: [Ref(range_1.Range)],
            }));
        }
        get x_ranges() {
            return new Map([["default", this.x_source]]);
        }
        get y_ranges() {
            return new Map([["default", this.y_source]]);
        }
        _get_scale(range, scale, target) {
            const factor_range = range instanceof factor_range_1.FactorRange;
            const categorical_scale = scale instanceof categorical_scale_1.CategoricalScale;
            if (factor_range != categorical_scale) {
                throw new Error(`Range ${range.type} is incompatible is Scale ${scale.type}`);
            }
            if (scale instanceof log_scale_1.LogScale && range instanceof data_range1d_1.DataRange1d) {
                range.scale_hint = "log";
            }
            const derived_scale = scale.clone();
            derived_scale.setv({ source_range: range, target_range: target });
            return derived_scale;
        }
        get_transform(frame) {
            const { x_source, x_scale, x_target } = this;
            const x_source_scale = this._get_scale(x_source, x_scale, x_target);
            const { y_source, y_scale, y_target } = this;
            const y_source_scale = this._get_scale(y_source, y_scale, y_target);
            const xscale = new composite_scale_1.CompositeScale({
                source_scale: x_source_scale, source_range: x_source_scale.source_range,
                target_scale: frame.x_scale, target_range: frame.x_target,
            });
            const yscale = new composite_scale_1.CompositeScale({
                source_scale: y_source_scale, source_range: y_source_scale.source_range,
                target_scale: frame.y_scale, target_range: frame.y_target,
            });
            return new CoordinateTransform(xscale, yscale);
        }
    }
    exports.CoordinateMapping = CoordinateMapping;
},
/* models/scales/scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const transform_1 = require(109) /* ../transforms/transform */;
    const range_1 = require(110) /* ../ranges/range */;
    const range1d_1 = require(111) /* ../ranges/range1d */;
    const types_1 = require(25) /* ../../core/types */;
    class Scale extends transform_1.Transform {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.internal(({ Ref }) => ({
                source_range: [Ref(range_1.Range)],
                target_range: [Ref(range1d_1.Range1d)],
            }));
        }
        compute(x) {
            return this.s_compute(x);
        }
        v_compute(xs) {
            const n = xs.length;
            const result = new types_1.ScreenArray(n);
            const { s_compute } = this;
            for (let i = 0; i < n; i++) {
                result[i] = s_compute(xs[i]);
            }
            return result;
        }
        invert(sx) {
            return this.s_invert(sx);
        }
        v_invert(sxs) {
            const n = sxs.length;
            const result = new Float64Array(n);
            const { s_invert } = this;
            for (let i = 0; i < n; i++) {
                result[i] = s_invert(sxs[i]);
            }
            return result;
        }
        r_compute(x0, x1) {
            const { s_compute } = this;
            if (this.target_range.is_reversed) {
                return [s_compute(x1), s_compute(x0)];
            }
            else {
                return [s_compute(x0), s_compute(x1)];
            }
        }
        r_invert(sx0, sx1) {
            const { s_invert } = this;
            if (this.target_range.is_reversed) {
                return [s_invert(sx1), s_invert(sx0)];
            }
            else {
                return [s_invert(sx0), s_invert(sx1)];
            }
        }
    }
    exports.Scale = Scale;
},
/* models/transforms/transform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    class Transform extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Transform = Transform;
},
/* models/ranges/range.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    const kinds_1 = require(22) /* ../../core/kinds */;
    const iterator_1 = require(15) /* ../../core/util/iterator */;
    const Bounds = (0, kinds_1.Nullable)((0, kinds_1.Or)((0, kinds_1.Tuple)((0, kinds_1.Nullable)(kinds_1.Float), (0, kinds_1.Nullable)(kinds_1.Float)), kinds_1.Auto));
    class Range extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.internal(({ Tuple, Float }) => ({
                computed_bounds: [Tuple(Float, Float)],
            }));
            this.define(({ Float, Nullable }) => ({
                bounds: [Bounds, null, {
                        on_update(bounds, obj) {
                            const [lower, upper] = bounds == "auto" || bounds == null ? [null, null] : bounds;
                            obj.computed_bounds = [lower ?? -Infinity, upper ?? Infinity];
                        },
                    }],
                min_interval: [Nullable(Float), null],
                max_interval: [Nullable(Float), null],
            }));
        }
        have_updated_interactively = false;
        get is_reversed() {
            return this.start > this.end;
        }
        get is_valid() {
            return isFinite(this.min) && isFinite(this.max);
        }
        get interval() {
            return [this.start, this.end];
        }
        get span() {
            return Math.abs(this.end - this.start);
        }
        /** @internal */
        frames = new Set();
        get linked_plots() {
            return new Set((0, iterator_1.map)(this.frames, (frame) => frame.parent));
        }
    }
    exports.Range = Range;
},
/* models/ranges/range1d.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const numerical_range_1 = require(112) /* ./numerical_range */;
    class Range1d extends numerical_range_1.NumericalRange {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.internal(({ Float }) => ({
                _reset_start: [Float],
                _reset_end: [Float],
            }));
            this.define(({ Float, Nullable }) => ({
                reset_start: [Nullable(Float), null, {
                        on_update(reset_start, self) {
                            self._reset_start = reset_start ?? self.start;
                        },
                    }],
                reset_end: [Nullable(Float), null, {
                        on_update(reset_end, self) {
                            self._reset_end = reset_end ?? self.end;
                        },
                    }],
            }));
            this.override({
                start: 0,
                end: 1,
            });
        }
        _set_auto_bounds() {
            if (this.bounds == "auto") {
                const min = Math.min(this._reset_start, this._reset_end);
                const max = Math.max(this._reset_start, this._reset_end);
                this.computed_bounds = [min, max];
            }
        }
        initialize() {
            super.initialize();
            this._set_auto_bounds();
        }
        get min() {
            return Math.min(this.start, this.end);
        }
        get max() {
            return Math.max(this.start, this.end);
        }
        reset() {
            this._set_auto_bounds();
            const { _reset_start, _reset_end } = this;
            if (this.start != _reset_start || this.end != _reset_end) {
                this.setv({ start: _reset_start, end: _reset_end });
            }
            else {
                this.change.emit();
            }
        }
        map(fn) {
            return new Range1d({ start: fn(this.start), end: fn(this.end) });
        }
        widen(v) {
            let { start, end } = this;
            if (this.is_reversed) {
                start += v;
                end -= v;
            }
            else {
                start -= v;
                end += v;
            }
            return new Range1d({ start, end });
        }
    }
    exports.Range1d = Range1d;
},
/* models/ranges/numerical_range.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const range_1 = require(110) /* ./range */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const math_1 = require(12) /* ../../core/util/math */;
    class NumericalRange extends range_1.Range {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Float }) => ({
                start: [Float, p.unset, {
                        convert(value, obj) {
                            const [lower, upper] = obj.computed_bounds;
                            return (0, math_1.clamp)(value, lower, upper);
                        },
                    }],
                end: [Float, p.unset, {
                        convert(value, obj) {
                            const [lower, upper] = obj.computed_bounds;
                            return (0, math_1.clamp)(value, lower, upper);
                        },
                    }],
            }));
        }
    }
    exports.NumericalRange = NumericalRange;
},
/* models/scales/linear_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_scale_1 = require(114) /* ./continuous_scale */;
    class LinearScale extends continuous_scale_1.ContinuousScale {
        constructor(attrs) {
            super(attrs);
        }
        get s_compute() {
            const { source_range: source, target_range: target } = this;
            const [factor, offset] = LinearScale.linear_compute(source.start, source.end, target.start, target.end);
            return (x) => factor * x + offset;
        }
        get s_invert() {
            const { source_range: source, target_range: target } = this;
            const [factor, offset] = LinearScale.linear_compute(source.start, source.end, target.start, target.end);
            return (sx) => (sx - offset) / factor;
        }
        static linear_compute(source_start, source_end, target_start, target_end) {
            //
            //  (t1 - t0)       (t1 - t0)
            //  --------- * x - --------- * s0 + t0
            //  (s1 - s0)       (s1 - s0)
            //
            // [  factor  ]     [    offset    ]
            //
            const factor = (target_end - target_start) / (source_end - source_start);
            const offset = -(factor * source_start) + target_start;
            return [factor, offset];
        }
    }
    exports.LinearScale = LinearScale;
},
/* models/scales/continuous_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const scale_1 = require(108) /* ./scale */;
    class ContinuousScale extends scale_1.Scale {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ContinuousScale = ContinuousScale;
},
/* models/scales/log_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_scale_1 = require(114) /* ./continuous_scale */;
    class LogScale extends continuous_scale_1.ContinuousScale {
        constructor(attrs) {
            super(attrs);
        }
        get s_compute() {
            const [factor, offset, inter_factor, inter_offset] = this._compute_state();
            return (x) => {
                if (inter_factor == 0) {
                    return 0;
                }
                else {
                    const _x = (Math.log(x) - inter_offset) / inter_factor;
                    return isFinite(_x) ? _x * factor + offset : NaN;
                }
            };
        }
        get s_invert() {
            const [factor, offset, inter_factor, inter_offset] = this._compute_state();
            return (xprime) => {
                const value = (xprime - offset) / factor;
                return Math.exp(inter_factor * value + inter_offset);
            };
        }
        _get_safe_factor(orig_start, orig_end) {
            let start = orig_start < 0 ? 0 : orig_start;
            let end = orig_end < 0 ? 0 : orig_end;
            if (start == end) {
                if (start == 0) {
                    [start, end] = [1, 10];
                }
                else {
                    const log_val = Math.log10(start);
                    start = 10 ** Math.floor(log_val);
                    if (Math.ceil(log_val) != Math.floor(log_val)) {
                        end = 10 ** Math.ceil(log_val);
                    }
                    else {
                        end = 10 ** (Math.ceil(log_val) + 1);
                    }
                }
            }
            return [start, end];
        }
        /*protected*/ _compute_state() {
            const source_start = this.source_range.start;
            const source_end = this.source_range.end;
            const target_start = this.target_range.start;
            const target_end = this.target_range.end;
            const screen_range = target_end - target_start;
            const [start, end] = this._get_safe_factor(source_start, source_end);
            let inter_factor;
            let inter_offset;
            if (start == 0) {
                inter_factor = Math.log(end);
                inter_offset = 0;
            }
            else {
                inter_factor = Math.log(end / start);
                inter_offset = Math.log(start);
            }
            const factor = screen_range;
            const offset = target_start;
            return [factor, offset, inter_factor, inter_offset];
        }
    }
    exports.LogScale = LogScale;
},
/* models/scales/categorical_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const scale_1 = require(108) /* ./scale */;
    const linear_scale_1 = require(113) /* ./linear_scale */;
    class CategoricalScale extends scale_1.Scale {
        constructor(attrs) {
            super(attrs);
        }
        get s_compute() {
            const { source_range: source, target_range: target } = this;
            const [factor, offset] = linear_scale_1.LinearScale.linear_compute(source.start, source.end, target.start, target.end);
            const range = this.source_range;
            return (x) => factor * range.synthetic(x) + offset;
        }
        get s_invert() {
            const { source_range: source, target_range: target } = this;
            const [factor, offset] = linear_scale_1.LinearScale.linear_compute(source.start, source.end, target.start, target.end);
            return (sx) => (sx - offset) / factor;
        }
    }
    exports.CategoricalScale = CategoricalScale;
},
/* models/scales/composite_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const scale_1 = require(108) /* ../scales/scale */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    class CompositeScale extends scale_1.Scale {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Ref }) => ({
                source_scale: [Ref(scale_1.Scale)],
                target_scale: [Ref(scale_1.Scale)],
            }));
        }
        get s_compute() {
            const source_compute = this.source_scale.s_compute;
            const target_compute = this.target_scale.s_compute;
            return (x) => target_compute(source_compute(x));
        }
        get s_invert() {
            const source_invert = this.source_scale.s_invert;
            const target_invert = this.target_scale.s_invert;
            return (sx) => source_invert(target_invert(sx));
        }
        compute(x) {
            return this.s_compute(x);
        }
        v_compute(xs) {
            const { s_compute } = this;
            return (0, arrayable_1.map)(xs, s_compute); // XXX
        }
        invert(sx) {
            return this.s_invert(sx);
        }
        v_invert(sxs) {
            const { s_invert } = this;
            return (0, arrayable_1.map)(sxs, s_invert); // XXX
        }
    }
    exports.CompositeScale = CompositeScale;
},
/* models/ranges/data_range1d.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.is_auto_ranged = is_auto_ranged;
    const tslib_1 = require(1) /* tslib */;
    const data_range_1 = require(119) /* ./data_range */;
    const enums_1 = require(21) /* ../../core/enums */;
    const iterator_1 = require(15) /* ../../core/util/iterator */;
    const math_1 = require(12) /* ../../core/util/math */;
    const logging_1 = require(11) /* ../../core/logging */;
    const bbox = tslib_1.__importStar(require(62) /* ../../core/util/bbox */);
    const util_1 = require(120) /* ../util */;
    exports.auto_ranged = Symbol("auto_ranged");
    function is_auto_ranged(r) {
        return exports.auto_ranged in r;
    }
    class DataRange1d extends data_range_1.DataRange {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Bool, Float, Nullable }) => ({
                range_padding: [Float, 0.1],
                range_padding_units: [enums_1.PaddingUnits, "percent"],
                flipped: [Bool, false],
                follow: [Nullable(enums_1.StartEnd), null],
                follow_interval: [Nullable(Float), null],
                default_span: [Float, 2.0],
                only_visible: [Bool, false],
            }));
            this.internal(({ Enum, Float, Nullable }) => ({
                scale_hint: [Enum("log", "auto"), "auto"],
                _initial_start: [Nullable(Float), (obj) => isNaN(obj.start) ? null : obj.start],
                _initial_end: [Nullable(Float), (obj) => isNaN(obj.end) ? null : obj.end],
                _initial_range_padding: [Float, (obj) => obj.range_padding],
                _initial_range_padding_units: [enums_1.PaddingUnits, (obj) => obj.range_padding_units],
                _initial_follow: [Nullable(enums_1.StartEnd), (obj) => obj.follow],
                _initial_follow_interval: [Nullable(Float), (obj) => obj.follow_interval],
                _initial_default_span: [Float, (obj) => obj.default_span],
            }));
        }
        _plot_bounds = new Map();
        connect_signals() {
            super.connect_signals();
            const { range_padding, range_padding_units, flipped, follow, follow_interval, default_span, only_visible, } = this.properties;
            this.on_change([
                range_padding,
                range_padding_units,
                flipped,
                follow,
                follow_interval,
                default_span,
                only_visible,
            ], () => this._invalidate_dataranges());
        }
        _invalidate_dataranges() {
            this.have_updated_interactively = false;
            for (const plot of this.linked_plots) {
                plot.invalidate_dataranges = true;
                plot.request_repaint();
            }
        }
        get min() {
            return Math.min(this.start, this.end);
        }
        get max() {
            return Math.max(this.start, this.end);
        }
        computed_renderers() {
            // TODO (bev) check that renderers actually configured with this range
            const { renderers } = this;
            const all_renderers = (0, iterator_1.flat_map)(this.linked_plots, (plot) => plot.auto_ranged_renderers.map((r) => r.model));
            return (0, util_1.compute_renderers)(renderers.length == 0 ? "auto" : renderers, [...all_renderers]);
        }
        /*protected*/ _compute_plot_bounds(renderers, bounds) {
            let result = bbox.empty();
            for (const r of renderers) {
                const rect = bounds.get(r);
                if (rect != null && (r.visible || !this.only_visible)) {
                    result = bbox.union(result, rect);
                }
            }
            return result;
        }
        adjust_bounds_for_aspect(bounds, ratio) {
            const result = bbox.empty();
            let width = bounds.x1 - bounds.x0;
            if (width <= 0) {
                width = 1.0;
            }
            let height = bounds.y1 - bounds.y0;
            if (height <= 0) {
                height = 1.0;
            }
            const xcenter = 0.5 * (bounds.x1 + bounds.x0);
            const ycenter = 0.5 * (bounds.y1 + bounds.y0);
            if (width < ratio * height) {
                width = ratio * height;
            }
            else {
                height = width / ratio;
            }
            result.x1 = xcenter + 0.5 * width;
            result.x0 = xcenter - 0.5 * width;
            result.y1 = ycenter + 0.5 * height;
            result.y0 = ycenter - 0.5 * height;
            return result;
        }
        /*protected*/ _compute_min_max(plot_bounds, dimension) {
            let overall = bbox.empty();
            for (const [plot, rect] of plot_bounds) {
                if (plot.model.visible) {
                    overall = bbox.union(overall, rect);
                }
            }
            let min, max;
            if (dimension == 0) {
                [min, max] = [overall.x0, overall.x1];
            }
            else {
                [min, max] = [overall.y0, overall.y1];
            }
            return [min, max];
        }
        /*protected*/ _compute_range(min, max) {
            const { range_padding } = this;
            const min_interval = this.min_interval ?? 0;
            const max_interval = this.max_interval ?? Infinity;
            let start, end;
            if (this._initial_start != null) {
                min = this._initial_start;
            }
            if (this._initial_end != null) {
                max = this._initial_end;
            }
            if (this.scale_hint == "log") {
                if (isNaN(min) || !isFinite(min) || min <= 0) {
                    if (isNaN(max) || !isFinite(max) || max <= 0) {
                        min = 0.1;
                    }
                    else {
                        min = max / 100;
                    }
                    logging_1.logger.warn(`could not determine minimum data value for log axis, DataRange1d using value ${min}`);
                }
                if (isNaN(max) || !isFinite(max) || max <= 0) {
                    if (isNaN(min) || !isFinite(min) || min <= 0) {
                        max = 10;
                    }
                    else {
                        max = min * 100;
                    }
                    logging_1.logger.warn(`could not determine maximum data value for log axis, DataRange1d using value ${max}`);
                }
                let center, span;
                if (max == min) {
                    span = this.default_span + 0.001;
                    center = Math.log10(min);
                }
                else {
                    let log_min, log_max;
                    if (this.range_padding_units == "percent") {
                        log_min = Math.log10(min);
                        log_max = Math.log10(max);
                        span = (log_max - log_min) * (1 + range_padding);
                    }
                    else {
                        log_min = Math.log10(min - range_padding);
                        log_max = Math.log10(max + range_padding);
                        span = log_max - log_min;
                    }
                    center = (log_min + log_max) / 2.0;
                }
                span = (0, math_1.clamp)(span, min_interval, max_interval);
                start = 10 ** (center - span / 2.0);
                end = 10 ** (center + span / 2.0);
            }
            else {
                let span;
                if (max == min) {
                    span = this.default_span;
                }
                else {
                    if (this.range_padding_units == "percent") {
                        span = (max - min) * (1 + range_padding);
                    }
                    else {
                        span = (max - min) + 2 * range_padding;
                    }
                }
                span = (0, math_1.clamp)(span, min_interval, max_interval);
                const center = (max + min) / 2.0;
                start = center - span / 2.0;
                end = center + span / 2.0;
            }
            let follow_sign = +1;
            if (this.flipped) {
                [start, end] = [end, start];
                follow_sign = -1;
            }
            const follow_interval = this.follow_interval;
            if (follow_interval != null && Math.abs(start - end) > follow_interval) {
                if (this.follow == "start") {
                    end = start + follow_sign * follow_interval;
                }
                else if (this.follow == "end") {
                    start = end - follow_sign * follow_interval;
                }
            }
            return [start, end];
        }
        update(bounds, dimension, plot, ratio) {
            if (this.have_updated_interactively) {
                return;
            }
            const renderers = this.computed_renderers();
            // update the raw data bounds for all renderers we care about
            let total_bounds = this._compute_plot_bounds(renderers, bounds);
            if (ratio != null) {
                total_bounds = this.adjust_bounds_for_aspect(total_bounds, ratio);
            }
            this._plot_bounds.set(plot, total_bounds);
            // compute the min/mix for our specified dimension
            const [min, max] = this._compute_min_max(this._plot_bounds.entries(), dimension);
            // derive start, end from bounds and data range config
            let [start, end] = this._compute_range(min, max);
            if (this._initial_start != null) {
                if (this.scale_hint == "log") {
                    if (this._initial_start > 0) {
                        start = this._initial_start;
                    }
                }
                else {
                    start = this._initial_start;
                }
            }
            if (this._initial_end != null) {
                if (this.scale_hint == "log") {
                    if (this._initial_end > 0) {
                        end = this._initial_end;
                    }
                }
                else {
                    end = this._initial_end;
                }
            }
            let needs_emit = false;
            if (this.bounds == "auto") {
                this.computed_bounds = [start, end];
                needs_emit = true;
            }
            // only trigger updates when there are changes
            const [_start, _end] = [this.start, this.end];
            if (start != _start || end != _end) {
                const new_range = {};
                if (start != _start) {
                    new_range.start = start;
                }
                if (end != _end) {
                    new_range.end = end;
                }
                this.setv(new_range);
                needs_emit = false;
            }
            if (needs_emit) {
                this.change.emit();
            }
        }
        reset() {
            this.have_updated_interactively = false;
            // change events silenced as PlotView.update_dataranges triggers property callbacks
            this.setv({
                range_padding: this._initial_range_padding,
                range_padding_units: this._initial_range_padding_units,
                follow: this._initial_follow,
                follow_interval: this._initial_follow_interval,
                default_span: this._initial_default_span,
            }, { silent: true });
            this.change.emit();
        }
    }
    exports.DataRange1d = DataRange1d;
},
/* models/ranges/data_range.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const numerical_range_1 = require(112) /* ./numerical_range */;
    class DataRange extends numerical_range_1.NumericalRange {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ List, AnyRef, Or, Auto }) => ({
                renderers: [Or(List(AnyRef()), Auto), []],
            }));
            this.override({
                start: NaN,
                end: NaN,
            });
        }
    }
    exports.DataRange = DataRange;
},
/* models/util.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.compute_renderers = compute_renderers;
    function compute_renderers(renderers, all_renderers) {
        return renderers == "auto" ? all_renderers : renderers ?? [];
    }
},
/* models/ranges/factor_range.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.map_one_level = map_one_level;
    exports.map_two_levels = map_two_levels;
    exports.map_three_levels = map_three_levels;
    const range_1 = require(110) /* ./range */;
    const enums_1 = require(21) /* ../../core/enums */;
    const kinds_1 = require(22) /* ../../core/kinds */;
    const signaling_1 = require(17) /* ../../core/signaling */;
    const types_1 = require(25) /* ../../core/types */;
    const array_1 = require(10) /* ../../core/util/array */;
    const math_1 = require(12) /* ../../core/util/math */;
    const types_2 = require(8) /* ../../core/util/types */;
    exports.L1Factor = kinds_1.Str;
    exports.L2Factor = (0, kinds_1.Tuple)(kinds_1.Str, kinds_1.Str);
    exports.L3Factor = (0, kinds_1.Tuple)(kinds_1.Str, kinds_1.Str, kinds_1.Str);
    exports.L1FactorSeq = (0, kinds_1.List)(exports.L1Factor);
    exports.L2FactorSeq = (0, kinds_1.List)(exports.L2Factor);
    exports.L3FactorSeq = (0, kinds_1.List)(exports.L3Factor);
    exports.L1OffsetFactor = (0, kinds_1.Tuple)(kinds_1.Str, kinds_1.Float);
    exports.L2OffsetFactor = (0, kinds_1.Tuple)(kinds_1.Str, kinds_1.Str, kinds_1.Float);
    exports.L3OffsetFactor = (0, kinds_1.Tuple)(kinds_1.Str, kinds_1.Str, kinds_1.Str, kinds_1.Float);
    exports.Factor = (0, kinds_1.Or)(exports.L1Factor, exports.L2Factor, exports.L3Factor);
    exports.FactorSeq = (0, kinds_1.Or)(exports.L1FactorSeq, exports.L2FactorSeq, exports.L3FactorSeq);
    exports.OffsetFactor = (0, kinds_1.Or)(exports.L1OffsetFactor, exports.L2OffsetFactor, exports.L3OffsetFactor);
    exports.FactorLike = (0, kinds_1.Or)(kinds_1.Float, exports.Factor, exports.OffsetFactor);
    function map_one_level(factors, padding, offset = 0) {
        const mapping = new Map();
        for (let i = 0; i < factors.length; i++) {
            const factor = factors[i];
            if (mapping.has(factor)) {
                throw new Error(`duplicate factor or subfactor: ${factor}`);
            }
            mapping.set(factor, { value: 0.5 + i * (1 + padding) + offset });
        }
        const inner_padding = (factors.length - 1) * padding;
        return { mapping, inner_padding };
    }
    function map_two_levels(factors, outer_pad, factor_pad, offset = 0) {
        const mapping = new Map();
        const tops = new Map();
        for (const [f0, f1] of factors) {
            const top = tops.get(f0) ?? [];
            tops.set(f0, [...top, f1]);
        }
        let suboffset = offset;
        let total_subpad = 0;
        for (const [f0, top] of tops) {
            const n = top.length;
            const sub = map_one_level(top, factor_pad, suboffset);
            total_subpad += sub.inner_padding;
            const subtot = (0, array_1.sum)(top.map((f1) => sub.mapping.get(f1).value));
            mapping.set(f0, { value: subtot / n, mapping: sub.mapping });
            suboffset += n + outer_pad + sub.inner_padding;
        }
        const inner_padding = (tops.size - 1) * outer_pad + total_subpad;
        return { mapping, tops: [...mapping.keys()], inner_padding };
    }
    function map_three_levels(factors, outer_pad, inner_pad, factor_pad, offset = 0) {
        const mapping = new Map();
        const tops = new Map();
        for (const [f0, f1, f2] of factors) {
            const top = tops.get(f0) ?? [];
            tops.set(f0, [...top, [f1, f2]]);
        }
        let suboffset = offset;
        let total_subpad = 0;
        for (const [f0, top] of tops) {
            const n = top.length;
            const sub = map_two_levels(top, inner_pad, factor_pad, suboffset);
            total_subpad += sub.inner_padding;
            const subtot = (0, array_1.sum)(top.map(([f1]) => sub.mapping.get(f1).value));
            mapping.set(f0, { value: subtot / n, mapping: sub.mapping });
            suboffset += n + outer_pad + sub.inner_padding;
        }
        const mids = [];
        for (const [f0, L2] of mapping) {
            for (const f1 of L2.mapping.keys()) {
                mids.push([f0, f1]);
            }
        }
        const inner_padding = (tops.size - 1) * outer_pad + total_subpad;
        return { mapping, tops: [...mapping.keys()], mids, inner_padding };
    }
    const is_l1 = (x) => (0, types_2.isString)(x);
    const is_l2 = (x) => (0, types_2.isArray)(x) && x.length == 2 && (0, types_2.isString)(x[0]) && (0, types_2.isString)(x[1]);
    const is_l3 = (x) => (0, types_2.isArray)(x) && x.length == 3 && (0, types_2.isString)(x[0]) && (0, types_2.isString)(x[1]) && (0, types_2.isString)(x[2]);
    class FactorMapper {
        levels;
        mids;
        tops;
        inner_padding;
        mapping;
        constructor({ levels, mapping, tops = null, mids = null, inner_padding }) {
            this.levels = levels;
            this.mapping = mapping;
            this.tops = tops;
            this.mids = mids;
            this.inner_padding = inner_padding;
        }
        static compute_levels(factors) {
            if ((0, array_1.every)(factors, is_l1)) {
                return 1;
            }
            if ((0, array_1.every)(factors, is_l2)) {
                return 2;
            }
            if ((0, array_1.every)(factors, is_l3)) {
                return 3;
            }
            throw TypeError("factor levels are inconsistent");
        }
        static for(range) {
            switch (this.compute_levels(range.factors)) {
                case 1: {
                    return new L1FactorMapper(range);
                }
                case 2: {
                    return new L2FactorMapper(range);
                }
                case 3: {
                    return new L3FactorMapper(range);
                }
            }
        }
        map(x) {
            if ((0, types_2.isNumber)(x)) {
                return x;
            }
            const [boxed, offset] = (() => {
                if ((0, types_2.isString)(x)) {
                    return [[x], 0];
                }
                const last = x[x.length - 1];
                if ((0, types_2.isNumber)(last)) {
                    return [x.slice(0, -1), last];
                }
                return [x, 0];
            })();
            if (boxed.length > this.levels) {
                throw new Error(`Attempted to map ${boxed.length} levels of factors with an L${this.levels}FactorMap`);
            }
            return this.lookup_value(boxed) + offset;
        }
        lookup_value(x) {
            return this.lookup_entry(x)?.value ?? NaN;
        }
    }
    exports.FactorMapper = FactorMapper;
    class L1FactorMapper extends FactorMapper {
        constructor(range) {
            const { factors, factor_padding } = range;
            const spec = map_one_level(factors, factor_padding);
            super({ levels: 1, ...spec });
        }
        lookup_entry(x) {
            const [f0] = x;
            return this.mapping.get(f0) ?? null;
        }
    }
    class L2FactorMapper extends FactorMapper {
        constructor(range) {
            const { factors, group_padding, factor_padding } = range;
            const spec = map_two_levels(factors, group_padding, factor_padding);
            super({ levels: 2, ...spec });
        }
        lookup_entry(x) {
            if (x.length == 1) {
                const [f0] = x;
                return this.mapping.get(f0) ?? null;
            }
            else {
                const [f0, f1] = x;
                return this.mapping.get(f0)?.mapping.get(f1) ?? null;
            }
        }
    }
    class L3FactorMapper extends FactorMapper {
        constructor(range) {
            const { factors, group_padding, subgroup_padding, factor_padding } = range;
            const spec = map_three_levels(factors, group_padding, subgroup_padding, factor_padding);
            super({ levels: 3, ...spec });
        }
        lookup_entry(x) {
            if (x.length == 1) {
                const [f0] = x;
                return this.mapping.get(f0) ?? null;
            }
            else if (x.length == 2) {
                const [f0, f1] = x;
                return this.mapping.get(f0)?.mapping.get(f1) ?? null;
            }
            else {
                const [f0, f1, f2] = x;
                return this.mapping.get(f0)?.mapping.get(f1)?.mapping.get(f2) ?? null;
            }
        }
    }
    class FactorRange extends range_1.Range {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Float }) => ({
                factors: [exports.FactorSeq, []],
                factor_padding: [Float, 0],
                subgroup_padding: [Float, 0.8],
                group_padding: [Float, 1.4],
                range_padding: [Float, 0],
                range_padding_units: [enums_1.PaddingUnits, "percent"],
                start: [Float, 0, { readonly: true }],
                end: [Float, 0, { readonly: true }],
            }));
            this.internal(({ AnyRef }) => ({
                mapper: [AnyRef()],
            }));
        }
        get min() {
            return this.start;
        }
        get max() {
            return this.end;
        }
        initialize() {
            super.initialize();
            this.configure();
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.properties.factors.change, () => this.reset());
            this.connect(this.properties.factor_padding.change, () => this.reset());
            this.connect(this.properties.group_padding.change, () => this.reset());
            this.connect(this.properties.subgroup_padding.change, () => this.reset());
            this.connect(this.properties.range_padding.change, () => this.reset());
            this.connect(this.properties.range_padding_units.change, () => this.reset());
        }
        invalidate_synthetic = new signaling_1.Signal0(this, "invalidate_synthetic");
        reset() {
            this.configure();
            this.invalidate_synthetic.emit();
        }
        /** Convert a categorical factor into a synthetic coordinate. */
        synthetic(x) {
            return this.mapper.map(x);
        }
        /** Convert an array of categorical factors into synthetic coordinates. */
        v_synthetic(xs) {
            return types_1.ScreenArray.from(xs, (x) => this.synthetic(x));
        }
        /** Convert a synthetic coordinate into a categorical factor. */
        factor(x) {
            for (const f of this.factors) {
                const v = this.mapper.map(f);
                if (x >= (v - 0.5) && x < (v + 0.5)) {
                    return f;
                }
            }
            return null;
        }
        compute_bounds(inner_padding) {
            const interval = this.factors.length + inner_padding;
            const padding = (() => {
                switch (this.range_padding_units) {
                    case "percent": {
                        return interval * this.range_padding / 2;
                    }
                    case "absolute": {
                        return this.range_padding;
                    }
                }
            })();
            return [-padding, interval + padding];
        }
        configure() {
            this.mapper = FactorMapper.for(this);
            let [start, end] = this.compute_bounds(this.mapper.inner_padding);
            if (this.bounds != "auto" && this.bounds != null) {
                const [lower, upper] = this.computed_bounds;
                start = (0, math_1.clamp)(start, lower, upper);
                end = (0, math_1.clamp)(end, lower, upper);
            }
            this.setv({ start, end }, { silent: true });
            if (this.bounds == "auto") {
                this.computed_bounds = [start, end];
            }
        }
    }
    exports.FactorRange = FactorRange;
},
/* models/ui/menus/menu.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const ui_element_1 = require(55) /* ../ui_element */;
    const menu_item_1 = require(123) /* ./menu_item */;
    const divider_item_1 = require(126) /* ./divider_item */;
    const resolve_1 = require(127) /* ../../common/resolve */;
    const types_1 = require(8) /* ../../../core/util/types */;
    const dom_1 = require(61) /* ../../../core/dom */;
    const kinds_1 = require(22) /* ../../../core/kinds */;
    const build_views_1 = require(69) /* ../../../core/build_views */;
    const array_1 = require(10) /* ../../../core/util/array */;
    const callbacks_1 = require(51) /* ../../../core/util/callbacks */;
    const menus_css_1 = tslib_1.__importStar(require(128) /* ../../../styles/menus.css */), menus = menus_css_1;
    const icons_css_1 = tslib_1.__importDefault(require(76) /* ../../../styles/icons.css */);
    function to_val(val) {
        return (0, types_1.isFunction)(val) ? val() : val;
    }
    exports.MenuItemLike = (0, kinds_1.Or)((0, kinds_1.Ref)(menu_item_1.MenuItem), (0, kinds_1.Ref)(divider_item_1.DividerItem), kinds_1.Null);
    class MenuView extends ui_element_1.UIElementView {
        _menu_views = new Map();
        children_views() {
            return [...super.children_views(), ...this._menu_views.values()];
        }
        _menu_items = [];
        get menu_items() {
            const items = this._menu_items;
            const { reversed } = this.model;
            return reversed ? (0, array_1.reversed)(items) : items;
        }
        _compute_menu_items() {
            return this.model.items;
        }
        _update_menu_items() {
            this._menu_items = this._compute_menu_items();
        }
        get is_empty() {
            return this.menu_items.length == 0;
        }
        initialize() {
            super.initialize();
            this._update_menu_items();
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const menus = this.menu_items
                .filter((item) => item instanceof menu_item_1.MenuItem)
                .map((item) => item.menu)
                .filter((menu) => menu != null);
            await (0, build_views_1.build_views)(this._menu_views, menus, { parent: this });
        }
        connect_signals() {
            super.connect_signals();
            const { items } = this.model.properties;
            this.on_change(items, () => this._update_menu_items());
        }
        prevent_hide;
        _open = false;
        get is_open() {
            return this._open;
        }
        _item_click = (item) => {
            if (!to_val(item.disabled)) {
                const { action } = item;
                if (action != null) {
                    void (0, callbacks_1.execute)(action, this.model, { item });
                }
                this.hide();
            }
        };
        _on_mousedown = (event) => {
            if (event.composedPath().includes(this.el)) {
                return;
            }
            if (this.prevent_hide?.(event) ?? false) {
                return;
            }
            this.hide();
        };
        _on_keydown = (event) => {
            switch (event.key) {
                case "Escape": {
                    this.hide();
                    break;
                }
                default:
            }
        };
        _on_blur = () => {
            this.hide();
        };
        remove() {
            this._unlisten();
            super.remove();
        }
        _listen() {
            document.addEventListener("mousedown", this._on_mousedown);
            document.addEventListener("keydown", this._on_keydown);
            window.addEventListener("blur", this._on_blur);
        }
        _unlisten() {
            document.removeEventListener("mousedown", this._on_mousedown);
            document.removeEventListener("keydown", this._on_keydown);
            window.removeEventListener("blur", this._on_blur);
        }
        stylesheets() {
            return [...super.stylesheets(), menus_css_1.default, icons_css_1.default];
        }
        render() {
            super.render();
            const items = this.menu_items;
            const entries = [];
            if (items.length == 0) {
                return;
            }
            for (const item of items) {
                if (item instanceof menu_item_1.MenuItem) {
                    const check_el = (0, dom_1.div)({ class: menus.check });
                    const label_el = (0, dom_1.div)({ class: menus.label }, item.label);
                    const shortcut_el = (0, dom_1.div)({ class: menus.shortcut }, item.shortcut);
                    const chevron_el = (0, dom_1.div)({ class: menus.chevron });
                    const icon_el = (() => {
                        const { icon } = item;
                        if (icon != null) {
                            const icon_el = (0, dom_1.div)({ class: menus.icon });
                            (0, resolve_1.apply_icon)(icon_el, icon);
                            return icon_el;
                        }
                        else {
                            return null;
                        }
                    })();
                    const item_el = (0, dom_1.div)({ class: menus.item, title: item.tooltip, tabIndex: 0 }, check_el, icon_el, label_el, shortcut_el, chevron_el);
                    const has_menu = item.menu != null && !this._menu_views.get(item.menu).is_empty;
                    item_el.classList.toggle(menus.menu, has_menu);
                    item_el.classList.toggle(menus.disabled, to_val(item.disabled));
                    if (item.checked != null) {
                        item_el.classList.add(menus.checkable);
                        item_el.classList.toggle(menus.checked, to_val(item.checked));
                    }
                    const show_submenu = (item) => {
                        if (item.menu != null) {
                            const menu_view = this._menu_views.get(item.menu);
                            menu_view._show_submenu(item_el);
                        }
                    };
                    const hide_submenu = (item) => {
                        if (item.menu != null) {
                            const menu_view = this._menu_views.get(item.menu);
                            menu_view.hide();
                        }
                    };
                    function is_target(event) {
                        const { currentTarget, target } = event;
                        return currentTarget instanceof Node && target instanceof Node && currentTarget.contains(target);
                    }
                    item_el.addEventListener("click", (event) => {
                        if (is_target(event)) {
                            this._item_click(item);
                        }
                        else {
                            this.hide();
                        }
                    });
                    item_el.addEventListener("keydown", (event) => {
                        // TODO https://github.com/bokeh/bokeh/issues/14241
                        switch (event.key) {
                            case "Enter": {
                                this._item_click(item);
                                break;
                            }
                            case "ArrowDown": {
                                break;
                            }
                            case "ArrowUp": {
                                break;
                            }
                            case "ArrowLeft": {
                                break;
                            }
                            case "ArrowRight": {
                                break;
                            }
                            default:
                        }
                    });
                    const { menu } = item;
                    if (menu != null) {
                        item_el.addEventListener("pointerenter", () => {
                            show_submenu(item);
                        });
                        item_el.addEventListener("pointerleave", () => {
                            hide_submenu(item);
                        });
                    }
                    this.shadow_el.append(item_el);
                    entries.push({ item, el: item_el });
                }
                else {
                    const item_el = (0, dom_1.div)({ class: menus.divider });
                    this.shadow_el.append(item_el);
                }
            }
        }
        _show_submenu(target) {
            if (this.is_empty) {
                this.hide();
                return;
            }
            this.render();
            target.append(this.el);
            const { style } = this.el;
            style.left = "100%";
            style.top = "0";
            this._listen();
            this._open = true;
        }
        show(at) {
            if (this.is_empty) {
                this.hide();
                return false;
            }
            const { parent } = this;
            if (parent == null) {
                // TODO position: fixed
                this.hide();
                return false;
            }
            this.render();
            const target = parent.el.shadowRoot ?? parent.el;
            target.append(this.el);
            const { style } = this.el;
            style.left = (0, dom_1.px)(at.x);
            style.top = (0, dom_1.px)(at.y);
            this._listen();
            this._open = true;
            return true;
        }
        hide() {
            if (this._open) {
                this._open = false;
                this._unlisten();
                this.el.remove();
            }
        }
    }
    exports.MenuView = MenuView;
    class Menu extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = MenuView;
            this.define(({ Bool, List }) => ({
                items: [List(exports.MenuItemLike), []],
                reversed: [Bool, false],
            }));
        }
    }
    exports.Menu = Menu;
},
/* models/ui/menus/menu_item.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../../model */;
    const kinds_1 = require(124) /* ../../common/kinds */;
    const callback_1 = require(125) /* ../../callbacks/callback */;
    class MenuItem extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Bool, Str, Nullable, AnyRef, Ref, Func, Func0, Or }) => ({
                checked: [Nullable(Or(Bool, Func0(Bool))), null],
                icon: [Nullable(kinds_1.IconLike), null],
                label: [Str],
                tooltip: [Nullable(Str), null],
                shortcut: [Nullable(Str), null],
                menu: [Nullable(AnyRef()), null],
                disabled: [Or(Bool, Func0(Bool)), false],
                action: [Nullable(Or(Ref(callback_1.Callback), Func())), null],
            }));
        }
    }
    exports.MenuItem = MenuItem;
},
/* models/common/kinds.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const kinds_1 = require(22) /* ../../core/kinds */;
    const enums = tslib_1.__importStar(require(21) /* ../../core/enums */);
    exports.Length = (0, kinds_1.NonNegative)(kinds_1.Int);
    const XY = (type) => (0, kinds_1.PartialStruct)({ x: type, y: type });
    const LRTB = (type) => (0, kinds_1.PartialStruct)({ left: type, right: type, top: type, bottom: type });
    exports.HAnchor = (0, kinds_1.Or)(enums.Align, enums.HAlign, kinds_1.Percent);
    exports.VAnchor = (0, kinds_1.Or)(enums.Align, enums.VAlign, kinds_1.Percent);
    exports.Anchor = (0, kinds_1.Or)(enums.Anchor, (0, kinds_1.Tuple)(exports.HAnchor, exports.VAnchor));
    exports.AutoAnchor = (0, kinds_1.Or)(kinds_1.Auto, enums.Anchor, (0, kinds_1.Tuple)((0, kinds_1.Or)(exports.HAnchor, kinds_1.Auto), (0, kinds_1.Or)(exports.VAnchor, kinds_1.Auto)));
    exports.TextAnchor = (0, kinds_1.Or)(exports.Anchor, kinds_1.Auto);
    exports.Padding = ((0, kinds_1.Or)(exports.Length, (0, kinds_1.Tuple)(exports.Length, exports.Length), XY(exports.Length), (0, kinds_1.Tuple)(exports.Length, exports.Length, exports.Length, exports.Length), LRTB(exports.Length)));
    exports.BorderRadius = ((0, kinds_1.Or)(exports.Length, (0, kinds_1.Tuple)(exports.Length, exports.Length, exports.Length, exports.Length), (0, kinds_1.PartialStruct)({
        top_left: exports.Length,
        top_right: exports.Length,
        bottom_right: exports.Length,
        bottom_left: exports.Length,
    })));
    exports.Index = (0, kinds_1.NonNegative)(kinds_1.Int);
    exports.Span = (0, kinds_1.NonNegative)(kinds_1.Int);
    const GridChild = (child) => (0, kinds_1.Tuple)((0, kinds_1.Ref)(child), exports.Index, exports.Index, (0, kinds_1.Opt)(exports.Span), (0, kinds_1.Opt)(exports.Span));
    exports.GridChild = GridChild;
    exports.GridSpacing = (0, kinds_1.Or)(exports.Length, (0, kinds_1.Tuple)(exports.Length, exports.Length));
    exports.TrackAlign = (0, kinds_1.Enum)("start", "center", "end", "auto");
    exports.TrackSize = kinds_1.Str;
    exports.TrackSizing = (0, kinds_1.PartialStruct)({ size: exports.TrackSize, align: exports.TrackAlign });
    exports.TrackSizingLike = (0, kinds_1.Or)(exports.TrackSize, exports.TrackSizing);
    exports.TracksSizing = (0, kinds_1.Or)(exports.TrackSizingLike, (0, kinds_1.List)(exports.TrackSizingLike), (0, kinds_1.Mapping)(kinds_1.Int, exports.TrackSizingLike));
    exports.IconLike = (0, kinds_1.Or)(enums.ToolIcon, (0, kinds_1.PrefixedStr)("--"), (0, kinds_1.PrefixedStr)("."), (0, kinds_1.PrefixedStr)("data:image"));
},
/* models/callbacks/callback.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    class Callback extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Callback = Callback;
},
/* models/ui/menus/divider_item.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../../model */;
    class DividerItem extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.DividerItem = DividerItem;
},
/* models/common/resolve.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.normalized_anchor = normalized_anchor;
    exports.anchor = anchor;
    exports.text_anchor = text_anchor;
    exports.padding = padding;
    exports.border_radius = border_radius;
    exports.apply_icon = apply_icon;
    const enums_1 = require(21) /* ../../core/enums */;
    const types_1 = require(8) /* ../../core/util/types */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    const logging_1 = require(11) /* ../../core/logging */;
    function normalized_anchor(anchor) {
        if (anchor == "auto") {
            return { x: "auto", y: "auto" };
        }
        const normalized = (() => {
            switch (anchor) {
                case "top": return "top_center";
                case "bottom": return "bottom_center";
                case "left": return "center_left";
                case "center": return "center_center";
                case "right": return "center_right";
                default: return anchor;
            }
        })();
        if ((0, types_1.isString)(normalized)) {
            const [y, x] = normalized.split("_");
            return { x, y };
        }
        else {
            const [x, y] = normalized;
            return { x, y };
        }
    }
    function anchor(anchor) {
        const { x, y } = normalized_anchor(anchor);
        const x_anchor = (() => {
            switch (x) {
                case "start":
                case "left": return 0.0;
                case "center": return 0.5;
                case "end":
                case "right": return 1.0;
                default: return x;
            }
        })();
        const y_anchor = (() => {
            switch (y) {
                case "start":
                case "top": return 0.0;
                case "center": return 0.5;
                case "end":
                case "bottom": return 1.0;
                default: return y;
            }
        })();
        return { x: x_anchor, y: y_anchor };
    }
    function text_anchor(text_anchor, align, baseline) {
        if (text_anchor != "auto") {
            return anchor(text_anchor);
        }
        else {
            const x_anchor = (() => {
                switch (align) {
                    case "left": return "start";
                    case "center": return "center";
                    case "right": return "end";
                }
            })();
            const y_anchor = (() => {
                switch (baseline) {
                    case "alphabetic":
                    case "ideographic":
                    case "hanging":
                        return "center";
                    case "top": return "start";
                    case "middle": return "center";
                    case "bottom": return "end";
                }
            })();
            return anchor([x_anchor, y_anchor]);
        }
    }
    function padding(padding) {
        if ((0, types_1.isNumber)(padding)) {
            return { left: padding, right: padding, top: padding, bottom: padding };
        }
        else if ((0, types_1.isPlainObject)(padding)) {
            if ("x" in padding || "y" in padding) {
                const { x = 0, y = 0 } = padding;
                return { left: x, right: x, top: y, bottom: y };
            }
            else if ("left" in padding || "right" in padding || "top" in padding || "bottom" in padding) {
                const { left = 0, right = 0, top = 0, bottom = 0 } = padding;
                return { left, right, top, bottom };
            }
            else {
                (0, assert_1.unreachable)(); // TODO: TypeScript 4.9
            }
        }
        else {
            if (padding.length == 2) {
                const [x = 0, y = 0] = padding;
                return { left: x, right: x, top: y, bottom: y };
            }
            else {
                const [left = 0, right = 0, top = 0, bottom = 0] = padding;
                return { left, right, top, bottom };
            }
        }
    }
    function border_radius(border_radius) {
        if ((0, types_1.isNumber)(border_radius)) {
            return {
                top_left: border_radius,
                top_right: border_radius,
                bottom_right: border_radius,
                bottom_left: border_radius,
            };
        }
        else if ((0, types_1.isPlainObject)(border_radius)) {
            return {
                top_left: border_radius.top_left ?? 0,
                top_right: border_radius.top_right ?? 0,
                bottom_right: border_radius.bottom_right ?? 0,
                bottom_left: border_radius.bottom_left ?? 0,
            };
        }
        else {
            const [top_left = 0, top_right = 0, bottom_right = 0, bottom_left = 0] = border_radius;
            return { top_left, top_right, bottom_right, bottom_left };
        }
    }
    function apply_icon(el, icon) {
        if (icon.startsWith("data:image")) {
            const url = `url("${encodeURI(icon)}")`;
            el.style.backgroundImage = url;
        }
        else if (icon.startsWith("--")) {
            el.style.backgroundImage = `var(${icon})`;
        }
        else if (icon.startsWith(".")) {
            const cls = icon.substring(1);
            el.classList.add(cls);
        }
        else if (enums_1.ToolIcon.valid(icon)) {
            const cls = `bk-tool-icon-${icon.replace(/_/g, "-")}`;
            el.classList.add(cls);
        }
        else {
            logging_1.logger.warn(`unable to resolve icon: ${icon}`);
        }
    }
},
/* styles/menus.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.item = "bk-item";
    exports.divider = "bk-divider";
    exports.check = "bk-check";
    exports.icon = "bk-icon";
    exports.label = "bk-label";
    exports.shortcut = "bk-shortcut";
    exports.chevron = "bk-chevron";
    exports.disabled = "bk-disabled";
    exports.menu = "bk-menu";
    exports.checkable = "bk-checkable";
    exports.checked = "bk-checked";
    exports.default = `:host{position:absolute;display:inline-grid;grid-template-columns:var(--menu-template-columns, repeat(5, max-content));grid-template-rows:auto;user-select:none;-webkit-user-select:none;cursor:pointer;width:var(--menu-width, auto);height:auto;z-index:var(--bokeh-top-level);font-size:var(--font-size);background-color:var(--background-color);border:1px solid var(--border-color);border-radius:var(--border-radius);box-shadow:var(--box-shadow);}.bk-item,.bk-divider{position:relative;display:grid;grid-template-columns:subgrid;grid-column:span 5;align-items:center;}.bk-check{grid-column:1;}.bk-icon{grid-column:2;}.bk-label{grid-column:3;}.bk-shortcut{grid-column:4;}.bk-chevron{grid-column:5;}.bk-divider{cursor:default;overflow:hidden;background-color:var(--divider-color);height:1px;margin:1px 5px;}.bk-item{padding:0.5em;}.bk-item:hover{background-color:var(--hover-color);}.bk-item:focus,.bk-item:focus-visible{outline:1px dotted var(--highlight-color);outline-offset:-1px;}.bk-item::-moz-focus-inner{border:0;}.bk-item[disabled],.bk-item.bk-disabled{background-color:inherit;color:var(--disabled-color);cursor:not-allowed;pointer-events:none;opacity:inherit;}.bk-item[disabled] .bk-icon,.bk-item.bk-disabled .bk-icon{color:var(--icon-color-disabled);}.bk-item:first-of-type{border-top-left-radius:var(--border-radius);border-top-right-radius:var(--border-radius);}.bk-item:last-of-type{border-bottom-left-radius:var(--border-radius);border-bottom-right-radius:var(--border-radius);}.bk-icon{position:relative;width:16px;height:16px;mask-size:100% 100%;-webkit-mask-size:100% 100%;mask-position:center center;-webkit-mask-position:center center;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat;background-size:100% 100%;background-origin:border-box;background-position:center center;background-repeat:no-repeat;}.bk-label{padding:0 0.5em;}.bk-shortcut{text-align:right;font-size:90%;color:var(--shortcut-color);}.bk-chevron{background-color:var(--icon-color);mask-image:var(--bokeh-icon-caret-right);-webkit-mask-image:var(--bokeh-icon-caret-right);mask-size:100% 100%;-webkit-mask-size:100% 100%;mask-position:center center;-webkit-mask-position:center center;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat;width:12px;height:12px;}.bk-item:not(.bk-menu) .bk-chevron{display:none;}.bk-item.bk-checkable .bk-check{width:16px;height:16px;}.bk-item.bk-checkable.bk-checked .bk-check{background-color:var(--icon-color);mask-image:var(--bokeh-icon-check);-webkit-mask-image:var(--bokeh-icon-check);mask-size:100% 100%;-webkit-mask-size:100% 100%;mask-position:center center;-webkit-mask-position:center center;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat;}`;
},
/* models/renderers/renderer_group.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    class RendererGroup extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Bool }) => ({
                visible: [Bool, true],
            }));
        }
    }
    exports.RendererGroup = RendererGroup;
},
/* models/dom/dom_node.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const dom_view_1 = require(64) /* ../../core/dom_view */;
    const model_1 = require(52) /* ../../model */;
    class DOMNodeView extends dom_view_1.DOMView {
    }
    exports.DOMNodeView = DOMNodeView;
    class DOMNode extends model_1.Model {
        static __module__ = "bokeh.models.dom";
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.DOMNode = DOMNode;
},
/* models/layouts/layout_dom.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const pane_1 = require(132) /* ../ui/pane */;
    const logging_1 = require(11) /* ../../core/logging */;
    const signaling_1 = require(17) /* ../../core/signaling */;
    const enums_1 = require(21) /* ../../core/enums */;
    const dom_1 = require(61) /* ../../core/dom */;
    const types_1 = require(8) /* ../../core/util/types */;
    const iterator_1 = require(15) /* ../../core/util/iterator */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const layout_1 = require(135) /* ../../core/layout */;
    const canvas_1 = require(71) /* ../../core/util/canvas */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    class LayoutDOMView extends pane_1.PaneView {
        _child_views = new Map();
        layout;
        mouseenter = new signaling_1.Signal(this, "mouseenter");
        mouseleave = new signaling_1.Signal(this, "mouseleave");
        disabled = new signaling_1.Signal(this, "disabled");
        get is_layout_root() {
            return this.is_root || !(this.parent instanceof LayoutDOMView);
        }
        _after_resize() {
            super._after_resize();
            if (this.is_layout_root && !this._was_built) {
                // This can happen only in pathological cases primarily in tests.
                logging_1.logger.warn(`${this} wasn't built properly`);
                this.render();
                this.r_after_render();
            }
            else {
                this.compute_layout();
            }
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this.build_child_views();
        }
        connect_signals() {
            super.connect_signals();
            this.el.addEventListener("mouseenter", (event) => {
                this.mouseenter.emit(event);
            });
            this.el.addEventListener("mouseleave", (event) => {
                this.mouseleave.emit(event);
            });
            if (this.parent instanceof LayoutDOMView) {
                this.connect(this.parent.disabled, (disabled) => {
                    this.disabled.emit(disabled || this.model.disabled);
                });
            }
            const p = this.model.properties;
            this.on_change(p.disabled, () => {
                this.disabled.emit(this.model.disabled);
            });
            this.on_change([
                p.css_classes,
                p.stylesheets,
                p.width, p.height,
                p.min_width, p.min_height,
                p.max_width, p.max_height,
                p.margin,
                p.width_policy, p.height_policy,
                p.flow_mode, p.sizing_mode,
                p.aspect_ratio,
                p.visible,
                p.resizable,
            ], () => this.invalidate_layout());
        }
        children_views() {
            return [...super.children_views(), ...this.child_views];
        }
        get child_views() {
            // TODO In case of a race condition somewhere between layout, resize and children updates,
            // child_models and _child_views may be temporarily inconsistent, resulting in undefined
            // values. Eventually this shouldn't happen and undefined should be treated as a bug.
            return this.child_models.map((child) => this._child_views.get(child)).filter((view) => view != null);
        }
        get layoutable_views() {
            return this.child_views.filter((c) => c instanceof LayoutDOMView);
        }
        async build_child_views() {
            const { created, removed } = await (0, build_views_1.build_views)(this._child_views, this.child_models, { parent: this });
            for (const view of removed) {
                this._resize_observer.unobserve(view.el);
            }
            for (const view of created) {
                this._resize_observer.observe(view.el, { box: "border-box" });
            }
            return created;
        }
        render() {
            super.render();
            for (const child_view of this.child_views) {
                const target = child_view.rendering_target() ?? this.shadow_el;
                child_view.render_to(target);
            }
        }
        rerender() {
            super.rerender();
            this.update_layout();
            this.compute_layout();
        }
        _update_children() { }
        async update_children() {
            const created = await this.build_child_views();
            const created_views = new Set(created);
            // Find index up to which the order of the existing views
            // matches the order of the new views. This allows us to
            // skip re-inserting the views up to this point
            const current_views = Array.from(this.shadow_el.children).flatMap(el => {
                const view = this.child_views.find(view => view.el === el);
                return view === undefined ? [] : [view];
            });
            let matching_index = null;
            for (let i = 0; i < current_views.length; i++) {
                if (current_views[i] === this.child_views[i]) {
                    matching_index = i;
                }
                else {
                    break;
                }
            }
            // Since appending to a DOM node will move the node to the end if it has
            // already been added appending all the children in order will result in
            // correct ordering.
            for (const [view, i] of (0, iterator_1.enumerate)(this.child_views)) {
                const is_new = created_views.has(view);
                const target = view.rendering_target() ?? this.self_target;
                if (is_new) {
                    view.render_to(target);
                }
                else if (matching_index === null || i > matching_index) {
                    target.append(view.el);
                }
            }
            this.r_after_render();
            this._update_children();
            this.invalidate_layout();
        }
        _auto_width = "fit-content";
        _auto_height = "fit-content";
        _intrinsic_display() {
            return { inner: this.model.flow_mode, outer: "flow" };
        }
        _update_layout() {
            function css_sizing(policy, size, auto_size, margin) {
                switch (policy) {
                    case "auto":
                        return size != null ? (0, dom_1.px)(size) : auto_size;
                    case "fixed":
                        return size != null ? (0, dom_1.px)(size) : "fit-content";
                    case "fit":
                        return "fit-content";
                    case "min":
                        return "min-content";
                    case "max":
                        return margin == null ? "100%" : `calc(100% - ${margin})`;
                }
            }
            function css_display(display) {
                // Convert to legacy values due to limited browser support.
                const { inner, outer } = display;
                switch (`${inner} ${outer}`) {
                    case "block flow": return "block";
                    case "inline flow": return "inline";
                    case "block flow-root": return "flow-root";
                    case "inline flow-root": return "inline-block";
                    case "block flex": return "flex";
                    case "inline flex": return "inline-flex";
                    case "block grid": return "grid";
                    case "inline grid": return "inline-grid";
                    case "block table": return "table";
                    case "inline table": return "inline-table";
                    default: (0, assert_1.unreachable)();
                }
            }
            function to_css(value) {
                return (0, types_1.isNumber)(value) ? (0, dom_1.px)(value) : `${value.percent}%`;
            }
            const styles = {};
            const display = this._intrinsic_display();
            styles.display = css_display(display);
            const sizing = this.box_sizing();
            const { width_policy, height_policy, width, height, aspect_ratio } = sizing;
            const computed_aspect = (() => {
                if (aspect_ratio == "auto") {
                    if (width != null && height != null) {
                        return width / height;
                    }
                }
                else if ((0, types_1.isNumber)(aspect_ratio)) {
                    return aspect_ratio;
                }
                return null;
            })();
            if (aspect_ratio == "auto") {
                if (width != null && height != null) {
                    styles.aspect_ratio = `${width} / ${height}`;
                }
                else {
                    styles.aspect_ratio = "auto";
                }
            }
            else if ((0, types_1.isNumber)(aspect_ratio)) {
                styles.aspect_ratio = `${aspect_ratio}`;
            }
            const { margin } = this.model;
            const margins = (() => {
                if (margin != null) {
                    if ((0, types_1.isNumber)(margin)) {
                        styles.margin = (0, dom_1.px)(margin);
                        return { width: (0, dom_1.px)(2 * margin), height: (0, dom_1.px)(2 * margin) };
                    }
                    else if (margin.length == 2) {
                        const [vertical, horizontal] = margin;
                        styles.margin = `${(0, dom_1.px)(vertical)} ${(0, dom_1.px)(horizontal)}`;
                        return { width: (0, dom_1.px)(2 * horizontal), height: (0, dom_1.px)(2 * vertical) };
                    }
                    else {
                        const [top, right, bottom, left] = margin;
                        styles.margin = `${(0, dom_1.px)(top)} ${(0, dom_1.px)(right)} ${(0, dom_1.px)(bottom)} ${(0, dom_1.px)(left)}`;
                        return { width: (0, dom_1.px)(left + right), height: (0, dom_1.px)(top + bottom) };
                    }
                }
                else {
                    return { width: null, height: null };
                }
            })();
            const [css_width, css_height] = (() => {
                const css_width = css_sizing(width_policy, width, this._auto_width, margins.width);
                const css_height = css_sizing(height_policy, height, this._auto_height, margins.height);
                if (aspect_ratio != null) {
                    if (width_policy != height_policy) {
                        if (width_policy == "fixed") {
                            return [css_width, "auto"];
                        }
                        if (height_policy == "fixed") {
                            return ["auto", css_height];
                        }
                        if (width_policy == "max") {
                            return [css_width, "auto"];
                        }
                        if (height_policy == "max") {
                            return ["auto", css_height];
                        }
                        return ["auto", "auto"];
                    }
                    else {
                        if (width_policy != "fixed" && height_policy != "fixed") {
                            if (computed_aspect != null) {
                                if (computed_aspect >= 1) {
                                    return [css_width, "auto"];
                                }
                                else {
                                    return ["auto", css_height];
                                }
                            }
                        }
                    }
                }
                return [css_width, css_height];
            })();
            styles.width = css_width;
            styles.height = css_height;
            const { min_width, max_width } = this.model;
            const { min_height, max_height } = this.model;
            if (min_width != null) {
                styles.min_width = to_css(min_width);
            }
            if (min_height != null) {
                styles.min_height = to_css(min_height);
            }
            if (this.is_layout_root) {
                if (max_width != null) {
                    styles.max_width = to_css(max_width);
                }
                if (max_height != null) {
                    styles.max_height = to_css(max_height);
                }
            }
            else {
                if (max_width != null) {
                    styles.max_width = `min(${to_css(max_width)}, 100%)`;
                }
                else if (width_policy != "fixed") {
                    styles.max_width = "100%";
                }
                if (max_height != null) {
                    styles.max_height = `min(${to_css(max_height)}, 100%)`;
                }
                else if (height_policy != "fixed") {
                    styles.max_height = "100%";
                }
            }
            const { resizable } = this.model;
            if (resizable !== false) {
                const resize = (() => {
                    switch (resizable) {
                        case "width": return "horizontal";
                        case "height": return "vertical";
                        case true:
                        case "both": return "both";
                    }
                })();
                styles.resize = resize;
                styles.overflow = "auto";
            }
            this.style.append(":host", styles);
        }
        update_layout() {
            this.update_style();
            for (const child_view of this.child_views) {
                child_view.parent_style.clear();
            }
            for (const child_view of this.layoutable_views) {
                child_view.update_layout();
            }
            this._update_layout();
        }
        get is_managed() {
            return this.parent instanceof LayoutDOMView;
        }
        /**
         * Update CSS layout with computed values from canvas layout.
         * This can be done more frequently than `_update_layout()`.
         */
        _measure_layout() { }
        measure_layout() {
            for (const child_view of this.layoutable_views) {
                child_view.measure_layout();
            }
            this._measure_layout();
        }
        _layout_computed = false;
        compute_layout() {
            if (this.parent instanceof LayoutDOMView) { // TODO: this.is_managed
                this.parent.compute_layout();
            }
            else {
                this.measure_layout();
                this.update_bbox();
                this._compute_layout();
                this.after_layout();
            }
            this._layout_computed = true;
        }
        _compute_layout() {
            if (this.layout != null) {
                this.layout.compute(this.bbox.size);
                for (const child_view of this.layoutable_views) {
                    if (child_view.layout == null) {
                        child_view._compute_layout();
                    }
                    else {
                        child_view._propagate_layout();
                    }
                }
            }
            else {
                for (const child_view of this.layoutable_views) {
                    child_view._compute_layout();
                }
            }
        }
        _propagate_layout() {
            for (const child_view of this.layoutable_views) {
                if (child_view.layout == null) {
                    child_view._compute_layout();
                }
            }
        }
        update_bbox() {
            for (const child_view of this.layoutable_views) {
                child_view.update_bbox();
            }
            const changed = super.update_bbox();
            if (this.layout != null) {
                this.layout.visible = this.is_displayed;
            }
            return changed;
        }
        _after_layout() { }
        after_layout() {
            for (const child_view of this.layoutable_views) {
                child_view.after_layout();
            }
            this._after_layout();
        }
        _after_render() {
            // XXX no super
            if (!this.is_managed) {
                this.invalidate_layout();
            }
        }
        invalidate_layout() {
            // TODO: it would be better and more efficient to do a localized
            // update, but for now this guarantees consistent state of layout.
            if (this.parent instanceof LayoutDOMView) {
                this.parent.invalidate_layout();
            }
            else {
                this.update_layout();
                this.compute_layout();
            }
        }
        invalidate_render() {
            this.render();
            this.r_after_render();
            this.invalidate_layout();
        }
        has_finished() {
            if (!super.has_finished()) {
                return false;
            }
            if (this.is_layout_root && !this._layout_computed) {
                return false;
            }
            for (const child_view of this.child_views) {
                if (!child_view.has_finished()) {
                    return false;
                }
            }
            return true;
        }
        box_sizing() {
            let { width_policy, height_policy, aspect_ratio } = this.model;
            const { sizing_mode } = this.model;
            if (sizing_mode != null) {
                if (sizing_mode == "inherit") {
                    if (this.parent instanceof LayoutDOMView) {
                        const sizing = this.parent.box_sizing();
                        width_policy = sizing.width_policy;
                        height_policy = sizing.height_policy;
                        if (aspect_ratio == null) {
                            aspect_ratio = sizing.aspect_ratio;
                        }
                    }
                }
                else if (sizing_mode == "fixed") {
                    width_policy = height_policy = "fixed";
                }
                else if (sizing_mode == "stretch_both") {
                    width_policy = height_policy = "max";
                }
                else if (sizing_mode == "stretch_width") {
                    width_policy = "max";
                }
                else if (sizing_mode == "stretch_height") {
                    height_policy = "max";
                }
                else {
                    if (aspect_ratio == null) {
                        aspect_ratio = "auto";
                    }
                    switch (sizing_mode) {
                        case "scale_width":
                            width_policy = "max";
                            height_policy = "min";
                            break;
                        case "scale_height":
                            width_policy = "min";
                            height_policy = "max";
                            break;
                        case "scale_both":
                            width_policy = "max";
                            height_policy = "max";
                            break;
                    }
                }
            }
            const [halign, valign] = (() => {
                const { align } = this.model;
                if (align == "auto") {
                    return [undefined, undefined];
                }
                else if ((0, types_1.isArray)(align)) {
                    return align;
                }
                else {
                    return [align, align];
                }
            })();
            const { width, height } = this.model;
            return {
                width_policy,
                height_policy,
                width,
                height,
                aspect_ratio,
                halign,
                valign,
            };
        }
        export(type = "auto", hidpi = true) {
            const output_backend = (() => {
                switch (type) {
                    case "auto": // TODO: actually infer the best type
                    case "png": return "canvas";
                    case "svg": return "svg";
                }
            })();
            const composite = new canvas_1.CanvasLayer(output_backend, hidpi);
            const { x, y, width, height } = this.bbox;
            composite.resize(width, height);
            const bg_color = getComputedStyle(this.el).backgroundColor;
            composite.ctx.fillStyle = bg_color;
            composite.ctx.fillRect(x, y, width, height);
            for (const view of this.child_views) {
                const region = view.export(type, hidpi);
                const { x, y } = view.bbox.scale(composite.pixel_ratio);
                composite.ctx.drawImage(region.canvas, x, y);
            }
            return composite;
        }
    }
    exports.LayoutDOMView = LayoutDOMView;
    class LayoutDOM extends pane_1.Pane {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define((types) => {
                const { Bool, Float, Auto, Tuple, Or, Null, Nullable } = types;
                const Number2 = Tuple(Float, Float);
                const Number4 = Tuple(Float, Float, Float, Float);
                return {
                    width: [Nullable(Float), null],
                    height: [Nullable(Float), null],
                    min_width: [Nullable(Float), null],
                    min_height: [Nullable(Float), null],
                    max_width: [Nullable(Float), null],
                    max_height: [Nullable(Float), null],
                    margin: [Nullable(Or(Float, Number2, Number4)), null],
                    width_policy: [Or(layout_1.SizingPolicy, Auto), "auto"],
                    height_policy: [Or(layout_1.SizingPolicy, Auto), "auto"],
                    aspect_ratio: [Or(Float, Auto, Null), null],
                    flow_mode: [enums_1.FlowMode, "block"],
                    sizing_mode: [Nullable(enums_1.SizingMode), null],
                    disabled: [Bool, false],
                    align: [Or(enums_1.Align, Tuple(enums_1.Align, enums_1.Align), Auto), "auto"],
                    resizable: [Or(Bool, enums_1.Dimensions), false],
                };
            });
        }
    }
    exports.LayoutDOM = LayoutDOM;
},
/* models/ui/pane.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const ui_element_1 = require(55) /* ./ui_element */;
    const dom_node_1 = require(130) /* ../dom/dom_node */;
    const html_1 = require(133) /* ../dom/html */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const kinds_1 = require(22) /* ../../core/kinds */;
    // TODO UIElement needs to inherit from DOMNode
    exports.ElementLike = (0, kinds_1.Or)((0, kinds_1.Ref)(ui_element_1.UIElement), (0, kinds_1.Ref)(dom_node_1.DOMNode), (0, kinds_1.Ref)(html_1.HTML));
    class PaneView extends ui_element_1.UIElementView {
        _element_views = new Map();
        get elements() {
            return this.model.elements;
        }
        get element_views() {
            return this.elements.map((element) => this._element_views.get(element)).filter((view) => view != null);
        }
        children_views() {
            return [...super.children_views(), ...this.element_views];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._build_elements();
        }
        async _build_elements() {
            return await (0, build_views_1.build_views)(this._element_views, this.elements, { parent: this });
        }
        async _update_elements() {
            const { created } = await this._build_elements();
            const created_views = new Set(created);
            // Since appending to a DOM node will move the node to the end if it has
            // already been added appending all the children in order will result in
            // correct ordering.
            for (const view of this.element_views) {
                const is_new = created_views.has(view);
                const target = view.rendering_target() ?? this.self_target;
                if (is_new) {
                    view.render_to(target);
                }
                else {
                    target.append(view.el);
                }
            }
            this.r_after_render();
        }
        connect_signals() {
            super.connect_signals();
            const { elements } = this.model.properties;
            this.on_change(elements, async () => {
                await this._update_elements();
            });
        }
        render() {
            super.render();
            for (const element_view of this.element_views) {
                const target = element_view.rendering_target() ?? this.self_target;
                element_view.render_to(target);
            }
        }
        has_finished() {
            if (!super.has_finished()) {
                return false;
            }
            for (const element_view of this.element_views) {
                if (!element_view.has_finished()) {
                    return false;
                }
            }
            return true;
        }
    }
    exports.PaneView = PaneView;
    class Pane extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = PaneView;
            this.define(({ List }) => ({
                elements: [List(exports.ElementLike), []],
            }));
        }
    }
    exports.Pane = Pane;
},
/* models/dom/html.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const dom_element_1 = require(134) /* ./dom_element */;
    const ui_element_1 = require(55) /* ../ui/ui_element */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const dom_1 = require(61) /* ../../core/dom */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    const types_1 = require(8) /* ../../core/util/types */;
    const kinds_1 = require(22) /* ../../core/kinds */;
    const HTMLRef = (0, kinds_1.Or)((0, kinds_1.Ref)(dom_element_1.DOMElement), (0, kinds_1.Ref)(ui_element_1.UIElement));
    const HTMLMarkup = kinds_1.Str;
    class HTMLView extends dom_element_1.DOMElementView {
        _refs = new Map();
        get refs() {
            const { html, refs } = this.model;
            return [
                ...(0, types_1.isArray)(html) ? html.filter((item) => !(0, types_1.isString)(item)) : [],
                ...refs,
            ];
        }
        async _update_refs() {
            await (0, build_views_1.build_views)(this._refs, this.refs);
        }
        children_views() {
            return [...super.children_views(), ...this._refs.values()];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._update_refs();
        }
        connect_signals() {
            super.connect_signals();
            const { refs, html } = this.model.properties;
            this.on_change([refs, html], async () => {
                await this._update_refs();
                this.render();
            });
        }
        render() {
            super.render();
            const html = (() => {
                const { html } = this.model;
                if ((0, types_1.isArray)(html)) {
                    return html.map((item) => (0, types_1.isString)(item) ? item : `<ref id="${item.id}"></ref>`).join("");
                }
                else {
                    return html;
                }
            })();
            const nodes = (() => {
                if ((0, types_1.isString)(html)) {
                    return this.parse_html(html);
                }
                else {
                    return [html];
                }
            })();
            this.el.append(...nodes);
            this.finish();
        }
        parse_html(html) {
            const parser = new DOMParser();
            const document = parser.parseFromString(html, "text/html");
            const iter = document.createNodeIterator(document, NodeFilter.SHOW_ELEMENT, (node) => {
                return node.nodeName.toLowerCase() == "ref" ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
            });
            let node;
            next_node: while ((node = iter.nextNode()) != null) {
                (0, assert_1.assert)(node instanceof Element);
                const id = node.getAttribute("id");
                if (id != null) {
                    for (const [model, view] of this._refs) {
                        if (model.id == id) {
                            view.render();
                            node.replaceWith(view.el);
                            continue next_node;
                        }
                    }
                    node.replaceWith((0, dom_1.span)(`<not found: id=${id}>`));
                    continue;
                }
                const name = node.getAttribute("name");
                if (name != null) {
                    for (const [model, view] of this._refs) {
                        if (model.name == name) {
                            view.render();
                            node.replaceWith(view.el);
                            continue next_node;
                        }
                    }
                    node.replaceWith((0, dom_1.span)(`<not found: name=${name}>`));
                    continue;
                }
            }
            return [...document.body.childNodes];
        }
    }
    exports.HTMLView = HTMLView;
    class HTML extends dom_element_1.DOMElement {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = HTMLView;
            this.define(({ Node, List, Or }) => ({
                html: [Or(Node, HTMLMarkup, List(Or(HTMLMarkup, HTMLRef)))],
                refs: [List(HTMLRef), []],
            }));
        }
    }
    exports.HTML = HTML;
},
/* models/dom/dom_element.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const dom_node_1 = require(130) /* ./dom_node */;
    const styled_element_1 = require(56) /* ../ui/styled_element */;
    const ui_element_1 = require(55) /* ../ui/ui_element */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const types_1 = require(8) /* ../../core/util/types */;
    const css_1 = require(63) /* ../../core/css */;
    const dom_1 = require(61) /* ../../core/dom */;
    class DOMElementView extends dom_node_1.DOMNodeView {
        get bbox() {
            return (0, dom_1.bounding_box)(this.el).relative();
        }
        get self_target() {
            return this.el;
        }
        child_views = new Map();
        children_views() {
            return [...super.children_views(), ...this.child_views.values()];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const children = this.model.children.filter((obj) => !(0, types_1.isString)(obj));
            await (0, build_views_1.build_views)(this.child_views, children, { parent: this });
        }
        connect_signals() {
            super.connect_signals();
            const { children, style } = this.model.properties;
            this.on_change(children, async () => {
                await this._update_children();
            });
            this.on_change(style, () => {
                this.el.removeAttribute("style");
                (0, css_1.apply_styles)(this.el.style, this.model.style);
            });
        }
        async _build_children() {
            const children = this.model.children.filter((obj) => !(0, types_1.isString)(obj));
            return await (0, build_views_1.build_views)(this.child_views, children, { parent: this });
        }
        async _update_children() {
            const { created } = await this._build_children();
            const created_views = new Set(created);
            // Since appending to a DOM node will move the node to the end if it has
            // already been added appending all the children in order will result in
            // correct ordering.
            for (const child of this.model.children) {
                if ((0, types_1.isString)(child)) {
                    const node = document.createTextNode(child);
                    this.self_target.append(node);
                }
                else {
                    const view = this.child_views.get(child);
                    if (view == null) {
                        continue;
                    }
                    const is_new = created_views.has(view);
                    const target = view.rendering_target() ?? this.self_target;
                    if (is_new) {
                        view.render_to(target);
                    }
                    else {
                        target.append(view.el);
                    }
                }
            }
            this.r_after_render();
        }
        render() {
            (0, dom_1.empty)(this.el);
            (0, css_1.apply_styles)(this.el.style, this.model.style);
            for (const child of this.model.children) {
                if ((0, types_1.isString)(child)) {
                    const node = document.createTextNode(child);
                    this.el.append(node);
                }
                else {
                    const child_view = this.child_views.get(child);
                    if (child_view == null) {
                        continue;
                    }
                    const target = child_view.rendering_target() ?? this.self_target;
                    child_view.render_to(target);
                }
            }
            this.finish();
        }
    }
    exports.DOMElementView = DOMElementView;
    class DOMElement extends dom_node_1.DOMNode {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Str, List, Or, Ref }) => {
                return {
                    style: [styled_element_1.StylesLike, {}],
                    children: [List(Or(Str, Ref(dom_node_1.DOMNode), Ref(ui_element_1.UIElement))), []],
                };
            });
        }
    }
    exports.DOMElement = DOMElement;
},
/* core/layout/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var types_1 = require(136) /* ./types */;
    __esExport("Sizeable", types_1.Sizeable);
    __esExport("SizingPolicy", types_1.SizingPolicy);
    var layoutable_1 = require(137) /* ./layoutable */;
    __esExport("Layoutable", layoutable_1.Layoutable);
    __esExport("ContentLayoutable", layoutable_1.ContentLayoutable);
    __esExport("ElementLayout", layoutable_1.ElementLayout);
    __esExport("TextLayout", layoutable_1.TextLayout);
    __esExport("FixedLayout", layoutable_1.FixedLayout);
    var alignments_1 = require(138) /* ./alignments */;
    __esExport("HStack", alignments_1.HStack);
    __esExport("VStack", alignments_1.VStack);
    var grid_1 = require(139) /* ./grid */;
    __esExport("Grid", grid_1.Grid);
    __esExport("Row", grid_1.Row);
    __esExport("Column", grid_1.Column);
},
/* core/layout/types.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const kinds_1 = require(22) /* ../kinds */;
    const { min, max } = Math;
    class Sizeable {
        width;
        height;
        constructor(size = {}) {
            this.width = size.width != null ? size.width : 0;
            this.height = size.height != null ? size.height : 0;
        }
        bounded_to({ width, height }) {
            return new Sizeable({
                width: this.width == Infinity && width != null ? width : this.width,
                height: this.height == Infinity && height != null ? height : this.height,
            });
        }
        expanded_to({ width, height }) {
            return new Sizeable({
                width: width != Infinity ? max(this.width, width) : this.width,
                height: height != Infinity ? max(this.height, height) : this.height,
            });
        }
        expand_to({ width, height }) {
            this.width = max(this.width, width);
            this.height = max(this.height, height);
        }
        narrowed_to({ width, height }) {
            return new Sizeable({
                width: min(this.width, width),
                height: min(this.height, height),
            });
        }
        narrow_to({ width, height }) {
            this.width = min(this.width, width);
            this.height = min(this.height, height);
        }
        grow_by({ left, right, top, bottom }) {
            const width = this.width + left + right;
            const height = this.height + top + bottom;
            return new Sizeable({ width, height });
        }
        shrink_by({ left, right, top, bottom }) {
            const width = max(this.width - left - right, 0);
            const height = max(this.height - top - bottom, 0);
            return new Sizeable({ width, height });
        }
        map(w_fn, h_fn) {
            return new Sizeable({
                width: w_fn(this.width),
                height: (h_fn != null ? h_fn : w_fn)(this.height),
            });
        }
    }
    exports.Sizeable = Sizeable;
    exports.SizingPolicy = (0, kinds_1.Enum)("fixed", "fit", "min", "max");
},
/* core/layout/layoutable.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(136) /* ./types */;
    const bbox_1 = require(62) /* ../util/bbox */;
    const types_2 = require(8) /* ../util/types */;
    const assert_1 = require(13) /* ../util/assert */;
    const { abs, min, max, round } = Math;
    class Layoutable {
        *[Symbol.iterator]() { }
        absolute = false;
        position = { left: 0, top: 0 };
        _bbox = new bbox_1.BBox();
        _inner_bbox = new bbox_1.BBox();
        get bbox() {
            return this._bbox;
        }
        get inner_bbox() {
            return this._inner_bbox;
        }
        _sizing = null;
        get sizing() {
            (0, assert_1.assert)(this._sizing != null);
            return this._sizing;
        }
        _dirty = false;
        set dirty(dirty) {
            this._dirty = dirty;
        }
        get dirty() {
            return this._dirty;
        }
        get visible() {
            return this.sizing.visible;
        }
        set visible(visible) {
            if (this.sizing.visible != visible) {
                this.sizing.visible = visible;
                this._dirty = true;
            }
        }
        set_sizing(sizing = {}) {
            const width_policy = sizing.width_policy ?? "fit";
            const width = sizing.width;
            const min_width = sizing.min_width;
            const max_width = sizing.max_width;
            const height_policy = sizing.height_policy ?? "fit";
            const height = sizing.height;
            const min_height = sizing.min_height;
            const max_height = sizing.max_height;
            const aspect = sizing.aspect;
            const margin = sizing.margin ?? { top: 0, right: 0, bottom: 0, left: 0 };
            const visible = sizing.visible ?? true;
            const halign = sizing.halign ?? "start";
            const valign = sizing.valign ?? "start";
            this._sizing = {
                width_policy, min_width, width, max_width,
                height_policy, min_height, height, max_height,
                aspect,
                margin,
                visible,
                halign,
                valign,
                size: { width, height },
            };
            this._init();
        }
        _init() { }
        _set_geometry(outer, inner) {
            this._bbox = outer;
            this._inner_bbox = inner;
        }
        set_geometry(outer, inner) {
            const { fixup_geometry } = this;
            if (fixup_geometry != null) {
                [outer, inner] = fixup_geometry(outer, inner);
            }
            this._set_geometry(outer, inner ?? outer);
            for (const handler of this._handlers) {
                handler(this._bbox, this._inner_bbox);
            }
        }
        _handlers = [];
        on_resize(handler) {
            this._handlers.push(handler);
        }
        is_width_expanding() {
            return this.sizing.width_policy == "max";
        }
        is_height_expanding() {
            return this.sizing.height_policy == "max";
        }
        apply_aspect(viewport, { width, height }) {
            const { aspect } = this.sizing;
            if (aspect != null) {
                const { width_policy, height_policy } = this.sizing;
                const gt = (width, height) => {
                    const policies = { max: 4, fit: 3, min: 2, fixed: 1 };
                    return policies[width] > policies[height];
                };
                if (width_policy != "fixed" && height_policy != "fixed") {
                    if (width_policy == height_policy) {
                        const w_width = width;
                        const w_height = round(width / aspect);
                        const h_width = round(height * aspect);
                        const h_height = height;
                        const w_diff = abs(viewport.width - w_width) + abs(viewport.height - w_height);
                        const h_diff = abs(viewport.width - h_width) + abs(viewport.height - h_height);
                        if (w_diff <= h_diff) {
                            width = w_width;
                            height = w_height;
                        }
                        else {
                            width = h_width;
                            height = h_height;
                        }
                    }
                    else if (gt(width_policy, height_policy)) {
                        height = round(width / aspect);
                    }
                    else {
                        width = round(height * aspect);
                    }
                }
                else if (width_policy == "fixed") {
                    height = round(width / aspect);
                }
                else if (height_policy == "fixed") {
                    width = round(height * aspect);
                }
            }
            return { width, height };
        }
        measure(viewport_size) {
            if (this._sizing == null) {
                this.set_sizing();
            }
            if (!this.sizing.visible) {
                return { width: 0, height: 0 };
            }
            const exact_width = (width) => {
                return this.sizing.width_policy == "fixed" && this.sizing.width != null ? this.sizing.width : width;
            };
            const exact_height = (height) => {
                return this.sizing.height_policy == "fixed" && this.sizing.height != null ? this.sizing.height : height;
            };
            const viewport = new types_1.Sizeable(viewport_size)
                .shrink_by(this.sizing.margin)
                .map(exact_width, exact_height);
            const computed = this._measure(viewport);
            const clipped = this.clip_size(computed, viewport);
            const width = exact_width(clipped.width);
            const height = exact_height(clipped.height);
            const size = this.apply_aspect(viewport, { width, height });
            return { ...computed, ...size };
        }
        _compute(viewport) {
            const size_hint = this.measure({
                width: viewport.width != null && this.is_width_expanding() ? viewport.width : Infinity,
                height: viewport.height != null && this.is_height_expanding() ? viewport.height : Infinity,
            });
            const { width, height } = size_hint;
            const { left, top } = this.position;
            const outer = new bbox_1.BBox({ left, top, width, height });
            let inner = undefined;
            if (size_hint.inner != null) {
                const { left, top, right, bottom } = size_hint.inner;
                inner = new bbox_1.BBox({ left, top, right: width - right, bottom: height - bottom });
            }
            return { outer, inner };
        }
        compute(viewport = {}) {
            const { outer, inner } = this._compute(viewport);
            this.set_geometry(outer, inner);
        }
        get xview() {
            return this.bbox.xview;
        }
        get yview() {
            return this.bbox.yview;
        }
        clip_size(size, viewport) {
            function clip(size, vsize, min_size, max_size) {
                if (min_size == null) {
                    min_size = 0;
                }
                else if (!(0, types_2.isNumber)(min_size)) {
                    min_size = round(min_size.percent * vsize);
                }
                if (max_size == null) {
                    max_size = Infinity;
                }
                else if (!(0, types_2.isNumber)(max_size)) {
                    max_size = round(max_size.percent * vsize);
                }
                return max(min_size, min(size, max_size));
            }
            return {
                width: clip(size.width, viewport.width, this.sizing.min_width, this.sizing.max_width),
                height: clip(size.height, viewport.height, this.sizing.min_height, this.sizing.max_height),
            };
        }
        has_size_changed() {
            const { _dirty } = this;
            this._dirty = false;
            return _dirty;
        }
    }
    exports.Layoutable = Layoutable;
    class ContentLayoutable extends Layoutable {
        _measure(viewport) {
            const content_size = this._content_size();
            const bounds = viewport
                .bounded_to(this.sizing.size)
                .bounded_to(content_size);
            const width = (() => {
                switch (this.sizing.width_policy) {
                    case "fixed":
                        return this.sizing.width != null ? this.sizing.width : content_size.width;
                    case "min":
                        return content_size.width;
                    case "fit":
                        return bounds.width;
                    case "max":
                        return max(content_size.width, bounds.width);
                }
            })();
            const height = (() => {
                switch (this.sizing.height_policy) {
                    case "fixed":
                        return this.sizing.height != null ? this.sizing.height : content_size.height;
                    case "min":
                        return content_size.height;
                    case "fit":
                        return bounds.height;
                    case "max":
                        return max(content_size.height, bounds.height);
                }
            })();
            return { width, height };
        }
    }
    exports.ContentLayoutable = ContentLayoutable;
    class ElementLayout extends ContentLayoutable {
        el;
        constructor(el) {
            super();
            this.el = el;
        }
        _content_size() {
            const { width, height } = this.el.getBoundingClientRect();
            return new types_1.Sizeable({ width, height });
        }
    }
    exports.ElementLayout = ElementLayout;
    class TextLayout extends ContentLayoutable {
        text;
        constructor(text) {
            super();
            this.text = text;
        }
        _content_size() {
            return new types_1.Sizeable(this.text.size());
        }
    }
    exports.TextLayout = TextLayout;
    class FixedLayout extends ContentLayoutable {
        size;
        constructor(size = {}) {
            super();
            this.size = size;
        }
        _content_size() {
            return new types_1.Sizeable(this.size);
        }
    }
    exports.FixedLayout = FixedLayout;
},
/* core/layout/alignments.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const layoutable_1 = require(137) /* ./layoutable */;
    const bbox_1 = require(62) /* ../util/bbox */;
    const { max, round } = Math;
    class Stack extends layoutable_1.Layoutable {
        *[Symbol.iterator]() {
            yield* this.children;
        }
        children = [];
    }
    exports.Stack = Stack;
    class HStack extends Stack {
        _measure(_viewport) {
            let width = 0;
            let height = 0;
            for (const child of this.children) {
                const size_hint = child.measure({ width: 0, height: 0 });
                width += size_hint.width;
                height = max(height, size_hint.height);
            }
            return { width, height };
        }
        _set_geometry(outer, inner) {
            super._set_geometry(outer, inner);
            if (outer.is_empty) {
                for (const child of this.children) {
                    child.set_geometry(new bbox_1.BBox());
                }
            }
            else {
                const top = this.absolute ? outer.top : 0;
                let left = this.absolute ? outer.left : 0;
                const { height } = outer;
                for (const child of this.children) {
                    const { width } = child.measure({ width: 0, height: 0 });
                    child.set_geometry(new bbox_1.BBox({ left, width, top, height }));
                    left += width;
                }
            }
        }
    }
    exports.HStack = HStack;
    class VStack extends Stack {
        _measure(_viewport) {
            let width = 0;
            let height = 0;
            for (const child of this.children) {
                const size_hint = child.measure({ width: 0, height: 0 });
                width = max(width, size_hint.width);
                height += size_hint.height;
            }
            return { width, height };
        }
        _set_geometry(outer, inner) {
            super._set_geometry(outer, inner);
            if (outer.is_empty) {
                for (const child of this.children) {
                    child.set_geometry(new bbox_1.BBox());
                }
            }
            else {
                const left = this.absolute ? outer.left : 0;
                let top = this.absolute ? outer.top : 0;
                const { width } = outer;
                for (const child of this.children) {
                    const size_hint = child.measure({ width: 0, height: 0 });
                    const { height } = size_hint;
                    child.set_geometry(new bbox_1.BBox({ top, height, left, width }));
                    top += height;
                }
            }
        }
    }
    exports.VStack = VStack;
    class NodeLayout extends layoutable_1.Layoutable {
        *[Symbol.iterator]() {
            yield* this.children;
        }
        children = [];
        _measure(viewport) {
            const { width_policy, height_policy } = this.sizing;
            const { min, max } = Math;
            let max_width = 0;
            let max_height = 0;
            for (const layout of this.children) {
                const { width, height } = layout.measure(viewport);
                max_width = max(max_width, width);
                max_height = max(max_height, height);
            }
            const width = (() => {
                const { width } = this.sizing;
                if (viewport.width == Infinity) {
                    return width_policy == "fixed" ? width ?? max_width : max_width;
                }
                else {
                    switch (width_policy) {
                        case "fixed": return width ?? max_width;
                        case "min": return /*width != null ? min(viewport.width, width) :*/ max_width;
                        case "fit": return width != null ? min(viewport.width, width) : viewport.width;
                        case "max": return width != null ? max(viewport.width, width) : viewport.width;
                    }
                }
            })();
            const height = (() => {
                const { height } = this.sizing;
                if (viewport.height == Infinity) {
                    return height_policy == "fixed" ? height ?? max_height : max_height;
                }
                else {
                    switch (height_policy) {
                        case "fixed": return height ?? max_height;
                        case "min": return /*height != null ? min(viewport.height, height) :*/ max_height;
                        case "fit": return height != null ? min(viewport.height, height) : viewport.height;
                        case "max": return height != null ? max(viewport.height, height) : viewport.height;
                    }
                }
            })();
            return { width, height };
        }
        _set_geometry(outer, inner) {
            super._set_geometry(outer, inner);
            if (outer.is_empty) {
                for (const child of this.children) {
                    child.set_geometry(new bbox_1.BBox());
                }
            }
            else {
                const bbox = this.absolute ? outer : outer.relative();
                const { left, right, top, bottom } = bbox;
                const vcenter = round(bbox.vcenter);
                const hcenter = round(bbox.hcenter);
                for (const layout of this.children) {
                    const { margin, halign = "start", valign = "start" } = layout.sizing;
                    const { width, height, inner } = layout.measure(outer);
                    const bbox = (() => {
                        const anchor = `${valign}_${halign}`;
                        switch (anchor) {
                            case "start_start": // "top_left"
                                return new bbox_1.BBox({ left: left + margin.left, top: top + margin.top, width, height });
                            case "start_center": // "top_center"
                                return new bbox_1.BBox({ hcenter, top: top + margin.top, width, height });
                            case "start_end": // "top_right"
                                return new bbox_1.BBox({ right: right - margin.right, top: top + margin.top, width, height });
                            case "center_start": // "center_left"
                                return new bbox_1.BBox({ left: left + margin.left, vcenter, width, height });
                            case "center_center": // "center"
                                return new bbox_1.BBox({ hcenter, vcenter, width, height });
                            case "center_end": // "center_right"
                                return new bbox_1.BBox({ right: right - margin.right, vcenter, width, height });
                            case "end_start": // "bottom_left"
                                return new bbox_1.BBox({ left: left + margin.left, bottom: bottom - margin.bottom, width, height });
                            case "end_center": // "bottom_center"
                                return new bbox_1.BBox({ hcenter, bottom: bottom - margin.bottom, width, height });
                            case "end_end": // "bottom_right"
                                return new bbox_1.BBox({ right: right - margin.right, bottom: bottom - margin.bottom, width, height });
                        }
                    })();
                    const inner_bbox = inner == null ? bbox : new bbox_1.BBox({
                        left: bbox.left + inner.left,
                        top: bbox.top + inner.top,
                        right: bbox.right - inner.right,
                        bottom: bbox.bottom - inner.bottom,
                    });
                    layout.set_geometry(bbox, inner_bbox);
                }
            }
        }
    }
    exports.NodeLayout = NodeLayout;
},
/* core/layout/grid.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(136) /* ./types */;
    const layoutable_1 = require(137) /* ./layoutable */;
    const types_2 = require(8) /* ../util/types */;
    const bbox_1 = require(62) /* ../util/bbox */;
    const array_1 = require(10) /* ../util/array */;
    const { max, round } = Math;
    class DefaultMap {
        def;
        _map = new Map();
        constructor(def) {
            this.def = def;
        }
        get(key) {
            let value = this._map.get(key);
            if (value === undefined) {
                value = this.def();
                this._map.set(key, value);
            }
            return value;
        }
        apply(key, fn) {
            const value = this.get(key);
            this._map.set(key, fn(value));
        }
    }
    exports.DefaultMap = DefaultMap;
    class Container {
        _items = [];
        get size() {
            return this._items.length;
        }
        _nrows = 0;
        _ncols = 0;
        get nrows() {
            return this._nrows;
        }
        get ncols() {
            return this._ncols;
        }
        add(span, data) {
            const { r1, c1 } = span;
            this._nrows = max(this._nrows, r1 + 1);
            this._ncols = max(this._ncols, c1 + 1);
            this._items.push({ span, data });
        }
        at(r, c) {
            const selected = this._items.filter(({ span }) => {
                return span.r0 <= r && r <= span.r1 &&
                    span.c0 <= c && c <= span.c1;
            });
            return selected.map(({ data }) => data);
        }
        row(r) {
            const selected = this._items.filter(({ span }) => span.r0 <= r && r <= span.r1);
            return selected.map(({ data }) => data);
        }
        col(c) {
            const selected = this._items.filter(({ span }) => span.c0 <= c && c <= span.c1);
            return selected.map(({ data }) => data);
        }
        *[Symbol.iterator]() {
            yield* this._items;
        }
        foreach(fn) {
            for (const { span, data } of this._items) {
                fn(span, data);
            }
        }
        map(fn) {
            const result = new Container();
            for (const { span, data } of this._items) {
                result.add(span, fn(span, data));
            }
            return result;
        }
    }
    exports.Container = Container;
    class Grid extends layoutable_1.Layoutable {
        items;
        *[Symbol.iterator]() {
            for (const { layout } of this.items) {
                yield layout;
            }
        }
        rows = "auto";
        cols = "auto";
        spacing = 0;
        _state;
        constructor(items = []) {
            super();
            this.items = items;
        }
        is_width_expanding() {
            if (super.is_width_expanding()) {
                return true;
            }
            if (this.sizing.width_policy == "fixed") {
                return false;
            }
            const { cols } = this._state;
            return (0, array_1.some)(cols, (col) => col.policy == "max");
        }
        is_height_expanding() {
            if (super.is_height_expanding()) {
                return true;
            }
            if (this.sizing.height_policy == "fixed") {
                return false;
            }
            const { rows } = this._state;
            return (0, array_1.some)(rows, (row) => row.policy == "max");
        }
        _init() {
            super._init();
            const items = new Container();
            for (const { layout, row, col, row_span = 1, col_span = 1 } of this.items) {
                if (layout.sizing.visible) {
                    const r0 = row;
                    const c0 = col;
                    const r1 = row + row_span - 1;
                    const c1 = col + col_span - 1;
                    items.add({ r0, c0, r1, c1 }, layout);
                }
            }
            const { nrows, ncols } = items;
            const rows = new Array(nrows);
            for (let y = 0; y < nrows; y++) {
                const row = (() => {
                    const sizing = (0, types_2.isPlainObject)(this.rows) ? this.rows[y] ?? this.rows["*"] : this.rows;
                    if (sizing == null) {
                        return { policy: "auto" };
                    }
                    else if ((0, types_2.isNumber)(sizing)) {
                        return { policy: "fixed", height: sizing };
                    }
                    else if ((0, types_2.isString)(sizing)) {
                        return { policy: sizing };
                    }
                    else {
                        return sizing;
                    }
                })();
                const align = row.align ?? "auto";
                if (row.policy == "fixed") {
                    rows[y] = { policy: "fixed", height: row.height, align };
                }
                else if (row.policy == "min") {
                    rows[y] = { policy: "min", align };
                }
                else if (row.policy == "fit" || row.policy == "max") {
                    rows[y] = { policy: row.policy, flex: row.flex ?? 1, align };
                }
                else {
                    if ((0, array_1.some)(items.row(y), (layout) => layout.is_height_expanding())) {
                        rows[y] = { policy: "max", flex: 1, align };
                    }
                    else {
                        rows[y] = { policy: "min", align };
                    }
                }
            }
            const cols = new Array(ncols);
            for (let x = 0; x < ncols; x++) {
                const col = (() => {
                    const sizing = (0, types_2.isPlainObject)(this.cols) ? this.cols[x] ?? this.cols["*"] : this.cols;
                    if (sizing == null) {
                        return { policy: "auto" };
                    }
                    else if ((0, types_2.isNumber)(sizing)) {
                        return { policy: "fixed", width: sizing };
                    }
                    else if ((0, types_2.isString)(sizing)) {
                        return { policy: sizing };
                    }
                    else {
                        return sizing;
                    }
                })();
                const align = col.align ?? "auto";
                if (col.policy == "fixed") {
                    cols[x] = { policy: "fixed", width: col.width, align };
                }
                else if (col.policy == "min") {
                    cols[x] = { policy: "min", align };
                }
                else if (col.policy == "fit" || col.policy == "max") {
                    cols[x] = { policy: col.policy, flex: col.flex ?? 1, align };
                }
                else {
                    if ((0, array_1.some)(items.col(x), (layout) => layout.is_width_expanding())) {
                        cols[x] = { policy: "max", flex: 1, align };
                    }
                    else {
                        cols[x] = { policy: "min", align };
                    }
                }
            }
            const [rspacing, cspacing] = (0, types_2.isNumber)(this.spacing) ? [this.spacing, this.spacing] : this.spacing;
            this._state = { items, nrows, ncols, rows, cols, rspacing, cspacing };
        }
        _measure_totals(row_heights, col_widths) {
            const { nrows, ncols, rspacing, cspacing } = this._state;
            return {
                height: (0, array_1.sum)(row_heights) + (nrows - 1) * rspacing,
                width: (0, array_1.sum)(col_widths) + (ncols - 1) * cspacing,
            };
        }
        _measure_cells(cell_viewport) {
            const { items, nrows, ncols, rows, cols, rspacing, cspacing } = this._state;
            const row_heights = new Array(nrows);
            for (let r = 0; r < nrows; r++) {
                const row = rows[r];
                row_heights[r] = row.policy == "fixed" ? row.height : 0;
            }
            const col_widths = new Array(ncols);
            for (let c = 0; c < ncols; c++) {
                const col = cols[c];
                col_widths[c] = col.policy == "fixed" ? col.width : 0;
            }
            const size_hints = new Container();
            items.foreach((span, layout) => {
                const { r0, c0, r1, c1 } = span;
                const rspace = (r1 - r0) * rspacing;
                const cspace = (c1 - c0) * cspacing;
                let height = 0;
                for (let r = r0; r <= r1; r++) {
                    height += cell_viewport(r, c0).height;
                }
                height += rspace;
                let width = 0;
                for (let c = c0; c <= c1; c++) {
                    width += cell_viewport(r0, c).width;
                }
                width += cspace;
                const size_hint = layout.measure({ width, height });
                size_hints.add(span, { layout, size_hint });
                const size = new types_1.Sizeable(size_hint).grow_by(layout.sizing.margin);
                size.height -= rspace;
                size.width -= cspace;
                const radjustable = [];
                for (let r = r0; r <= r1; r++) {
                    const row = rows[r];
                    if (row.policy == "fixed") {
                        size.height -= row.height;
                    }
                    else {
                        radjustable.push(r);
                    }
                }
                if (size.height > 0) {
                    const rheight = round(size.height / radjustable.length);
                    for (const r of radjustable) {
                        row_heights[r] = max(row_heights[r], rheight);
                    }
                }
                const cadjustable = [];
                for (let c = c0; c <= c1; c++) {
                    const col = cols[c];
                    if (col.policy == "fixed") {
                        size.width -= col.width;
                    }
                    else {
                        cadjustable.push(c);
                    }
                }
                if (size.width > 0) {
                    const cwidth = round(size.width / cadjustable.length);
                    for (const c of cadjustable) {
                        col_widths[c] = max(col_widths[c], cwidth);
                    }
                }
            });
            const size = this._measure_totals(row_heights, col_widths);
            return { size, row_heights, col_widths, size_hints };
        }
        _measure_grid(viewport) {
            const { nrows, ncols, rows, cols, rspacing, cspacing } = this._state;
            const preferred = this._measure_cells((y, x) => {
                const row = rows[y];
                const col = cols[x];
                return {
                    width: col.policy == "fixed" ? col.width : Infinity,
                    height: row.policy == "fixed" ? row.height : Infinity,
                };
            });
            let available_height;
            if (this.sizing.height_policy == "fixed" && this.sizing.height != null) {
                available_height = this.sizing.height;
            }
            else if (viewport.height != Infinity && this.is_height_expanding()) {
                available_height = viewport.height;
            }
            else {
                available_height = preferred.size.height;
            }
            let height_flex = 0;
            for (let y = 0; y < nrows; y++) {
                const row = rows[y];
                if (row.policy == "fit" || row.policy == "max") {
                    height_flex += row.flex;
                }
                else {
                    available_height -= preferred.row_heights[y];
                }
            }
            available_height -= (nrows - 1) * rspacing;
            if (height_flex != 0 && available_height > 0) {
                for (let y = 0; y < nrows; y++) {
                    const row = rows[y];
                    if (row.policy == "fit" || row.policy == "max") {
                        const height = round(available_height * (row.flex / height_flex));
                        available_height -= height;
                        preferred.row_heights[y] = height;
                        height_flex -= row.flex;
                    }
                }
            }
            else if (available_height < 0) {
                let nadjustable = 0;
                for (let y = 0; y < nrows; y++) {
                    const row = rows[y];
                    if (row.policy != "fixed") {
                        nadjustable++;
                    }
                }
                let overflow_height = -available_height;
                for (let y = 0; y < nrows; y++) {
                    const row = rows[y];
                    if (row.policy != "fixed") {
                        const height = preferred.row_heights[y];
                        const cutoff = round(overflow_height / nadjustable);
                        preferred.row_heights[y] = max(height - cutoff, 0);
                        overflow_height -= cutoff > height ? height : cutoff;
                        nadjustable--;
                    }
                }
            }
            let available_width;
            if (this.sizing.width_policy == "fixed" && this.sizing.width != null) {
                available_width = this.sizing.width;
            }
            else if (viewport.width != Infinity && this.is_width_expanding()) {
                available_width = viewport.width;
            }
            else {
                available_width = preferred.size.width;
            }
            let width_flex = 0;
            for (let x = 0; x < ncols; x++) {
                const col = cols[x];
                if (col.policy == "fit" || col.policy == "max") {
                    width_flex += col.flex;
                }
                else {
                    available_width -= preferred.col_widths[x];
                }
            }
            available_width -= (ncols - 1) * cspacing;
            if (width_flex != 0 && available_width > 0) {
                for (let x = 0; x < ncols; x++) {
                    const col = cols[x];
                    if (col.policy == "fit" || col.policy == "max") {
                        const width = round(available_width * (col.flex / width_flex));
                        available_width -= width;
                        preferred.col_widths[x] = width;
                        width_flex -= col.flex;
                    }
                }
            }
            else if (available_width < 0) {
                let nadjustable = 0;
                for (let x = 0; x < ncols; x++) {
                    const col = cols[x];
                    if (col.policy != "fixed") {
                        nadjustable++;
                    }
                }
                let overflow_width = -available_width;
                for (let x = 0; x < ncols; x++) {
                    const col = cols[x];
                    if (col.policy != "fixed") {
                        const width = preferred.col_widths[x];
                        const cutoff = round(overflow_width / nadjustable);
                        preferred.col_widths[x] = max(width - cutoff, 0);
                        overflow_width -= cutoff > width ? width : cutoff;
                        nadjustable--;
                    }
                }
            }
            const { row_heights, col_widths, size_hints } = this._measure_cells((y, x) => {
                return {
                    width: preferred.col_widths[x],
                    height: preferred.row_heights[y],
                };
            });
            const size = this._measure_totals(row_heights, col_widths);
            return { size, row_heights, col_widths, size_hints };
        }
        _measure(viewport) {
            const { size } = this._measure_grid(viewport);
            return size;
        }
        _set_geometry(outer, inner) {
            super._set_geometry(outer, inner);
            const { nrows, ncols, rspacing, cspacing } = this._state;
            const { row_heights, col_widths, size_hints } = this._measure_grid(outer);
            const rows = this._state.rows.map((row, r) => {
                return { ...row, top: 0, height: row_heights[r], get bottom() {
                        return this.top + this.height;
                    } };
            });
            const cols = this._state.cols.map((col, c) => {
                return { ...col, left: 0, width: col_widths[c], get right() {
                        return this.left + this.width;
                    } };
            });
            const items = size_hints.map((_, item) => {
                return { ...item, outer: new bbox_1.BBox(), inner: new bbox_1.BBox() };
            });
            for (let r = 0, top = !this.absolute ? this.position.top : outer.top; r < nrows; r++) {
                const row = rows[r];
                row.top = top;
                top += row.height + rspacing;
            }
            for (let c = 0, left = !this.absolute ? this.position.left : outer.left; c < ncols; c++) {
                const col = cols[c];
                col.left = left;
                left += col.width + cspacing;
            }
            function span_width(c0, c1) {
                let width = (c1 - c0) * cspacing;
                for (let c = c0; c <= c1; c++) {
                    width += cols[c].width;
                }
                return width;
            }
            function span_height(r0, r1) {
                let height = (r1 - r0) * rspacing;
                for (let r = r0; r <= r1; r++) {
                    height += rows[r].height;
                }
                return height;
            }
            items.foreach(({ r0, c0, r1, c1 }, item) => {
                const { layout, size_hint } = item;
                const { sizing } = layout;
                const { width, height } = size_hint;
                const span = {
                    width: span_width(c0, c1),
                    height: span_height(r0, r1),
                };
                const halign = c0 == c1 && cols[c0].align != "auto" ? cols[c0].align : sizing.halign;
                const valign = r0 == r1 && rows[r0].align != "auto" ? rows[r0].align : sizing.valign;
                let left = cols[c0].left;
                if (halign == "start") {
                    left += sizing.margin.left;
                }
                else if (halign == "center") {
                    left += round((span.width - width) / 2);
                }
                else if (halign == "end") {
                    left += span.width - sizing.margin.right - width;
                }
                let top = rows[r0].top;
                if (valign == "start") {
                    top += sizing.margin.top;
                }
                else if (valign == "center") {
                    top += round((span.height - height) / 2);
                }
                else if (valign == "end") {
                    top += span.height - sizing.margin.bottom - height;
                }
                item.outer = new bbox_1.BBox({ left, top, width, height });
            });
            const row_aligns = rows.map(() => {
                return {
                    start: new DefaultMap(() => 0),
                    end: new DefaultMap(() => 0),
                };
            });
            const col_aligns = cols.map(() => {
                return {
                    start: new DefaultMap(() => 0),
                    end: new DefaultMap(() => 0),
                };
            });
            items.foreach(({ r0, c0, r1, c1 }, { size_hint, outer }) => {
                const { inner } = size_hint;
                if (inner != null) {
                    row_aligns[r0].start.apply(outer.top, (v) => max(v, inner.top));
                    row_aligns[r1].end.apply(rows[r1].bottom - outer.bottom, (v) => max(v, inner.bottom));
                    col_aligns[c0].start.apply(outer.left, (v) => max(v, inner.left));
                    col_aligns[c1].end.apply(cols[c1].right - outer.right, (v) => max(v, inner.right));
                }
            });
            items.foreach(({ r0, c0, r1, c1 }, item) => {
                const { size_hint, outer } = item;
                const inner_bbox = (extents) => {
                    const outer_bbox = this.absolute ? outer : outer.relative();
                    const left = outer_bbox.left + extents.left;
                    const top = outer_bbox.top + extents.top;
                    const right = outer_bbox.right - extents.right;
                    const bottom = outer_bbox.bottom - extents.bottom;
                    return new bbox_1.BBox({ left, top, right, bottom });
                };
                if (size_hint.inner != null) {
                    let inner = inner_bbox(size_hint.inner);
                    //if (size_hint.align !== false) {
                    const top = row_aligns[r0].start.get(outer.top);
                    const bottom = row_aligns[r1].end.get(rows[r1].bottom - outer.bottom);
                    const left = col_aligns[c0].start.get(outer.left);
                    const right = col_aligns[c1].end.get(cols[c1].right - outer.right);
                    try {
                        inner = inner_bbox({ top, bottom, left, right });
                    }
                    catch { }
                    //}
                    item.inner = inner;
                }
                else {
                    item.inner = outer;
                }
            });
            items.foreach((_, { layout, outer, inner }) => {
                layout.set_geometry(outer, inner);
            });
        }
    }
    exports.Grid = Grid;
    class Row extends Grid {
        constructor(items) {
            super();
            this.items = items.map((item, i) => ({ layout: item, row: 0, col: i }));
            this.rows = "fit";
        }
    }
    exports.Row = Row;
    class Column extends Grid {
        constructor(items) {
            super();
            this.items = items.map((item, i) => ({ layout: item, row: i, col: 0 }));
            this.cols = "fit";
        }
    }
    exports.Column = Column;
},
/* models/annotations/arrow.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const data_annotation_1 = require(141) /* ./data_annotation */;
    const arrow_head_1 = require(252) /* ./arrow_head */;
    const property_mixins_1 = require(95) /* ../../core/property_mixins */;
    const enums_1 = require(21) /* ../../core/enums */;
    const types_1 = require(25) /* ../../core/types */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const types_2 = require(25) /* ../../core/types */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const math_1 = require(12) /* ../../core/util/math */;
    class ArrowView extends data_annotation_1.DataAnnotationView {
        start;
        end;
        _x_start;
        _y_start;
        _x_end;
        _y_end;
        _sx_start;
        _sy_start;
        _sx_end;
        _sy_end;
        _angles;
        children_views() {
            return [...super.children_views(), this.start, this.end];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const { start, end } = this.model;
            if (start != null) {
                this.start = await (0, build_views_1.build_view)(start, { parent: this });
            }
            if (end != null) {
                this.end = await (0, build_views_1.build_view)(end, { parent: this });
            }
        }
        set_data(source) {
            super.set_data(source);
            const indices = types_2.Indices.all_set(this._x_start.length);
            this.start?.set_data(source, indices);
            this.end?.set_data(source, indices);
        }
        connect_signals() {
            super.connect_signals();
            const update = () => {
                this.set_data(this.model.source);
                this.request_paint();
            };
            this.on_transitive_change(this.model.properties.start, update);
            this.on_transitive_change(this.model.properties.end, update);
        }
        map_data() {
            const { frame } = this.plot_view;
            const [sx_start, sy_start] = (() => {
                switch (this.model.start_units) {
                    case "canvas": {
                        return [
                            new types_1.ScreenArray(this._x_start),
                            new types_1.ScreenArray(this._y_start),
                        ];
                    }
                    case "screen": {
                        return [
                            frame.bbox.xview.v_compute(this._x_start),
                            frame.bbox.yview.v_compute(this._y_start),
                        ];
                    }
                    case "data": {
                        return [
                            this.coordinates.x_scale.v_compute(this._x_start),
                            this.coordinates.y_scale.v_compute(this._y_start),
                        ];
                    }
                }
            })();
            const [sx_end, sy_end] = (() => {
                switch (this.model.end_units) {
                    case "canvas": {
                        return [
                            new types_1.ScreenArray(this._x_end),
                            new types_1.ScreenArray(this._y_end),
                        ];
                    }
                    case "screen": {
                        return [
                            frame.bbox.xview.v_compute(this._x_end),
                            frame.bbox.yview.v_compute(this._y_end),
                        ];
                    }
                    case "data": {
                        return [
                            this.coordinates.x_scale.v_compute(this._x_end),
                            this.coordinates.y_scale.v_compute(this._y_end),
                        ];
                    }
                }
            })();
            this._sx_start = sx_start;
            this._sy_start = sy_start;
            this._sx_end = sx_end;
            this._sy_end = sy_end;
            const n = sx_start.length;
            const angles = this._angles = new types_1.ScreenArray(n);
            for (let i = 0; i < n; i++) {
                // arrow head runs orthogonal to arrow body (???)
                angles[i] = Math.PI / 2 + (0, math_1.atan2)([sx_start[i], sy_start[i]], [sx_end[i], sy_end[i]]);
            }
        }
        _paint_data(ctx) {
            const { start, end } = this;
            const { _sx_start, _sy_start, _sx_end, _sy_end, _angles } = this;
            const { x, y, width, height } = this.plot_view.frame.bbox;
            for (let i = 0, n = _sx_start.length; i < n; i++) {
                if (end != null) {
                    ctx.save();
                    ctx.translate(_sx_end[i], _sy_end[i]);
                    ctx.rotate(_angles[i]);
                    end.paint(ctx, i);
                    ctx.restore();
                }
                if (start != null) {
                    ctx.save();
                    ctx.translate(_sx_start[i], _sy_start[i]);
                    ctx.rotate(_angles[i] + Math.PI);
                    start.paint(ctx, i);
                    ctx.restore();
                }
                if (!this.visuals.line.doit) {
                    continue;
                }
                ctx.save();
                if (start != null || end != null) {
                    ctx.beginPath();
                    ctx.rect(x, y, width, height);
                    if (end != null) {
                        ctx.save();
                        ctx.translate(_sx_end[i], _sy_end[i]);
                        ctx.rotate(_angles[i]);
                        end.clip(ctx, i);
                        ctx.restore();
                    }
                    if (start != null) {
                        ctx.save();
                        ctx.translate(_sx_start[i], _sy_start[i]);
                        ctx.rotate(_angles[i] + Math.PI);
                        start.clip(ctx, i);
                        ctx.restore();
                    }
                    ctx.closePath();
                    ctx.clip();
                }
                ctx.beginPath();
                ctx.moveTo(_sx_start[i], _sy_start[i]);
                ctx.lineTo(_sx_end[i], _sy_end[i]);
                this.visuals.line.apply(ctx, i);
                ctx.restore();
            }
        }
    }
    exports.ArrowView = ArrowView;
    class Arrow extends data_annotation_1.DataAnnotation {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ArrowView;
            this.mixins(property_mixins_1.LineVector);
            this.define(({ Ref, Nullable }) => ({
                x_start: [p.XCoordinateSpec, { field: "x_start" }],
                y_start: [p.YCoordinateSpec, { field: "y_start" }],
                start_units: [enums_1.CoordinateUnits, "data"],
                start: [Nullable(Ref(arrow_head_1.ArrowHead)), null],
                x_end: [p.XCoordinateSpec, { field: "x_end" }],
                y_end: [p.YCoordinateSpec, { field: "y_end" }],
                end_units: [enums_1.CoordinateUnits, "data"],
                end: [Nullable(Ref(arrow_head_1.ArrowHead)), () => new arrow_head_1.OpenHead()],
            }));
        }
    }
    exports.Arrow = Arrow;
},
/* models/annotations/data_annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(96) /* ./annotation */;
    const columnar_data_source_1 = require(142) /* ../sources/columnar_data_source */;
    const column_data_source_1 = require(147) /* ../sources/column_data_source */;
    const projections_1 = require(148) /* ../../core/util/projections */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    class DataAnnotationView extends annotation_1.AnnotationView {
        connect_signals() {
            super.connect_signals();
            const update = () => {
                this.set_data(this.model.source);
                this._rerender();
            };
            this.connect(this.model.change, update);
            this.connect(this.model.source.streaming, update);
            this.connect(this.model.source.patching, update);
            this.connect(this.model.source.change, update);
        }
        _rerender() {
            this.request_paint();
        }
        set_data(source) {
            const self = this;
            for (const prop of this.model) {
                if (!(prop instanceof p.VectorSpec || prop instanceof p.ScalarSpec)) {
                    continue;
                }
                if (prop instanceof p.BaseCoordinateSpec) {
                    const array = prop.array(source);
                    self[`_${prop.attr}`] = array;
                }
                else {
                    const uniform = prop.uniform(source);
                    self[`${prop.attr}`] = uniform;
                }
            }
            if (this.plot_model.use_map) {
                if (self._x != null) {
                    projections_1.inplace.project_xy(self._x, self._y);
                }
                if (self._xs != null) {
                    projections_1.inplace.project_xsys(self._xs, self._ys);
                }
            }
            for (const visual of this.visuals) {
                visual.update();
            }
        }
        _initial_set_data = false;
        _paint(ctx) {
            if (!this._initial_set_data) {
                this.set_data(this.model.source);
                this._initial_set_data = true;
            }
            this.map_data();
            this._paint_data(ctx);
        }
    }
    exports.DataAnnotationView = DataAnnotationView;
    class DataAnnotation extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Ref }) => ({
                source: [Ref(columnar_data_source_1.ColumnarDataSource), () => new column_data_source_1.ColumnDataSource()],
            }));
        }
    }
    exports.DataAnnotation = DataAnnotation;
},
/* models/sources/columnar_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const logging_1 = require(11) /* ../../core/logging */;
    const selection_manager_1 = require(143) /* ../../core/selection_manager */;
    const signaling_1 = require(17) /* ../../core/signaling */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    const array_1 = require(10) /* ../../core/util/array */;
    const ndarray_1 = require(31) /* ../../core/util/ndarray */;
    const object_1 = require(9) /* ../../core/util/object */;
    const types_1 = require(8) /* ../../core/util/types */;
    const interaction_policy_1 = require(145) /* ../selections/interaction_policy */;
    const selection_1 = require(144) /* ../selections/selection */;
    const data_source_1 = require(146) /* ./data_source */;
    class ColumnarDataSource extends data_source_1.DataSource {
        get_array(key) {
            const data = (0, object_1.dict)(this.data);
            let column = data.get(key);
            if (column == null) {
                data.set(key, column = []);
            }
            else if (!(0, types_1.isArray)(column)) {
                data.set(key, column = Array.from(column));
            }
            return column;
        }
        _select = new signaling_1.Signal0(this, "select");
        inspect = new signaling_1.Signal(this, "inspect");
        selection_manager = new selection_manager_1.SelectionManager(this);
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Ref, Dict, Unknown }) => ({
                default_values: [Dict(Unknown), {}],
                selection_policy: [Ref(interaction_policy_1.SelectionPolicy), () => new interaction_policy_1.UnionRenderers()],
            }));
            this.internal(({ AnyRef }) => ({
                inspected: [AnyRef(), () => new selection_1.Selection()],
            }));
        }
        get inferred_defaults() {
            const defaults = new Map();
            for (const [name, array] of (0, object_1.entries)(this.data)) {
                const value = (() => {
                    if ((0, ndarray_1.is_NDArray)(array)) {
                        switch (array.dtype) {
                            case "bool":
                                return false;
                            case "uint8":
                            case "int8":
                            case "uint16":
                            case "int16":
                            case "uint32":
                            case "int32":
                            case "float32":
                            case "float64":
                                return 0;
                            case "object":
                                return null;
                        }
                    }
                    else if ((0, types_1.isArray)(array) && array.length != 0) {
                        const [item] = array;
                        if (item === null) {
                            return null;
                        }
                        else if ((0, types_1.isBoolean)(item)) {
                            return false;
                        }
                        else if ((0, types_1.isNumber)(item)) {
                            return 0;
                        }
                        else if ((0, types_1.isString)(item)) {
                            return "";
                        }
                        else if ((0, types_1.isArray)(item)) {
                            return [];
                        }
                    }
                    return undefined;
                })();
                if (value !== undefined) {
                    defaults.set(name, value);
                }
            }
            return defaults;
        }
        get(name) {
            const column = this.get_column(name);
            (0, assert_1.assert)(column != null, `unknown column '${name}' in ${this}`);
            return column;
        }
        set(name, column) {
            (0, object_1.dict)(this.data).set(name, column);
        }
        get_column(name) {
            const data = (0, object_1.dict)(this.data);
            return data.get(name) ?? null;
        }
        get_row(index) {
            const i = (0, types_1.isNumber)(index) ? index : index.index;
            const result = {};
            for (const [column, array] of (0, object_1.entries)(this.data)) {
                result[column] = array[i];
            }
            return result;
        }
        columns() {
            // return the column names in this data source
            return (0, object_1.keys)(this.data);
        }
        get_length(soft = true) {
            const lengths = (0, array_1.uniq)((0, object_1.values)(this.data).map((v) => (0, ndarray_1.is_NDArray)(v) ? v.shape[0] : v.length));
            switch (lengths.length) {
                case 0: {
                    return null; // XXX: don't guess, treat on case-by-case basis
                }
                case 1: {
                    return lengths[0];
                }
                default: {
                    const msg = "data source has columns of inconsistent lengths";
                    if (soft) {
                        logging_1.logger.warn(msg);
                        return lengths.sort()[0];
                    }
                    else {
                        throw new Error(msg);
                    }
                }
            }
        }
        get length() {
            return this.get_length() ?? 0;
        }
        clear() {
            const data = (0, object_1.clone)(this.data);
            const proxy = (0, object_1.dict)(data);
            for (const [name, column] of proxy) {
                const empty = new column.constructor(0);
                proxy.set(name, empty);
            }
            this.data = data;
        }
        stream(new_data, rollover, { sync } = {}) {
            this.stream_to(this.properties.data, new_data, rollover, { sync });
        }
        patch(patches, { sync } = {}) {
            this.patch_to(this.properties.data, patches, { sync });
        }
    }
    exports.ColumnarDataSource = ColumnarDataSource;
},
/* core/selection_manager.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const selection_1 = require(144) /* ../models/selections/selection */;
    // XXX: this is needed to cut circular dependency between this, models/renderers/* and models/sources/*
    function is_GlyphRendererView(renderer_view) {
        return renderer_view.model.type == "GlyphRenderer";
    }
    function is_GraphRendererView(renderer_view) {
        return renderer_view.model.type == "GraphRenderer";
    }
    class SelectionManager {
        source;
        constructor(source) {
            this.source = source;
        }
        inspectors = new Map();
        select(renderer_views, geometry, final, mode = "replace") {
            // divide renderers into glyph_renderers or graph_renderers
            const glyph_renderer_views = [];
            const graph_renderer_views = [];
            for (const r of renderer_views) {
                if (is_GlyphRendererView(r)) {
                    glyph_renderer_views.push(r);
                }
                else if (is_GraphRendererView(r)) {
                    graph_renderer_views.push(r);
                }
            }
            let did_hit = false;
            // graph renderer case
            for (const r of graph_renderer_views) {
                const hit_test_result = r.model.selection_policy.hit_test(geometry, r);
                did_hit = did_hit || r.model.selection_policy.do_selection(hit_test_result, r.model, final, mode);
            }
            // glyph renderers
            if (glyph_renderer_views.length > 0) {
                const hit_test_result = this.source.selection_policy.hit_test(geometry, glyph_renderer_views);
                did_hit = did_hit || this.source.selection_policy.do_selection(hit_test_result, this.source, final, mode);
            }
            return did_hit;
        }
        inspect(renderer_view, geometry) {
            let did_hit = false;
            if (is_GlyphRendererView(renderer_view)) {
                const hit_test_result = renderer_view.hit_test(geometry);
                if (hit_test_result != null) {
                    did_hit = !hit_test_result.is_empty();
                    const inspection = this.get_or_create_inspector(renderer_view.model);
                    inspection.update(hit_test_result, true, "replace");
                    this.source.setv({ inspected: inspection }, { silent: true });
                    this.source.inspect.emit([renderer_view.model, { geometry }]);
                }
            }
            else if (is_GraphRendererView(renderer_view)) {
                const hit_test_result = renderer_view.model.inspection_policy.hit_test(geometry, renderer_view);
                did_hit = renderer_view.model.inspection_policy.do_inspection(hit_test_result, geometry, renderer_view, false, "replace");
            }
            return did_hit;
        }
        invert(rview) {
            const n = this.source.get_length();
            if (n == null) {
                return;
            }
            this.source.selected.invert(n);
            if (rview != null) {
                this.get_or_create_inspector(rview.model).invert(n);
            }
        }
        clear(rview) {
            this.source.selected.clear();
            if (rview != null) {
                this.get_or_create_inspector(rview.model).clear();
            }
        }
        get_or_create_inspector(renderer) {
            let selection = this.inspectors.get(renderer);
            if (selection == null) {
                selection = new selection_1.Selection();
                this.inspectors.set(renderer, selection);
            }
            return selection;
        }
    }
    exports.SelectionManager = SelectionManager;
},
/* models/selections/selection.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    const array_1 = require(10) /* ../../core/util/array */;
    const object_1 = require(9) /* ../../core/util/object */;
    const kinds_1 = require(22) /* ../../core/kinds */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    exports.OpaqueIndices = (0, kinds_1.Arrayable)(kinds_1.Int);
    exports.MultiIndices = (0, kinds_1.Mapping)(kinds_1.Int, exports.OpaqueIndices);
    exports.ImageIndex = (0, kinds_1.Struct)({ index: kinds_1.Int, i: kinds_1.Int, j: kinds_1.Int, flat_index: kinds_1.Int });
    exports.ImageIndices = (0, kinds_1.List)(exports.ImageIndex);
    class Selection extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        get_view() {
            return this.view;
        }
        static {
            this.define({
                indices: [exports.OpaqueIndices, []],
                line_indices: [exports.OpaqueIndices, []],
                multiline_indices: [exports.MultiIndices, new Map()],
                image_indices: [exports.ImageIndices, []],
            });
            this.internal(({ List, AnyRef, Nullable }) => ({
                selected_glyphs: [List(AnyRef()), []],
                view: [Nullable(AnyRef()), null],
            }));
        }
        get selected_glyph() {
            return this.selected_glyphs.length > 0 ? this.selected_glyphs[0] : null;
        }
        add_to_selected_glyphs(glyph) {
            this.selected_glyphs.push(glyph);
        }
        update(selection, _final = true, mode = "replace") {
            switch (mode) {
                case "replace": {
                    this.update_through_replacement(selection);
                    break;
                }
                case "toggle": {
                    this.update_through_toggle(selection);
                    break;
                }
                case "append": {
                    this.update_through_union(selection);
                    break;
                }
                case "intersect": {
                    this.update_through_intersection(selection);
                    break;
                }
                case "subtract": {
                    this.update_through_subtraction(selection);
                    break;
                }
                case "xor": {
                    this.update_through_symmetric_difference(selection);
                    break;
                }
            }
        }
        // TODO `size` wouldn't be needed if `indices` was an instance of
        // `Indices` class, instead of an array of numbers. Then also we
        // could just call `.invert()` on the class.
        invert(size) {
            const indices = new Set(this.indices);
            const inversion = [];
            for (let i = 0; i < size; i++) {
                if (!indices.has(i)) {
                    inversion.push(i);
                }
            }
            this.indices = inversion;
            // this.line_indices
            // this.multiline_indices
            // this.image_indices
        }
        clear() {
            this.indices = [];
            this.line_indices = [];
            this.multiline_indices = new Map();
            this.image_indices = [];
            this.view = null;
            this.selected_glyphs = [];
        }
        map(mapper) {
            return new Selection({
                ...this.attributes,
                indices: (0, arrayable_1.map)(this.indices, mapper),
                // NOTE: line_indices don't support subset indexing
                multiline_indices: new Map((0, arrayable_1.map)([...this.multiline_indices.entries()], ([index, line_indices]) => [mapper(index), line_indices])),
                image_indices: this.image_indices.map((image_index) => ({ ...image_index, index: mapper(image_index.index) })),
            });
        }
        is_empty() {
            return this.indices.length == 0 && this.line_indices.length == 0 && this.image_indices.length == 0 && this.selected_glyphs.length == 0;
        }
        _union_image_indices(...collection) {
            const is = new Map();
            const js = new Map();
            const result = [];
            for (const indices of collection) {
                for (const image_index of indices) {
                    const { index, i, j } = image_index;
                    const iis = is.get(index);
                    const ijs = js.get(index);
                    if (iis != null && ijs != null) {
                        if (!iis.has(i) || !ijs.has(j)) {
                            result.push(image_index);
                            iis.add(i);
                            ijs.add(j);
                        }
                    }
                    else {
                        result.push(image_index);
                        is.set(index, new Set([i]));
                        js.set(index, new Set([j]));
                    }
                }
            }
            return result;
        }
        update_through_replacement(other) {
            this.indices = other.indices;
            this.line_indices = other.line_indices;
            this.multiline_indices = other.multiline_indices;
            this.image_indices = other.image_indices;
            this.view = other.view;
            this.selected_glyphs = other.selected_glyphs;
        }
        update_through_toggle(other) {
            // note the order of arguments when comparing with update_through_subtraction()
            this.indices = (0, array_1.difference)(other.indices, this.indices);
            // TODO: think through and fix any logic below
            this.selected_glyphs = (0, array_1.union)(other.selected_glyphs, this.selected_glyphs);
            this.line_indices = (0, array_1.union)(other.line_indices, this.line_indices);
            this.image_indices = this._union_image_indices(this.image_indices, other.image_indices); // TODO
            this.view = other.view;
            this.multiline_indices = (0, object_1.merge)(other.multiline_indices, this.multiline_indices);
        }
        update_through_union(other) {
            this.indices = (0, array_1.union)(this.indices, other.indices);
            this.selected_glyphs = (0, array_1.union)(other.selected_glyphs, this.selected_glyphs);
            this.line_indices = (0, array_1.union)(other.line_indices, this.line_indices);
            this.image_indices = this._union_image_indices(this.image_indices, other.image_indices); // TODO
            this.view = other.view;
            this.multiline_indices = (0, object_1.merge)(other.multiline_indices, this.multiline_indices);
        }
        update_through_intersection(other) {
            this.indices = (0, array_1.intersection)(this.indices, other.indices);
            // TODO: think through and fix any logic below
            this.selected_glyphs = (0, array_1.union)(other.selected_glyphs, this.selected_glyphs);
            this.line_indices = (0, array_1.union)(other.line_indices, this.line_indices);
            this.image_indices = this._union_image_indices(this.image_indices, other.image_indices); // TODO
            this.view = other.view;
            this.multiline_indices = (0, object_1.merge)(other.multiline_indices, this.multiline_indices);
        }
        update_through_subtraction(other) {
            this.indices = (0, array_1.difference)(this.indices, other.indices);
            // TODO: think through and fix any logic below
            this.selected_glyphs = (0, array_1.union)(other.selected_glyphs, this.selected_glyphs);
            this.line_indices = (0, array_1.union)(other.line_indices, this.line_indices);
            this.image_indices = this._union_image_indices(this.image_indices, other.image_indices); // TODO
            this.view = other.view;
            this.multiline_indices = (0, object_1.merge)(other.multiline_indices, this.multiline_indices);
        }
        update_through_symmetric_difference(other) {
            this.indices = (0, array_1.symmetric_difference)(this.indices, other.indices);
            // TODO: think through and fix any logic below
            this.selected_glyphs = (0, array_1.union)(other.selected_glyphs, this.selected_glyphs);
            this.line_indices = (0, array_1.union)(other.line_indices, this.line_indices);
            this.image_indices = this._union_image_indices(this.image_indices, other.image_indices); // TODO
            this.view = other.view;
            this.multiline_indices = (0, object_1.merge)(other.multiline_indices, this.multiline_indices);
        }
    }
    exports.Selection = Selection;
},
/* models/selections/interaction_policy.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    class SelectionPolicy extends model_1.Model {
        do_selection(hit_test_result, source, final, mode) {
            if (hit_test_result == null) {
                return false;
            }
            else {
                source.selected.update(hit_test_result, final, mode);
                source._select.emit();
                return !source.selected.is_empty();
            }
        }
    }
    exports.SelectionPolicy = SelectionPolicy;
    class IntersectRenderers extends SelectionPolicy {
        hit_test(geometry, renderer_views) {
            const hit_test_result_renderers = [];
            for (const r of renderer_views) {
                const result = r.hit_test(geometry);
                if (result != null) {
                    hit_test_result_renderers.push(result);
                }
            }
            if (hit_test_result_renderers.length > 0) {
                const hit_test_result = hit_test_result_renderers[0];
                for (const hit_test_result_other of hit_test_result_renderers) {
                    hit_test_result.update_through_intersection(hit_test_result_other);
                }
                return hit_test_result;
            }
            else {
                return null;
            }
        }
    }
    exports.IntersectRenderers = IntersectRenderers;
    class UnionRenderers extends SelectionPolicy {
        hit_test(geometry, renderer_views) {
            const hit_test_result_renderers = [];
            for (const r of renderer_views) {
                const result = r.hit_test(geometry);
                if (result != null) {
                    hit_test_result_renderers.push(result);
                }
            }
            if (hit_test_result_renderers.length > 0) {
                const hit_test_result = hit_test_result_renderers[0];
                const { length } = hit_test_result_renderers;
                for (let i = 1; i < length; i++) {
                    hit_test_result.update_through_union(hit_test_result_renderers[i]);
                }
                return hit_test_result;
            }
            else {
                return null;
            }
        }
    }
    exports.UnionRenderers = UnionRenderers;
},
/* models/sources/data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    const selection_1 = require(144) /* ../selections/selection */;
    class DataSource extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Ref }) => ({
                selected: [Ref(selection_1.Selection), () => new selection_1.Selection(), { readonly: true }],
            }));
        }
    }
    exports.DataSource = DataSource;
},
/* models/sources/column_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const columnar_data_source_1 = require(142) /* ./columnar_data_source */;
    class ColumnDataSource extends columnar_data_source_1.ColumnarDataSource {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Unknown, Dict, Arrayable }) => ({
                data: [Dict(Arrayable(Unknown)), {}],
            }));
        }
    }
    exports.ColumnDataSource = ColumnDataSource;
},
/* core/util/projections.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.clip_mercator = clip_mercator;
    exports.in_bounds = in_bounds;
    exports.project_xy = project_xy;
    exports.project_xsys = project_xsys;
    const tslib_1 = require(1) /* tslib */;
    const proj4_1 = tslib_1.__importDefault(require(149) /* proj4 */);
    const types_1 = require(25) /* ../types */;
    const mercator = "GOOGLE";
    const wgs84 = "WGS84";
    const _wgs84_mercator = (0, proj4_1.default)(wgs84, mercator);
    exports.wgs84_mercator = {
        compute(x, y) {
            if (isFinite(x) && isFinite(y)) {
                return _wgs84_mercator.forward([x, y]);
            }
            else {
                return [NaN, NaN];
            }
        },
        invert(merc_x, merc_y) {
            if (isFinite(merc_x) && isFinite(merc_y)) {
                return _wgs84_mercator.inverse([merc_x, merc_y]);
            }
            else {
                return [NaN, NaN];
            }
        },
    };
    const mercator_bounds = {
        lon: [-20026376.39, 20026376.39],
        lat: [-20048966.10, 20048966.10],
    };
    const latlon_bounds = {
        lon: [-180, 180],
        lat: [-85.06, 85.06],
    };
    const { min, max } = Math;
    function clip_mercator(low, high, dimension) {
        const [vmin, vmax] = mercator_bounds[dimension];
        return [max(low, vmin), min(high, vmax)];
    }
    function in_bounds(value, dimension) {
        const [min, max] = latlon_bounds[dimension];
        return min < value && value < max;
    }
    (function (inplace) {
        function project_xy(x, y, merc_x, merc_y) {
            const n = min(x.length, y.length);
            merc_x = merc_x ?? x;
            merc_y = merc_y ?? y;
            for (let i = 0; i < n; i++) {
                const xi = x[i];
                const yi = y[i];
                const [merc_xi, merc_yi] = exports.wgs84_mercator.compute(xi, yi);
                merc_x[i] = merc_xi;
                merc_y[i] = merc_yi;
            }
        }
        inplace.project_xy = project_xy;
        function project_xsys(xs, ys, merc_xs, merc_ys) {
            const n = min(xs.length, ys.length);
            merc_xs = merc_xs ?? xs;
            merc_ys = merc_ys ?? ys;
            for (let i = 0; i < n; i++) {
                project_xy(xs[i], ys[i], merc_xs[i], merc_ys[i]);
            }
        }
        inplace.project_xsys = project_xsys;
    })(exports.inplace || (exports.inplace = {}));
    function project_xy(x, y) {
        const n = min(x.length, y.length);
        const ArrayType = (0, types_1.infer_type)(x, y);
        const merc_x = new ArrayType(n);
        const merc_y = new ArrayType(n);
        exports.inplace.project_xy(x, y, merc_x, merc_y);
        return [merc_x, merc_y];
    }
    function project_xsys(xs, ys) {
        const n = min(xs.length, ys.length);
        const merc_xs = new Array(n);
        const merc_ys = new Array(n);
        for (let i = 0; i < n; i++) {
            const [merc_x, merc_y] = project_xy(xs[i], ys[i]);
            merc_xs[i] = merc_x;
            merc_ys[i] = merc_y;
        }
        return [merc_xs, merc_ys];
    }
},
/* proj4/lib/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const core_1 = tslib_1.__importDefault(require(150) /* ./core */);
    const Proj_1 = tslib_1.__importDefault(require(151) /* ./Proj */);
    const Point_1 = tslib_1.__importDefault(require(188) /* ./Point */);
    const toPoint_1 = tslib_1.__importDefault(require(186) /* ./common/toPoint */);
    const defs_1 = tslib_1.__importDefault(require(153) /* ./defs */);
    const nadgrid_1 = tslib_1.__importDefault(require(181) /* ./nadgrid */);
    const transform_1 = tslib_1.__importDefault(require(182) /* ./transform */);
    const mgrs_1 = tslib_1.__importDefault(require(189) /* mgrs */);
    const projs_1 = tslib_1.__importDefault(require(190) /* ../projs */);
    /**
     * @typedef {Object} Mgrs
     * @property {(lonlat: [number, number]) => string} forward
     * @property {(mgrsString: string) => [number, number, number, number]} inverse
     * @property {(mgrsString: string) => [number, number]} toPoint
     */
    /**
     * @typedef {import('./defs').ProjectionDefinition} ProjectionDefinition
     * @typedef {import('./core').TemplateCoordinates} TemplateCoordinates
     * @typedef {import('./core').InterfaceCoordinates} InterfaceCoordinates
     * @typedef {import('./core').Converter} Converter
     * @typedef {import('./Proj').DatumDefinition} DatumDefinition
     */
    /**
     * @template {import('./core').TemplateCoordinates} T
     * @type {core<T> & {defaultDatum: string, Proj: typeof Proj, WGS84: Proj, Point: typeof Point, toPoint: typeof common, defs: typeof defs, nadgrid: typeof nadgrid, transform: typeof transform, mgrs: Mgrs, version: string}}
     */
    const proj4 = Object.assign(core_1.default, {
        defaultDatum: 'WGS84',
        Proj: Proj_1.default,
        WGS84: new Proj_1.default('WGS84'),
        Point: Point_1.default,
        toPoint: toPoint_1.default,
        defs: defs_1.default,
        nadgrid: nadgrid_1.default,
        transform: transform_1.default,
        mgrs: mgrs_1.default,
        version: '__VERSION__'
    });
    (0, projs_1.default)(proj4);
    exports.default = proj4;
},
/* proj4/lib/core.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const Proj_1 = tslib_1.__importDefault(require(151) /* ./Proj */);
    const transform_1 = require(182) /* ./transform */;
    const toPoint_1 = tslib_1.__importDefault(require(186) /* ./common/toPoint */);
    var wgs84 = (0, Proj_1.default)('WGS84');
    /**
     * @typedef {{x: number, y: number, z?: number, m?: number}} InterfaceCoordinates
     */
    /**
     * @typedef {Array<number> | InterfaceCoordinates} TemplateCoordinates
     */
    /**
     * @typedef {Object} Converter
     * @property {<T extends TemplateCoordinates>(coordinates: T, enforceAxis?: boolean) => T} forward
     * @property {<T extends TemplateCoordinates>(coordinates: T, enforceAxis?: boolean) => T} inverse
     * @property {proj} [oProj]
     */
    /**
     * @typedef {Object} PROJJSONDefinition
     * @property {string} [$schema]
     * @property {string} type
     * @property {string} [name]
     * @property {{authority: string, code: number}} [id]
     * @property {string} [scope]
     * @property {string} [area]
     * @property {{south_latitude: number, west_longitude: number, north_latitude: number, east_longitude: number}} [bbox]
     * @property {PROJJSONDefinition[]} [components]
     * @property {{type: string, name: string}} [datum]
     * @property {{
     *   name: string,
     *   members: Array<{
     *     name: string,
     *     id?: {authority: string, code: number}
     *   }>,
     *   ellipsoid?: {
     *     name: string,
     *     semi_major_axis: number,
     *     inverse_flattening?: number
     *   },
     *   accuracy?: string,
     *   id?: {authority: string, code: number}
     * }} [datum_ensemble]
     * @property {{
     *   subtype: string,
     *   axis: Array<{
     *     name: string,
     *     abbreviation?: string,
     *     direction: string,
     *     unit: string
     *   }>
     * }} [coordinate_system]
     * @property {{
     *   name: string,
     *   method: {name: string},
     *   parameters: Array<{
     *     name: string,
     *     value: number,
     *     unit?: string
     *   }>
     * }} [conversion]
     * @property {{
     *   name: string,
     *   method: {name: string},
     *   parameters: Array<{
     *     name: string,
     *     value: number,
     *     unit?: string,
     *     type?: string,
     *     file_name?: string
     *   }>
     * }} [transformation]
     */
    /**
     * @template {TemplateCoordinates} T
     * @param {proj} from
     * @param {proj} to
     * @param {T} coords
     * @param {boolean} [enforceAxis]
     * @returns {T}
     */
    function transformer(from, to, coords, enforceAxis) {
        var out, geocent, keys;
        if (Array.isArray(coords)) {
            out = (0, transform_1.transformInternal)(from, to, (0, toPoint_1.default)(coords), enforceAxis) || { x: NaN, y: NaN };
            if (coords.length > 2) {
                geocent = (typeof from.name !== 'undefined' && from.name === 'geocent') || (typeof to.name !== 'undefined' && to.name === 'geocent');
                if (geocent) {
                    if (typeof out.z === 'number') {
                        return /** @type {T} */ ([out.x, out.y, out.z].concat(coords.slice(3)));
                    }
                    return /** @type {T} */ ([out.x, out.y, coords[2]].concat(coords.slice(3)));
                }
                if (enforceAxis && typeof out.z === 'number') {
                    return /** @type {T} */ ([out.x, out.y, out.z].concat(coords.slice(3)));
                }
                return /** @type {T} */ ([out.x, out.y].concat(coords.slice(2)));
            }
            return /** @type {T} */ ([out.x, out.y]);
        }
        else {
            out = (0, transform_1.transformInternal)(from, to, { x: coords.x, y: coords.y, z: coords.z, m: coords.m }, enforceAxis) || { x: NaN, y: NaN };
            keys = Object.keys(coords);
            if (keys.length === 2) {
                return /** @type {T} */ (out);
            }
            geocent = (typeof from.name !== 'undefined' && from.name === 'geocent') || (typeof to.name !== 'undefined' && to.name === 'geocent');
            keys.forEach(function (key) {
                if (key === 'x' || key === 'y') {
                    return;
                }
                if (key === 'z' && (geocent || enforceAxis)) {
                    return;
                }
                out[key] = coords[key];
            });
            return /** @type {T} */ (out);
        }
    }
    /**
     * @param {proj | string | PROJJSONDefinition | Converter} item
     * @returns {import('./Proj').default}
     */
    function checkProj(item) {
        if (item instanceof Proj_1.default) {
            return item;
        }
        if (typeof item === 'object' && 'oProj' in item) {
            return item.oProj;
        }
        return (0, Proj_1.default)(/** @type {string | PROJJSONDefinition} */ (item));
    }
    /**
     * @overload
     * @param {string | PROJJSONDefinition | proj} toProj
     * @returns {Converter}
     */
    /**
     * @overload
     * @param {string | PROJJSONDefinition | proj} fromProj
     * @param {string | PROJJSONDefinition | proj} toProj
     * @returns {Converter}
     */
    /**
     * @template {TemplateCoordinates} T
     * @overload
     * @param {string | PROJJSONDefinition | proj} toProj
     * @param {T} coord
     * @returns {T}
     */
    /**
     * @template {TemplateCoordinates} T
     * @overload
     * @param {string | PROJJSONDefinition | proj} fromProj
     * @param {string | PROJJSONDefinition | proj} toProj
     * @param {T} coord
     * @returns {T}
     */
    /**
     * @template {TemplateCoordinates} T
     * @param {string | PROJJSONDefinition | proj} fromProjOrToProj
     * @param {string | PROJJSONDefinition | proj | TemplateCoordinates} [toProjOrCoord]
     * @param {T} [coord]
     * @returns {T|Converter}
     */
    function proj4(fromProjOrToProj, toProjOrCoord, coord) {
        /** @type {proj} */
        var fromProj;
        /** @type {proj} */
        var toProj;
        var single = false;
        /** @type {Converter} */
        var obj;
        if (typeof toProjOrCoord === 'undefined') {
            toProj = checkProj(fromProjOrToProj);
            fromProj = wgs84;
            single = true;
        }
        else if (typeof /** @type {?} */ (toProjOrCoord).x !== 'undefined' || Array.isArray(toProjOrCoord)) {
            coord = /** @type {T} */ ( /** @type {?} */(toProjOrCoord));
            toProj = checkProj(fromProjOrToProj);
            fromProj = wgs84;
            single = true;
        }
        if (!fromProj) {
            fromProj = checkProj(fromProjOrToProj);
        }
        if (!toProj) {
            toProj = checkProj(/** @type {string | PROJJSONDefinition | proj } */ (toProjOrCoord));
        }
        if (coord) {
            return transformer(fromProj, toProj, coord);
        }
        else {
            obj = {
                /**
                 * @template {TemplateCoordinates} T
                 * @param {T} coords
                 * @param {boolean=} enforceAxis
                 * @returns {T}
                 */
                forward: function (coords, enforceAxis) {
                    return transformer(fromProj, toProj, coords, enforceAxis);
                },
                /**
                 * @template {TemplateCoordinates} T
                 * @param {T} coords
                 * @param {boolean=} enforceAxis
                 * @returns {T}
                 */
                inverse: function (coords, enforceAxis) {
                    return transformer(toProj, fromProj, coords, enforceAxis);
                }
            };
            if (single) {
                obj.oProj = toProj;
            }
            return obj;
        }
    }
    exports.default = proj4;
},
/* proj4/lib/Proj.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const parseCode_1 = tslib_1.__importDefault(require(152) /* ./parseCode */);
    const extend_1 = tslib_1.__importDefault(require(168) /* ./extend */);
    const projections_1 = tslib_1.__importDefault(require(169) /* ./projections */);
    const deriveConstants_1 = require(177) /* ./deriveConstants */;
    const Datum_1 = tslib_1.__importDefault(require(179) /* ./constants/Datum */);
    const datum_1 = tslib_1.__importDefault(require(180) /* ./datum */);
    const match_1 = tslib_1.__importDefault(require(159) /* ./match */);
    const nadgrid_1 = require(181) /* ./nadgrid */;
    /**
     * @typedef {Object} DatumDefinition
     * @property {number} datum_type - The type of datum.
     * @property {number} a - Semi-major axis of the ellipsoid.
     * @property {number} b - Semi-minor axis of the ellipsoid.
     * @property {number} es - Eccentricity squared of the ellipsoid.
     * @property {number} ep2 - Second eccentricity squared of the ellipsoid.
     */
    /**
     * @param {string | import('./core').PROJJSONDefinition | import('./defs').ProjectionDefinition} srsCode
     * @param {(errorMessage?: string, instance?: Projection) => void} [callback]
     */
    function Projection(srsCode, callback) {
        if (!(this instanceof Projection)) {
            return new Projection(srsCode);
        }
        /** @type {<T extends import('./core').TemplateCoordinates>(coordinates: T, enforceAxis?: boolean) => T} */
        this.forward = null;
        /** @type {<T extends import('./core').TemplateCoordinates>(coordinates: T, enforceAxis?: boolean) => T} */
        this.inverse = null;
        /** @type {function(): void} */
        this.init = null;
        /** @type {string} */
        this.name;
        /** @type {string} */
        this.axis;
        /** @type {Array<string>} */
        this.names = null;
        /** @type {string} */
        this.title;
        callback = callback || function (error) {
            if (error) {
                throw error;
            }
        };
        var json = (0, parseCode_1.default)(srsCode);
        if (typeof json !== 'object') {
            callback('Could not parse to valid json: ' + srsCode);
            return;
        }
        var ourProj = Projection.projections.get(json.projName);
        if (!ourProj) {
            callback('Could not get projection name from: ' + srsCode);
            return;
        }
        if (json.datumCode && json.datumCode !== 'none') {
            var datumDef = (0, match_1.default)(Datum_1.default, json.datumCode);
            if (datumDef) {
                json.datum_params = json.datum_params || (datumDef.towgs84 ? datumDef.towgs84.split(',') : null);
                json.ellps = datumDef.ellipse;
                json.datumName = datumDef.datumName ? datumDef.datumName : json.datumCode;
            }
        }
        json.k0 = json.k0 || 1.0;
        json.axis = json.axis || 'enu';
        json.ellps = json.ellps || 'wgs84';
        json.lat1 = json.lat1 || json.lat0; // Lambert_Conformal_Conic_1SP, for example, needs this
        var sphere_ = (0, deriveConstants_1.sphere)(json.a, json.b, json.rf, json.ellps, json.sphere);
        var ecc = (0, deriveConstants_1.eccentricity)(sphere_.a, sphere_.b, sphere_.rf, json.R_A);
        var nadgrids = (0, nadgrid_1.getNadgrids)(json.nadgrids);
        /** @type {DatumDefinition} */
        var datumObj = json.datum || (0, datum_1.default)(json.datumCode, json.datum_params, sphere_.a, sphere_.b, ecc.es, ecc.ep2, nadgrids);
        (0, extend_1.default)(this, json); // transfer everything over from the projection because we don't know what we'll need
        (0, extend_1.default)(this, ourProj); // transfer all the methods from the projection
        // copy the 4 things over we calculated in deriveConstants.sphere
        this.a = sphere_.a;
        this.b = sphere_.b;
        this.rf = sphere_.rf;
        this.sphere = sphere_.sphere;
        // copy the 3 things we calculated in deriveConstants.eccentricity
        this.es = ecc.es;
        this.e = ecc.e;
        this.ep2 = ecc.ep2;
        // add in the datum object
        this.datum = datumObj;
        // init the projection
        if ('init' in this && typeof this.init === 'function') {
            this.init();
        }
        // legecy callback from back in the day when it went to spatialreference.org
        callback(null, this);
    }
    Projection.projections = projections_1.default;
    Projection.projections.start();
    exports.default = Projection;
},
/* proj4/lib/parseCode.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const defs_1 = tslib_1.__importDefault(require(153) /* ./defs */);
    const wkt_parser_1 = tslib_1.__importDefault(require(160) /* wkt-parser */);
    const projString_1 = tslib_1.__importDefault(require(155) /* ./projString */);
    const match_1 = tslib_1.__importDefault(require(159) /* ./match */);
    function testObj(code) {
        return typeof code === 'string';
    }
    function testDef(code) {
        return code in defs_1.default;
    }
    function testWKT(code) {
        return (code.indexOf('+') !== 0 && code.indexOf('[') !== -1) || (typeof code === 'object' && !('srsCode' in code));
    }
    var codes = ['3857', '900913', '3785', '102113'];
    function checkMercator(item) {
        if (item.title) {
            return item.title.toLowerCase().indexOf('epsg:') === 0 && codes.indexOf(item.title.substr(5)) > -1;
        }
        var auth = (0, match_1.default)(item, 'authority');
        if (!auth) {
            return;
        }
        var code = (0, match_1.default)(auth, 'epsg');
        return code && codes.indexOf(code) > -1;
    }
    function checkProjStr(item) {
        var ext = (0, match_1.default)(item, 'extension');
        if (!ext) {
            return;
        }
        return (0, match_1.default)(ext, 'proj4');
    }
    function testProj(code) {
        return code[0] === '+';
    }
    /**
     * @param {string | import('./core').PROJJSONDefinition | import('./defs').ProjectionDefinition} code
     * @returns {import('./defs').ProjectionDefinition}
     */
    function parse(code) {
        let out;
        if (testObj(code)) {
            // check to see if this is a WKT string
            if (testDef(code)) {
                out = defs_1.default[code];
            }
            else if (testWKT(code)) {
                out = (0, wkt_parser_1.default)(code);
                var maybeProjStr = checkProjStr(out);
                if (maybeProjStr) {
                    out = (0, projString_1.default)(maybeProjStr);
                }
            }
            else if (testProj(code)) {
                out = (0, projString_1.default)(code);
            }
        }
        else if (!('projName' in code)) {
            out = (0, wkt_parser_1.default)(code);
        }
        else {
            out = code;
        }
        // test for special Web Mercator case, due to this being a very common and often malformed
        return out && checkMercator(out) ? defs_1.default['EPSG:3857'] : out;
    }
    exports.default = parse;
},
/* proj4/lib/defs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const global_1 = tslib_1.__importDefault(require(154) /* ./global */);
    const projString_1 = tslib_1.__importDefault(require(155) /* ./projString */);
    const wkt_parser_1 = tslib_1.__importDefault(require(160) /* wkt-parser */);
    /**
     * @typedef {Object} ProjectionDefinition
     * @property {string} title
     * @property {string} [projName]
     * @property {string} [ellps]
     * @property {import('./Proj.js').DatumDefinition} [datum]
     * @property {string} [datumName]
     * @property {number} [rf]
     * @property {number} [lat0]
     * @property {number} [lat1]
     * @property {number} [lat2]
     * @property {number} [lat_ts]
     * @property {number} [long0]
     * @property {number} [long1]
     * @property {number} [long2]
     * @property {number} [alpha]
     * @property {number} [longc]
     * @property {number} [x0]
     * @property {number} [y0]
     * @property {number} [k0]
     * @property {number} [a]
     * @property {number} [b]
     * @property {true} [R_A]
     * @property {number} [zone]
     * @property {true} [utmSouth]
     * @property {string|Array<number>} [datum_params]
     * @property {number} [to_meter]
     * @property {string} [units]
     * @property {number} [from_greenwich]
     * @property {string} [datumCode]
     * @property {string} [nadgrids]
     * @property {string} [axis]
     * @property {boolean} [sphere]
     * @property {number} [rectified_grid_angle]
     * @property {boolean} [approx]
     * @property {boolean} [over]
     * @property {string} [projStr]
     * @property {<T extends import('./core').TemplateCoordinates>(coordinates: T, enforceAxis?: boolean) => T} inverse
     * @property {<T extends import('./core').TemplateCoordinates>(coordinates: T, enforceAxis?: boolean) => T} forward
     */
    /**
     * @overload
     * @param {string} name
     * @param {string|ProjectionDefinition|import('./core.js').PROJJSONDefinition} projection
     * @returns {void}
     */
    /**
     * @overload
     * @param {Array<[string, string]>} name
     * @returns {Array<ProjectionDefinition|undefined>}
     */
    /**
     * @overload
     * @param {string} name
     * @returns {ProjectionDefinition}
     */
    /**
     * @param {string | Array<Array<string>> | Partial<Record<'EPSG'|'ESRI'|'IAU2000', ProjectionDefinition>>} name
     * @returns {ProjectionDefinition | Array<ProjectionDefinition|undefined> | void}
     */
    function defs(name) {
        /* global console */
        var that = this;
        if (arguments.length === 2) {
            var def = arguments[1];
            if (typeof def === 'string') {
                if (def.charAt(0) === '+') {
                    defs[ /** @type {string} */(name)] = (0, projString_1.default)(arguments[1]);
                }
                else {
                    defs[ /** @type {string} */(name)] = (0, wkt_parser_1.default)(arguments[1]);
                }
            }
            else if (def && typeof def === 'object' && !('projName' in def)) {
                // PROJJSON
                defs[ /** @type {string} */(name)] = (0, wkt_parser_1.default)(arguments[1]);
            }
            else {
                defs[ /** @type {string} */(name)] = def;
                if (!def) {
                    delete defs[ /** @type {string} */(name)];
                }
            }
        }
        else if (arguments.length === 1) {
            if (Array.isArray(name)) {
                return name.map(function (v) {
                    if (Array.isArray(v)) {
                        return defs.apply(that, v);
                    }
                    else {
                        return defs(v);
                    }
                });
            }
            else if (typeof name === 'string') {
                if (name in defs) {
                    return defs[name];
                }
            }
            else if ('EPSG' in name) {
                defs['EPSG:' + name.EPSG] = name;
            }
            else if ('ESRI' in name) {
                defs['ESRI:' + name.ESRI] = name;
            }
            else if ('IAU2000' in name) {
                defs['IAU2000:' + name.IAU2000] = name;
            }
            else {
                console.log(name);
            }
            return;
        }
    }
    (0, global_1.default)(defs);
    exports.default = defs;
},
/* proj4/lib/global.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(defs) {
        defs('EPSG:4326', '+title=WGS 84 (long/lat) +proj=longlat +ellps=WGS84 +datum=WGS84 +units=degrees');
        defs('EPSG:4269', '+title=NAD83 (long/lat) +proj=longlat +a=6378137.0 +b=6356752.31414036 +ellps=GRS80 +datum=NAD83 +units=degrees');
        defs('EPSG:3857', '+title=WGS 84 / Pseudo-Mercator +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs');
        // UTM WGS84
        for (var i = 1; i <= 60; ++i) {
            defs('EPSG:' + (32600 + i), '+proj=utm +zone=' + i + ' +datum=WGS84 +units=m');
            defs('EPSG:' + (32700 + i), '+proj=utm +zone=' + i + ' +south +datum=WGS84 +units=m');
        }
        defs('EPSG:5041', '+title=WGS 84 / UPS North (E,N) +proj=stere +lat_0=90 +lon_0=0 +k=0.994 +x_0=2000000 +y_0=2000000 +datum=WGS84 +units=m');
        defs('EPSG:5042', '+title=WGS 84 / UPS South (E,N) +proj=stere +lat_0=-90 +lon_0=0 +k=0.994 +x_0=2000000 +y_0=2000000 +datum=WGS84 +units=m');
        defs.WGS84 = defs['EPSG:4326'];
        defs['EPSG:3785'] = defs['EPSG:3857']; // maintain backward compat, official code is 3857
        defs.GOOGLE = defs['EPSG:3857'];
        defs['EPSG:900913'] = defs['EPSG:3857'];
        defs['EPSG:102113'] = defs['EPSG:3857'];
    }
},
/* proj4/lib/projString.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    const tslib_1 = require(1) /* tslib */;
    const values_1 = require(156) /* ./constants/values */;
    const PrimeMeridian_1 = tslib_1.__importDefault(require(157) /* ./constants/PrimeMeridian */);
    const units_1 = tslib_1.__importDefault(require(158) /* ./constants/units */);
    const match_1 = tslib_1.__importDefault(require(159) /* ./match */);
    /**
     * @param {string} defData
     * @returns {import('./defs').ProjectionDefinition}
     */
    function default_1(defData) {
        /** @type {import('./defs').ProjectionDefinition} */
        var self = {};
        var paramObj = defData.split('+').map(function (v) {
            return v.trim();
        }).filter(function (a) {
            return a;
        }).reduce(function (p, a) {
            /** @type {Array<?>} */
            var split = a.split('=');
            split.push(true);
            p[split[0].toLowerCase()] = split[1];
            return p;
        }, {});
        var paramName, paramVal, paramOutname;
        var params = {
            proj: 'projName',
            datum: 'datumCode',
            rf: function (v) {
                self.rf = parseFloat(v);
            },
            lat_0: function (v) {
                self.lat0 = v * values_1.D2R;
            },
            lat_1: function (v) {
                self.lat1 = v * values_1.D2R;
            },
            lat_2: function (v) {
                self.lat2 = v * values_1.D2R;
            },
            lat_ts: function (v) {
                self.lat_ts = v * values_1.D2R;
            },
            lon_0: function (v) {
                self.long0 = v * values_1.D2R;
            },
            lon_1: function (v) {
                self.long1 = v * values_1.D2R;
            },
            lon_2: function (v) {
                self.long2 = v * values_1.D2R;
            },
            alpha: function (v) {
                self.alpha = parseFloat(v) * values_1.D2R;
            },
            gamma: function (v) {
                self.rectified_grid_angle = parseFloat(v) * values_1.D2R;
            },
            lonc: function (v) {
                self.longc = v * values_1.D2R;
            },
            x_0: function (v) {
                self.x0 = parseFloat(v);
            },
            y_0: function (v) {
                self.y0 = parseFloat(v);
            },
            k_0: function (v) {
                self.k0 = parseFloat(v);
            },
            k: function (v) {
                self.k0 = parseFloat(v);
            },
            a: function (v) {
                self.a = parseFloat(v);
            },
            b: function (v) {
                self.b = parseFloat(v);
            },
            r: function (v) {
                self.a = self.b = parseFloat(v);
            },
            r_a: function () {
                self.R_A = true;
            },
            zone: function (v) {
                self.zone = parseInt(v, 10);
            },
            south: function () {
                self.utmSouth = true;
            },
            towgs84: function (v) {
                self.datum_params = v.split(',').map(function (a) {
                    return parseFloat(a);
                });
            },
            to_meter: function (v) {
                self.to_meter = parseFloat(v);
            },
            units: function (v) {
                self.units = v;
                var unit = (0, match_1.default)(units_1.default, v);
                if (unit) {
                    self.to_meter = unit.to_meter;
                }
            },
            from_greenwich: function (v) {
                self.from_greenwich = v * values_1.D2R;
            },
            pm: function (v) {
                var pm = (0, match_1.default)(PrimeMeridian_1.default, v);
                self.from_greenwich = (pm ? pm : parseFloat(v)) * values_1.D2R;
            },
            nadgrids: function (v) {
                if (v === '@null') {
                    self.datumCode = 'none';
                }
                else {
                    self.nadgrids = v;
                }
            },
            axis: function (v) {
                var legalAxis = 'ewnsud';
                if (v.length === 3 && legalAxis.indexOf(v.substr(0, 1)) !== -1 && legalAxis.indexOf(v.substr(1, 1)) !== -1 && legalAxis.indexOf(v.substr(2, 1)) !== -1) {
                    self.axis = v;
                }
            },
            approx: function () {
                self.approx = true;
            },
            over: function () {
                self.over = true;
            }
        };
        for (paramName in paramObj) {
            paramVal = paramObj[paramName];
            if (paramName in params) {
                paramOutname = params[paramName];
                if (typeof paramOutname === 'function') {
                    paramOutname(paramVal);
                }
                else {
                    self[paramOutname] = paramVal;
                }
            }
            else {
                self[paramName] = paramVal;
            }
        }
        if (typeof self.datumCode === 'string' && self.datumCode !== 'WGS84') {
            self.datumCode = self.datumCode.toLowerCase();
        }
        self['projStr'] = defData;
        return self;
    }
},
/* proj4/lib/constants/values.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.PJD_3PARAM = 1;
    exports.PJD_7PARAM = 2;
    exports.PJD_GRIDSHIFT = 3;
    exports.PJD_WGS84 = 4; // WGS84 or equivalent
    exports.PJD_NODATUM = 5; // WGS84 or equivalent
    exports.SRS_WGS84_SEMIMAJOR = 6378137.0; // only used in grid shift transforms
    exports.SRS_WGS84_SEMIMINOR = 6356752.314; // only used in grid shift transforms
    exports.SRS_WGS84_ESQUARED = 0.0066943799901413165; // only used in grid shift transforms
    exports.SEC_TO_RAD = 4.84813681109535993589914102357e-6;
    exports.HALF_PI = Math.PI / 2;
    // ellipoid pj_set_ell.c
    exports.SIXTH = 0.1666666666666666667;
    /* 1/6 */
    exports.RA4 = 0.04722222222222222222;
    /* 17/360 */
    exports.RA6 = 0.02215608465608465608;
    exports.EPSLN = 1.0e-10;
    // you'd think you could use Number.EPSILON above but that makes
    // Mollweide get into an infinate loop.
    exports.D2R = 0.01745329251994329577;
    exports.R2D = 57.29577951308232088;
    exports.FORTPI = Math.PI / 4;
    exports.TWO_PI = Math.PI * 2;
    // SPI is slightly greater than Math.PI, so values that exceed the -180..180
    // degree range by a tiny amount don't get wrapped. This prevents points that
    // have drifted from their original location along the 180th meridian (due to
    // floating point error) from changing their sign.
    exports.SPI = 3.14159265359;
},
/* proj4/lib/constants/PrimeMeridian.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var primeMeridian = {};
    primeMeridian.greenwich = 0.0; // "0dE",
    primeMeridian.lisbon = -9.131906111111; // "9d07'54.862\"W",
    primeMeridian.paris = 2.337229166667; // "2d20'14.025\"E",
    primeMeridian.bogota = -74.080916666667; // "74d04'51.3\"W",
    primeMeridian.madrid = -3.687938888889; // "3d41'16.58\"W",
    primeMeridian.rome = 12.452333333333; // "12d27'8.4\"E",
    primeMeridian.bern = 7.439583333333; // "7d26'22.5\"E",
    primeMeridian.jakarta = 106.807719444444; // "106d48'27.79\"E",
    primeMeridian.ferro = -17.666666666667; // "17d40'W",
    primeMeridian.brussels = 4.367975; // "4d22'4.71\"E",
    primeMeridian.stockholm = 18.058277777778; // "18d3'29.8\"E",
    primeMeridian.athens = 23.7163375; // "23d42'58.815\"E",
    primeMeridian.oslo = 10.722916666667; // "10d43'22.5\"E"
    exports.default = primeMeridian;
},
/* proj4/lib/constants/units.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = {
        mm: { to_meter: 0.001 },
        cm: { to_meter: 0.01 },
        ft: { to_meter: 0.3048 },
        'us-ft': { to_meter: 1200 / 3937 },
        fath: { to_meter: 1.8288 },
        kmi: { to_meter: 1852 },
        'us-ch': { to_meter: 20.1168402336805 },
        'us-mi': { to_meter: 1609.34721869444 },
        km: { to_meter: 1000 },
        'ind-ft': { to_meter: 0.30479841 },
        'ind-yd': { to_meter: 0.91439523 },
        mi: { to_meter: 1609.344 },
        yd: { to_meter: 0.9144 },
        ch: { to_meter: 20.1168 },
        link: { to_meter: 0.201168 },
        dm: { to_meter: 0.1 },
        in: { to_meter: 0.0254 },
        'ind-ch': { to_meter: 20.11669506 },
        'us-in': { to_meter: 0.025400050800101 },
        'us-yd': { to_meter: 0.914401828803658 }
    };
},
/* proj4/lib/match.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = match;
    var ignoredChar = /[\s_\-\/\(\)]/g;
    function match(obj, key) {
        if (obj[key]) {
            return obj[key];
        }
        var keys = Object.keys(obj);
        var lkey = key.toLowerCase().replace(ignoredChar, '');
        var i = -1;
        var testkey, processedKey;
        while (++i < keys.length) {
            testkey = keys[i];
            processedKey = testkey.toLowerCase().replace(ignoredChar, '');
            if (processedKey === lkey) {
                return obj[testkey];
            }
        }
    }
},
/* wkt-parser/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    const tslib_1 = require(1) /* tslib */;
    const buildPROJJSON_js_1 = require(161) /* ./buildPROJJSON.js */;
    const detectWKTVersion_js_1 = require(163) /* ./detectWKTVersion.js */;
    const parser_js_1 = tslib_1.__importDefault(require(164) /* ./parser.js */);
    const process_js_1 = require(165) /* ./process.js */;
    const transformPROJJSON_js_1 = require(166) /* ./transformPROJJSON.js */;
    const util_js_1 = require(167) /* ./util.js */;
    var knownTypes = ['PROJECTEDCRS', 'PROJCRS', 'GEOGCS', 'GEOCCS', 'PROJCS', 'LOCAL_CS', 'GEODCRS',
        'GEODETICCRS', 'GEODETICDATUM', 'ENGCRS', 'ENGINEERINGCRS'];
    function rename(obj, params) {
        var outName = params[0];
        var inName = params[1];
        if (!(outName in obj) && (inName in obj)) {
            obj[outName] = obj[inName];
            if (params.length === 3) {
                obj[outName] = params[2](obj[outName]);
            }
        }
    }
    function cleanWKT(wkt) {
        var keys = Object.keys(wkt);
        for (var i = 0, ii = keys.length; i < ii; ++i) {
            var key = keys[i];
            // the followings are the crs defined in
            // https://github.com/proj4js/proj4js/blob/1da4ed0b865d0fcb51c136090569210cdcc9019e/lib/parseCode.js#L11
            if (knownTypes.indexOf(key) !== -1) {
                setPropertiesFromWkt(wkt[key]);
            }
            if (typeof wkt[key] === 'object') {
                cleanWKT(wkt[key]);
            }
        }
    }
    function setPropertiesFromWkt(wkt) {
        if (wkt.AUTHORITY) {
            var authority = Object.keys(wkt.AUTHORITY)[0];
            if (authority && authority in wkt.AUTHORITY) {
                wkt.title = authority + ':' + wkt.AUTHORITY[authority];
            }
        }
        if (wkt.type === 'GEOGCS') {
            wkt.projName = 'longlat';
        }
        else if (wkt.type === 'LOCAL_CS') {
            wkt.projName = 'identity';
            wkt.local = true;
        }
        else {
            if (typeof wkt.PROJECTION === 'object') {
                wkt.projName = Object.keys(wkt.PROJECTION)[0];
            }
            else {
                wkt.projName = wkt.PROJECTION;
            }
        }
        if (wkt.AXIS) {
            var axisOrder = '';
            for (var i = 0, ii = wkt.AXIS.length; i < ii; ++i) {
                var axis = [wkt.AXIS[i][0].toLowerCase(), wkt.AXIS[i][1].toLowerCase()];
                if (axis[0].indexOf('north') !== -1 || ((axis[0] === 'y' || axis[0] === 'lat') && axis[1] === 'north')) {
                    axisOrder += 'n';
                }
                else if (axis[0].indexOf('south') !== -1 || ((axis[0] === 'y' || axis[0] === 'lat') && axis[1] === 'south')) {
                    axisOrder += 's';
                }
                else if (axis[0].indexOf('east') !== -1 || ((axis[0] === 'x' || axis[0] === 'lon') && axis[1] === 'east')) {
                    axisOrder += 'e';
                }
                else if (axis[0].indexOf('west') !== -1 || ((axis[0] === 'x' || axis[0] === 'lon') && axis[1] === 'west')) {
                    axisOrder += 'w';
                }
            }
            if (axisOrder.length === 2) {
                axisOrder += 'u';
            }
            if (axisOrder.length === 3) {
                wkt.axis = axisOrder;
            }
        }
        if (wkt.UNIT) {
            wkt.units = wkt.UNIT.name.toLowerCase();
            if (wkt.units === 'metre') {
                wkt.units = 'meter';
            }
            if (wkt.UNIT.convert) {
                if (wkt.type === 'GEOGCS') {
                    if (wkt.DATUM && wkt.DATUM.SPHEROID) {
                        wkt.to_meter = wkt.UNIT.convert * wkt.DATUM.SPHEROID.a;
                    }
                }
                else {
                    wkt.to_meter = wkt.UNIT.convert;
                }
            }
        }
        var geogcs = wkt.GEOGCS;
        if (wkt.type === 'GEOGCS') {
            geogcs = wkt;
        }
        if (geogcs) {
            if (geogcs.PRIMEM && geogcs.PRIMEM.convert) {
                wkt.from_greenwich = (0, util_js_1.d2r)(geogcs.PRIMEM.convert);
            }
            if (geogcs.DATUM) {
                wkt.datumCode = geogcs.DATUM.name.toLowerCase();
            }
            else {
                wkt.datumCode = geogcs.name.toLowerCase();
            }
            if (wkt.datumCode.slice(0, 2) === 'd_') {
                wkt.datumCode = wkt.datumCode.slice(2);
            }
            if (wkt.datumCode === 'new_zealand_1949') {
                wkt.datumCode = 'nzgd49';
            }
            if (wkt.datumCode === 'wgs_1984' || wkt.datumCode === 'world_geodetic_system_1984') {
                if (wkt.PROJECTION === 'Mercator_Auxiliary_Sphere') {
                    wkt.sphere = true;
                }
                wkt.datumCode = 'wgs84';
            }
            if (wkt.datumCode === 'belge_1972') {
                wkt.datumCode = 'rnb72';
            }
            if (geogcs.DATUM && geogcs.DATUM.SPHEROID) {
                wkt.ellps = geogcs.DATUM.SPHEROID.name.replace('_19', '').replace(/[Cc]larke\_18/, 'clrk');
                if (wkt.ellps.toLowerCase().slice(0, 13) === 'international') {
                    wkt.ellps = 'intl';
                }
                wkt.a = geogcs.DATUM.SPHEROID.a;
                wkt.rf = parseFloat(geogcs.DATUM.SPHEROID.rf);
            }
            if (geogcs.DATUM && geogcs.DATUM.TOWGS84) {
                wkt.datum_params = geogcs.DATUM.TOWGS84;
            }
            if (~wkt.datumCode.indexOf('osgb_1936')) {
                wkt.datumCode = 'osgb36';
            }
            if (~wkt.datumCode.indexOf('osni_1952')) {
                wkt.datumCode = 'osni52';
            }
            if (~wkt.datumCode.indexOf('tm65')
                || ~wkt.datumCode.indexOf('geodetic_datum_of_1965')) {
                wkt.datumCode = 'ire65';
            }
            if (wkt.datumCode === 'ch1903+') {
                wkt.datumCode = 'ch1903';
            }
            if (~wkt.datumCode.indexOf('israel')) {
                wkt.datumCode = 'isr93';
            }
        }
        if (wkt.b && !isFinite(wkt.b)) {
            wkt.b = wkt.a;
        }
        if (wkt.rectified_grid_angle) {
            wkt.rectified_grid_angle = (0, util_js_1.d2r)(wkt.rectified_grid_angle);
        }
        function toMeter(input) {
            var ratio = wkt.to_meter || 1;
            return input * ratio;
        }
        var renamer = function (a) {
            return rename(wkt, a);
        };
        var list = [
            ['standard_parallel_1', 'Standard_Parallel_1'],
            ['standard_parallel_1', 'Latitude of 1st standard parallel'],
            ['standard_parallel_2', 'Standard_Parallel_2'],
            ['standard_parallel_2', 'Latitude of 2nd standard parallel'],
            ['false_easting', 'False_Easting'],
            ['false_easting', 'False easting'],
            ['false-easting', 'Easting at false origin'],
            ['false_northing', 'False_Northing'],
            ['false_northing', 'False northing'],
            ['false_northing', 'Northing at false origin'],
            ['central_meridian', 'Central_Meridian'],
            ['central_meridian', 'Longitude of natural origin'],
            ['central_meridian', 'Longitude of false origin'],
            ['latitude_of_origin', 'Latitude_Of_Origin'],
            ['latitude_of_origin', 'Central_Parallel'],
            ['latitude_of_origin', 'Latitude of natural origin'],
            ['latitude_of_origin', 'Latitude of false origin'],
            ['scale_factor', 'Scale_Factor'],
            ['k0', 'scale_factor'],
            ['latitude_of_center', 'Latitude_Of_Center'],
            ['latitude_of_center', 'Latitude_of_center'],
            ['lat0', 'latitude_of_center', util_js_1.d2r],
            ['longitude_of_center', 'Longitude_Of_Center'],
            ['longitude_of_center', 'Longitude_of_center'],
            ['longc', 'longitude_of_center', util_js_1.d2r],
            ['x0', 'false_easting', toMeter],
            ['y0', 'false_northing', toMeter],
            ['long0', 'central_meridian', util_js_1.d2r],
            ['lat0', 'latitude_of_origin', util_js_1.d2r],
            ['lat0', 'standard_parallel_1', util_js_1.d2r],
            ['lat1', 'standard_parallel_1', util_js_1.d2r],
            ['lat2', 'standard_parallel_2', util_js_1.d2r],
            ['azimuth', 'Azimuth'],
            ['alpha', 'azimuth', util_js_1.d2r],
            ['srsCode', 'name']
        ];
        list.forEach(renamer);
        (0, util_js_1.applyProjectionDefaults)(wkt);
    }
    function default_1(wkt) {
        if (typeof wkt === 'object') {
            return (0, transformPROJJSON_js_1.transformPROJJSON)(wkt);
        }
        const version = (0, detectWKTVersion_js_1.detectWKTVersion)(wkt);
        var lisp = (0, parser_js_1.default)(wkt);
        if (version === 'WKT2') {
            const projjson = (0, buildPROJJSON_js_1.buildPROJJSON)(lisp);
            return (0, transformPROJJSON_js_1.transformPROJJSON)(projjson);
        }
        var type = lisp[0];
        var obj = {};
        (0, process_js_1.sExpr)(lisp, obj);
        cleanWKT(obj);
        return obj[type];
    }
},
/* wkt-parser/buildPROJJSON.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.buildPROJJSON = buildPROJJSON;
    const tslib_1 = require(1) /* tslib */;
    const PROJJSONBuilder_js_1 = tslib_1.__importDefault(require(162) /* ./PROJJSONBuilder.js */);
    /**
     * Builds a PROJJSON object from a WKT array structure.
     * @param {Array} root The root WKT array node.
     * @returns {Object} The PROJJSON object.
     */
    function buildPROJJSON(root) {
        return PROJJSONBuilder_js_1.default.convert(root);
    }
},
/* wkt-parser/PROJJSONBuilder.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    class PROJJSONBuilderBase {
        static getId(node) {
            const idNode = node.find((child) => Array.isArray(child) && child[0] === 'ID');
            if (idNode && idNode.length >= 3) {
                return {
                    authority: idNode[1],
                    code: parseInt(idNode[2], 10),
                };
            }
            return null;
        }
        static convertUnit(node, type = 'unit') {
            if (!node || node.length < 3) {
                return { type, name: 'unknown', conversion_factor: null };
            }
            const name = node[1];
            const conversionFactor = parseFloat(node[2]) || null;
            const idNode = node.find((child) => Array.isArray(child) && child[0] === 'ID');
            const id = idNode
                ? {
                    authority: idNode[1],
                    code: parseInt(idNode[2], 10),
                }
                : null;
            return {
                type,
                name,
                conversion_factor: conversionFactor,
                id,
            };
        }
        static convertAxis(node) {
            const name = node[1] || 'Unknown';
            // Determine the direction
            let direction;
            const abbreviationMatch = name.match(/^\((.)\)$/); // Match abbreviations like "(E)" or "(N)"
            if (abbreviationMatch) {
                // Use the abbreviation to determine the direction
                const abbreviation = abbreviationMatch[1].toUpperCase();
                if (abbreviation === 'E')
                    direction = 'east';
                else if (abbreviation === 'N')
                    direction = 'north';
                else if (abbreviation === 'U')
                    direction = 'up';
                else if (node[2])
                    direction = node[2];
                else
                    throw new Error(`Unknown axis abbreviation: ${abbreviation}`);
            }
            else {
                // Use the explicit direction provided in the AXIS node
                direction = node[2] || 'unknown';
            }
            const orderNode = node.find((child) => Array.isArray(child) && child[0] === 'ORDER');
            const order = orderNode ? parseInt(orderNode[1], 10) : null;
            const unitNode = node.find((child) => Array.isArray(child) &&
                (child[0] === 'LENGTHUNIT' || child[0] === 'ANGLEUNIT' || child[0] === 'SCALEUNIT'));
            const unit = this.convertUnit(unitNode);
            return {
                name,
                direction, // Use the valid PROJJSON direction value
                unit,
                order,
            };
        }
        static extractAxes(node) {
            return node
                .filter((child) => Array.isArray(child) && child[0] === 'AXIS')
                .map((axis) => this.convertAxis(axis))
                .sort((a, b) => (a.order || 0) - (b.order || 0)); // Sort by the "order" property
        }
        static convert(node, result = {}) {
            switch (node[0]) {
                case 'PROJCRS':
                    result.type = 'ProjectedCRS';
                    result.name = node[1];
                    result.base_crs = node.find((child) => Array.isArray(child) && child[0] === 'BASEGEOGCRS')
                        ? this.convert(node.find((child) => Array.isArray(child) && child[0] === 'BASEGEOGCRS'))
                        : null;
                    result.conversion = node.find((child) => Array.isArray(child) && child[0] === 'CONVERSION')
                        ? this.convert(node.find((child) => Array.isArray(child) && child[0] === 'CONVERSION'))
                        : null;
                    const csNode = node.find((child) => Array.isArray(child) && child[0] === 'CS');
                    if (csNode) {
                        result.coordinate_system = {
                            subtype: csNode[1],
                            axis: this.extractAxes(node),
                        };
                    }
                    const lengthUnitNode = node.find((child) => Array.isArray(child) && child[0] === 'LENGTHUNIT');
                    if (lengthUnitNode) {
                        const unit = this.convertUnit(lengthUnitNode);
                        result.coordinate_system.unit = unit; // Add unit to coordinate_system
                    }
                    result.id = this.getId(node);
                    break;
                case 'BASEGEOGCRS':
                case 'GEOGCRS':
                case 'GEODCRS':
                    result.type = node[0] === 'GEODCRS' ? 'GeodeticCRS' : 'GeographicCRS';
                    result.name = node[1];
                    // Handle DATUM or ENSEMBLE
                    const datumOrEnsembleNode = node.find((child) => Array.isArray(child) && (child[0] === 'DATUM' || child[0] === 'ENSEMBLE'));
                    if (datumOrEnsembleNode) {
                        const datumOrEnsemble = this.convert(datumOrEnsembleNode);
                        if (datumOrEnsembleNode[0] === 'ENSEMBLE') {
                            result.datum_ensemble = datumOrEnsemble;
                        }
                        else {
                            result.datum = datumOrEnsemble;
                        }
                        const primem = node.find((child) => Array.isArray(child) && child[0] === 'PRIMEM');
                        if (primem && primem[1] !== 'Greenwich') {
                            datumOrEnsemble.prime_meridian = {
                                name: primem[1],
                                longitude: parseFloat(primem[2]),
                            };
                        }
                    }
                    const geogCsNode = node.find((child) => Array.isArray(child) && child[0] === 'CS');
                    result.coordinate_system = {
                        subtype: geogCsNode ? geogCsNode[1] : 'ellipsoidal',
                        axis: this.extractAxes(node),
                    };
                    result.id = this.getId(node);
                    break;
                case 'DATUM':
                    result.type = 'GeodeticReferenceFrame';
                    result.name = node[1];
                    result.ellipsoid = node.find((child) => Array.isArray(child) && child[0] === 'ELLIPSOID')
                        ? this.convert(node.find((child) => Array.isArray(child) && child[0] === 'ELLIPSOID'))
                        : null;
                    break;
                case 'ENSEMBLE':
                    result.type = 'DatumEnsemble';
                    result.name = node[1];
                    // Extract ensemble members
                    result.members = node
                        .filter((child) => Array.isArray(child) && child[0] === 'MEMBER')
                        .map((member) => ({
                        type: 'DatumEnsembleMember',
                        name: member[1],
                        id: this.getId(member), // Extract ID as { authority, code }
                    }));
                    // Extract accuracy
                    const accuracyNode = node.find((child) => Array.isArray(child) && child[0] === 'ENSEMBLEACCURACY');
                    if (accuracyNode) {
                        result.accuracy = parseFloat(accuracyNode[1]);
                    }
                    // Extract ellipsoid
                    const ellipsoidNode = node.find((child) => Array.isArray(child) && child[0] === 'ELLIPSOID');
                    if (ellipsoidNode) {
                        result.ellipsoid = this.convert(ellipsoidNode); // Convert the ellipsoid node
                    }
                    // Extract identifier for the ensemble
                    result.id = this.getId(node);
                    break;
                case 'ELLIPSOID':
                    result.type = 'Ellipsoid';
                    result.name = node[1];
                    result.semi_major_axis = parseFloat(node[2]);
                    result.inverse_flattening = parseFloat(node[3]);
                    const units = node.find((child) => Array.isArray(child) && child[0] === 'LENGTHUNIT')
                        ? this.convert(node.find((child) => Array.isArray(child) && child[0] === 'LENGTHUNIT'), result)
                        : null;
                    break;
                case 'CONVERSION':
                    result.type = 'Conversion';
                    result.name = node[1];
                    result.method = node.find((child) => Array.isArray(child) && child[0] === 'METHOD')
                        ? this.convert(node.find((child) => Array.isArray(child) && child[0] === 'METHOD'))
                        : null;
                    result.parameters = node
                        .filter((child) => Array.isArray(child) && child[0] === 'PARAMETER')
                        .map((param) => this.convert(param));
                    break;
                case 'METHOD':
                    result.type = 'Method';
                    result.name = node[1];
                    result.id = this.getId(node);
                    break;
                case 'PARAMETER':
                    result.type = 'Parameter';
                    result.name = node[1];
                    result.value = parseFloat(node[2]);
                    result.unit = this.convertUnit(node.find((child) => Array.isArray(child) &&
                        (child[0] === 'LENGTHUNIT' || child[0] === 'ANGLEUNIT' || child[0] === 'SCALEUNIT')));
                    result.id = this.getId(node);
                    break;
                case 'BOUNDCRS':
                    result.type = 'BoundCRS';
                    // Process SOURCECRS
                    const sourceCrsNode = node.find((child) => Array.isArray(child) && child[0] === 'SOURCECRS');
                    if (sourceCrsNode) {
                        const sourceCrsContent = sourceCrsNode.find((child) => Array.isArray(child));
                        result.source_crs = sourceCrsContent ? this.convert(sourceCrsContent) : null;
                    }
                    // Process TARGETCRS
                    const targetCrsNode = node.find((child) => Array.isArray(child) && child[0] === 'TARGETCRS');
                    if (targetCrsNode) {
                        const targetCrsContent = targetCrsNode.find((child) => Array.isArray(child));
                        result.target_crs = targetCrsContent ? this.convert(targetCrsContent) : null;
                    }
                    // Process ABRIDGEDTRANSFORMATION
                    const transformationNode = node.find((child) => Array.isArray(child) && child[0] === 'ABRIDGEDTRANSFORMATION');
                    if (transformationNode) {
                        result.transformation = this.convert(transformationNode);
                    }
                    else {
                        result.transformation = null;
                    }
                    break;
                case 'ABRIDGEDTRANSFORMATION':
                    result.type = 'Transformation';
                    result.name = node[1];
                    result.method = node.find((child) => Array.isArray(child) && child[0] === 'METHOD')
                        ? this.convert(node.find((child) => Array.isArray(child) && child[0] === 'METHOD'))
                        : null;
                    result.parameters = node
                        .filter((child) => Array.isArray(child) && (child[0] === 'PARAMETER' || child[0] === 'PARAMETERFILE'))
                        .map((param) => {
                        if (param[0] === 'PARAMETER') {
                            return this.convert(param);
                        }
                        else if (param[0] === 'PARAMETERFILE') {
                            return {
                                name: param[1],
                                value: param[2],
                                id: {
                                    'authority': 'EPSG',
                                    'code': 8656
                                }
                            };
                        }
                    });
                    // Adjust the Scale difference parameter if present
                    if (result.parameters.length === 7) {
                        const scaleDifference = result.parameters[6];
                        if (scaleDifference.name === 'Scale difference') {
                            scaleDifference.value = Math.round((scaleDifference.value - 1) * 1e12) / 1e6;
                        }
                    }
                    result.id = this.getId(node);
                    break;
                case 'AXIS':
                    if (!result.coordinate_system) {
                        result.coordinate_system = { type: 'unspecified', axis: [] };
                    }
                    result.coordinate_system.axis.push(this.convertAxis(node));
                    break;
                case 'LENGTHUNIT':
                    const unit = this.convertUnit(node, 'LinearUnit');
                    if (result.coordinate_system && result.coordinate_system.axis) {
                        result.coordinate_system.axis.forEach((axis) => {
                            if (!axis.unit) {
                                axis.unit = unit;
                            }
                        });
                    }
                    if (unit.conversion_factor && unit.conversion_factor !== 1) {
                        if (result.semi_major_axis) {
                            result.semi_major_axis = {
                                value: result.semi_major_axis,
                                unit,
                            };
                        }
                    }
                    break;
                default:
                    result.keyword = node[0];
                    break;
            }
            return result;
        }
    }
    exports.default = PROJJSONBuilderBase;
},
/* wkt-parser/detectWKTVersion.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.detectWKTVersion = detectWKTVersion;
    /**
     * Detects whether the WKT string is WKT1 or WKT2.
     * @param {string} wkt The WKT string.
     * @returns {string} The detected version ("WKT1" or "WKT2").
     */
    function detectWKTVersion(wkt) {
        // Normalize the WKT string for easier keyword matching
        const normalizedWKT = wkt.toUpperCase();
        // Check for WKT2-specific keywords
        if (normalizedWKT.includes('PROJCRS') ||
            normalizedWKT.includes('GEOGCRS') ||
            normalizedWKT.includes('BOUNDCRS') ||
            normalizedWKT.includes('VERTCRS') ||
            normalizedWKT.includes('LENGTHUNIT') ||
            normalizedWKT.includes('ANGLEUNIT') ||
            normalizedWKT.includes('SCALEUNIT')) {
            return 'WKT2';
        }
        // Check for WKT1-specific keywords
        if (normalizedWKT.includes('PROJCS') ||
            normalizedWKT.includes('GEOGCS') ||
            normalizedWKT.includes('LOCAL_CS') ||
            normalizedWKT.includes('VERT_CS') ||
            normalizedWKT.includes('UNIT')) {
            return 'WKT1';
        }
        // Default to WKT1 if no specific indicators are found
        return 'WKT1';
    }
},
/* wkt-parser/parser.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = parseString;
    var NEUTRAL = 1;
    var KEYWORD = 2;
    var NUMBER = 3;
    var QUOTED = 4;
    var AFTERQUOTE = 5;
    var ENDED = -1;
    var whitespace = /\s/;
    var latin = /[A-Za-z]/;
    var keyword = /[A-Za-z84_]/;
    var endThings = /[,\]]/;
    var digets = /[\d\.E\-\+]/;
    // const ignoredChar = /[\s_\-\/\(\)]/g;
    function Parser(text) {
        if (typeof text !== 'string') {
            throw new Error('not a string');
        }
        this.text = text.trim();
        this.level = 0;
        this.place = 0;
        this.root = null;
        this.stack = [];
        this.currentObject = null;
        this.state = NEUTRAL;
    }
    Parser.prototype.readCharicter = function () {
        var char = this.text[this.place++];
        if (this.state !== QUOTED) {
            while (whitespace.test(char)) {
                if (this.place >= this.text.length) {
                    return;
                }
                char = this.text[this.place++];
            }
        }
        switch (this.state) {
            case NEUTRAL:
                return this.neutral(char);
            case KEYWORD:
                return this.keyword(char);
            case QUOTED:
                return this.quoted(char);
            case AFTERQUOTE:
                return this.afterquote(char);
            case NUMBER:
                return this.number(char);
            case ENDED:
                return;
        }
    };
    Parser.prototype.afterquote = function (char) {
        if (char === '"') {
            this.word += '"';
            this.state = QUOTED;
            return;
        }
        if (endThings.test(char)) {
            this.word = this.word.trim();
            this.afterItem(char);
            return;
        }
        throw new Error('havn\'t handled "' + char + '" in afterquote yet, index ' + this.place);
    };
    Parser.prototype.afterItem = function (char) {
        if (char === ',') {
            if (this.word !== null) {
                this.currentObject.push(this.word);
            }
            this.word = null;
            this.state = NEUTRAL;
            return;
        }
        if (char === ']') {
            this.level--;
            if (this.word !== null) {
                this.currentObject.push(this.word);
                this.word = null;
            }
            this.state = NEUTRAL;
            this.currentObject = this.stack.pop();
            if (!this.currentObject) {
                this.state = ENDED;
            }
            return;
        }
    };
    Parser.prototype.number = function (char) {
        if (digets.test(char)) {
            this.word += char;
            return;
        }
        if (endThings.test(char)) {
            this.word = parseFloat(this.word);
            this.afterItem(char);
            return;
        }
        throw new Error('havn\'t handled "' + char + '" in number yet, index ' + this.place);
    };
    Parser.prototype.quoted = function (char) {
        if (char === '"') {
            this.state = AFTERQUOTE;
            return;
        }
        this.word += char;
        return;
    };
    Parser.prototype.keyword = function (char) {
        if (keyword.test(char)) {
            this.word += char;
            return;
        }
        if (char === '[') {
            var newObjects = [];
            newObjects.push(this.word);
            this.level++;
            if (this.root === null) {
                this.root = newObjects;
            }
            else {
                this.currentObject.push(newObjects);
            }
            this.stack.push(this.currentObject);
            this.currentObject = newObjects;
            this.state = NEUTRAL;
            return;
        }
        if (endThings.test(char)) {
            this.afterItem(char);
            return;
        }
        throw new Error('havn\'t handled "' + char + '" in keyword yet, index ' + this.place);
    };
    Parser.prototype.neutral = function (char) {
        if (latin.test(char)) {
            this.word = char;
            this.state = KEYWORD;
            return;
        }
        if (char === '"') {
            this.word = '';
            this.state = QUOTED;
            return;
        }
        if (digets.test(char)) {
            this.word = char;
            this.state = NUMBER;
            return;
        }
        if (endThings.test(char)) {
            this.afterItem(char);
            return;
        }
        throw new Error('havn\'t handled "' + char + '" in neutral yet, index ' + this.place);
    };
    Parser.prototype.output = function () {
        while (this.place < this.text.length) {
            this.readCharicter();
        }
        if (this.state === ENDED) {
            return this.root;
        }
        throw new Error('unable to parse string "' + this.text + '". State is ' + this.state);
    };
    function parseString(txt) {
        var parser = new Parser(txt);
        return parser.output();
    }
},
/* wkt-parser/process.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.sExpr = sExpr;
    function mapit(obj, key, value) {
        if (Array.isArray(key)) {
            value.unshift(key);
            key = null;
        }
        var thing = key ? {} : obj;
        var out = value.reduce(function (newObj, item) {
            sExpr(item, newObj);
            return newObj;
        }, thing);
        if (key) {
            obj[key] = out;
        }
    }
    function sExpr(v, obj) {
        if (!Array.isArray(v)) {
            obj[v] = true;
            return;
        }
        var key = v.shift();
        if (key === 'PARAMETER') {
            key = v.shift();
        }
        if (v.length === 1) {
            if (Array.isArray(v[0])) {
                obj[key] = {};
                sExpr(v[0], obj[key]);
                return;
            }
            obj[key] = v[0];
            return;
        }
        if (!v.length) {
            obj[key] = true;
            return;
        }
        if (key === 'TOWGS84') {
            obj[key] = v;
            return;
        }
        if (key === 'AXIS') {
            if (!(key in obj)) {
                obj[key] = [];
            }
            obj[key].push(v);
            return;
        }
        if (!Array.isArray(key)) {
            obj[key] = {};
        }
        var i;
        switch (key) {
            case 'UNIT':
            case 'PRIMEM':
            case 'VERT_DATUM':
                obj[key] = {
                    name: v[0].toLowerCase(),
                    convert: v[1]
                };
                if (v.length === 3) {
                    sExpr(v[2], obj[key]);
                }
                return;
            case 'SPHEROID':
            case 'ELLIPSOID':
                obj[key] = {
                    name: v[0],
                    a: v[1],
                    rf: v[2]
                };
                if (v.length === 4) {
                    sExpr(v[3], obj[key]);
                }
                return;
            case 'EDATUM':
            case 'ENGINEERINGDATUM':
            case 'LOCAL_DATUM':
            case 'DATUM':
            case 'VERT_CS':
            case 'VERTCRS':
            case 'VERTICALCRS':
                v[0] = ['name', v[0]];
                mapit(obj, key, v);
                return;
            case 'COMPD_CS':
            case 'COMPOUNDCRS':
            case 'FITTED_CS':
            // the followings are the crs defined in
            // https://github.com/proj4js/proj4js/blob/1da4ed0b865d0fcb51c136090569210cdcc9019e/lib/parseCode.js#L11
            case 'PROJECTEDCRS':
            case 'PROJCRS':
            case 'GEOGCS':
            case 'GEOCCS':
            case 'PROJCS':
            case 'LOCAL_CS':
            case 'GEODCRS':
            case 'GEODETICCRS':
            case 'GEODETICDATUM':
            case 'ENGCRS':
            case 'ENGINEERINGCRS':
                v[0] = ['name', v[0]];
                mapit(obj, key, v);
                obj[key].type = key;
                return;
            default:
                i = -1;
                while (++i < v.length) {
                    if (!Array.isArray(v[i])) {
                        return sExpr(v, obj[key]);
                    }
                }
                return mapit(obj, key, v);
        }
    }
},
/* wkt-parser/transformPROJJSON.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.transformPROJJSON = transformPROJJSON;
    const util_js_1 = require(167) /* ./util.js */;
    // Helper function to process units and to_meter
    function processUnit(unit) {
        let result = { units: null, to_meter: undefined };
        if (typeof unit === 'string') {
            result.units = unit.toLowerCase();
            if (result.units === 'metre') {
                result.units = 'meter'; // Normalize 'metre' to 'meter'
            }
            if (result.units === 'meter') {
                result.to_meter = 1; // Only set to_meter if units are 'meter'
            }
        }
        else if (unit && unit.name) {
            result.units = unit.name.toLowerCase();
            if (result.units === 'metre') {
                result.units = 'meter'; // Normalize 'metre' to 'meter'
            }
            result.to_meter = unit.conversion_factor;
        }
        return result;
    }
    function toValue(valueOrObject) {
        if (typeof valueOrObject === 'object') {
            return valueOrObject.value * valueOrObject.unit.conversion_factor;
        }
        return valueOrObject;
    }
    function calculateEllipsoid(value, result) {
        if (value.ellipsoid.radius) {
            result.a = value.ellipsoid.radius;
            result.rf = 0;
        }
        else {
            result.a = toValue(value.ellipsoid.semi_major_axis);
            if (value.ellipsoid.inverse_flattening !== undefined) {
                result.rf = value.ellipsoid.inverse_flattening;
            }
            else if (value.ellipsoid.semi_major_axis !== undefined && value.ellipsoid.semi_minor_axis !== undefined) {
                result.rf = result.a / (result.a - toValue(value.ellipsoid.semi_minor_axis));
            }
        }
    }
    function transformPROJJSON(projjson, result = {}) {
        if (!projjson || typeof projjson !== 'object') {
            return projjson; // Return primitive values as-is
        }
        if (projjson.type === 'BoundCRS') {
            transformPROJJSON(projjson.source_crs, result);
            if (projjson.transformation) {
                if (projjson.transformation.method && projjson.transformation.method.name === 'NTv2') {
                    // Set nadgrids to the filename from the parameterfile
                    result.nadgrids = projjson.transformation.parameters[0].value;
                }
                else {
                    // Populate datum_params if no parameterfile is found
                    result.datum_params = projjson.transformation.parameters.map((param) => param.value);
                }
            }
            return result; // Return early for BoundCRS
        }
        // Handle specific keys in PROJJSON
        Object.keys(projjson).forEach((key) => {
            const value = projjson[key];
            if (value === null) {
                return;
            }
            switch (key) {
                case 'name':
                    if (result.srsCode) {
                        break;
                    }
                    result.name = value;
                    result.srsCode = value; // Map `name` to `srsCode`
                    break;
                case 'type':
                    if (value === 'GeographicCRS') {
                        result.projName = 'longlat';
                    }
                    else if (value === 'GeodeticCRS') {
                        if (projjson.coordinate_system && projjson.coordinate_system.subtype === 'Cartesian') {
                            result.projName = 'geocent';
                        }
                        else {
                            result.projName = 'longlat';
                        }
                    }
                    else if (value === 'ProjectedCRS' && projjson.conversion && projjson.conversion.method) {
                        result.projName = projjson.conversion.method.name; // Retain original capitalization
                    }
                    break;
                case 'datum':
                case 'datum_ensemble': // Handle both datum and ensemble
                    if (value.ellipsoid) {
                        // Extract ellipsoid properties
                        result.ellps = value.ellipsoid.name;
                        calculateEllipsoid(value, result);
                    }
                    if (value.prime_meridian) {
                        result.from_greenwich = value.prime_meridian.longitude * Math.PI / 180; // Convert to radians
                    }
                    break;
                case 'ellipsoid':
                    result.ellps = value.name;
                    calculateEllipsoid(value, result);
                    break;
                case 'prime_meridian':
                    result.long0 = (value.longitude || 0) * Math.PI / 180; // Convert to radians
                    break;
                case 'coordinate_system':
                    if (value.axis) {
                        const directionMap = {
                            'east': 'e',
                            'north': 'n',
                            'west': 'w',
                            'south': 's',
                            'up': 'u',
                            'down': 'd',
                            'geocentricx': 'e',
                            'geocentricy': 'n',
                            'geocentricz': 'u',
                        };
                        const mapped = value.axis.map((axis) => directionMap[axis.direction.toLowerCase()]);
                        if (mapped.every(Boolean)) {
                            result.axis = mapped.join('');
                            if (result.axis.length === 2) {
                                result.axis += 'u';
                            }
                        }
                        if (value.unit) {
                            const { units, to_meter } = processUnit(value.unit);
                            result.units = units;
                            result.to_meter = to_meter;
                        }
                        else if (value.axis[0] && value.axis[0].unit) {
                            const { units, to_meter } = processUnit(value.axis[0].unit);
                            result.units = units;
                            result.to_meter = to_meter;
                        }
                    }
                    break;
                case 'id':
                    if (value.authority && value.code) {
                        result.title = value.authority + ':' + value.code;
                    }
                    break;
                case 'conversion':
                    if (value.method && value.method.name) {
                        result.projName = value.method.name; // Retain original capitalization
                    }
                    if (value.parameters) {
                        value.parameters.forEach((param) => {
                            const paramName = param.name.toLowerCase().replace(/\s+/g, '_');
                            const paramValue = param.value;
                            if (param.unit && param.unit.conversion_factor) {
                                result[paramName] = paramValue * param.unit.conversion_factor; // Convert to radians or meters
                            }
                            else if (param.unit === 'degree') {
                                result[paramName] = paramValue * Math.PI / 180; // Convert to radians
                            }
                            else {
                                result[paramName] = paramValue;
                            }
                        });
                    }
                    break;
                case 'unit':
                    if (value.name) {
                        result.units = value.name.toLowerCase();
                        if (result.units === 'metre') {
                            result.units = 'meter';
                        }
                    }
                    if (value.conversion_factor) {
                        result.to_meter = value.conversion_factor;
                    }
                    break;
                case 'base_crs':
                    transformPROJJSON(value, result); // Pass `result` directly
                    result.datumCode = value.id ? value.id.authority + '_' + value.id.code : value.name; // Set datumCode
                    break;
                default:
                    // Ignore irrelevant or unneeded properties
                    break;
            }
        });
        // Additional calculated properties
        if (result.latitude_of_false_origin !== undefined) {
            result.lat0 = result.latitude_of_false_origin; // Already in radians
        }
        if (result.longitude_of_false_origin !== undefined) {
            result.long0 = result.longitude_of_false_origin;
        }
        if (result.latitude_of_standard_parallel !== undefined) {
            result.lat0 = result.latitude_of_standard_parallel;
            result.lat1 = result.latitude_of_standard_parallel;
        }
        if (result.latitude_of_1st_standard_parallel !== undefined) {
            result.lat1 = result.latitude_of_1st_standard_parallel;
        }
        if (result.latitude_of_2nd_standard_parallel !== undefined) {
            result.lat2 = result.latitude_of_2nd_standard_parallel;
        }
        if (result.latitude_of_projection_centre !== undefined) {
            result.lat0 = result.latitude_of_projection_centre;
        }
        if (result.longitude_of_projection_centre !== undefined) {
            result.longc = result.longitude_of_projection_centre;
        }
        if (result.easting_at_false_origin !== undefined) {
            result.x0 = result.easting_at_false_origin;
        }
        if (result.northing_at_false_origin !== undefined) {
            result.y0 = result.northing_at_false_origin;
        }
        if (result.latitude_of_natural_origin !== undefined) {
            result.lat0 = result.latitude_of_natural_origin;
        }
        if (result.longitude_of_natural_origin !== undefined) {
            result.long0 = result.longitude_of_natural_origin;
        }
        if (result.longitude_of_origin !== undefined) {
            result.long0 = result.longitude_of_origin;
        }
        if (result.false_easting !== undefined) {
            result.x0 = result.false_easting;
        }
        if (result.easting_at_projection_centre) {
            result.x0 = result.easting_at_projection_centre;
        }
        if (result.false_northing !== undefined) {
            result.y0 = result.false_northing;
        }
        if (result.northing_at_projection_centre) {
            result.y0 = result.northing_at_projection_centre;
        }
        if (result.standard_parallel_1 !== undefined) {
            result.lat1 = result.standard_parallel_1;
        }
        if (result.standard_parallel_2 !== undefined) {
            result.lat2 = result.standard_parallel_2;
        }
        if (result.scale_factor_at_natural_origin !== undefined) {
            result.k0 = result.scale_factor_at_natural_origin;
        }
        if (result.scale_factor_at_projection_centre !== undefined) {
            result.k0 = result.scale_factor_at_projection_centre;
        }
        if (result.scale_factor_on_pseudo_standard_parallel !== undefined) {
            result.k0 = result.scale_factor_on_pseudo_standard_parallel;
        }
        if (result.azimuth !== undefined) {
            result.alpha = result.azimuth;
        }
        if (result.azimuth_at_projection_centre !== undefined) {
            result.alpha = result.azimuth_at_projection_centre;
        }
        if (result.angle_from_rectified_to_skew_grid) {
            result.rectified_grid_angle = result.angle_from_rectified_to_skew_grid;
        }
        // Apply projection defaults
        (0, util_js_1.applyProjectionDefaults)(result);
        return result;
    }
},
/* wkt-parser/util.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.d2r = d2r;
    exports.applyProjectionDefaults = applyProjectionDefaults;
    var D2R = 0.01745329251994329577;
    function d2r(input) {
        return input * D2R;
    }
    function applyProjectionDefaults(wkt) {
        // Normalize projName for WKT2 compatibility
        const normalizedProjName = (wkt.projName || '').toLowerCase().replace(/_/g, ' ');
        if (wkt.long0 === undefined && wkt.longc !== undefined) {
            wkt.long0 = wkt.longc; // keep in the projection's native prime meridian frame
        }
        if (!wkt.lat_ts && wkt.lat1 && (normalizedProjName === 'stereographic south pole' || normalizedProjName === 'polar stereographic (variant b)')) {
            wkt.lat0 = d2r(wkt.lat1 > 0 ? 90 : -90);
            wkt.lat_ts = wkt.lat1;
            delete wkt.lat1;
        }
        else if (!wkt.lat_ts && wkt.lat0 && (normalizedProjName === 'polar stereographic' || normalizedProjName === 'polar stereographic (variant a)')) {
            wkt.lat_ts = wkt.lat0;
            wkt.lat0 = d2r(wkt.lat0 > 0 ? 90 : -90);
            delete wkt.lat1;
        }
    }
},
/* proj4/lib/extend.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(destination, source) {
        destination = destination || {};
        var value, property;
        if (!source) {
            return destination;
        }
        for (property in source) {
            value = source[property];
            if (value !== undefined) {
                destination[property] = value;
            }
        }
        return destination;
    }
},
/* proj4/lib/projections.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.add = add;
    exports.getNormalizedProjName = getNormalizedProjName;
    exports.get = get;
    exports.start = start;
    const tslib_1 = require(1) /* tslib */;
    const merc_1 = tslib_1.__importDefault(require(170) /* ./projections/merc */);
    const longlat_1 = tslib_1.__importDefault(require(176) /* ./projections/longlat */);
    /** @type {Array<Partial<import('./Proj').default>>} */
    var projs = [merc_1.default, longlat_1.default];
    var names = {};
    var projStore = [];
    /**
     * @param {import('./Proj').default} proj
     * @param {number} i
     */
    function add(proj, i) {
        var len = projStore.length;
        if (!proj.names) {
            console.log(i);
            return true;
        }
        projStore[len] = proj;
        proj.names.forEach(function (n) {
            names[n.toLowerCase()] = len;
        });
        return this;
    }
    function getNormalizedProjName(n) {
        return n.replace(/[-\(\)\s]+/g, ' ').trim().replace(/ /g, '_');
    }
    /**
     * Get a projection by name.
     * @param {string} name
     * @returns {import('./Proj').default|false}
     */
    function get(name) {
        if (!name) {
            return false;
        }
        var n = name.toLowerCase();
        if (typeof names[n] !== 'undefined' && projStore[names[n]]) {
            return projStore[names[n]];
        }
        n = getNormalizedProjName(n);
        if (n in names && projStore[names[n]]) {
            return projStore[names[n]];
        }
    }
    function start() {
        projs.forEach(add);
    }
    exports.default = {
        start: start,
        add: add,
        get: get
    };
},
/* proj4/lib/projections/merc.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const msfnz_1 = tslib_1.__importDefault(require(171) /* ../common/msfnz */);
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    const tsfnz_1 = tslib_1.__importDefault(require(174) /* ../common/tsfnz */);
    const phi2z_1 = tslib_1.__importDefault(require(175) /* ../common/phi2z */);
    const values_1 = require(156) /* ../constants/values */;
    /**
     * @typedef {Object} LocalThis
     * @property {number} es
     * @property {number} e
     * @property {number} k
     */
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function init() {
        var con = this.b / this.a;
        this.es = 1 - con * con;
        if (!('x0' in this)) {
            this.x0 = 0;
        }
        if (!('y0' in this)) {
            this.y0 = 0;
        }
        this.e = Math.sqrt(this.es);
        if (this.lat_ts) {
            if (this.sphere) {
                this.k0 = Math.cos(this.lat_ts);
            }
            else {
                this.k0 = (0, msfnz_1.default)(this.e, Math.sin(this.lat_ts), Math.cos(this.lat_ts));
            }
        }
        else {
            if (!this.k0) {
                if (this.k) {
                    this.k0 = this.k;
                }
                else {
                    this.k0 = 1;
                }
            }
        }
    }
    /* Mercator forward equations--mapping lat,long to x,y
      -------------------------------------------------- */
    function forward(p) {
        var lon = p.x;
        var lat = p.y;
        // convert to radians
        if (lat * values_1.R2D > 90 && lat * values_1.R2D < -90 && lon * values_1.R2D > 180 && lon * values_1.R2D < -180) {
            return null;
        }
        var x, y;
        if (Math.abs(Math.abs(lat) - values_1.HALF_PI) <= values_1.EPSLN) {
            return null;
        }
        else {
            if (this.sphere) {
                x = this.x0 + this.a * this.k0 * (0, adjust_lon_1.default)(lon - this.long0, this.over);
                y = this.y0 + this.a * this.k0 * Math.log(Math.tan(values_1.FORTPI + 0.5 * lat));
            }
            else {
                var sinphi = Math.sin(lat);
                var ts = (0, tsfnz_1.default)(this.e, lat, sinphi);
                x = this.x0 + this.a * this.k0 * (0, adjust_lon_1.default)(lon - this.long0, this.over);
                y = this.y0 - this.a * this.k0 * Math.log(ts);
            }
            p.x = x;
            p.y = y;
            return p;
        }
    }
    /* Mercator inverse equations--mapping x,y to lat/long
      -------------------------------------------------- */
    function inverse(p) {
        var x = p.x - this.x0;
        var y = p.y - this.y0;
        var lon, lat;
        if (this.sphere) {
            lat = values_1.HALF_PI - 2 * Math.atan(Math.exp(-y / (this.a * this.k0)));
        }
        else {
            var ts = Math.exp(-y / (this.a * this.k0));
            lat = (0, phi2z_1.default)(this.e, ts);
            if (lat === -9999) {
                return null;
            }
        }
        lon = (0, adjust_lon_1.default)(this.long0 + x / (this.a * this.k0), this.over);
        p.x = lon;
        p.y = lat;
        return p;
    }
    exports.names = ['Mercator', 'Popular Visualisation Pseudo Mercator', 'Mercator_1SP', 'Mercator_Auxiliary_Sphere', 'Mercator_Variant_A', 'merc'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/common/msfnz.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(eccent, sinphi, cosphi) {
        var con = eccent * sinphi;
        return cosphi / (Math.sqrt(1 - con * con));
    }
},
/* proj4/lib/common/adjust_lon.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    const tslib_1 = require(1) /* tslib */;
    const values_1 = require(156) /* ../constants/values */;
    const sign_1 = tslib_1.__importDefault(require(173) /* ./sign */);
    function default_1(x, skipAdjust) {
        if (skipAdjust) {
            return x;
        }
        return (Math.abs(x) <= values_1.SPI) ? x : (x - ((0, sign_1.default)(x) * values_1.TWO_PI));
    }
},
/* proj4/lib/common/sign.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(x) {
        return x < 0 ? -1 : 1;
    }
},
/* proj4/lib/common/tsfnz.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    const values_1 = require(156) /* ../constants/values */;
    function default_1(eccent, phi, sinphi) {
        var con = eccent * sinphi;
        var com = 0.5 * eccent;
        con = Math.pow(((1 - con) / (1 + con)), com);
        return (Math.tan(0.5 * (values_1.HALF_PI - phi)) / con);
    }
},
/* proj4/lib/common/phi2z.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    const values_1 = require(156) /* ../constants/values */;
    function default_1(eccent, ts) {
        var eccnth = 0.5 * eccent;
        var con, dphi;
        var phi = values_1.HALF_PI - 2 * Math.atan(ts);
        for (var i = 0; i <= 15; i++) {
            con = eccent * Math.sin(phi);
            dphi = values_1.HALF_PI - 2 * Math.atan(ts * (Math.pow(((1 - con) / (1 + con)), eccnth))) - phi;
            phi += dphi;
            if (Math.abs(dphi) <= 0.0000000001) {
                return phi;
            }
        }
        // console.log("phi2z has NoConvergence");
        return -9999;
    }
},
/* proj4/lib/projections/longlat.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = identity;
    exports.inverse = identity;
    function init() {
        // no-op for longlat
    }
    function identity(pt) {
        return pt;
    }
    exports.names = ['longlat', 'identity'];
    exports.default = {
        init: init,
        forward: identity,
        inverse: identity,
        names: exports.names
    };
},
/* proj4/lib/deriveConstants.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.eccentricity = eccentricity;
    exports.sphere = sphere;
    const tslib_1 = require(1) /* tslib */;
    const values_1 = require(156) /* ./constants/values */;
    const Ellipsoid_1 = tslib_1.__importDefault(require(178) /* ./constants/Ellipsoid */);
    const match_1 = tslib_1.__importDefault(require(159) /* ./match */);
    const WGS84 = Ellipsoid_1.default.WGS84; // default ellipsoid
    function eccentricity(a, b, rf, R_A) {
        var a2 = a * a; // used in geocentric
        var b2 = b * b; // used in geocentric
        var es = (a2 - b2) / a2; // e ^ 2
        var e = 0;
        if (R_A) {
            a *= 1 - es * (values_1.SIXTH + es * (values_1.RA4 + es * values_1.RA6));
            a2 = a * a;
            es = 0;
        }
        else {
            e = Math.sqrt(es); // eccentricity
        }
        var ep2 = (a2 - b2) / b2; // used in geocentric
        return {
            es: es,
            e: e,
            ep2: ep2
        };
    }
    function sphere(a, b, rf, ellps, sphere) {
        if (!a) { // do we have an ellipsoid?
            var ellipse = (0, match_1.default)(Ellipsoid_1.default, ellps);
            if (!ellipse) {
                ellipse = WGS84;
            }
            a = ellipse.a;
            b = ellipse.b;
            rf = ellipse.rf;
        }
        if (rf && !b) {
            b = (1.0 - 1.0 / rf) * a;
        }
        if (rf === 0 || Math.abs(a - b) < values_1.EPSLN) {
            sphere = true;
            b = a;
        }
        return {
            a: a,
            b: b,
            rf: rf,
            sphere: sphere
        };
    }
},
/* proj4/lib/constants/Ellipsoid.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var ellipsoids = {
        MERIT: {
            a: 6378137,
            rf: 298.257,
            ellipseName: 'MERIT 1983'
        },
        SGS85: {
            a: 6378136,
            rf: 298.257,
            ellipseName: 'Soviet Geodetic System 85'
        },
        GRS80: {
            a: 6378137,
            rf: 298.257222101,
            ellipseName: 'GRS 1980(IUGG, 1980)'
        },
        IAU76: {
            a: 6378140,
            rf: 298.257,
            ellipseName: 'IAU 1976'
        },
        airy: {
            a: 6377563.396,
            b: 6356256.91,
            ellipseName: 'Airy 1830'
        },
        APL4: {
            a: 6378137,
            rf: 298.25,
            ellipseName: 'Appl. Physics. 1965'
        },
        NWL9D: {
            a: 6378145,
            rf: 298.25,
            ellipseName: 'Naval Weapons Lab., 1965'
        },
        mod_airy: {
            a: 6377340.189,
            b: 6356034.446,
            ellipseName: 'Modified Airy'
        },
        andrae: {
            a: 6377104.43,
            rf: 300,
            ellipseName: 'Andrae 1876 (Den., Iclnd.)'
        },
        aust_SA: {
            a: 6378160,
            rf: 298.25,
            ellipseName: 'Australian Natl & S. Amer. 1969'
        },
        GRS67: {
            a: 6378160,
            rf: 298.247167427,
            ellipseName: 'GRS 67(IUGG 1967)'
        },
        bessel: {
            a: 6377397.155,
            rf: 299.1528128,
            ellipseName: 'Bessel 1841'
        },
        bess_nam: {
            a: 6377483.865,
            rf: 299.1528128,
            ellipseName: 'Bessel 1841 (Namibia)'
        },
        clrk66: {
            a: 6378206.4,
            b: 6356583.8,
            ellipseName: 'Clarke 1866'
        },
        clrk80: {
            a: 6378249.145,
            rf: 293.4663,
            ellipseName: 'Clarke 1880 mod.'
        },
        clrk80ign: {
            a: 6378249.2,
            b: 6356515,
            rf: 293.4660213,
            ellipseName: 'Clarke 1880 (IGN)'
        },
        clrk58: {
            a: 6378293.645208759,
            rf: 294.2606763692654,
            ellipseName: 'Clarke 1858'
        },
        CPM: {
            a: 6375738.7,
            rf: 334.29,
            ellipseName: 'Comm. des Poids et Mesures 1799'
        },
        delmbr: {
            a: 6376428,
            rf: 311.5,
            ellipseName: 'Delambre 1810 (Belgium)'
        },
        engelis: {
            a: 6378136.05,
            rf: 298.2566,
            ellipseName: 'Engelis 1985'
        },
        evrst30: {
            a: 6377276.345,
            rf: 300.8017,
            ellipseName: 'Everest 1830'
        },
        evrst48: {
            a: 6377304.063,
            rf: 300.8017,
            ellipseName: 'Everest 1948'
        },
        evrst56: {
            a: 6377301.243,
            rf: 300.8017,
            ellipseName: 'Everest 1956'
        },
        evrst69: {
            a: 6377295.664,
            rf: 300.8017,
            ellipseName: 'Everest 1969'
        },
        evrstSS: {
            a: 6377298.556,
            rf: 300.8017,
            ellipseName: 'Everest (Sabah & Sarawak)'
        },
        fschr60: {
            a: 6378166,
            rf: 298.3,
            ellipseName: 'Fischer (Mercury Datum) 1960'
        },
        fschr60m: {
            a: 6378155,
            rf: 298.3,
            ellipseName: 'Fischer 1960'
        },
        fschr68: {
            a: 6378150,
            rf: 298.3,
            ellipseName: 'Fischer 1968'
        },
        helmert: {
            a: 6378200,
            rf: 298.3,
            ellipseName: 'Helmert 1906'
        },
        hough: {
            a: 6378270,
            rf: 297,
            ellipseName: 'Hough'
        },
        intl: {
            a: 6378388,
            rf: 297,
            ellipseName: 'International 1909 (Hayford)'
        },
        kaula: {
            a: 6378163,
            rf: 298.24,
            ellipseName: 'Kaula 1961'
        },
        lerch: {
            a: 6378139,
            rf: 298.257,
            ellipseName: 'Lerch 1979'
        },
        mprts: {
            a: 6397300,
            rf: 191,
            ellipseName: 'Maupertius 1738'
        },
        new_intl: {
            a: 6378157.5,
            b: 6356772.2,
            ellipseName: 'New International 1967'
        },
        plessis: {
            a: 6376523,
            rf: 6355863,
            ellipseName: 'Plessis 1817 (France)'
        },
        krass: {
            a: 6378245,
            rf: 298.3,
            ellipseName: 'Krassovsky, 1942'
        },
        SEasia: {
            a: 6378155,
            b: 6356773.3205,
            ellipseName: 'Southeast Asia'
        },
        walbeck: {
            a: 6376896,
            b: 6355834.8467,
            ellipseName: 'Walbeck'
        },
        WGS60: {
            a: 6378165,
            rf: 298.3,
            ellipseName: 'WGS 60'
        },
        WGS66: {
            a: 6378145,
            rf: 298.25,
            ellipseName: 'WGS 66'
        },
        WGS7: {
            a: 6378135,
            rf: 298.26,
            ellipseName: 'WGS 72'
        },
        WGS84: {
            a: 6378137,
            rf: 298.257223563,
            ellipseName: 'WGS 84'
        },
        sphere: {
            a: 6370997,
            b: 6370997,
            ellipseName: 'Normal Sphere (r=6370997)'
        }
    };
    exports.default = ellipsoids;
},
/* proj4/lib/constants/Datum.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var datums = {
        wgs84: {
            towgs84: '0,0,0',
            ellipse: 'WGS84',
            datumName: 'WGS84'
        },
        ch1903: {
            towgs84: '674.374,15.056,405.346',
            ellipse: 'bessel',
            datumName: 'swiss'
        },
        ggrs87: {
            towgs84: '-199.87,74.79,246.62',
            ellipse: 'GRS80',
            datumName: 'Greek_Geodetic_Reference_System_1987'
        },
        nad83: {
            towgs84: '0,0,0',
            ellipse: 'GRS80',
            datumName: 'North_American_Datum_1983'
        },
        nad27: {
            nadgrids: '@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat',
            ellipse: 'clrk66',
            datumName: 'North_American_Datum_1927'
        },
        potsdam: {
            towgs84: '598.1,73.7,418.2,0.202,0.045,-2.455,6.7',
            ellipse: 'bessel',
            datumName: 'Potsdam Rauenberg 1950 DHDN'
        },
        carthage: {
            towgs84: '-263.0,6.0,431.0',
            ellipse: 'clark80',
            datumName: 'Carthage 1934 Tunisia'
        },
        hermannskogel: {
            towgs84: '577.326,90.129,463.919,5.137,1.474,5.297,2.4232',
            ellipse: 'bessel',
            datumName: 'Hermannskogel'
        },
        mgi: {
            towgs84: '577.326,90.129,463.919,5.137,1.474,5.297,2.4232',
            ellipse: 'bessel',
            datumName: 'Militar-Geographische Institut'
        },
        osni52: {
            towgs84: '482.530,-130.596,564.557,-1.042,-0.214,-0.631,8.15',
            ellipse: 'airy',
            datumName: 'Irish National'
        },
        ire65: {
            towgs84: '482.530,-130.596,564.557,-1.042,-0.214,-0.631,8.15',
            ellipse: 'mod_airy',
            datumName: 'Ireland 1965'
        },
        rassadiran: {
            towgs84: '-133.63,-157.5,-158.62',
            ellipse: 'intl',
            datumName: 'Rassadiran'
        },
        nzgd49: {
            towgs84: '59.47,-5.04,187.44,0.47,-0.1,1.024,-4.5993',
            ellipse: 'intl',
            datumName: 'New Zealand Geodetic Datum 1949'
        },
        osgb36: {
            towgs84: '446.448,-125.157,542.060,0.1502,0.2470,0.8421,-20.4894',
            ellipse: 'airy',
            datumName: 'Ordnance Survey of Great Britain 1936'
        },
        s_jtsk: {
            towgs84: '589,76,480',
            ellipse: 'bessel',
            datumName: 'S-JTSK (Ferro)'
        },
        beduaram: {
            towgs84: '-106,-87,188',
            ellipse: 'clrk80',
            datumName: 'Beduaram'
        },
        gunung_segara: {
            towgs84: '-403,684,41',
            ellipse: 'bessel',
            datumName: 'Gunung Segara Jakarta'
        },
        rnb72: {
            towgs84: '106.869,-52.2978,103.724,-0.33657,0.456955,-1.84218,1',
            ellipse: 'intl',
            datumName: 'Reseau National Belge 1972'
        },
        EPSG_5451: {
            towgs84: '6.41,-49.05,-11.28,1.5657,0.5242,6.9718,-5.7649'
        },
        IGNF_LURESG: {
            towgs84: '-192.986,13.673,-39.309,-0.4099,-2.9332,2.6881,0.43'
        },
        EPSG_4614: {
            towgs84: '-119.4248,-303.65872,-11.00061,1.164298,0.174458,1.096259,3.657065'
        },
        EPSG_4615: {
            towgs84: '-494.088,-312.129,279.877,-1.423,-1.013,1.59,-0.748'
        },
        ESRI_37241: {
            towgs84: '-76.822,257.457,-12.817,2.136,-0.033,-2.392,-0.031'
        },
        ESRI_37249: {
            towgs84: '-440.296,58.548,296.265,1.128,10.202,4.559,-0.438'
        },
        ESRI_37245: {
            towgs84: '-511.151,-181.269,139.609,1.05,2.703,1.798,3.071'
        },
        EPSG_4178: {
            towgs84: '24.9,-126.4,-93.2,-0.063,-0.247,-0.041,1.01'
        },
        EPSG_4622: {
            towgs84: '-472.29,-5.63,-304.12,0.4362,-0.8374,0.2563,1.8984'
        },
        EPSG_4625: {
            towgs84: '126.93,547.94,130.41,-2.7867,5.1612,-0.8584,13.8227'
        },
        EPSG_5252: {
            towgs84: '0.023,0.036,-0.068,0.00176,0.00912,-0.01136,0.00439'
        },
        EPSG_4314: {
            towgs84: '597.1,71.4,412.1,0.894,0.068,-1.563,7.58'
        },
        EPSG_4282: {
            towgs84: '-178.3,-316.7,-131.5,5.278,6.077,10.979,19.166'
        },
        EPSG_4231: {
            towgs84: '-83.11,-97.38,-117.22,0.005693,-0.044698,0.044285,0.1218'
        },
        EPSG_4274: {
            towgs84: '-230.994,102.591,25.199,0.633,-0.239,0.9,1.95'
        },
        EPSG_4134: {
            towgs84: '-180.624,-225.516,173.919,-0.81,-1.898,8.336,16.71006'
        },
        EPSG_4254: {
            towgs84: '18.38,192.45,96.82,0.056,-0.142,-0.2,-0.0013'
        },
        EPSG_4159: {
            towgs84: '-194.513,-63.978,-25.759,-3.4027,3.756,-3.352,-0.9175'
        },
        EPSG_4687: {
            towgs84: '0.072,-0.507,-0.245,0.0183,-0.0003,0.007,-0.0093'
        },
        EPSG_4227: {
            towgs84: '-83.58,-397.54,458.78,-17.595,-2.847,4.256,3.225'
        },
        EPSG_4746: {
            towgs84: '599.4,72.4,419.2,-0.062,-0.022,-2.723,6.46'
        },
        EPSG_4745: {
            towgs84: '612.4,77,440.2,-0.054,0.057,-2.797,2.55'
        },
        EPSG_6311: {
            towgs84: '8.846,-4.394,-1.122,-0.00237,-0.146528,0.130428,0.783926'
        },
        EPSG_4289: {
            towgs84: '565.7381,50.4018,465.2904,-0.395026,0.330772,-1.876073,4.07244'
        },
        EPSG_4230: {
            towgs84: '-68.863,-134.888,-111.49,-0.53,-0.14,0.57,-3.4'
        },
        EPSG_4154: {
            towgs84: '-123.02,-158.95,-168.47'
        },
        EPSG_4156: {
            towgs84: '570.8,85.7,462.8,4.998,1.587,5.261,3.56'
        },
        EPSG_4299: {
            towgs84: '482.5,-130.6,564.6,-1.042,-0.214,-0.631,8.15'
        },
        EPSG_4179: {
            towgs84: '33.4,-146.6,-76.3,-0.359,-0.053,0.844,-0.84'
        },
        EPSG_4313: {
            towgs84: '-106.8686,52.2978,-103.7239,0.3366,-0.457,1.8422,-1.2747'
        },
        EPSG_4194: {
            towgs84: '163.511,127.533,-159.789'
        },
        EPSG_4195: {
            towgs84: '105,326,-102.5'
        },
        EPSG_4196: {
            towgs84: '-45,417,-3.5'
        },
        EPSG_4611: {
            towgs84: '-162.619,-276.959,-161.764,0.067753,-2.243648,-1.158828,-1.094246'
        },
        EPSG_4633: {
            towgs84: '137.092,131.66,91.475,-1.9436,-11.5993,-4.3321,-7.4824'
        },
        EPSG_4641: {
            towgs84: '-408.809,366.856,-412.987,1.8842,-0.5308,2.1655,-121.0993'
        },
        EPSG_4643: {
            towgs84: '-480.26,-438.32,-643.429,16.3119,20.1721,-4.0349,-111.7002'
        },
        EPSG_4300: {
            towgs84: '482.5,-130.6,564.6,-1.042,-0.214,-0.631,8.15'
        },
        EPSG_4188: {
            towgs84: '482.5,-130.6,564.6,-1.042,-0.214,-0.631,8.15'
        },
        EPSG_4660: {
            towgs84: '982.6087,552.753,-540.873,6.681627,-31.611492,-19.848161,16.805'
        },
        EPSG_4662: {
            towgs84: '97.295,-263.247,310.882,-1.5999,0.8386,3.1409,13.3259'
        },
        EPSG_3906: {
            towgs84: '577.88891,165.22205,391.18289,4.9145,-0.94729,-13.05098,7.78664'
        },
        EPSG_4307: {
            towgs84: '-209.3622,-87.8162,404.6198,0.0046,3.4784,0.5805,-1.4547'
        },
        EPSG_6892: {
            towgs84: '-76.269,-16.683,68.562,-6.275,10.536,-4.286,-13.686'
        },
        EPSG_4690: {
            towgs84: '221.597,152.441,176.523,2.403,1.3893,0.884,11.4648'
        },
        EPSG_4691: {
            towgs84: '218.769,150.75,176.75,3.5231,2.0037,1.288,10.9817'
        },
        EPSG_4629: {
            towgs84: '72.51,345.411,79.241,-1.5862,-0.8826,-0.5495,1.3653'
        },
        EPSG_4630: {
            towgs84: '165.804,216.213,180.26,-0.6251,-0.4515,-0.0721,7.4111'
        },
        EPSG_4692: {
            towgs84: '217.109,86.452,23.711,0.0183,-0.0003,0.007,-0.0093'
        },
        EPSG_9333: {
            towgs84: '0,0,0,-0.008393,0.000749,-0.010276,0'
        },
        EPSG_9059: {
            towgs84: '0,0,0'
        },
        EPSG_4312: {
            towgs84: '601.705,84.263,485.227,4.7354,1.3145,5.393,-2.3887'
        },
        EPSG_4123: {
            towgs84: '-96.062,-82.428,-121.753,4.801,0.345,-1.376,1.496'
        },
        EPSG_4309: {
            towgs84: '-124.45,183.74,44.64,-0.4384,0.5446,-0.9706,-2.1365'
        },
        ESRI_104106: {
            towgs84: '-283.088,-70.693,117.445,-1.157,0.059,-0.652,-4.058'
        },
        EPSG_4281: {
            towgs84: '-219.247,-73.802,269.529'
        },
        EPSG_4322: {
            towgs84: '0,0,4.5'
        },
        EPSG_4324: {
            towgs84: '0,0,1.9'
        },
        EPSG_4284: {
            towgs84: '43.822,-108.842,-119.585,1.455,-0.761,0.737,0.549'
        },
        EPSG_4277: {
            towgs84: '446.448,-125.157,542.06,0.15,0.247,0.842,-20.489'
        },
        EPSG_4207: {
            towgs84: '-282.1,-72.2,120,-1.529,0.145,-0.89,-4.46'
        },
        EPSG_4688: {
            towgs84: '347.175,1077.618,2623.677,33.9058,-70.6776,9.4013,186.0647'
        },
        EPSG_4689: {
            towgs84: '410.793,54.542,80.501,-2.5596,-2.3517,-0.6594,17.3218'
        },
        EPSG_4720: {
            towgs84: '0,0,4.5'
        },
        EPSG_4273: {
            towgs84: '278.3,93,474.5,7.889,0.05,-6.61,6.21'
        },
        EPSG_4240: {
            towgs84: '204.64,834.74,293.8'
        },
        EPSG_4817: {
            towgs84: '278.3,93,474.5,7.889,0.05,-6.61,6.21'
        },
        ESRI_104131: {
            towgs84: '426.62,142.62,460.09,4.98,4.49,-12.42,-17.1'
        },
        EPSG_4265: {
            towgs84: '-104.1,-49.1,-9.9,0.971,-2.917,0.714,-11.68'
        },
        EPSG_4263: {
            towgs84: '-111.92,-87.85,114.5,1.875,0.202,0.219,0.032'
        },
        EPSG_4298: {
            towgs84: '-689.5937,623.84046,-65.93566,-0.02331,1.17094,-0.80054,5.88536'
        },
        EPSG_4270: {
            towgs84: '-253.4392,-148.452,386.5267,0.15605,0.43,-0.1013,-0.0424'
        },
        EPSG_4229: {
            towgs84: '-121.8,98.1,-10.7'
        },
        EPSG_4220: {
            towgs84: '-55.5,-348,-229.2'
        },
        EPSG_4214: {
            towgs84: '12.646,-155.176,-80.863'
        },
        EPSG_4232: {
            towgs84: '-345,3,223'
        },
        EPSG_4238: {
            towgs84: '-1.977,-13.06,-9.993,0.364,0.254,0.689,-1.037'
        },
        EPSG_4168: {
            towgs84: '-170,33,326'
        },
        EPSG_4131: {
            towgs84: '199,931,318.9'
        },
        EPSG_4152: {
            towgs84: '-0.9102,2.0141,0.5602,0.029039,0.010065,0.010101,0'
        },
        EPSG_5228: {
            towgs84: '572.213,85.334,461.94,4.9732,1.529,5.2484,3.5378'
        },
        EPSG_8351: {
            towgs84: '485.021,169.465,483.839,7.786342,4.397554,4.102655,0'
        },
        EPSG_4683: {
            towgs84: '-127.62,-67.24,-47.04,-3.068,4.903,1.578,-1.06'
        },
        EPSG_4133: {
            towgs84: '0,0,0'
        },
        EPSG_7373: {
            towgs84: '0.819,-0.5762,-1.6446,-0.00378,-0.03317,0.00318,0.0693'
        },
        EPSG_9075: {
            towgs84: '-0.9102,2.0141,0.5602,0.029039,0.010065,0.010101,0'
        },
        EPSG_9072: {
            towgs84: '-0.9102,2.0141,0.5602,0.029039,0.010065,0.010101,0'
        },
        EPSG_9294: {
            towgs84: '1.16835,-1.42001,-2.24431,-0.00822,-0.05508,0.01818,0.23388'
        },
        EPSG_4212: {
            towgs84: '-267.434,173.496,181.814,-13.4704,8.7154,7.3926,14.7492'
        },
        EPSG_4191: {
            towgs84: '-44.183,-0.58,-38.489,2.3867,2.7072,-3.5196,-8.2703'
        },
        EPSG_4237: {
            towgs84: '52.684,-71.194,-13.975,-0.312,-0.1063,-0.3729,1.0191'
        },
        EPSG_4740: {
            towgs84: '-1.08,-0.27,-0.9'
        },
        EPSG_4124: {
            towgs84: '419.3836,99.3335,591.3451,0.850389,1.817277,-7.862238,-0.99496'
        },
        EPSG_5681: {
            towgs84: '584.9636,107.7175,413.8067,1.1155,0.2824,-3.1384,7.9922'
        },
        EPSG_4141: {
            towgs84: '23.772,17.49,17.859,-0.3132,-1.85274,1.67299,-5.4262'
        },
        EPSG_4204: {
            towgs84: '-85.645,-273.077,-79.708,2.289,-1.421,2.532,3.194'
        },
        EPSG_4319: {
            towgs84: '226.702,-193.337,-35.371,-2.229,-4.391,9.238,0.9798'
        },
        EPSG_4200: {
            towgs84: '24.82,-131.21,-82.66'
        },
        EPSG_4130: {
            towgs84: '0,0,0'
        },
        EPSG_4127: {
            towgs84: '-82.875,-57.097,-156.768,-2.158,1.524,-0.982,-0.359'
        },
        EPSG_4149: {
            towgs84: '674.374,15.056,405.346'
        },
        EPSG_4617: {
            towgs84: '-0.991,1.9072,0.5129,0.02579,0.00965,0.01166,0'
        },
        EPSG_4663: {
            towgs84: '-210.502,-66.902,-48.476,2.094,-15.067,-5.817,0.485'
        },
        EPSG_4664: {
            towgs84: '-211.939,137.626,58.3,-0.089,0.251,0.079,0.384'
        },
        EPSG_4665: {
            towgs84: '-105.854,165.589,-38.312,-0.003,-0.026,0.024,-0.048'
        },
        EPSG_4666: {
            towgs84: '631.392,-66.551,481.442,1.09,-4.445,-4.487,-4.43'
        },
        EPSG_4756: {
            towgs84: '-192.873,-39.382,-111.202,-0.00205,-0.0005,0.00335,0.0188'
        },
        EPSG_4723: {
            towgs84: '-179.483,-69.379,-27.584,-7.862,8.163,6.042,-13.925'
        },
        EPSG_4726: {
            towgs84: '8.853,-52.644,180.304,-0.393,-2.323,2.96,-24.081'
        },
        EPSG_4267: {
            towgs84: '-8.0,160.0,176.0'
        },
        EPSG_5365: {
            towgs84: '-0.16959,0.35312,0.51846,0.03385,-0.16325,0.03446,0.03693'
        },
        EPSG_4218: {
            towgs84: '304.5,306.5,-318.1'
        },
        EPSG_4242: {
            towgs84: '-33.722,153.789,94.959,-8.581,-4.478,4.54,8.95'
        },
        EPSG_4216: {
            towgs84: '-292.295,248.758,429.447,4.9971,2.99,6.6906,1.0289'
        },
        ESRI_104105: {
            towgs84: '631.392,-66.551,481.442,1.09,-4.445,-4.487,-4.43'
        },
        ESRI_104129: {
            towgs84: '0,0,0'
        },
        EPSG_4673: {
            towgs84: '174.05,-25.49,112.57'
        },
        EPSG_4202: {
            towgs84: '-124,-60,154'
        },
        EPSG_4203: {
            towgs84: '-117.763,-51.51,139.061,0.292,0.443,0.277,-0.191'
        },
        EPSG_3819: {
            towgs84: '595.48,121.69,515.35,4.115,-2.9383,0.853,-3.408'
        },
        EPSG_8694: {
            towgs84: '-93.799,-132.737,-219.073,-1.844,0.648,-6.37,-0.169'
        },
        EPSG_4145: {
            towgs84: '275.57,676.78,229.6'
        },
        EPSG_4283: {
            towgs84: '0.06155,-0.01087,-0.04019,0.039492,0.032722,0.032898,-0.009994'
        },
        EPSG_4317: {
            towgs84: '2.3287,-147.0425,-92.0802,-0.309248,0.324822,0.497299,5.689063'
        },
        EPSG_4272: {
            towgs84: '59.47,-5.04,187.44,0.47,-0.1,1.024,-4.5993'
        },
        EPSG_4248: {
            towgs84: '-307.7,265.3,-363.5'
        },
        EPSG_5561: {
            towgs84: '24,-121,-76'
        },
        EPSG_5233: {
            towgs84: '-0.293,766.95,87.713,0.195704,1.695068,3.473016,-0.039338'
        },
        ESRI_104130: {
            towgs84: '-86,-98,-119'
        },
        ESRI_104102: {
            towgs84: '682,-203,480'
        },
        ESRI_37207: {
            towgs84: '7,-10,-26'
        },
        EPSG_4675: {
            towgs84: '59.935,118.4,-10.871'
        },
        ESRI_104109: {
            towgs84: '-89.121,-348.182,260.871'
        },
        ESRI_104112: {
            towgs84: '-185.583,-230.096,281.361'
        },
        ESRI_104113: {
            towgs84: '25.1,-275.6,222.6'
        },
        IGNF_WGS72G: {
            towgs84: '0,12,6'
        },
        IGNF_NTFG: {
            towgs84: '-168,-60,320'
        },
        IGNF_EFATE57G: {
            towgs84: '-127,-769,472'
        },
        IGNF_PGP50G: {
            towgs84: '324.8,153.6,172.1'
        },
        IGNF_REUN47G: {
            towgs84: '94,-948,-1262'
        },
        IGNF_CSG67G: {
            towgs84: '-186,230,110'
        },
        IGNF_GUAD48G: {
            towgs84: '-467,-16,-300'
        },
        IGNF_TAHI51G: {
            towgs84: '162,117,154'
        },
        IGNF_TAHAAG: {
            towgs84: '65,342,77'
        },
        IGNF_NUKU72G: {
            towgs84: '84,274,65'
        },
        IGNF_PETRELS72G: {
            towgs84: '365,194,166'
        },
        IGNF_WALL78G: {
            towgs84: '253,-133,-127'
        },
        IGNF_MAYO50G: {
            towgs84: '-382,-59,-262'
        },
        IGNF_TANNAG: {
            towgs84: '-139,-967,436'
        },
        IGNF_IGN72G: {
            towgs84: '-13,-348,292'
        },
        IGNF_ATIGG: {
            towgs84: '1118,23,66'
        },
        IGNF_FANGA84G: {
            towgs84: '150.57,158.33,118.32'
        },
        IGNF_RUSAT84G: {
            towgs84: '202.13,174.6,-15.74'
        },
        IGNF_KAUE70G: {
            towgs84: '126.74,300.1,-75.49'
        },
        IGNF_MOP90G: {
            towgs84: '-10.8,-1.8,12.77'
        },
        IGNF_MHPF67G: {
            towgs84: '338.08,212.58,-296.17'
        },
        IGNF_TAHI79G: {
            towgs84: '160.61,116.05,153.69'
        },
        IGNF_ANAA92G: {
            towgs84: '1.5,3.84,4.81'
        },
        IGNF_MARQUI72G: {
            towgs84: '330.91,-13.92,58.56'
        },
        IGNF_APAT86G: {
            towgs84: '143.6,197.82,74.05'
        },
        IGNF_TUBU69G: {
            towgs84: '237.17,171.61,-77.84'
        },
        IGNF_STPM50G: {
            towgs84: '11.363,424.148,373.13'
        },
        EPSG_4150: {
            towgs84: '674.374,15.056,405.346'
        },
        EPSG_4754: {
            towgs84: '-208.4058,-109.8777,-2.5764'
        },
        ESRI_104101: {
            towgs84: '372.87,149.23,585.29'
        },
        EPSG_4693: {
            towgs84: '0,-0.15,0.68'
        },
        EPSG_6207: {
            towgs84: '293.17,726.18,245.36'
        },
        EPSG_4153: {
            towgs84: '-133.63,-157.5,-158.62'
        },
        EPSG_4132: {
            towgs84: '-241.54,-163.64,396.06'
        },
        EPSG_4221: {
            towgs84: '-154.5,150.7,100.4'
        },
        EPSG_4266: {
            towgs84: '-80.7,-132.5,41.1'
        },
        EPSG_4193: {
            towgs84: '-70.9,-151.8,-41.4'
        },
        EPSG_5340: {
            towgs84: '-0.41,0.46,-0.35'
        },
        EPSG_4246: {
            towgs84: '-294.7,-200.1,525.5'
        },
        EPSG_4318: {
            towgs84: '-3.2,-5.7,2.8'
        },
        EPSG_4121: {
            towgs84: '-199.87,74.79,246.62'
        },
        EPSG_4223: {
            towgs84: '-260.1,5.5,432.2'
        },
        EPSG_4158: {
            towgs84: '-0.465,372.095,171.736'
        },
        EPSG_4285: {
            towgs84: '-128.16,-282.42,21.93'
        },
        EPSG_4613: {
            towgs84: '-404.78,685.68,45.47'
        },
        EPSG_4607: {
            towgs84: '195.671,332.517,274.607'
        },
        EPSG_4475: {
            towgs84: '-381.788,-57.501,-256.673'
        },
        EPSG_4208: {
            towgs84: '-157.84,308.54,-146.6'
        },
        EPSG_4743: {
            towgs84: '70.995,-335.916,262.898'
        },
        EPSG_4710: {
            towgs84: '-323.65,551.39,-491.22'
        },
        EPSG_7881: {
            towgs84: '-0.077,0.079,0.086'
        },
        EPSG_4682: {
            towgs84: '283.729,735.942,261.143'
        },
        EPSG_4739: {
            towgs84: '-156,-271,-189'
        },
        EPSG_4679: {
            towgs84: '-80.01,253.26,291.19'
        },
        EPSG_4750: {
            towgs84: '-56.263,16.136,-22.856'
        },
        EPSG_4644: {
            towgs84: '-10.18,-350.43,291.37'
        },
        EPSG_4695: {
            towgs84: '-103.746,-9.614,-255.95'
        },
        EPSG_4292: {
            towgs84: '-355,21,72'
        },
        EPSG_4302: {
            towgs84: '-61.702,284.488,472.052'
        },
        EPSG_4143: {
            towgs84: '-124.76,53,466.79'
        },
        EPSG_4606: {
            towgs84: '-153,153,307'
        },
        EPSG_4699: {
            towgs84: '-770.1,158.4,-498.2'
        },
        EPSG_4247: {
            towgs84: '-273.5,110.6,-357.9'
        },
        EPSG_4160: {
            towgs84: '8.88,184.86,106.69'
        },
        EPSG_4161: {
            towgs84: '-233.43,6.65,173.64'
        },
        EPSG_9251: {
            towgs84: '-9.5,122.9,138.2'
        },
        EPSG_9253: {
            towgs84: '-78.1,101.6,133.3'
        },
        EPSG_4297: {
            towgs84: '-198.383,-240.517,-107.909'
        },
        EPSG_4269: {
            towgs84: '0,0,0'
        },
        EPSG_4301: {
            towgs84: '-147,506,687'
        },
        EPSG_4618: {
            towgs84: '-59,-11,-52'
        },
        EPSG_4612: {
            towgs84: '0,0,0'
        },
        EPSG_4678: {
            towgs84: '44.585,-131.212,-39.544'
        },
        EPSG_4250: {
            towgs84: '-130,29,364'
        },
        EPSG_4144: {
            towgs84: '214,804,268'
        },
        EPSG_4147: {
            towgs84: '-17.51,-108.32,-62.39'
        },
        EPSG_4259: {
            towgs84: '-254.1,-5.36,-100.29'
        },
        EPSG_4164: {
            towgs84: '-76,-138,67'
        },
        EPSG_4211: {
            towgs84: '-378.873,676.002,-46.255'
        },
        EPSG_4182: {
            towgs84: '-422.651,-172.995,84.02'
        },
        EPSG_4224: {
            towgs84: '-143.87,243.37,-33.52'
        },
        EPSG_4225: {
            towgs84: '-205.57,168.77,-4.12'
        },
        EPSG_5527: {
            towgs84: '-67.35,3.88,-38.22'
        },
        EPSG_4752: {
            towgs84: '98,390,-22'
        },
        EPSG_4310: {
            towgs84: '-30,190,89'
        },
        EPSG_9248: {
            towgs84: '-192.26,65.72,132.08'
        },
        EPSG_4680: {
            towgs84: '124.5,-63.5,-281'
        },
        EPSG_4701: {
            towgs84: '-79.9,-158,-168.9'
        },
        EPSG_4706: {
            towgs84: '-146.21,112.63,4.05'
        },
        EPSG_4805: {
            towgs84: '682,-203,480'
        },
        EPSG_4201: {
            towgs84: '-165,-11,206'
        },
        EPSG_4210: {
            towgs84: '-157,-2,-299'
        },
        EPSG_4183: {
            towgs84: '-104,167,-38'
        },
        EPSG_4139: {
            towgs84: '11,72,-101'
        },
        EPSG_4668: {
            towgs84: '-86,-98,-119'
        },
        EPSG_4717: {
            towgs84: '-2,151,181'
        },
        EPSG_4732: {
            towgs84: '102,52,-38'
        },
        EPSG_4280: {
            towgs84: '-377,681,-50'
        },
        EPSG_4209: {
            towgs84: '-138,-105,-289'
        },
        EPSG_4261: {
            towgs84: '31,146,47'
        },
        EPSG_4658: {
            towgs84: '-73,46,-86'
        },
        EPSG_4721: {
            towgs84: '265.025,384.929,-194.046'
        },
        EPSG_4222: {
            towgs84: '-136,-108,-292'
        },
        EPSG_4601: {
            towgs84: '-255,-15,71'
        },
        EPSG_4602: {
            towgs84: '725,685,536'
        },
        EPSG_4603: {
            towgs84: '72,213.7,93'
        },
        EPSG_4605: {
            towgs84: '9,183,236'
        },
        EPSG_4621: {
            towgs84: '137,248,-430'
        },
        EPSG_4657: {
            towgs84: '-28,199,5'
        },
        EPSG_4316: {
            towgs84: '103.25,-100.4,-307.19'
        },
        EPSG_4642: {
            towgs84: '-13,-348,292'
        },
        EPSG_4698: {
            towgs84: '145,-187,103'
        },
        EPSG_4192: {
            towgs84: '-206.1,-174.7,-87.7'
        },
        EPSG_4311: {
            towgs84: '-265,120,-358'
        },
        EPSG_4135: {
            towgs84: '58,-283,-182'
        },
        ESRI_104138: {
            towgs84: '198,-226,-347'
        },
        EPSG_4245: {
            towgs84: '-11,851,5'
        },
        EPSG_4142: {
            towgs84: '-125,53,467'
        },
        EPSG_4213: {
            towgs84: '-106,-87,188'
        },
        EPSG_4253: {
            towgs84: '-133,-77,-51'
        },
        EPSG_4129: {
            towgs84: '-132,-110,-335'
        },
        EPSG_4713: {
            towgs84: '-77,-128,142'
        },
        EPSG_4239: {
            towgs84: '217,823,299'
        },
        EPSG_4146: {
            towgs84: '295,736,257'
        },
        EPSG_4155: {
            towgs84: '-83,37,124'
        },
        EPSG_4165: {
            towgs84: '-173,253,27'
        },
        EPSG_4672: {
            towgs84: '175,-38,113'
        },
        EPSG_4236: {
            towgs84: '-637,-549,-203'
        },
        EPSG_4251: {
            towgs84: '-90,40,88'
        },
        EPSG_4271: {
            towgs84: '-2,374,172'
        },
        EPSG_4175: {
            towgs84: '-88,4,101'
        },
        EPSG_4716: {
            towgs84: '298,-304,-375'
        },
        EPSG_4315: {
            towgs84: '-23,259,-9'
        },
        EPSG_4744: {
            towgs84: '-242.2,-144.9,370.3'
        },
        EPSG_4244: {
            towgs84: '-97,787,86'
        },
        EPSG_4293: {
            towgs84: '616,97,-251'
        },
        EPSG_4714: {
            towgs84: '-127,-769,472'
        },
        EPSG_4736: {
            towgs84: '260,12,-147'
        },
        EPSG_6883: {
            towgs84: '-235,-110,393'
        },
        EPSG_6894: {
            towgs84: '-63,176,185'
        },
        EPSG_4205: {
            towgs84: '-43,-163,45'
        },
        EPSG_4256: {
            towgs84: '41,-220,-134'
        },
        EPSG_4262: {
            towgs84: '639,405,60'
        },
        EPSG_4604: {
            towgs84: '174,359,365'
        },
        EPSG_4169: {
            towgs84: '-115,118,426'
        },
        EPSG_4620: {
            towgs84: '-106,-129,165'
        },
        EPSG_4184: {
            towgs84: '-203,141,53'
        },
        EPSG_4616: {
            towgs84: '-289,-124,60'
        },
        EPSG_9403: {
            towgs84: '-307,-92,127'
        },
        EPSG_4684: {
            towgs84: '-133,-321,50'
        },
        EPSG_4708: {
            towgs84: '-491,-22,435'
        },
        EPSG_4707: {
            towgs84: '114,-116,-333'
        },
        EPSG_4709: {
            towgs84: '145,75,-272'
        },
        EPSG_4712: {
            towgs84: '-205,107,53'
        },
        EPSG_4711: {
            towgs84: '124,-234,-25'
        },
        EPSG_4718: {
            towgs84: '230,-199,-752'
        },
        EPSG_4719: {
            towgs84: '211,147,111'
        },
        EPSG_4724: {
            towgs84: '208,-435,-229'
        },
        EPSG_4725: {
            towgs84: '189,-79,-202'
        },
        EPSG_4735: {
            towgs84: '647,1777,-1124'
        },
        EPSG_4722: {
            towgs84: '-794,119,-298'
        },
        EPSG_4728: {
            towgs84: '-307,-92,127'
        },
        EPSG_4734: {
            towgs84: '-632,438,-609'
        },
        EPSG_4727: {
            towgs84: '912,-58,1227'
        },
        EPSG_4729: {
            towgs84: '185,165,42'
        },
        EPSG_4730: {
            towgs84: '170,42,84'
        },
        EPSG_4733: {
            towgs84: '276,-57,149'
        },
        ESRI_37218: {
            towgs84: '230,-199,-752'
        },
        ESRI_37240: {
            towgs84: '-7,215,225'
        },
        ESRI_37221: {
            towgs84: '252,-209,-751'
        },
        ESRI_4305: {
            towgs84: '-123,-206,219'
        },
        ESRI_104139: {
            towgs84: '-73,-247,227'
        },
        EPSG_4748: {
            towgs84: '51,391,-36'
        },
        EPSG_4219: {
            towgs84: '-384,664,-48'
        },
        EPSG_4255: {
            towgs84: '-333,-222,114'
        },
        EPSG_4257: {
            towgs84: '-587.8,519.75,145.76'
        },
        EPSG_4646: {
            towgs84: '-963,510,-359'
        },
        EPSG_6881: {
            towgs84: '-24,-203,268'
        },
        EPSG_6882: {
            towgs84: '-183,-15,273'
        },
        EPSG_4715: {
            towgs84: '-104,-129,239'
        },
        IGNF_RGF93GDD: {
            towgs84: '0,0,0'
        },
        IGNF_RGM04GDD: {
            towgs84: '0,0,0'
        },
        IGNF_RGSPM06GDD: {
            towgs84: '0,0,0'
        },
        IGNF_RGTAAF07GDD: {
            towgs84: '0,0,0'
        },
        IGNF_RGFG95GDD: {
            towgs84: '0,0,0'
        },
        IGNF_RGNCG: {
            towgs84: '0,0,0'
        },
        IGNF_RGPFGDD: {
            towgs84: '0,0,0'
        },
        IGNF_ETRS89G: {
            towgs84: '0,0,0'
        },
        IGNF_RGR92GDD: {
            towgs84: '0,0,0'
        },
        EPSG_4173: {
            towgs84: '0,0,0'
        },
        EPSG_4180: {
            towgs84: '0,0,0'
        },
        EPSG_4619: {
            towgs84: '0,0,0'
        },
        EPSG_4667: {
            towgs84: '0,0,0'
        },
        EPSG_4075: {
            towgs84: '0,0,0'
        },
        EPSG_6706: {
            towgs84: '0,0,0'
        },
        EPSG_7798: {
            towgs84: '0,0,0'
        },
        EPSG_4661: {
            towgs84: '0,0,0'
        },
        EPSG_4669: {
            towgs84: '0,0,0'
        },
        EPSG_8685: {
            towgs84: '0,0,0'
        },
        EPSG_4151: {
            towgs84: '0,0,0'
        },
        EPSG_9702: {
            towgs84: '0,0,0'
        },
        EPSG_4758: {
            towgs84: '0,0,0'
        },
        EPSG_4761: {
            towgs84: '0,0,0'
        },
        EPSG_4765: {
            towgs84: '0,0,0'
        },
        EPSG_8997: {
            towgs84: '0,0,0'
        },
        EPSG_4023: {
            towgs84: '0,0,0'
        },
        EPSG_4670: {
            towgs84: '0,0,0'
        },
        EPSG_4694: {
            towgs84: '0,0,0'
        },
        EPSG_4148: {
            towgs84: '0,0,0'
        },
        EPSG_4163: {
            towgs84: '0,0,0'
        },
        EPSG_4167: {
            towgs84: '0,0,0'
        },
        EPSG_4189: {
            towgs84: '0,0,0'
        },
        EPSG_4190: {
            towgs84: '0,0,0'
        },
        EPSG_4176: {
            towgs84: '0,0,0'
        },
        EPSG_4659: {
            towgs84: '0,0,0'
        },
        EPSG_3824: {
            towgs84: '0,0,0'
        },
        EPSG_3889: {
            towgs84: '0,0,0'
        },
        EPSG_4046: {
            towgs84: '0,0,0'
        },
        EPSG_4081: {
            towgs84: '0,0,0'
        },
        EPSG_4558: {
            towgs84: '0,0,0'
        },
        EPSG_4483: {
            towgs84: '0,0,0'
        },
        EPSG_5013: {
            towgs84: '0,0,0'
        },
        EPSG_5264: {
            towgs84: '0,0,0'
        },
        EPSG_5324: {
            towgs84: '0,0,0'
        },
        EPSG_5354: {
            towgs84: '0,0,0'
        },
        EPSG_5371: {
            towgs84: '0,0,0'
        },
        EPSG_5373: {
            towgs84: '0,0,0'
        },
        EPSG_5381: {
            towgs84: '0,0,0'
        },
        EPSG_5393: {
            towgs84: '0,0,0'
        },
        EPSG_5489: {
            towgs84: '0,0,0'
        },
        EPSG_5593: {
            towgs84: '0,0,0'
        },
        EPSG_6135: {
            towgs84: '0,0,0'
        },
        EPSG_6365: {
            towgs84: '0,0,0'
        },
        EPSG_5246: {
            towgs84: '0,0,0'
        },
        EPSG_7886: {
            towgs84: '0,0,0'
        },
        EPSG_8431: {
            towgs84: '0,0,0'
        },
        EPSG_8427: {
            towgs84: '0,0,0'
        },
        EPSG_8699: {
            towgs84: '0,0,0'
        },
        EPSG_8818: {
            towgs84: '0,0,0'
        },
        EPSG_4757: {
            towgs84: '0,0,0'
        },
        EPSG_9140: {
            towgs84: '0,0,0'
        },
        EPSG_8086: {
            towgs84: '0,0,0'
        },
        EPSG_4686: {
            towgs84: '0,0,0'
        },
        EPSG_4737: {
            towgs84: '0,0,0'
        },
        EPSG_4702: {
            towgs84: '0,0,0'
        },
        EPSG_4747: {
            towgs84: '0,0,0'
        },
        EPSG_4749: {
            towgs84: '0,0,0'
        },
        EPSG_4674: {
            towgs84: '0,0,0'
        },
        EPSG_4755: {
            towgs84: '0,0,0'
        },
        EPSG_4759: {
            towgs84: '0,0,0'
        },
        EPSG_4762: {
            towgs84: '0,0,0'
        },
        EPSG_4763: {
            towgs84: '0,0,0'
        },
        EPSG_4764: {
            towgs84: '0,0,0'
        },
        EPSG_4166: {
            towgs84: '0,0,0'
        },
        EPSG_4170: {
            towgs84: '0,0,0'
        },
        EPSG_5546: {
            towgs84: '0,0,0'
        },
        EPSG_7844: {
            towgs84: '0,0,0'
        },
        EPSG_4818: {
            towgs84: '589,76,480'
        },
        EPSG_10328: {
            towgs84: '0,0,0'
        },
        EPSG_9782: {
            towgs84: '0,0,0'
        },
        EPSG_9777: {
            towgs84: '0,0,0'
        },
        EPSG_10690: {
            towgs84: '0,0,0'
        },
        EPSG_10639: {
            towgs84: '0,0,0'
        },
        EPSG_10739: {
            towgs84: '0,0,0'
        },
        EPSG_7686: {
            towgs84: '0,0,0'
        },
        EPSG_8900: {
            towgs84: '0,0,0'
        },
        EPSG_5886: {
            towgs84: '0,0,0'
        },
        EPSG_7683: {
            towgs84: '0,0,0'
        },
        EPSG_6668: {
            towgs84: '0,0,0'
        },
        EPSG_20046: {
            towgs84: '0,0,0'
        },
        EPSG_10299: {
            towgs84: '0,0,0'
        },
        EPSG_10310: {
            towgs84: '0,0,0'
        },
        EPSG_10475: {
            towgs84: '0,0,0'
        },
        EPSG_4742: {
            towgs84: '0,0,0'
        },
        EPSG_10671: {
            towgs84: '0,0,0'
        },
        EPSG_10762: {
            towgs84: '0,0,0'
        },
        EPSG_10725: {
            towgs84: '0,0,0'
        },
        EPSG_10791: {
            towgs84: '0,0,0'
        },
        EPSG_10800: {
            towgs84: '0,0,0'
        },
        EPSG_10305: {
            towgs84: '0,0,0'
        },
        EPSG_10941: {
            towgs84: '0,0,0'
        },
        EPSG_10968: {
            towgs84: '0,0,0'
        },
        EPSG_10875: {
            towgs84: '0,0,0'
        },
        EPSG_6318: {
            towgs84: '0,0,0'
        },
        EPSG_10910: {
            towgs84: '0,0,0'
        }
    };
    for (var key in datums) {
        var datum = datums[key];
        if (!datum.datumName) {
            continue;
        }
        datums[datum.datumName] = datum;
    }
    exports.default = datums;
},
/* proj4/lib/datum.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const values_1 = require(156) /* ./constants/values */;
    function datum(datumCode, datum_params, a, b, es, ep2, nadgrids) {
        var out = {};
        out.datum_type = values_1.PJD_NODATUM;
        if (datum_params) {
            out.datum_type = values_1.PJD_WGS84;
            out.datum_params = datum_params.map(parseFloat);
            if (out.datum_params[0] !== 0 || out.datum_params[1] !== 0 || out.datum_params[2] !== 0) {
                out.datum_type = values_1.PJD_3PARAM;
            }
            if (out.datum_params.length > 3) {
                if (out.datum_params[3] !== 0 || out.datum_params[4] !== 0 || out.datum_params[5] !== 0 || out.datum_params[6] !== 0) {
                    out.datum_type = values_1.PJD_7PARAM;
                    out.datum_params[3] *= values_1.SEC_TO_RAD;
                    out.datum_params[4] *= values_1.SEC_TO_RAD;
                    out.datum_params[5] *= values_1.SEC_TO_RAD;
                    out.datum_params[6] = (out.datum_params[6] / 1000000.0) + 1.0;
                }
            }
        }
        if (nadgrids) {
            out.datum_type = values_1.PJD_GRIDSHIFT;
            out.grids = nadgrids;
        }
        out.a = a; // datum object also uses these values
        out.b = b;
        out.es = es;
        out.ep2 = ep2;
        return out;
    }
    exports.default = datum;
},
/* proj4/lib/nadgrid.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = nadgrid;
    exports.getNadgrids = getNadgrids;
    /**
     * @typedef {Object} NadgridInfo
     * @property {string} name The name of the NAD grid or 'null' if not specified.
     * @property {boolean} mandatory Indicates if the grid is mandatory (true) or optional (false).
     * @property {*} grid The loaded NAD grid object, or null if not loaded or not applicable.
     * @property {boolean} isNull True if the grid is explicitly 'null', otherwise false.
     */
    /**
     * @typedef {Object} NTV2GridOptions
     * @property {boolean} [includeErrorFields=true] Whether to include error fields in the subgrids.
     */
    /**
     * @typedef {Object} NadgridHeader
     * @property {number} [nFields] Number of fields in the header.
     * @property {number} [nSubgridFields] Number of fields in each subgrid header.
     * @property {number} nSubgrids Number of subgrids in the file.
     * @property {string} [shiftType] Type of shift (e.g., "SECONDS").
     * @property {number} [fromSemiMajorAxis] Source ellipsoid semi-major axis.
     * @property {number} [fromSemiMinorAxis] Source ellipsoid semi-minor axis.
     * @property {number} [toSemiMajorAxis] Target ellipsoid semi-major axis.
     * @property {number} [toSemiMinorAxis] Target ellipsoid semi-minor axis.
     */
    /**
     * @typedef {Object} Subgrid
     * @property {Array<number>} ll Lower left corner of the grid in radians [longitude, latitude].
     * @property {Array<number>} del Grid spacing in radians [longitude interval, latitude interval].
     * @property {Array<number>} lim Number of columns in the grid [longitude columns, latitude columns].
     * @property {number} [count] Total number of grid nodes.
     * @property {Array} cvs Mapped node values for the grid.
     */
    /** @typedef {{header: NadgridHeader, subgrids: Array<Subgrid>}} NADGrid */
    var loadedNadgrids = {};
    /**
     * @overload
     * @param {string} key - The key to associate with the loaded grid.
     * @param {ArrayBuffer} data - The NTv2 grid data as an ArrayBuffer.
     * @param {NTV2GridOptions} [options] - Optional parameters for loading the grid.
     * @returns {NADGrid} - The loaded NAD grid information.
     */
    /**
     * @overload
     * @param {string} key - The key to associate with the loaded grid.
     * @param {import('geotiff').GeoTIFF} data - The GeoTIFF instance to read the grid from.
     * @returns {{ready: Promise<NADGrid>}} - A promise that resolves to the loaded grid information.
     */
    /**
     * Load either a NTv2 file (.gsb) or a Geotiff (.tif) to a key that can be used in a proj string like +nadgrids=<key>. Pass the NTv2 file
     * as an ArrayBuffer. Pass Geotiff as a GeoTIFF instance from the geotiff.js library.
     * @param {string} key - The key to associate with the loaded grid.
     * @param {ArrayBuffer|import('geotiff').GeoTIFF} data The data to load, either an ArrayBuffer for NTv2 or a GeoTIFF instance.
     * @param {NTV2GridOptions} [options] Optional parameters.
     * @returns {{ready: Promise<NADGrid>}|NADGrid} - A promise that resolves to the loaded grid information.
     */
    function nadgrid(key, data, options) {
        if (data instanceof ArrayBuffer) {
            return readNTV2Grid(key, data, options);
        }
        return { ready: readGeotiffGrid(key, data) };
    }
    /**
     * @param {string} key The key to associate with the loaded grid.
     * @param {ArrayBuffer} data The NTv2 grid data as an ArrayBuffer.
     * @param {NTV2GridOptions} [options] Optional parameters for loading the grid.
     * @returns {NADGrid} The loaded NAD grid information.
     */
    function readNTV2Grid(key, data, options) {
        var includeErrorFields = true;
        if (options !== undefined && options.includeErrorFields === false) {
            includeErrorFields = false;
        }
        var view = new DataView(data);
        var isLittleEndian = detectLittleEndian(view);
        var header = readHeader(view, isLittleEndian);
        var subgrids = readSubgrids(view, header, isLittleEndian, includeErrorFields);
        var nadgrid = { header: header, subgrids: subgrids };
        loadedNadgrids[key] = nadgrid;
        return nadgrid;
    }
    /**
     * @param {string} key The key to associate with the loaded grid.
     * @param {import('geotiff').GeoTIFF} tiff The GeoTIFF instance to read the grid from.
     * @returns {Promise<NADGrid>} A promise that resolves to the loaded NAD grid information.
     */
    async function readGeotiffGrid(key, tiff) {
        var subgrids = [];
        var subGridCount = await tiff.getImageCount();
        // proj produced tiff grid shift files appear to organize lower res subgrids first, higher res/ child subgrids last.
        for (var subgridIndex = subGridCount - 1; subgridIndex >= 0; subgridIndex--) {
            var image = await tiff.getImage(subgridIndex);
            var rasters = await image.readRasters();
            var data = rasters;
            var lim = [image.getWidth(), image.getHeight()];
            var imageBBoxRadians = image.getBoundingBox().map(degreesToRadians);
            var modelPixelScale = typeof image.fileDirectory.getValue === 'function'
                // geotiff v3
                ? image.fileDirectory.getValue('ModelPixelScale')
                // geotiff v2
                : /** @type {any} */ (image.fileDirectory).ModelPixelScale;
            var del = [modelPixelScale[0], modelPixelScale[1]].map(degreesToRadians);
            var maxX = imageBBoxRadians[0] + (lim[0] - 1) * del[0];
            var minY = imageBBoxRadians[3] - (lim[1] - 1) * del[1];
            var latitudeOffsetBand = data[0];
            var longitudeOffsetBand = data[1];
            var nodes = [];
            for (let i = lim[1] - 1; i >= 0; i--) {
                for (let j = lim[0] - 1; j >= 0; j--) {
                    var index = i * lim[0] + j;
                    nodes.push([-secondsToRadians(longitudeOffsetBand[index]), secondsToRadians(latitudeOffsetBand[index])]);
                }
            }
            subgrids.push({
                del: del,
                lim: lim,
                ll: [-maxX, minY],
                cvs: nodes
            });
        }
        var tifGrid = {
            header: {
                nSubgrids: subGridCount
            },
            subgrids: subgrids
        };
        loadedNadgrids[key] = tifGrid;
        return tifGrid;
    }
    ;
    /**
     * Given a proj4 value for nadgrids, return an array of loaded grids
     * @param {string} nadgrids A comma-separated list of grid names, optionally prefixed with '@' to indicate optional grids.
     * @returns
     */
    function getNadgrids(nadgrids) {
        // Format details: http://proj.maptools.org/gen_parms.html
        if (nadgrids === undefined) {
            return null;
        }
        var grids = nadgrids.split(',');
        return grids.map(parseNadgridString);
    }
    /**
     * @param {string} value The nadgrid string to get information for.
     * @returns {NadgridInfo|null} An object with grid information, or null if the input is empty.
     */
    function parseNadgridString(value) {
        if (value.length === 0) {
            return null;
        }
        var optional = value[0] === '@';
        if (optional) {
            value = value.slice(1);
        }
        if (value === 'null') {
            return { name: 'null', mandatory: !optional, grid: null, isNull: true };
        }
        return {
            name: value,
            mandatory: !optional,
            grid: loadedNadgrids[value] || null,
            isNull: false
        };
    }
    function degreesToRadians(degrees) {
        return (degrees) * Math.PI / 180;
    }
    function secondsToRadians(seconds) {
        return (seconds / 3600) * Math.PI / 180;
    }
    function detectLittleEndian(view) {
        var nFields = view.getInt32(8, false);
        if (nFields === 11) {
            return false;
        }
        nFields = view.getInt32(8, true);
        if (nFields !== 11) {
            console.warn('Failed to detect nadgrid endian-ness, defaulting to little-endian');
        }
        return true;
    }
    function readHeader(view, isLittleEndian) {
        return {
            nFields: view.getInt32(8, isLittleEndian),
            nSubgridFields: view.getInt32(24, isLittleEndian),
            nSubgrids: view.getInt32(40, isLittleEndian),
            shiftType: decodeString(view, 56, 56 + 8).trim(),
            fromSemiMajorAxis: view.getFloat64(120, isLittleEndian),
            fromSemiMinorAxis: view.getFloat64(136, isLittleEndian),
            toSemiMajorAxis: view.getFloat64(152, isLittleEndian),
            toSemiMinorAxis: view.getFloat64(168, isLittleEndian)
        };
    }
    function decodeString(view, start, end) {
        return String.fromCharCode.apply(null, new Uint8Array(view.buffer.slice(start, end)));
    }
    function readSubgrids(view, header, isLittleEndian, includeErrorFields) {
        var gridOffset = 176;
        var grids = [];
        for (var i = 0; i < header.nSubgrids; i++) {
            var subHeader = readGridHeader(view, gridOffset, isLittleEndian);
            var nodes = readGridNodes(view, gridOffset, subHeader, isLittleEndian, includeErrorFields);
            var lngColumnCount = Math.round(1 + (subHeader.upperLongitude - subHeader.lowerLongitude) / subHeader.longitudeInterval);
            var latColumnCount = Math.round(1 + (subHeader.upperLatitude - subHeader.lowerLatitude) / subHeader.latitudeInterval);
            // Proj4 operates on radians whereas the coordinates are in seconds in the grid
            grids.push({
                ll: [secondsToRadians(subHeader.lowerLongitude), secondsToRadians(subHeader.lowerLatitude)],
                del: [secondsToRadians(subHeader.longitudeInterval), secondsToRadians(subHeader.latitudeInterval)],
                lim: [lngColumnCount, latColumnCount],
                count: subHeader.gridNodeCount,
                cvs: mapNodes(nodes)
            });
            var rowSize = 16;
            if (includeErrorFields === false) {
                rowSize = 8;
            }
            gridOffset += 176 + subHeader.gridNodeCount * rowSize;
        }
        return grids;
    }
    /**
     * @param {*} nodes
     * @returns Array<Array<number>>
     */
    function mapNodes(nodes) {
        return nodes.map(function (r) {
            return [secondsToRadians(r.longitudeShift), secondsToRadians(r.latitudeShift)];
        });
    }
    function readGridHeader(view, offset, isLittleEndian) {
        return {
            name: decodeString(view, offset + 8, offset + 16).trim(),
            parent: decodeString(view, offset + 24, offset + 24 + 8).trim(),
            lowerLatitude: view.getFloat64(offset + 72, isLittleEndian),
            upperLatitude: view.getFloat64(offset + 88, isLittleEndian),
            lowerLongitude: view.getFloat64(offset + 104, isLittleEndian),
            upperLongitude: view.getFloat64(offset + 120, isLittleEndian),
            latitudeInterval: view.getFloat64(offset + 136, isLittleEndian),
            longitudeInterval: view.getFloat64(offset + 152, isLittleEndian),
            gridNodeCount: view.getInt32(offset + 168, isLittleEndian)
        };
    }
    function readGridNodes(view, offset, gridHeader, isLittleEndian, includeErrorFields) {
        var nodesOffset = offset + 176;
        var gridRecordLength = 16;
        if (includeErrorFields === false) {
            gridRecordLength = 8;
        }
        var gridShiftRecords = [];
        for (var i = 0; i < gridHeader.gridNodeCount; i++) {
            var record = {
                latitudeShift: view.getFloat32(nodesOffset + i * gridRecordLength, isLittleEndian),
                longitudeShift: view.getFloat32(nodesOffset + i * gridRecordLength + 4, isLittleEndian)
            };
            if (includeErrorFields !== false) {
                record.latitudeAccuracy = view.getFloat32(nodesOffset + i * gridRecordLength + 8, isLittleEndian);
                record.longitudeAccuracy = view.getFloat32(nodesOffset + i * gridRecordLength + 12, isLittleEndian);
            }
            gridShiftRecords.push(record);
        }
        return gridShiftRecords;
    }
},
/* proj4/lib/transform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.transformInternal = transformInternal;
    exports.default = transform;
    const tslib_1 = require(1) /* tslib */;
    const values_1 = require(156) /* ./constants/values */;
    const datum_transform_1 = tslib_1.__importDefault(require(183) /* ./datum_transform */);
    const adjust_axis_1 = require(185) /* ./adjust_axis */;
    const Proj_1 = tslib_1.__importDefault(require(151) /* ./Proj */);
    const toPoint_1 = tslib_1.__importDefault(require(186) /* ./common/toPoint */);
    const checkSanity_1 = tslib_1.__importDefault(require(187) /* ./checkSanity */);
    function checkNotWGS(source, dest) {
        return ((source.datum.datum_type === values_1.PJD_3PARAM || source.datum.datum_type === values_1.PJD_7PARAM || source.datum.datum_type === values_1.PJD_GRIDSHIFT) && dest.datumCode !== 'WGS84')
            || ((dest.datum.datum_type === values_1.PJD_3PARAM || dest.datum.datum_type === values_1.PJD_7PARAM || dest.datum.datum_type === values_1.PJD_GRIDSHIFT) && source.datumCode !== 'WGS84');
    }
    /**
     * Internal transform: accepts an already-cloned point object, returns transformed point object.
     * @param {import('./defs').ProjectionDefinition} source
     * @param {import('./defs').ProjectionDefinition} dest
     * @param {import('./core').InterfaceCoordinates} point
     * @param {boolean} [enforceAxis]
     * @returns {import('./core').InterfaceCoordinates | undefined}
     */
    function transformInternal(source, dest, point, enforceAxis) {
        var wgs84;
        var hasZ = point.z !== undefined;
        (0, checkSanity_1.default)(point);
        // Workaround for datum shifts towgs84, if either source or destination projection is not wgs84
        if (source.datum && dest.datum && checkNotWGS(source, dest)) {
            wgs84 = new Proj_1.default('WGS84');
            point = transformInternal(source, wgs84, point, enforceAxis);
            source = wgs84;
        }
        // DGR, 2010/11/12
        if (enforceAxis && source.axis !== 'enu') {
            point = (0, adjust_axis_1.adjustAxisToEnu)(source, point);
        }
        // Transform source points to long/lat, if they aren't already.
        if (source.projName === 'longlat') {
            point = {
                x: point.x * values_1.D2R,
                y: point.y * values_1.D2R,
                z: point.z || 0
            };
        }
        else {
            if (source.to_meter) {
                point = {
                    x: point.x * source.to_meter,
                    y: point.y * source.to_meter,
                    z: point.z || 0
                };
            }
            point = source.inverse(point); // Convert Cartesian to longlat
            if (!point) {
                return;
            }
        }
        // Adjust for the prime meridian if necessary
        if (source.from_greenwich) {
            point.x += source.from_greenwich;
        }
        // Convert datums if needed, and if possible.
        point = (0, datum_transform_1.default)(source.datum, dest.datum, point);
        if (!point) {
            return;
        }
        point = /** @type {import('./core').InterfaceCoordinates} */ (point);
        // Adjust for the prime meridian if necessary
        if (dest.from_greenwich) {
            point = {
                x: point.x - dest.from_greenwich,
                y: point.y,
                z: point.z || 0
            };
        }
        if (dest.projName === 'longlat') {
            // convert radians to decimal degrees
            point = {
                x: point.x * values_1.R2D,
                y: point.y * values_1.R2D,
                z: point.z || 0
            };
        }
        else { // else project
            point = dest.forward(point);
            if (dest.to_meter) {
                point = {
                    x: point.x / dest.to_meter,
                    y: point.y / dest.to_meter,
                    z: point.z || 0
                };
            }
        }
        // DGR, 2010/11/12
        if (enforceAxis && dest.axis !== 'enu') {
            return (0, adjust_axis_1.adjustAxisFromEnu)(dest, point);
        }
        if (point && !hasZ && dest.projName !== 'geocent') {
            delete point.z;
        }
        return point;
    }
    /**
     * @param {import('./defs').ProjectionDefinition} source
     * @param {import('./defs').ProjectionDefinition} dest
     * @param {import('./core').TemplateCoordinates} point
     * @param {boolean} [enforceAxis]
     * @returns {import('./core').InterfaceCoordinates | undefined}
     */
    function transform(source, dest, point, enforceAxis) {
        var pt;
        if (Array.isArray(point)) {
            pt = (0, toPoint_1.default)(point);
        }
        else {
            // Clone the point object so inputs don't get modified
            pt = { x: point.x, y: point.y, z: point.z, m: point.m };
        }
        return transformInternal(source, dest, pt, enforceAxis);
    }
},
/* proj4/lib/datum_transform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    exports.applyGridShift = applyGridShift;
    const tslib_1 = require(1) /* tslib */;
    const values_1 = require(156) /* ./constants/values */;
    const datumUtils_1 = require(184) /* ./datumUtils */;
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ./common/adjust_lon */);
    function checkParams(type) {
        return (type === values_1.PJD_3PARAM || type === values_1.PJD_7PARAM);
    }
    function default_1(source, dest, point) {
        // Short cut if the datums are identical.
        if ((0, datumUtils_1.compareDatums)(source, dest)) {
            return point; // in this case, zero is sucess,
            // whereas cs_compare_datums returns 1 to indicate TRUE
            // confusing, should fix this
        }
        // Explicitly skip datum transform by setting 'datum=none' as parameter for either source or dest
        if (source.datum_type === values_1.PJD_NODATUM || dest.datum_type === values_1.PJD_NODATUM) {
            return point;
        }
        // If this datum requires grid shifts, then apply it to geodetic coordinates.
        var source_a = source.a;
        var source_es = source.es;
        if (source.datum_type === values_1.PJD_GRIDSHIFT) {
            var gridShiftCode = applyGridShift(source, false, point);
            if (gridShiftCode !== 0) {
                return undefined;
            }
            source_a = values_1.SRS_WGS84_SEMIMAJOR;
            source_es = values_1.SRS_WGS84_ESQUARED;
        }
        var dest_a = dest.a;
        var dest_b = dest.b;
        var dest_es = dest.es;
        if (dest.datum_type === values_1.PJD_GRIDSHIFT) {
            dest_a = values_1.SRS_WGS84_SEMIMAJOR;
            dest_b = values_1.SRS_WGS84_SEMIMINOR;
            dest_es = values_1.SRS_WGS84_ESQUARED;
        }
        // Do we need to go through geocentric coordinates?
        if (source_es === dest_es && source_a === dest_a && !checkParams(source.datum_type) && !checkParams(dest.datum_type)) {
            return point;
        }
        // Convert to geocentric coordinates.
        point = (0, datumUtils_1.geodeticToGeocentric)(point, source_es, source_a);
        // Convert between datums
        if (checkParams(source.datum_type)) {
            point = (0, datumUtils_1.geocentricToWgs84)(point, source.datum_type, source.datum_params);
        }
        if (checkParams(dest.datum_type)) {
            point = (0, datumUtils_1.geocentricFromWgs84)(point, dest.datum_type, dest.datum_params);
        }
        point = (0, datumUtils_1.geocentricToGeodetic)(point, dest_es, dest_a, dest_b);
        if (dest.datum_type === values_1.PJD_GRIDSHIFT) {
            var destGridShiftResult = applyGridShift(dest, true, point);
            if (destGridShiftResult !== 0) {
                return undefined;
            }
        }
        return point;
    }
    function applyGridShift(source, inverse, point) {
        if (source.grids === null || source.grids.length === 0) {
            console.log('Grid shift grids not found');
            return -1;
        }
        var input = { x: -point.x, y: point.y };
        var output = { x: Number.NaN, y: Number.NaN };
        var attemptedGrids = [];
        outer: for (var i = 0; i < source.grids.length; i++) {
            var grid = source.grids[i];
            attemptedGrids.push(grid.name);
            if (grid.isNull) {
                output = input;
                break;
            }
            if (grid.grid === null) {
                if (grid.mandatory) {
                    console.log('Unable to find mandatory grid \'' + grid.name + '\'');
                    return -1;
                }
                continue;
            }
            var subgrids = grid.grid.subgrids;
            for (var j = 0, jj = subgrids.length; j < jj; j++) {
                var subgrid = subgrids[j];
                // skip tables that don't match our point at all
                var epsilon = (Math.abs(subgrid.del[1]) + Math.abs(subgrid.del[0])) / 10000.0;
                var minX = subgrid.ll[0] - epsilon;
                var minY = subgrid.ll[1] - epsilon;
                var maxX = subgrid.ll[0] + (subgrid.lim[0] - 1) * subgrid.del[0] + epsilon;
                var maxY = subgrid.ll[1] + (subgrid.lim[1] - 1) * subgrid.del[1] + epsilon;
                if (minY > input.y || minX > input.x || maxY < input.y || maxX < input.x) {
                    continue;
                }
                output = applySubgridShift(input, inverse, subgrid);
                if (!isNaN(output.x)) {
                    break outer;
                }
            }
        }
        if (isNaN(output.x)) {
            console.log('Failed to find a grid shift table for location \''
                + -input.x * values_1.R2D + ' ' + input.y * values_1.R2D + ' tried: \'' + attemptedGrids + '\'');
            return -1;
        }
        point.x = -output.x;
        point.y = output.y;
        return 0;
    }
    function applySubgridShift(pin, inverse, ct) {
        var val = { x: Number.NaN, y: Number.NaN };
        if (isNaN(pin.x)) {
            return val;
        }
        var tb = { x: pin.x, y: pin.y };
        tb.x -= ct.ll[0];
        tb.y -= ct.ll[1];
        tb.x = (0, adjust_lon_1.default)(tb.x - Math.PI) + Math.PI;
        var t = nadInterpolate(tb, ct);
        if (inverse) {
            if (isNaN(t.x)) {
                return val;
            }
            t.x = tb.x - t.x;
            t.y = tb.y - t.y;
            var i = 9, tol = 1e-12;
            var dif, del;
            do {
                del = nadInterpolate(t, ct);
                if (isNaN(del.x)) {
                    console.log('Inverse grid shift iteration failed, presumably at grid edge.  Using first approximation.');
                    break;
                }
                dif = { x: tb.x - (del.x + t.x), y: tb.y - (del.y + t.y) };
                t.x += dif.x;
                t.y += dif.y;
            } while (i-- && Math.abs(dif.x) > tol && Math.abs(dif.y) > tol);
            if (i < 0) {
                console.log('Inverse grid shift iterator failed to converge.');
                return val;
            }
            val.x = (0, adjust_lon_1.default)(t.x + ct.ll[0]);
            val.y = t.y + ct.ll[1];
        }
        else {
            if (!isNaN(t.x)) {
                val.x = pin.x + t.x;
                val.y = pin.y + t.y;
            }
        }
        return val;
    }
    function nadInterpolate(pin, ct) {
        var t = { x: pin.x / ct.del[0], y: pin.y / ct.del[1] };
        var indx = { x: Math.floor(t.x), y: Math.floor(t.y) };
        var frct = { x: t.x - 1.0 * indx.x, y: t.y - 1.0 * indx.y };
        var val = { x: Number.NaN, y: Number.NaN };
        var inx;
        if (indx.x < 0 || indx.x >= ct.lim[0]) {
            return val;
        }
        if (indx.y < 0 || indx.y >= ct.lim[1]) {
            return val;
        }
        inx = (indx.y * ct.lim[0]) + indx.x;
        var f00 = { x: ct.cvs[inx][0], y: ct.cvs[inx][1] };
        inx++;
        var f10 = { x: ct.cvs[inx][0], y: ct.cvs[inx][1] };
        inx += ct.lim[0];
        var f11 = { x: ct.cvs[inx][0], y: ct.cvs[inx][1] };
        inx--;
        var f01 = { x: ct.cvs[inx][0], y: ct.cvs[inx][1] };
        var m11 = frct.x * frct.y, m10 = frct.x * (1.0 - frct.y), m00 = (1.0 - frct.x) * (1.0 - frct.y), m01 = (1.0 - frct.x) * frct.y;
        val.x = (m00 * f00.x + m10 * f10.x + m01 * f01.x + m11 * f11.x);
        val.y = (m00 * f00.y + m10 * f10.y + m01 * f01.y + m11 * f11.y);
        return val;
    }
},
/* proj4/lib/datumUtils.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.compareDatums = compareDatums;
    exports.geodeticToGeocentric = geodeticToGeocentric;
    exports.geocentricToGeodetic = geocentricToGeodetic;
    exports.geocentricToWgs84 = geocentricToWgs84;
    exports.geocentricFromWgs84 = geocentricFromWgs84;
    const values_1 = require(156) /* ./constants/values */;
    function compareDatums(source, dest) {
        if (source.datum_type !== dest.datum_type) {
            return false; // false, datums are not equal
        }
        else if (source.a !== dest.a || Math.abs(source.es - dest.es) > 0.000000000050) {
            // the tolerance for es is to ensure that GRS80 and WGS84
            // are considered identical
            return false;
        }
        else if (source.datum_type === values_1.PJD_3PARAM) {
            return (source.datum_params[0] === dest.datum_params[0] && source.datum_params[1] === dest.datum_params[1] && source.datum_params[2] === dest.datum_params[2]);
        }
        else if (source.datum_type === values_1.PJD_7PARAM) {
            return (source.datum_params[0] === dest.datum_params[0] && source.datum_params[1] === dest.datum_params[1] && source.datum_params[2] === dest.datum_params[2] && source.datum_params[3] === dest.datum_params[3] && source.datum_params[4] === dest.datum_params[4] && source.datum_params[5] === dest.datum_params[5] && source.datum_params[6] === dest.datum_params[6]);
        }
        else {
            return true; // datums are equal
        }
    } // cs_compare_datums()
    /*
     * The function Convert_Geodetic_To_Geocentric converts geodetic coordinates
     * (latitude, longitude, and height) to geocentric coordinates (X, Y, Z),
     * according to the current ellipsoid parameters.
     *
     *    Latitude  : Geodetic latitude in radians                     (input)
     *    Longitude : Geodetic longitude in radians                    (input)
     *    Height    : Geodetic height, in meters                       (input)
     *    X         : Calculated Geocentric X coordinate, in meters    (output)
     *    Y         : Calculated Geocentric Y coordinate, in meters    (output)
     *    Z         : Calculated Geocentric Z coordinate, in meters    (output)
     *
     */
    function geodeticToGeocentric(p, es, a) {
        var Longitude = p.x;
        var Latitude = p.y;
        var Height = p.z ? p.z : 0; // Z value not always supplied
        var Rn; /*  Earth radius at location  */
        var Sin_Lat; /*  Math.sin(Latitude)  */
        var Sin2_Lat; /*  Square of Math.sin(Latitude)  */
        var Cos_Lat; /*  Math.cos(Latitude)  */
        /*
         ** Don't blow up if Latitude is just a little out of the value
         ** range as it may just be a rounding issue.  Also removed longitude
         ** test, it should be wrapped by Math.cos() and Math.sin().  NFW for PROJ.4, Sep/2001.
         */
        if (Latitude < -values_1.HALF_PI && Latitude > -1.001 * values_1.HALF_PI) {
            Latitude = -values_1.HALF_PI;
        }
        else if (Latitude > values_1.HALF_PI && Latitude < 1.001 * values_1.HALF_PI) {
            Latitude = values_1.HALF_PI;
        }
        else if (Latitude < -values_1.HALF_PI) {
            /* Latitude out of range */
            // ..reportError('geocent:lat out of range:' + Latitude);
            return { x: -Infinity, y: -Infinity, z: p.z };
        }
        else if (Latitude > values_1.HALF_PI) {
            /* Latitude out of range */
            return { x: Infinity, y: Infinity, z: p.z };
        }
        if (Longitude > Math.PI) {
            Longitude -= (2 * Math.PI);
        }
        Sin_Lat = Math.sin(Latitude);
        Cos_Lat = Math.cos(Latitude);
        Sin2_Lat = Sin_Lat * Sin_Lat;
        Rn = a / (Math.sqrt(1.0e0 - es * Sin2_Lat));
        return {
            x: (Rn + Height) * Cos_Lat * Math.cos(Longitude),
            y: (Rn + Height) * Cos_Lat * Math.sin(Longitude),
            z: ((Rn * (1 - es)) + Height) * Sin_Lat
        };
    } // cs_geodetic_to_geocentric()
    function geocentricToGeodetic(p, es, a, b) {
        /* local defintions and variables */
        /* end-criterium of loop, accuracy of sin(Latitude) */
        var genau = 1e-12;
        var genau2 = (genau * genau);
        var maxiter = 30;
        var P; /* distance between semi-minor axis and location */
        var RR; /* distance between center and location */
        var CT; /* sin of geocentric latitude */
        var ST; /* cos of geocentric latitude */
        var RX;
        var RK;
        var RN; /* Earth radius at location */
        var CPHI0; /* cos of start or old geodetic latitude in iterations */
        var SPHI0; /* sin of start or old geodetic latitude in iterations */
        var CPHI; /* cos of searched geodetic latitude */
        var SPHI; /* sin of searched geodetic latitude */
        var SDPHI; /* end-criterium: addition-theorem of sin(Latitude(iter)-Latitude(iter-1)) */
        var iter; /* # of continous iteration, max. 30 is always enough (s.a.) */
        var X = p.x;
        var Y = p.y;
        var Z = p.z ? p.z : 0.0; // Z value not always supplied
        var Longitude;
        var Latitude;
        var Height;
        P = Math.sqrt(X * X + Y * Y);
        RR = Math.sqrt(X * X + Y * Y + Z * Z);
        /*      special cases for latitude and longitude */
        if (P / a < genau) {
            /*  special case, if P=0. (X=0., Y=0.) */
            Longitude = 0.0;
            /*  if (X,Y,Z)=(0.,0.,0.) then Height becomes semi-minor axis
             *  of ellipsoid (=center of mass), Latitude becomes PI/2 */
            if (RR / a < genau) {
                Latitude = values_1.HALF_PI;
                Height = -b;
                return {
                    x: p.x,
                    y: p.y,
                    z: p.z
                };
            }
        }
        else {
            /*  ellipsoidal (geodetic) longitude
             *  interval: -PI < Longitude <= +PI */
            Longitude = Math.atan2(Y, X);
        }
        /* --------------------------------------------------------------
         * Following iterative algorithm was developped by
         * "Institut for Erdmessung", University of Hannover, July 1988.
         * Internet: www.ife.uni-hannover.de
         * Iterative computation of CPHI,SPHI and Height.
         * Iteration of CPHI and SPHI to 10**-12 radian resp.
         * 2*10**-7 arcsec.
         * --------------------------------------------------------------
         */
        CT = Z / RR;
        ST = P / RR;
        RX = 1.0 / Math.sqrt(1.0 - es * (2.0 - es) * ST * ST);
        CPHI0 = ST * (1.0 - es) * RX;
        SPHI0 = CT * RX;
        iter = 0;
        /* loop to find sin(Latitude) resp. Latitude
         * until |sin(Latitude(iter)-Latitude(iter-1))| < genau */
        do {
            iter++;
            RN = a / Math.sqrt(1.0 - es * SPHI0 * SPHI0);
            /*  ellipsoidal (geodetic) height */
            Height = P * CPHI0 + Z * SPHI0 - RN * (1.0 - es * SPHI0 * SPHI0);
            RK = es * RN / (RN + Height);
            RX = 1.0 / Math.sqrt(1.0 - RK * (2.0 - RK) * ST * ST);
            CPHI = ST * (1.0 - RK) * RX;
            SPHI = CT * RX;
            SDPHI = SPHI * CPHI0 - CPHI * SPHI0;
            CPHI0 = CPHI;
            SPHI0 = SPHI;
        } while (SDPHI * SDPHI > genau2 && iter < maxiter);
        /*      ellipsoidal (geodetic) latitude */
        Latitude = Math.atan(SPHI / Math.abs(CPHI));
        return {
            x: Longitude,
            y: Latitude,
            z: Height
        };
    } // cs_geocentric_to_geodetic()
    /****************************************************************/
    // pj_geocentic_to_wgs84( p )
    //  p = point to transform in geocentric coordinates (x,y,z)
    /** point object, nothing fancy, just allows values to be
        passed back and forth by reference rather than by value.
        Other point classes may be used as long as they have
        x and y properties, which will get modified in the transform method.
    */
    function geocentricToWgs84(p, datum_type, datum_params) {
        if (datum_type === values_1.PJD_3PARAM) {
            // if( x[io] === HUGE_VAL )
            //    continue;
            return {
                x: p.x + datum_params[0],
                y: p.y + datum_params[1],
                z: p.z + datum_params[2]
            };
        }
        else if (datum_type === values_1.PJD_7PARAM) {
            var Dx_BF = datum_params[0];
            var Dy_BF = datum_params[1];
            var Dz_BF = datum_params[2];
            var Rx_BF = datum_params[3];
            var Ry_BF = datum_params[4];
            var Rz_BF = datum_params[5];
            var M_BF = datum_params[6];
            // if( x[io] === HUGE_VAL )
            //    continue;
            return {
                x: M_BF * (p.x - Rz_BF * p.y + Ry_BF * p.z) + Dx_BF,
                y: M_BF * (Rz_BF * p.x + p.y - Rx_BF * p.z) + Dy_BF,
                z: M_BF * (-Ry_BF * p.x + Rx_BF * p.y + p.z) + Dz_BF
            };
        }
    } // cs_geocentric_to_wgs84
    /****************************************************************/
    // pj_geocentic_from_wgs84()
    //  coordinate system definition,
    //  point to transform in geocentric coordinates (x,y,z)
    function geocentricFromWgs84(p, datum_type, datum_params) {
        if (datum_type === values_1.PJD_3PARAM) {
            // if( x[io] === HUGE_VAL )
            //    continue;
            return {
                x: p.x - datum_params[0],
                y: p.y - datum_params[1],
                z: p.z - datum_params[2]
            };
        }
        else if (datum_type === values_1.PJD_7PARAM) {
            var Dx_BF = datum_params[0];
            var Dy_BF = datum_params[1];
            var Dz_BF = datum_params[2];
            var Rx_BF = datum_params[3];
            var Ry_BF = datum_params[4];
            var Rz_BF = datum_params[5];
            var M_BF = datum_params[6];
            var x_tmp = (p.x - Dx_BF) / M_BF;
            var y_tmp = (p.y - Dy_BF) / M_BF;
            var z_tmp = (p.z - Dz_BF) / M_BF;
            // if( x[io] === HUGE_VAL )
            //    continue;
            return {
                x: x_tmp + Rz_BF * y_tmp - Ry_BF * z_tmp,
                y: -Rz_BF * x_tmp + y_tmp + Rx_BF * z_tmp,
                z: Ry_BF * x_tmp - Rx_BF * y_tmp + z_tmp
            };
        } // cs_geocentric_from_wgs84()
    }
},
/* proj4/lib/adjust_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.adjustAxisToEnu = adjustAxisToEnu;
    exports.adjustAxisFromEnu = adjustAxisFromEnu;
    var order = ['x', 'y', 'z'];
    /**
     * Convert a point in a given CRS axis order to ENU (east/north/up) order
     * @param {import('./defs').ProjectionDefinition} crs
     * @param {import('./core').InterfaceCoordinates} point
     * @returns {import('./core').InterfaceCoordinates | null}
     */
    function adjustAxisToEnu(crs, point) {
        /** @type {import("./core").InterfaceCoordinates} */
        const out = {};
        for (let i = 0, ii = crs.axis.length; i < ii; i++) {
            if (i === 2 && point.z === undefined) {
                continue;
            }
            let v = point[order[i]];
            switch (crs.axis[i]) {
                case 'e':
                    out.x = v;
                    break;
                case 'w':
                    out.x = -v;
                    break;
                case 'n':
                    out.y = v;
                    break;
                case 's':
                    out.y = -v;
                    break;
                case 'u':
                    out.z = v;
                    break;
                case 'd':
                    out.z = -v;
                    break;
                default:
                    // console.log("ERROR: unknown axis ("+crs.axis[i]+") - check definition of "+crs.projName);
                    return null;
            }
        }
        return out;
    }
    /**
     * Convert a point in ENU (east/north/up) order to the given CRS axis order.
     * @param {import('./defs').ProjectionDefinition} crs
     * @param {import('./core').InterfaceCoordinates} point
     * @returns {import('./core').InterfaceCoordinates | null}
     */
    function adjustAxisFromEnu(crs, point) {
        const out = /** @type {import("./core").InterfaceCoordinates} */ ({});
        for (let i = 0, ii = crs.axis.length; i < ii; i++) {
            if (i === 2 && point.z === undefined) {
                continue;
            }
            switch (crs.axis[i]) {
                case 'e':
                    out[order[i]] = point.x;
                    break;
                case 'w':
                    out[order[i]] = -point.x;
                    break;
                case 'n':
                    out[order[i]] = point.y;
                    break;
                case 's':
                    out[order[i]] = -point.y;
                    break;
                case 'u':
                    out[order[i]] = point.z;
                    break;
                case 'd':
                    out[order[i]] = -point.z;
                    break;
                default:
                    // console.log("ERROR: unknown axis ("+crs.axis[i]+") - check definition of "+crs.projName);
                    return null;
            }
        }
        return out;
    }
},
/* proj4/lib/common/toPoint.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    /**
     * @param {Array<number>} array
     * @returns {import("../core").InterfaceCoordinates}
     */
    function default_1(array) {
        var out = {
            x: array[0],
            y: array[1]
        };
        if (array.length > 2) {
            out.z = array[2];
        }
        if (array.length > 3) {
            out.m = array[3];
        }
        return out;
    }
},
/* proj4/lib/checkSanity.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(point) {
        checkCoord(point.x);
        checkCoord(point.y);
    }
    function checkCoord(num) {
        if (typeof Number.isFinite === 'function') {
            if (Number.isFinite(num)) {
                return;
            }
            throw new TypeError('coordinates must be finite numbers');
        }
        if (typeof num !== 'number' || num !== num || !isFinite(num)) {
            throw new TypeError('coordinates must be finite numbers');
        }
    }
},
/* proj4/lib/Point.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const mgrs_1 = require(189) /* mgrs */;
    /**
     * @deprecated v3.0.0 - use proj4.toPoint instead
     * @param {number | import('./core').TemplateCoordinates | string} x
     * @param {number} [y]
     * @param {number} [z]
     */
    function Point(x, y, z) {
        if (!(this instanceof Point)) {
            return new Point(x, y, z);
        }
        if (Array.isArray(x)) {
            this.x = x[0];
            this.y = x[1];
            this.z = x[2] || 0.0;
        }
        else if (typeof x === 'object') {
            this.x = x.x;
            this.y = x.y;
            this.z = x.z || 0.0;
        }
        else if (typeof x === 'string' && typeof y === 'undefined') {
            var coords = x.split(',');
            this.x = parseFloat(coords[0]);
            this.y = parseFloat(coords[1]);
            this.z = parseFloat(coords[2]) || 0.0;
        }
        else {
            this.x = x;
            this.y = y;
            this.z = z || 0.0;
        }
        console.warn('proj4.Point will be removed in version 3, use proj4.toPoint');
    }
    Point.fromMGRS = function (mgrsStr) {
        return new Point((0, mgrs_1.toPoint)(mgrsStr));
    };
    Point.prototype.toMGRS = function (accuracy) {
        return (0, mgrs_1.forward)([this.x, this.y], accuracy);
    };
    exports.default = Point;
},
/* mgrs/mgrs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.forward = forward;
    exports.inverse = inverse;
    exports.toPoint = toPoint;
    /**
     * UTM zones are grouped, and assigned to one of a group of 6
     * sets.
     *
     * {int} @private
     */
    var NUM_100K_SETS = 6;
    /**
     * The column letters (for easting) of the lower left value, per
     * set.
     *
     * {string} @private
     */
    var SET_ORIGIN_COLUMN_LETTERS = 'AJSAJS';
    /**
     * The row letters (for northing) of the lower left value, per
     * set.
     *
     * {string} @private
     */
    var SET_ORIGIN_ROW_LETTERS = 'AFAFAF';
    var A = 65; // A
    var I = 73; // I
    var O = 79; // O
    var V = 86; // V
    var Z = 90; // Z
    exports.default = {
        forward: forward,
        inverse: inverse,
        toPoint: toPoint
    };
    /**
     * Conversion of lat/lon to MGRS.
     *
     * @param {object} ll Object literal with lat and lon properties on a
     *     WGS84 ellipsoid.
     * @param {int} accuracy Accuracy in digits (5 for 1 m, 4 for 10 m, 3 for
     *      100 m, 2 for 1000 m or 1 for 10000 m). Optional, default is 5.
     * @return {string} the MGRS string for the given location and accuracy.
     */
    function forward(ll, accuracy) {
        accuracy = accuracy || 5; // default accuracy 1m
        return encode(LLtoUTM({
            lat: ll[1],
            lon: ll[0]
        }), accuracy);
    }
    ;
    /**
     * Conversion of MGRS to lat/lon.
     *
     * @param {string} mgrs MGRS string.
     * @return {array} An array with left (longitude), bottom (latitude), right
     *     (longitude) and top (latitude) values in WGS84, representing the
     *     bounding box for the provided MGRS reference.
     */
    function inverse(mgrs) {
        var bbox = UTMtoLL(decode(mgrs.toUpperCase()));
        if (bbox.lat && bbox.lon) {
            return [bbox.lon, bbox.lat, bbox.lon, bbox.lat];
        }
        return [bbox.left, bbox.bottom, bbox.right, bbox.top];
    }
    ;
    function toPoint(mgrs) {
        var bbox = UTMtoLL(decode(mgrs.toUpperCase()));
        if (bbox.lat && bbox.lon) {
            return [bbox.lon, bbox.lat];
        }
        return [(bbox.left + bbox.right) / 2, (bbox.top + bbox.bottom) / 2];
    }
    ;
    /**
     * Conversion from degrees to radians.
     *
     * @private
     * @param {number} deg the angle in degrees.
     * @return {number} the angle in radians.
     */
    function degToRad(deg) {
        return (deg * (Math.PI / 180.0));
    }
    /**
     * Conversion from radians to degrees.
     *
     * @private
     * @param {number} rad the angle in radians.
     * @return {number} the angle in degrees.
     */
    function radToDeg(rad) {
        return (180.0 * (rad / Math.PI));
    }
    /**
     * Converts a set of Longitude and Latitude co-ordinates to UTM
     * using the WGS84 ellipsoid.
     *
     * @private
     * @param {object} ll Object literal with lat and lon properties
     *     representing the WGS84 coordinate to be converted.
     * @return {object} Object literal containing the UTM value with easting,
     *     northing, zoneNumber and zoneLetter properties, and an optional
     *     accuracy property in digits. Returns null if the conversion failed.
     */
    function LLtoUTM(ll) {
        var Lat = ll.lat;
        var Long = ll.lon;
        var a = 6378137.0; //ellip.radius;
        var eccSquared = 0.00669438; //ellip.eccsq;
        var k0 = 0.9996;
        var LongOrigin;
        var eccPrimeSquared;
        var N, T, C, A, M;
        var LatRad = degToRad(Lat);
        var LongRad = degToRad(Long);
        var LongOriginRad;
        var ZoneNumber;
        // (int)
        ZoneNumber = Math.floor((Long + 180) / 6) + 1;
        //Make sure the longitude 180.00 is in Zone 60
        if (Long === 180) {
            ZoneNumber = 60;
        }
        // Special zone for Norway
        if (Lat >= 56.0 && Lat < 64.0 && Long >= 3.0 && Long < 12.0) {
            ZoneNumber = 32;
        }
        // Special zones for Svalbard
        if (Lat >= 72.0 && Lat < 84.0) {
            if (Long >= 0.0 && Long < 9.0) {
                ZoneNumber = 31;
            }
            else if (Long >= 9.0 && Long < 21.0) {
                ZoneNumber = 33;
            }
            else if (Long >= 21.0 && Long < 33.0) {
                ZoneNumber = 35;
            }
            else if (Long >= 33.0 && Long < 42.0) {
                ZoneNumber = 37;
            }
        }
        LongOrigin = (ZoneNumber - 1) * 6 - 180 + 3; //+3 puts origin
        // in middle of
        // zone
        LongOriginRad = degToRad(LongOrigin);
        eccPrimeSquared = (eccSquared) / (1 - eccSquared);
        N = a / Math.sqrt(1 - eccSquared * Math.sin(LatRad) * Math.sin(LatRad));
        T = Math.tan(LatRad) * Math.tan(LatRad);
        C = eccPrimeSquared * Math.cos(LatRad) * Math.cos(LatRad);
        A = Math.cos(LatRad) * (LongRad - LongOriginRad);
        M = a * ((1 - eccSquared / 4 - 3 * eccSquared * eccSquared / 64 - 5 * eccSquared * eccSquared * eccSquared / 256) * LatRad - (3 * eccSquared / 8 + 3 * eccSquared * eccSquared / 32 + 45 * eccSquared * eccSquared * eccSquared / 1024) * Math.sin(2 * LatRad) + (15 * eccSquared * eccSquared / 256 + 45 * eccSquared * eccSquared * eccSquared / 1024) * Math.sin(4 * LatRad) - (35 * eccSquared * eccSquared * eccSquared / 3072) * Math.sin(6 * LatRad));
        var UTMEasting = (k0 * N * (A + (1 - T + C) * A * A * A / 6.0 + (5 - 18 * T + T * T + 72 * C - 58 * eccPrimeSquared) * A * A * A * A * A / 120.0) + 500000.0);
        var UTMNorthing = (k0 * (M + N * Math.tan(LatRad) * (A * A / 2 + (5 - T + 9 * C + 4 * C * C) * A * A * A * A / 24.0 + (61 - 58 * T + T * T + 600 * C - 330 * eccPrimeSquared) * A * A * A * A * A * A / 720.0)));
        if (Lat < 0.0) {
            UTMNorthing += 10000000.0; //10000000 meter offset for
            // southern hemisphere
        }
        return {
            northing: Math.round(UTMNorthing),
            easting: Math.round(UTMEasting),
            zoneNumber: ZoneNumber,
            zoneLetter: getLetterDesignator(Lat)
        };
    }
    /**
     * Converts UTM coords to lat/long, using the WGS84 ellipsoid. This is a convenience
     * class where the Zone can be specified as a single string eg."60N" which
     * is then broken down into the ZoneNumber and ZoneLetter.
     *
     * @private
     * @param {object} utm An object literal with northing, easting, zoneNumber
     *     and zoneLetter properties. If an optional accuracy property is
     *     provided (in meters), a bounding box will be returned instead of
     *     latitude and longitude.
     * @return {object} An object literal containing either lat and lon values
     *     (if no accuracy was provided), or top, right, bottom and left values
     *     for the bounding box calculated according to the provided accuracy.
     *     Returns null if the conversion failed.
     */
    function UTMtoLL(utm) {
        var UTMNorthing = utm.northing;
        var UTMEasting = utm.easting;
        var zoneLetter = utm.zoneLetter;
        var zoneNumber = utm.zoneNumber;
        // check the ZoneNummber is valid
        if (zoneNumber < 0 || zoneNumber > 60) {
            return null;
        }
        var k0 = 0.9996;
        var a = 6378137.0; //ellip.radius;
        var eccSquared = 0.00669438; //ellip.eccsq;
        var eccPrimeSquared;
        var e1 = (1 - Math.sqrt(1 - eccSquared)) / (1 + Math.sqrt(1 - eccSquared));
        var N1, T1, C1, R1, D, M;
        var LongOrigin;
        var mu, phi1Rad;
        // remove 500,000 meter offset for longitude
        var x = UTMEasting - 500000.0;
        var y = UTMNorthing;
        // We must know somehow if we are in the Northern or Southern
        // hemisphere, this is the only time we use the letter So even
        // if the Zone letter isn't exactly correct it should indicate
        // the hemisphere correctly
        if (zoneLetter < 'N') {
            y -= 10000000.0; // remove 10,000,000 meter offset used
            // for southern hemisphere
        }
        // There are 60 zones with zone 1 being at West -180 to -174
        LongOrigin = (zoneNumber - 1) * 6 - 180 + 3; // +3 puts origin
        // in middle of
        // zone
        eccPrimeSquared = (eccSquared) / (1 - eccSquared);
        M = y / k0;
        mu = M / (a * (1 - eccSquared / 4 - 3 * eccSquared * eccSquared / 64 - 5 * eccSquared * eccSquared * eccSquared / 256));
        phi1Rad = mu + (3 * e1 / 2 - 27 * e1 * e1 * e1 / 32) * Math.sin(2 * mu) + (21 * e1 * e1 / 16 - 55 * e1 * e1 * e1 * e1 / 32) * Math.sin(4 * mu) + (151 * e1 * e1 * e1 / 96) * Math.sin(6 * mu);
        // double phi1 = ProjMath.radToDeg(phi1Rad);
        N1 = a / Math.sqrt(1 - eccSquared * Math.sin(phi1Rad) * Math.sin(phi1Rad));
        T1 = Math.tan(phi1Rad) * Math.tan(phi1Rad);
        C1 = eccPrimeSquared * Math.cos(phi1Rad) * Math.cos(phi1Rad);
        R1 = a * (1 - eccSquared) / Math.pow(1 - eccSquared * Math.sin(phi1Rad) * Math.sin(phi1Rad), 1.5);
        D = x / (N1 * k0);
        var lat = phi1Rad - (N1 * Math.tan(phi1Rad) / R1) * (D * D / 2 - (5 + 3 * T1 + 10 * C1 - 4 * C1 * C1 - 9 * eccPrimeSquared) * D * D * D * D / 24 + (61 + 90 * T1 + 298 * C1 + 45 * T1 * T1 - 252 * eccPrimeSquared - 3 * C1 * C1) * D * D * D * D * D * D / 720);
        lat = radToDeg(lat);
        var lon = (D - (1 + 2 * T1 + C1) * D * D * D / 6 + (5 - 2 * C1 + 28 * T1 - 3 * C1 * C1 + 8 * eccPrimeSquared + 24 * T1 * T1) * D * D * D * D * D / 120) / Math.cos(phi1Rad);
        lon = LongOrigin + radToDeg(lon);
        var result;
        if (utm.accuracy) {
            var topRight = UTMtoLL({
                northing: utm.northing + utm.accuracy,
                easting: utm.easting + utm.accuracy,
                zoneLetter: utm.zoneLetter,
                zoneNumber: utm.zoneNumber
            });
            result = {
                top: topRight.lat,
                right: topRight.lon,
                bottom: lat,
                left: lon
            };
        }
        else {
            result = {
                lat: lat,
                lon: lon
            };
        }
        return result;
    }
    /**
     * Calculates the MGRS letter designator for the given latitude.
     *
     * @private
     * @param {number} lat The latitude in WGS84 to get the letter designator
     *     for.
     * @return {char} The letter designator.
     */
    function getLetterDesignator(lat) {
        //This is here as an error flag to show that the Latitude is
        //outside MGRS limits
        var LetterDesignator = 'Z';
        if ((84 >= lat) && (lat >= 72)) {
            LetterDesignator = 'X';
        }
        else if ((72 > lat) && (lat >= 64)) {
            LetterDesignator = 'W';
        }
        else if ((64 > lat) && (lat >= 56)) {
            LetterDesignator = 'V';
        }
        else if ((56 > lat) && (lat >= 48)) {
            LetterDesignator = 'U';
        }
        else if ((48 > lat) && (lat >= 40)) {
            LetterDesignator = 'T';
        }
        else if ((40 > lat) && (lat >= 32)) {
            LetterDesignator = 'S';
        }
        else if ((32 > lat) && (lat >= 24)) {
            LetterDesignator = 'R';
        }
        else if ((24 > lat) && (lat >= 16)) {
            LetterDesignator = 'Q';
        }
        else if ((16 > lat) && (lat >= 8)) {
            LetterDesignator = 'P';
        }
        else if ((8 > lat) && (lat >= 0)) {
            LetterDesignator = 'N';
        }
        else if ((0 > lat) && (lat >= -8)) {
            LetterDesignator = 'M';
        }
        else if ((-8 > lat) && (lat >= -16)) {
            LetterDesignator = 'L';
        }
        else if ((-16 > lat) && (lat >= -24)) {
            LetterDesignator = 'K';
        }
        else if ((-24 > lat) && (lat >= -32)) {
            LetterDesignator = 'J';
        }
        else if ((-32 > lat) && (lat >= -40)) {
            LetterDesignator = 'H';
        }
        else if ((-40 > lat) && (lat >= -48)) {
            LetterDesignator = 'G';
        }
        else if ((-48 > lat) && (lat >= -56)) {
            LetterDesignator = 'F';
        }
        else if ((-56 > lat) && (lat >= -64)) {
            LetterDesignator = 'E';
        }
        else if ((-64 > lat) && (lat >= -72)) {
            LetterDesignator = 'D';
        }
        else if ((-72 > lat) && (lat >= -80)) {
            LetterDesignator = 'C';
        }
        return LetterDesignator;
    }
    /**
     * Encodes a UTM location as MGRS string.
     *
     * @private
     * @param {object} utm An object literal with easting, northing,
     *     zoneLetter, zoneNumber
     * @param {number} accuracy Accuracy in digits (1-5).
     * @return {string} MGRS string for the given UTM location.
     */
    function encode(utm, accuracy) {
        // prepend with leading zeroes
        var seasting = "00000" + utm.easting, snorthing = "00000" + utm.northing;
        return utm.zoneNumber + utm.zoneLetter + get100kID(utm.easting, utm.northing, utm.zoneNumber) + seasting.substr(seasting.length - 5, accuracy) + snorthing.substr(snorthing.length - 5, accuracy);
    }
    /**
     * Get the two letter 100k designator for a given UTM easting,
     * northing and zone number value.
     *
     * @private
     * @param {number} easting
     * @param {number} northing
     * @param {number} zoneNumber
     * @return the two letter 100k designator for the given UTM location.
     */
    function get100kID(easting, northing, zoneNumber) {
        var setParm = get100kSetForZone(zoneNumber);
        var setColumn = Math.floor(easting / 100000);
        var setRow = Math.floor(northing / 100000) % 20;
        return getLetter100kID(setColumn, setRow, setParm);
    }
    /**
     * Given a UTM zone number, figure out the MGRS 100K set it is in.
     *
     * @private
     * @param {number} i An UTM zone number.
     * @return {number} the 100k set the UTM zone is in.
     */
    function get100kSetForZone(i) {
        var setParm = i % NUM_100K_SETS;
        if (setParm === 0) {
            setParm = NUM_100K_SETS;
        }
        return setParm;
    }
    /**
     * Get the two-letter MGRS 100k designator given information
     * translated from the UTM northing, easting and zone number.
     *
     * @private
     * @param {number} column the column index as it relates to the MGRS
     *        100k set spreadsheet, created from the UTM easting.
     *        Values are 1-8.
     * @param {number} row the row index as it relates to the MGRS 100k set
     *        spreadsheet, created from the UTM northing value. Values
     *        are from 0-19.
     * @param {number} parm the set block, as it relates to the MGRS 100k set
     *        spreadsheet, created from the UTM zone. Values are from
     *        1-60.
     * @return two letter MGRS 100k code.
     */
    function getLetter100kID(column, row, parm) {
        // colOrigin and rowOrigin are the letters at the origin of the set
        var index = parm - 1;
        var colOrigin = SET_ORIGIN_COLUMN_LETTERS.charCodeAt(index);
        var rowOrigin = SET_ORIGIN_ROW_LETTERS.charCodeAt(index);
        // colInt and rowInt are the letters to build to return
        var colInt = colOrigin + column - 1;
        var rowInt = rowOrigin + row;
        var rollover = false;
        if (colInt > Z) {
            colInt = colInt - Z + A - 1;
            rollover = true;
        }
        if (colInt === I || (colOrigin < I && colInt > I) || ((colInt > I || colOrigin < I) && rollover)) {
            colInt++;
        }
        if (colInt === O || (colOrigin < O && colInt > O) || ((colInt > O || colOrigin < O) && rollover)) {
            colInt++;
            if (colInt === I) {
                colInt++;
            }
        }
        if (colInt > Z) {
            colInt = colInt - Z + A - 1;
        }
        if (rowInt > V) {
            rowInt = rowInt - V + A - 1;
            rollover = true;
        }
        else {
            rollover = false;
        }
        if (((rowInt === I) || ((rowOrigin < I) && (rowInt > I))) || (((rowInt > I) || (rowOrigin < I)) && rollover)) {
            rowInt++;
        }
        if (((rowInt === O) || ((rowOrigin < O) && (rowInt > O))) || (((rowInt > O) || (rowOrigin < O)) && rollover)) {
            rowInt++;
            if (rowInt === I) {
                rowInt++;
            }
        }
        if (rowInt > V) {
            rowInt = rowInt - V + A - 1;
        }
        var twoLetter = String.fromCharCode(colInt) + String.fromCharCode(rowInt);
        return twoLetter;
    }
    /**
     * Decode the UTM parameters from a MGRS string.
     *
     * @private
     * @param {string} mgrsString an UPPERCASE coordinate string is expected.
     * @return {object} An object literal with easting, northing, zoneLetter,
     *     zoneNumber and accuracy (in meters) properties.
     */
    function decode(mgrsString) {
        if (mgrsString && mgrsString.length === 0) {
            throw ("MGRSPoint coverting from nothing");
        }
        var length = mgrsString.length;
        var hunK = null;
        var sb = "";
        var testChar;
        var i = 0;
        // get Zone number
        while (!(/[A-Z]/).test(testChar = mgrsString.charAt(i))) {
            if (i >= 2) {
                throw ("MGRSPoint bad conversion from: " + mgrsString);
            }
            sb += testChar;
            i++;
        }
        var zoneNumber = parseInt(sb, 10);
        if (i === 0 || i + 3 > length) {
            // A good MGRS string has to be 4-5 digits long,
            // ##AAA/#AAA at least.
            throw ("MGRSPoint bad conversion from: " + mgrsString);
        }
        var zoneLetter = mgrsString.charAt(i++);
        // Should we check the zone letter here? Why not.
        if (zoneLetter <= 'A' || zoneLetter === 'B' || zoneLetter === 'Y' || zoneLetter >= 'Z' || zoneLetter === 'I' || zoneLetter === 'O') {
            throw ("MGRSPoint zone letter " + zoneLetter + " not handled: " + mgrsString);
        }
        hunK = mgrsString.substring(i, i += 2);
        var set = get100kSetForZone(zoneNumber);
        var east100k = getEastingFromChar(hunK.charAt(0), set);
        var north100k = getNorthingFromChar(hunK.charAt(1), set);
        // We have a bug where the northing may be 2000000 too low.
        // How
        // do we know when to roll over?
        while (north100k < getMinNorthing(zoneLetter)) {
            north100k += 2000000;
        }
        // calculate the char index for easting/northing separator
        var remainder = length - i;
        if (remainder % 2 !== 0) {
            throw ("MGRSPoint has to have an even number \nof digits after the zone letter and two 100km letters - front \nhalf for easting meters, second half for \nnorthing meters" + mgrsString);
        }
        var sep = remainder / 2;
        var sepEasting = 0.0;
        var sepNorthing = 0.0;
        var accuracyBonus, sepEastingString, sepNorthingString, easting, northing;
        if (sep > 0) {
            accuracyBonus = 100000.0 / Math.pow(10, sep);
            sepEastingString = mgrsString.substring(i, i + sep);
            sepEasting = parseFloat(sepEastingString) * accuracyBonus;
            sepNorthingString = mgrsString.substring(i + sep);
            sepNorthing = parseFloat(sepNorthingString) * accuracyBonus;
        }
        easting = sepEasting + east100k;
        northing = sepNorthing + north100k;
        return {
            easting: easting,
            northing: northing,
            zoneLetter: zoneLetter,
            zoneNumber: zoneNumber,
            accuracy: accuracyBonus
        };
    }
    /**
     * Given the first letter from a two-letter MGRS 100k zone, and given the
     * MGRS table set for the zone number, figure out the easting value that
     * should be added to the other, secondary easting value.
     *
     * @private
     * @param {char} e The first letter from a two-letter MGRS 100´k zone.
     * @param {number} set The MGRS table set for the zone number.
     * @return {number} The easting value for the given letter and set.
     */
    function getEastingFromChar(e, set) {
        // colOrigin is the letter at the origin of the set for the
        // column
        var curCol = SET_ORIGIN_COLUMN_LETTERS.charCodeAt(set - 1);
        var eastingValue = 100000.0;
        var rewindMarker = false;
        while (curCol !== e.charCodeAt(0)) {
            curCol++;
            if (curCol === I) {
                curCol++;
            }
            if (curCol === O) {
                curCol++;
            }
            if (curCol > Z) {
                if (rewindMarker) {
                    throw ("Bad character: " + e);
                }
                curCol = A;
                rewindMarker = true;
            }
            eastingValue += 100000.0;
        }
        return eastingValue;
    }
    /**
     * Given the second letter from a two-letter MGRS 100k zone, and given the
     * MGRS table set for the zone number, figure out the northing value that
     * should be added to the other, secondary northing value. You have to
     * remember that Northings are determined from the equator, and the vertical
     * cycle of letters mean a 2000000 additional northing meters. This happens
     * approx. every 18 degrees of latitude. This method does *NOT* count any
     * additional northings. You have to figure out how many 2000000 meters need
     * to be added for the zone letter of the MGRS coordinate.
     *
     * @private
     * @param {char} n Second letter of the MGRS 100k zone
     * @param {number} set The MGRS table set number, which is dependent on the
     *     UTM zone number.
     * @return {number} The northing value for the given letter and set.
     */
    function getNorthingFromChar(n, set) {
        if (n > 'V') {
            throw ("MGRSPoint given invalid Northing " + n);
        }
        // rowOrigin is the letter at the origin of the set for the
        // column
        var curRow = SET_ORIGIN_ROW_LETTERS.charCodeAt(set - 1);
        var northingValue = 0.0;
        var rewindMarker = false;
        while (curRow !== n.charCodeAt(0)) {
            curRow++;
            if (curRow === I) {
                curRow++;
            }
            if (curRow === O) {
                curRow++;
            }
            // fixing a bug making whole application hang in this loop
            // when 'n' is a wrong character
            if (curRow > V) {
                if (rewindMarker) { // making sure that this loop ends
                    throw ("Bad character: " + n);
                }
                curRow = A;
                rewindMarker = true;
            }
            northingValue += 100000.0;
        }
        return northingValue;
    }
    /**
     * The function getMinNorthing returns the minimum northing value of a MGRS
     * zone.
     *
     * Ported from Geotrans' c Lattitude_Band_Value structure table.
     *
     * @private
     * @param {char} zoneLetter The MGRS zone to get the min northing for.
     * @return {number}
     */
    function getMinNorthing(zoneLetter) {
        var northing;
        switch (zoneLetter) {
            case 'C':
                northing = 1100000.0;
                break;
            case 'D':
                northing = 2000000.0;
                break;
            case 'E':
                northing = 2800000.0;
                break;
            case 'F':
                northing = 3700000.0;
                break;
            case 'G':
                northing = 4600000.0;
                break;
            case 'H':
                northing = 5500000.0;
                break;
            case 'J':
                northing = 6400000.0;
                break;
            case 'K':
                northing = 7300000.0;
                break;
            case 'L':
                northing = 8200000.0;
                break;
            case 'M':
                northing = 9100000.0;
                break;
            case 'N':
                northing = 0.0;
                break;
            case 'P':
                northing = 800000.0;
                break;
            case 'Q':
                northing = 1700000.0;
                break;
            case 'R':
                northing = 2600000.0;
                break;
            case 'S':
                northing = 3500000.0;
                break;
            case 'T':
                northing = 4400000.0;
                break;
            case 'U':
                northing = 5300000.0;
                break;
            case 'V':
                northing = 6200000.0;
                break;
            case 'W':
                northing = 7000000.0;
                break;
            case 'X':
                northing = 7900000.0;
                break;
            default:
                northing = -1.0;
        }
        if (northing >= 0.0) {
            return northing;
        }
        else {
            throw ("Invalid zone letter: " + zoneLetter);
        }
    }
},
/* proj4/projs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    const tslib_1 = require(1) /* tslib */;
    const tmerc_1 = tslib_1.__importDefault(require(191) /* ./lib/projections/tmerc */);
    const etmerc_1 = tslib_1.__importDefault(require(195) /* ./lib/projections/etmerc */);
    const utm_1 = tslib_1.__importDefault(require(204) /* ./lib/projections/utm */);
    const sterea_1 = tslib_1.__importDefault(require(206) /* ./lib/projections/sterea */);
    const stere_1 = tslib_1.__importDefault(require(209) /* ./lib/projections/stere */);
    const somerc_1 = tslib_1.__importDefault(require(210) /* ./lib/projections/somerc */);
    const omerc_1 = tslib_1.__importDefault(require(211) /* ./lib/projections/omerc */);
    const lcc_1 = tslib_1.__importDefault(require(212) /* ./lib/projections/lcc */);
    const krovak_1 = tslib_1.__importDefault(require(213) /* ./lib/projections/krovak */);
    const cass_1 = tslib_1.__importDefault(require(214) /* ./lib/projections/cass */);
    const laea_1 = tslib_1.__importDefault(require(223) /* ./lib/projections/laea */);
    const aea_1 = tslib_1.__importDefault(require(227) /* ./lib/projections/aea */);
    const gnom_1 = tslib_1.__importDefault(require(229) /* ./lib/projections/gnom */);
    const cea_1 = tslib_1.__importDefault(require(230) /* ./lib/projections/cea */);
    const eqc_1 = tslib_1.__importDefault(require(232) /* ./lib/projections/eqc */);
    const poly_1 = tslib_1.__importDefault(require(233) /* ./lib/projections/poly */);
    const nzmg_1 = tslib_1.__importDefault(require(234) /* ./lib/projections/nzmg */);
    const mill_1 = tslib_1.__importDefault(require(235) /* ./lib/projections/mill */);
    const sinu_1 = tslib_1.__importDefault(require(236) /* ./lib/projections/sinu */);
    const eck6_1 = tslib_1.__importDefault(require(237) /* ./lib/projections/eck6 */);
    const moll_1 = tslib_1.__importDefault(require(238) /* ./lib/projections/moll */);
    const eqdc_1 = tslib_1.__importDefault(require(239) /* ./lib/projections/eqdc */);
    const vandg_1 = tslib_1.__importDefault(require(240) /* ./lib/projections/vandg */);
    const aeqd_1 = tslib_1.__importDefault(require(241) /* ./lib/projections/aeqd */);
    const ortho_1 = tslib_1.__importDefault(require(243) /* ./lib/projections/ortho */);
    const qsc_1 = tslib_1.__importDefault(require(244) /* ./lib/projections/qsc */);
    const robin_1 = tslib_1.__importDefault(require(245) /* ./lib/projections/robin */);
    const geocent_1 = tslib_1.__importDefault(require(246) /* ./lib/projections/geocent */);
    const tpers_1 = tslib_1.__importDefault(require(247) /* ./lib/projections/tpers */);
    const geos_1 = tslib_1.__importDefault(require(248) /* ./lib/projections/geos */);
    const eqearth_1 = tslib_1.__importDefault(require(249) /* ./lib/projections/eqearth */);
    const bonne_1 = tslib_1.__importDefault(require(250) /* ./lib/projections/bonne */);
    const ob_tran_1 = tslib_1.__importDefault(require(251) /* ./lib/projections/ob_tran */);
    function default_1(proj4) {
        proj4.Proj.projections.add(tmerc_1.default);
        proj4.Proj.projections.add(etmerc_1.default);
        proj4.Proj.projections.add(utm_1.default);
        proj4.Proj.projections.add(sterea_1.default);
        proj4.Proj.projections.add(stere_1.default);
        proj4.Proj.projections.add(somerc_1.default);
        proj4.Proj.projections.add(omerc_1.default);
        proj4.Proj.projections.add(lcc_1.default);
        proj4.Proj.projections.add(krovak_1.default);
        proj4.Proj.projections.add(cass_1.default);
        proj4.Proj.projections.add(laea_1.default);
        proj4.Proj.projections.add(aea_1.default);
        proj4.Proj.projections.add(gnom_1.default);
        proj4.Proj.projections.add(cea_1.default);
        proj4.Proj.projections.add(eqc_1.default);
        proj4.Proj.projections.add(poly_1.default);
        proj4.Proj.projections.add(nzmg_1.default);
        proj4.Proj.projections.add(mill_1.default);
        proj4.Proj.projections.add(sinu_1.default);
        proj4.Proj.projections.add(eck6_1.default);
        proj4.Proj.projections.add(moll_1.default);
        proj4.Proj.projections.add(eqdc_1.default);
        proj4.Proj.projections.add(vandg_1.default);
        proj4.Proj.projections.add(aeqd_1.default);
        proj4.Proj.projections.add(ortho_1.default);
        proj4.Proj.projections.add(qsc_1.default);
        proj4.Proj.projections.add(robin_1.default);
        proj4.Proj.projections.add(geocent_1.default);
        proj4.Proj.projections.add(tpers_1.default);
        proj4.Proj.projections.add(geos_1.default);
        proj4.Proj.projections.add(eqearth_1.default);
        proj4.Proj.projections.add(bonne_1.default);
        proj4.Proj.projections.add(ob_tran_1.default);
    }
},
/* proj4/lib/projections/tmerc.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const pj_enfn_1 = tslib_1.__importDefault(require(192) /* ../common/pj_enfn */);
    const pj_mlfn_1 = tslib_1.__importDefault(require(193) /* ../common/pj_mlfn */);
    const pj_inv_mlfn_1 = tslib_1.__importDefault(require(194) /* ../common/pj_inv_mlfn */);
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    const values_1 = require(156) /* ../constants/values */;
    const sign_1 = tslib_1.__importDefault(require(173) /* ../common/sign */);
    /**
     * @typedef {Object} LocalThis
     * @property {number} es
     * @property {Array<number>} en
     * @property {number} ml0
     */
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function init() {
        this.x0 = this.x0 !== undefined ? this.x0 : 0;
        this.y0 = this.y0 !== undefined ? this.y0 : 0;
        this.long0 = this.long0 !== undefined ? this.long0 : 0;
        this.lat0 = this.lat0 !== undefined ? this.lat0 : 0;
        if (this.es) {
            this.en = (0, pj_enfn_1.default)(this.es);
            this.ml0 = (0, pj_mlfn_1.default)(this.lat0, Math.sin(this.lat0), Math.cos(this.lat0), this.en);
        }
    }
    /**
        Transverse Mercator Forward  - long/lat to x/y
        long/lat in radians
      */
    function forward(p) {
        var lon = p.x;
        var lat = p.y;
        var delta_lon = (0, adjust_lon_1.default)(lon - this.long0, this.over);
        var con;
        var x, y;
        var sin_phi = Math.sin(lat);
        var cos_phi = Math.cos(lat);
        if (!this.es) {
            var b = cos_phi * Math.sin(delta_lon);
            if ((Math.abs(Math.abs(b) - 1)) < values_1.EPSLN) {
                return (93);
            }
            else {
                x = 0.5 * this.a * this.k0 * Math.log((1 + b) / (1 - b)) + this.x0;
                y = cos_phi * Math.cos(delta_lon) / Math.sqrt(1 - Math.pow(b, 2));
                b = Math.abs(y);
                if (b >= 1) {
                    if ((b - 1) > values_1.EPSLN) {
                        return (93);
                    }
                    else {
                        y = 0;
                    }
                }
                else {
                    y = Math.acos(y);
                }
                if (lat < 0) {
                    y = -y;
                }
                y = this.a * this.k0 * (y - this.lat0) + this.y0;
            }
        }
        else {
            var al = cos_phi * delta_lon;
            var als = Math.pow(al, 2);
            var c = this.ep2 * Math.pow(cos_phi, 2);
            var cs = Math.pow(c, 2);
            var tq = Math.abs(cos_phi) > values_1.EPSLN ? Math.tan(lat) : 0;
            var t = Math.pow(tq, 2);
            var ts = Math.pow(t, 2);
            con = 1 - this.es * Math.pow(sin_phi, 2);
            al = al / Math.sqrt(con);
            var ml = (0, pj_mlfn_1.default)(lat, sin_phi, cos_phi, this.en);
            x = this.a * (this.k0 * al * (1
                + als / 6 * (1 - t + c
                    + als / 20 * (5 - 18 * t + ts + 14 * c - 58 * t * c
                        + als / 42 * (61 + 179 * ts - ts * t - 479 * t)))))
                + this.x0;
            y = this.a * (this.k0 * (ml - this.ml0
                + sin_phi * delta_lon * al / 2 * (1
                    + als / 12 * (5 - t + 9 * c + 4 * cs
                        + als / 30 * (61 + ts - 58 * t + 270 * c - 330 * t * c
                            + als / 56 * (1385 + 543 * ts - ts * t - 3111 * t))))))
                + this.y0;
        }
        p.x = x;
        p.y = y;
        return p;
    }
    /**
        Transverse Mercator Inverse  -  x/y to long/lat
      */
    function inverse(p) {
        var con, phi;
        var lat, lon;
        var x = (p.x - this.x0) * (1 / this.a);
        var y = (p.y - this.y0) * (1 / this.a);
        if (!this.es) {
            var f = Math.exp(x / this.k0);
            var g = 0.5 * (f - 1 / f);
            var temp = this.lat0 + y / this.k0;
            var h = Math.cos(temp);
            con = Math.sqrt((1 - Math.pow(h, 2)) / (1 + Math.pow(g, 2)));
            lat = Math.asin(con);
            if (y < 0) {
                lat = -lat;
            }
            if ((g === 0) && (h === 0)) {
                lon = 0;
            }
            else {
                lon = (0, adjust_lon_1.default)(Math.atan2(g, h) + this.long0, this.over);
            }
        }
        else { // ellipsoidal form
            con = this.ml0 + y / this.k0;
            phi = (0, pj_inv_mlfn_1.default)(con, this.es, this.en);
            if (Math.abs(phi) < values_1.HALF_PI) {
                var sin_phi = Math.sin(phi);
                var cos_phi = Math.cos(phi);
                var tan_phi = Math.abs(cos_phi) > values_1.EPSLN ? Math.tan(phi) : 0;
                var c = this.ep2 * Math.pow(cos_phi, 2);
                var cs = Math.pow(c, 2);
                var t = Math.pow(tan_phi, 2);
                var ts = Math.pow(t, 2);
                con = 1 - this.es * Math.pow(sin_phi, 2);
                var d = x * Math.sqrt(con) / this.k0;
                var ds = Math.pow(d, 2);
                con = con * tan_phi;
                lat = phi - (con * ds / (1 - this.es)) * 0.5 * (1
                    - ds / 12 * (5 + 3 * t - 9 * c * t + c - 4 * cs
                        - ds / 30 * (61 + 90 * t - 252 * c * t + 45 * ts + 46 * c
                            - ds / 56 * (1385 + 3633 * t + 4095 * ts + 1574 * ts * t))));
                lon = (0, adjust_lon_1.default)(this.long0 + (d * (1
                    - ds / 6 * (1 + 2 * t + c
                        - ds / 20 * (5 + 28 * t + 24 * ts + 8 * c * t + 6 * c
                            - ds / 42 * (61 + 662 * t + 1320 * ts + 720 * ts * t)))) / cos_phi), this.over);
            }
            else {
                lat = values_1.HALF_PI * (0, sign_1.default)(y);
                lon = 0;
            }
        }
        p.x = lon;
        p.y = lat;
        return p;
    }
    exports.names = ['Fast_Transverse_Mercator', 'Fast Transverse Mercator'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/common/pj_enfn.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    var C00 = 1;
    var C02 = 0.25;
    var C04 = 0.046875;
    var C06 = 0.01953125;
    var C08 = 0.01068115234375;
    var C22 = 0.75;
    var C44 = 0.46875;
    var C46 = 0.01302083333333333333;
    var C48 = 0.00712076822916666666;
    var C66 = 0.36458333333333333333;
    var C68 = 0.00569661458333333333;
    var C88 = 0.3076171875;
    function default_1(es) {
        var en = [];
        en[0] = C00 - es * (C02 + es * (C04 + es * (C06 + es * C08)));
        en[1] = es * (C22 - es * (C04 + es * (C06 + es * C08)));
        var t = es * es;
        en[2] = t * (C44 - es * (C46 + es * C48));
        t *= es;
        en[3] = t * (C66 - es * C68);
        en[4] = t * es * C88;
        return en;
    }
},
/* proj4/lib/common/pj_mlfn.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(phi, sphi, cphi, en) {
        cphi *= sphi;
        sphi *= sphi;
        return (en[0] * phi - cphi * (en[1] + sphi * (en[2] + sphi * (en[3] + sphi * en[4]))));
    }
},
/* proj4/lib/common/pj_inv_mlfn.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    const tslib_1 = require(1) /* tslib */;
    const pj_mlfn_1 = tslib_1.__importDefault(require(193) /* ./pj_mlfn */);
    const values_1 = require(156) /* ../constants/values */;
    var MAX_ITER = 20;
    function default_1(arg, es, en) {
        var k = 1 / (1 - es);
        var phi = arg;
        for (var i = MAX_ITER; i; --i) { /* rarely goes over 2 iterations */
            var s = Math.sin(phi);
            var t = 1 - es * s * s;
            // t = this.pj_mlfn(phi, s, Math.cos(phi), en) - arg;
            // phi -= t * (t * Math.sqrt(t)) * k;
            t = ((0, pj_mlfn_1.default)(phi, s, Math.cos(phi), en) - arg) * (t * Math.sqrt(t)) * k;
            phi -= t;
            if (Math.abs(t) < values_1.EPSLN) {
                return phi;
            }
        }
        // ..reportError("cass:pj_inv_mlfn: Convergence error");
        return phi;
    }
},
/* proj4/lib/projections/etmerc.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const tmerc_1 = tslib_1.__importDefault(require(191) /* ../projections/tmerc */);
    const sinh_1 = tslib_1.__importDefault(require(196) /* ../common/sinh */);
    const hypot_1 = tslib_1.__importDefault(require(197) /* ../common/hypot */);
    const asinhy_1 = tslib_1.__importDefault(require(198) /* ../common/asinhy */);
    const gatg_1 = tslib_1.__importDefault(require(200) /* ../common/gatg */);
    const clens_1 = tslib_1.__importDefault(require(201) /* ../common/clens */);
    const clens_cmplx_1 = tslib_1.__importDefault(require(202) /* ../common/clens_cmplx */);
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    /**
     * @typedef {Object} LocalThis
     * @property {number} es
     * @property {Array<number>} cbg
     * @property {Array<number>} cgb
     * @property {Array<number>} utg
     * @property {Array<number>} gtu
     * @property {number} Qn
     * @property {number} Zb
     */
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function init() {
        if (!this.approx && (isNaN(this.es) || this.es <= 0)) {
            throw new Error('Incorrect elliptical usage. Try using the +approx option in the proj string, or PROJECTION["Fast_Transverse_Mercator"] in the WKT.');
        }
        if (this.approx) {
            // When '+approx' is set, use tmerc instead
            tmerc_1.default.init.apply(this);
            this.forward = tmerc_1.default.forward;
            this.inverse = tmerc_1.default.inverse;
        }
        this.x0 = this.x0 !== undefined ? this.x0 : 0;
        this.y0 = this.y0 !== undefined ? this.y0 : 0;
        this.long0 = this.long0 !== undefined ? this.long0 : 0;
        this.lat0 = this.lat0 !== undefined ? this.lat0 : 0;
        this.cgb = [];
        this.cbg = [];
        this.utg = [];
        this.gtu = [];
        var f = this.es / (1 + Math.sqrt(1 - this.es));
        var n = f / (2 - f);
        var np = n;
        this.cgb[0] = n * (2 + n * (-2 / 3 + n * (-2 + n * (116 / 45 + n * (26 / 45 + n * (-2854 / 675))))));
        this.cbg[0] = n * (-2 + n * (2 / 3 + n * (4 / 3 + n * (-82 / 45 + n * (32 / 45 + n * (4642 / 4725))))));
        np = np * n;
        this.cgb[1] = np * (7 / 3 + n * (-8 / 5 + n * (-227 / 45 + n * (2704 / 315 + n * (2323 / 945)))));
        this.cbg[1] = np * (5 / 3 + n * (-16 / 15 + n * (-13 / 9 + n * (904 / 315 + n * (-1522 / 945)))));
        np = np * n;
        this.cgb[2] = np * (56 / 15 + n * (-136 / 35 + n * (-1262 / 105 + n * (73814 / 2835))));
        this.cbg[2] = np * (-26 / 15 + n * (34 / 21 + n * (8 / 5 + n * (-12686 / 2835))));
        np = np * n;
        this.cgb[3] = np * (4279 / 630 + n * (-332 / 35 + n * (-399572 / 14175)));
        this.cbg[3] = np * (1237 / 630 + n * (-12 / 5 + n * (-24832 / 14175)));
        np = np * n;
        this.cgb[4] = np * (4174 / 315 + n * (-144838 / 6237));
        this.cbg[4] = np * (-734 / 315 + n * (109598 / 31185));
        np = np * n;
        this.cgb[5] = np * (601676 / 22275);
        this.cbg[5] = np * (444337 / 155925);
        np = Math.pow(n, 2);
        this.Qn = this.k0 / (1 + n) * (1 + np * (1 / 4 + np * (1 / 64 + np / 256)));
        this.utg[0] = n * (-0.5 + n * (2 / 3 + n * (-37 / 96 + n * (1 / 360 + n * (81 / 512 + n * (-96199 / 604800))))));
        this.gtu[0] = n * (0.5 + n * (-2 / 3 + n * (5 / 16 + n * (41 / 180 + n * (-127 / 288 + n * (7891 / 37800))))));
        this.utg[1] = np * (-1 / 48 + n * (-1 / 15 + n * (437 / 1440 + n * (-46 / 105 + n * (1118711 / 3870720)))));
        this.gtu[1] = np * (13 / 48 + n * (-3 / 5 + n * (557 / 1440 + n * (281 / 630 + n * (-1983433 / 1935360)))));
        np = np * n;
        this.utg[2] = np * (-17 / 480 + n * (37 / 840 + n * (209 / 4480 + n * (-5569 / 90720))));
        this.gtu[2] = np * (61 / 240 + n * (-103 / 140 + n * (15061 / 26880 + n * (167603 / 181440))));
        np = np * n;
        this.utg[3] = np * (-4397 / 161280 + n * (11 / 504 + n * (830251 / 7257600)));
        this.gtu[3] = np * (49561 / 161280 + n * (-179 / 168 + n * (6601661 / 7257600)));
        np = np * n;
        this.utg[4] = np * (-4583 / 161280 + n * (108847 / 3991680));
        this.gtu[4] = np * (34729 / 80640 + n * (-3418889 / 1995840));
        np = np * n;
        this.utg[5] = np * (-20648693 / 638668800);
        this.gtu[5] = np * (212378941 / 319334400);
        var Z = (0, gatg_1.default)(this.cbg, this.lat0);
        this.Zb = -this.Qn * (Z + (0, clens_1.default)(this.gtu, 2 * Z));
    }
    function forward(p) {
        var Ce = (0, adjust_lon_1.default)(p.x - this.long0, this.over);
        var Cn = p.y;
        Cn = (0, gatg_1.default)(this.cbg, Cn);
        var sin_Cn = Math.sin(Cn);
        var cos_Cn = Math.cos(Cn);
        var sin_Ce = Math.sin(Ce);
        var cos_Ce = Math.cos(Ce);
        Cn = Math.atan2(sin_Cn, cos_Ce * cos_Cn);
        Ce = Math.atan2(sin_Ce * cos_Cn, (0, hypot_1.default)(sin_Cn, cos_Cn * cos_Ce));
        Ce = (0, asinhy_1.default)(Math.tan(Ce));
        var tmp = (0, clens_cmplx_1.default)(this.gtu, 2 * Cn, 2 * Ce);
        Cn = Cn + tmp[0];
        Ce = Ce + tmp[1];
        var x;
        var y;
        if (Math.abs(Ce) <= 2.623395162778) {
            x = this.a * (this.Qn * Ce) + this.x0;
            y = this.a * (this.Qn * Cn + this.Zb) + this.y0;
        }
        else {
            x = Infinity;
            y = Infinity;
        }
        p.x = x;
        p.y = y;
        return p;
    }
    function inverse(p) {
        var Ce = (p.x - this.x0) * (1 / this.a);
        var Cn = (p.y - this.y0) * (1 / this.a);
        Cn = (Cn - this.Zb) / this.Qn;
        Ce = Ce / this.Qn;
        var lon;
        var lat;
        if (Math.abs(Ce) <= 2.623395162778) {
            var tmp = (0, clens_cmplx_1.default)(this.utg, 2 * Cn, 2 * Ce);
            Cn = Cn + tmp[0];
            Ce = Ce + tmp[1];
            Ce = Math.atan((0, sinh_1.default)(Ce));
            var sin_Cn = Math.sin(Cn);
            var cos_Cn = Math.cos(Cn);
            var sin_Ce = Math.sin(Ce);
            var cos_Ce = Math.cos(Ce);
            Cn = Math.atan2(sin_Cn * cos_Ce, (0, hypot_1.default)(sin_Ce, cos_Ce * cos_Cn));
            Ce = Math.atan2(sin_Ce, cos_Ce * cos_Cn);
            lon = (0, adjust_lon_1.default)(Ce + this.long0, this.over);
            lat = (0, gatg_1.default)(this.cgb, Cn);
        }
        else {
            lon = Infinity;
            lat = Infinity;
        }
        p.x = lon;
        p.y = lat;
        return p;
    }
    exports.names = ['Extended_Transverse_Mercator', 'Extended Transverse Mercator', 'etmerc', 'Transverse_Mercator', 'Transverse Mercator', 'Gauss Kruger', 'Gauss_Kruger', 'tmerc'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/common/sinh.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(x) {
        var r = Math.exp(x);
        r = (r - 1 / r) / 2;
        return r;
    }
},
/* proj4/lib/common/hypot.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(x, y) {
        x = Math.abs(x);
        y = Math.abs(y);
        var a = Math.max(x, y);
        var b = Math.min(x, y) / (a ? a : 1);
        return a * Math.sqrt(1 + Math.pow(b, 2));
    }
},
/* proj4/lib/common/asinhy.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    const tslib_1 = require(1) /* tslib */;
    const hypot_1 = tslib_1.__importDefault(require(197) /* ./hypot */);
    const log1py_1 = tslib_1.__importDefault(require(199) /* ./log1py */);
    function default_1(x) {
        var y = Math.abs(x);
        y = (0, log1py_1.default)(y * (1 + y / ((0, hypot_1.default)(1, y) + 1)));
        return x < 0 ? -y : y;
    }
},
/* proj4/lib/common/log1py.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(x) {
        var y = 1 + x;
        var z = y - 1;
        return z === 0 ? x : x * Math.log(y) / z;
    }
},
/* proj4/lib/common/gatg.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(pp, B) {
        var cos_2B = 2 * Math.cos(2 * B);
        var i = pp.length - 1;
        var h1 = pp[i];
        var h2 = 0;
        var h;
        while (--i >= 0) {
            h = -h2 + cos_2B * h1 + pp[i];
            h2 = h1;
            h1 = h;
        }
        return (B + h * Math.sin(2 * B));
    }
},
/* proj4/lib/common/clens.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(pp, arg_r) {
        var r = 2 * Math.cos(arg_r);
        var i = pp.length - 1;
        var hr1 = pp[i];
        var hr2 = 0;
        var hr;
        while (--i >= 0) {
            hr = -hr2 + r * hr1 + pp[i];
            hr2 = hr1;
            hr1 = hr;
        }
        return Math.sin(arg_r) * hr;
    }
},
/* proj4/lib/common/clens_cmplx.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    const tslib_1 = require(1) /* tslib */;
    const sinh_1 = tslib_1.__importDefault(require(196) /* ./sinh */);
    const cosh_1 = tslib_1.__importDefault(require(203) /* ./cosh */);
    function default_1(pp, arg_r, arg_i) {
        var sin_arg_r = Math.sin(arg_r);
        var cos_arg_r = Math.cos(arg_r);
        var sinh_arg_i = (0, sinh_1.default)(arg_i);
        var cosh_arg_i = (0, cosh_1.default)(arg_i);
        var r = 2 * cos_arg_r * cosh_arg_i;
        var i = -2 * sin_arg_r * sinh_arg_i;
        var j = pp.length - 1;
        var hr = pp[j];
        var hi1 = 0;
        var hr1 = 0;
        var hi = 0;
        var hr2;
        var hi2;
        while (--j >= 0) {
            hr2 = hr1;
            hi2 = hi1;
            hr1 = hr;
            hi1 = hi;
            hr = -hr2 + r * hr1 - i * hi1 + pp[j];
            hi = -hi2 + i * hr1 + r * hi1;
        }
        r = sin_arg_r * cosh_arg_i;
        i = cos_arg_r * sinh_arg_i;
        return [r * hr - i * hi, r * hi + i * hr];
    }
},
/* proj4/lib/common/cosh.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(x) {
        var r = Math.exp(x);
        r = (r + 1 / r) / 2;
        return r;
    }
},
/* proj4/lib/projections/utm.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    const tslib_1 = require(1) /* tslib */;
    const adjust_zone_1 = tslib_1.__importDefault(require(205) /* ../common/adjust_zone */);
    const etmerc_1 = tslib_1.__importDefault(require(195) /* ./etmerc */);
    exports.dependsOn = 'etmerc';
    const values_1 = require(156) /* ../constants/values */;
    /** @this {import('../defs.js').ProjectionDefinition} */
    function init() {
        var zone = (0, adjust_zone_1.default)(this.zone, this.long0);
        if (zone === undefined) {
            throw new Error('unknown utm zone');
        }
        this.lat0 = 0;
        this.long0 = ((6 * Math.abs(zone)) - 183) * values_1.D2R;
        this.x0 = 500000;
        this.y0 = this.utmSouth ? 10000000 : 0;
        this.k0 = 0.9996;
        etmerc_1.default.init.apply(this);
        this.forward = etmerc_1.default.forward;
        this.inverse = etmerc_1.default.inverse;
    }
    exports.names = ['Universal Transverse Mercator System', 'utm'];
    exports.default = {
        init: init,
        names: exports.names,
        dependsOn: exports.dependsOn
    };
},
/* proj4/lib/common/adjust_zone.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    const tslib_1 = require(1) /* tslib */;
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ./adjust_lon */);
    function default_1(zone, lon) {
        if (zone === undefined) {
            zone = Math.floor(((0, adjust_lon_1.default)(lon) + Math.PI) * 30 / Math.PI) + 1;
            if (zone < 0) {
                return 0;
            }
            else if (zone > 60) {
                return 60;
            }
        }
        return zone;
    }
},
/* proj4/lib/projections/sterea.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const gauss_1 = tslib_1.__importDefault(require(207) /* ./gauss */);
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    const hypot_1 = tslib_1.__importDefault(require(197) /* ../common/hypot */);
    /**
     * @typedef {Object} LocalThis
     * @property {number} sinc0
     * @property {number} cosc0
     * @property {number} R2
     * @property {number} rc
     * @property {number} phic0
     */
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function init() {
        gauss_1.default.init.apply(this);
        if (!this.rc) {
            return;
        }
        this.sinc0 = Math.sin(this.phic0);
        this.cosc0 = Math.cos(this.phic0);
        this.R2 = 2 * this.rc;
        if (!this.title) {
            this.title = 'Oblique Stereographic Alternative';
        }
    }
    function forward(p) {
        var sinc, cosc, cosl, k;
        p.x = (0, adjust_lon_1.default)(p.x - this.long0, this.over);
        gauss_1.default.forward.apply(this, [p]);
        sinc = Math.sin(p.y);
        cosc = Math.cos(p.y);
        cosl = Math.cos(p.x);
        k = this.k0 * this.R2 / (1 + this.sinc0 * sinc + this.cosc0 * cosc * cosl);
        p.x = k * cosc * Math.sin(p.x);
        p.y = k * (this.cosc0 * sinc - this.sinc0 * cosc * cosl);
        p.x = this.a * p.x + this.x0;
        p.y = this.a * p.y + this.y0;
        return p;
    }
    function inverse(p) {
        var sinc, cosc, lon, lat, rho;
        p.x = (p.x - this.x0) / this.a;
        p.y = (p.y - this.y0) / this.a;
        p.x /= this.k0;
        p.y /= this.k0;
        if ((rho = (0, hypot_1.default)(p.x, p.y))) {
            var c = 2 * Math.atan2(rho, this.R2);
            sinc = Math.sin(c);
            cosc = Math.cos(c);
            lat = Math.asin(cosc * this.sinc0 + p.y * sinc * this.cosc0 / rho);
            lon = Math.atan2(p.x * sinc, rho * this.cosc0 * cosc - p.y * this.sinc0 * sinc);
        }
        else {
            lat = this.phic0;
            lon = 0;
        }
        p.x = lon;
        p.y = lat;
        gauss_1.default.inverse.apply(this, [p]);
        p.x = (0, adjust_lon_1.default)(p.x + this.long0, this.over);
        return p;
    }
    exports.names = ['Stereographic_North_Pole', 'Oblique_Stereographic', 'sterea', 'Oblique Stereographic Alternative', 'Double_Stereographic'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/projections/gauss.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const srat_1 = tslib_1.__importDefault(require(208) /* ../common/srat */);
    var MAX_ITER = 20;
    const values_1 = require(156) /* ../constants/values */;
    /**
     * @typedef {Object} LocalThis
     * @property {number} rc
     * @property {number} C
     * @property {number} phic0
     * @property {number} ratexp
     * @property {number} K
     * @property {number} e
     * @property {number} es
     */
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function init() {
        var sphi = Math.sin(this.lat0);
        var cphi = Math.cos(this.lat0);
        cphi *= cphi;
        this.rc = Math.sqrt(1 - this.es) / (1 - this.es * sphi * sphi);
        this.C = Math.sqrt(1 + this.es * cphi * cphi / (1 - this.es));
        this.phic0 = Math.asin(sphi / this.C);
        this.ratexp = 0.5 * this.C * this.e;
        this.K = Math.tan(0.5 * this.phic0 + values_1.FORTPI) / (Math.pow(Math.tan(0.5 * this.lat0 + values_1.FORTPI), this.C) * (0, srat_1.default)(this.e * sphi, this.ratexp));
    }
    function forward(p) {
        var lon = p.x;
        var lat = p.y;
        p.y = 2 * Math.atan(this.K * Math.pow(Math.tan(0.5 * lat + values_1.FORTPI), this.C) * (0, srat_1.default)(this.e * Math.sin(lat), this.ratexp)) - values_1.HALF_PI;
        p.x = this.C * lon;
        return p;
    }
    function inverse(p) {
        var DEL_TOL = 1e-14;
        var lon = p.x / this.C;
        var lat = p.y;
        var num = Math.pow(Math.tan(0.5 * lat + values_1.FORTPI) / this.K, 1 / this.C);
        for (var i = MAX_ITER; i > 0; --i) {
            lat = 2 * Math.atan(num * (0, srat_1.default)(this.e * Math.sin(p.y), -0.5 * this.e)) - values_1.HALF_PI;
            if (Math.abs(lat - p.y) < DEL_TOL) {
                break;
            }
            p.y = lat;
        }
        /* convergence failed */
        if (!i) {
            return null;
        }
        p.x = lon;
        p.y = lat;
        return p;
    }
    exports.names = ['gauss'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/common/srat.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(esinp, exp) {
        return (Math.pow((1 - esinp) / (1 + esinp), exp));
    }
},
/* proj4/lib/projections/stere.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.ssfn_ = ssfn_;
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const values_1 = require(156) /* ../constants/values */;
    const sign_1 = tslib_1.__importDefault(require(173) /* ../common/sign */);
    const msfnz_1 = tslib_1.__importDefault(require(171) /* ../common/msfnz */);
    const tsfnz_1 = tslib_1.__importDefault(require(174) /* ../common/tsfnz */);
    const phi2z_1 = tslib_1.__importDefault(require(175) /* ../common/phi2z */);
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    /**
     * @typedef {Object} LocalThis
     * @property {number} coslat0
     * @property {number} sinlat0
     * @property {number} ms1
     * @property {number} X0
     * @property {number} cosX0
     * @property {number} sinX0
     * @property {number} con
     * @property {number} cons
     * @property {number} e
     */
    function ssfn_(phit, sinphi, eccen) {
        sinphi *= eccen;
        return (Math.tan(0.5 * (values_1.HALF_PI + phit)) * Math.pow((1 - sinphi) / (1 + sinphi), 0.5 * eccen));
    }
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function init() {
        // setting default parameters
        this.x0 = this.x0 || 0;
        this.y0 = this.y0 || 0;
        this.lat0 = this.lat0 || 0;
        this.long0 = this.long0 || 0;
        this.coslat0 = Math.cos(this.lat0);
        this.sinlat0 = Math.sin(this.lat0);
        if (this.sphere) {
            if (this.k0 === 1 && !isNaN(this.lat_ts) && Math.abs(this.coslat0) <= values_1.EPSLN) {
                this.k0 = 0.5 * (1 + (0, sign_1.default)(this.lat0) * Math.sin(this.lat_ts));
            }
        }
        else {
            if (Math.abs(this.coslat0) <= values_1.EPSLN) {
                if (this.lat0 > 0) {
                    // North pole
                    // trace('stere:north pole');
                    this.con = 1;
                }
                else {
                    // South pole
                    // trace('stere:south pole');
                    this.con = -1;
                }
            }
            this.cons = Math.sqrt(Math.pow(1 + this.e, 1 + this.e) * Math.pow(1 - this.e, 1 - this.e));
            if (this.k0 === 1 && !isNaN(this.lat_ts) && Math.abs(this.coslat0) <= values_1.EPSLN && Math.abs(Math.cos(this.lat_ts)) > values_1.EPSLN) {
                // When k0 is 1 (default value) and lat_ts is a vaild number and lat0 is at a pole and lat_ts is not at a pole
                // Recalculate k0 using formula 21-35 from p161 of Snyder, 1987
                this.k0 = 0.5 * this.cons * (0, msfnz_1.default)(this.e, Math.sin(this.lat_ts), Math.cos(this.lat_ts)) / (0, tsfnz_1.default)(this.e, this.con * this.lat_ts, this.con * Math.sin(this.lat_ts));
            }
            this.ms1 = (0, msfnz_1.default)(this.e, this.sinlat0, this.coslat0);
            this.X0 = 2 * Math.atan(ssfn_(this.lat0, this.sinlat0, this.e)) - values_1.HALF_PI;
            this.cosX0 = Math.cos(this.X0);
            this.sinX0 = Math.sin(this.X0);
        }
    }
    // Stereographic forward equations--mapping lat,long to x,y
    function forward(p) {
        var lon = p.x;
        var lat = p.y;
        var sinlat = Math.sin(lat);
        var coslat = Math.cos(lat);
        var A, X, sinX, cosX, ts, rh;
        var dlon = (0, adjust_lon_1.default)(lon - this.long0, this.over);
        if (Math.abs(Math.abs(lon - this.long0) - Math.PI) <= values_1.EPSLN && Math.abs(lat + this.lat0) <= values_1.EPSLN) {
            // case of the origine point
            // trace('stere:this is the origin point');
            p.x = NaN;
            p.y = NaN;
            return p;
        }
        if (this.sphere) {
            // trace('stere:sphere case');
            A = 2 * this.k0 / (1 + this.sinlat0 * sinlat + this.coslat0 * coslat * Math.cos(dlon));
            p.x = this.a * A * coslat * Math.sin(dlon) + this.x0;
            p.y = this.a * A * (this.coslat0 * sinlat - this.sinlat0 * coslat * Math.cos(dlon)) + this.y0;
            return p;
        }
        else {
            X = 2 * Math.atan(ssfn_(lat, sinlat, this.e)) - values_1.HALF_PI;
            cosX = Math.cos(X);
            sinX = Math.sin(X);
            if (Math.abs(this.coslat0) <= values_1.EPSLN) {
                ts = (0, tsfnz_1.default)(this.e, lat * this.con, this.con * sinlat);
                rh = 2 * this.a * this.k0 * ts / this.cons;
                p.x = this.x0 + rh * Math.sin(lon - this.long0);
                p.y = this.y0 - this.con * rh * Math.cos(lon - this.long0);
                // trace(p.toString());
                return p;
            }
            else if (Math.abs(this.sinlat0) < values_1.EPSLN) {
                // Eq
                // trace('stere:equateur');
                A = 2 * this.a * this.k0 / (1 + cosX * Math.cos(dlon));
                p.y = A * sinX;
            }
            else {
                // other case
                // trace('stere:normal case');
                A = 2 * this.a * this.k0 * this.ms1 / (this.cosX0 * (1 + this.sinX0 * sinX + this.cosX0 * cosX * Math.cos(dlon)));
                p.y = A * (this.cosX0 * sinX - this.sinX0 * cosX * Math.cos(dlon)) + this.y0;
            }
            p.x = A * cosX * Math.sin(dlon) + this.x0;
        }
        // trace(p.toString());
        return p;
    }
    //* Stereographic inverse equations--mapping x,y to lat/long
    function inverse(p) {
        p.x -= this.x0;
        p.y -= this.y0;
        var lon, lat, ts, ce, Chi;
        var rh = Math.sqrt(p.x * p.x + p.y * p.y);
        if (this.sphere) {
            var c = 2 * Math.atan(rh / (2 * this.a * this.k0));
            lon = this.long0;
            lat = this.lat0;
            if (rh <= values_1.EPSLN) {
                p.x = lon;
                p.y = lat;
                return p;
            }
            lat = Math.asin(Math.cos(c) * this.sinlat0 + p.y * Math.sin(c) * this.coslat0 / rh);
            if (Math.abs(this.coslat0) < values_1.EPSLN) {
                if (this.lat0 > 0) {
                    lon = (0, adjust_lon_1.default)(this.long0 + Math.atan2(p.x, -1 * p.y), this.over);
                }
                else {
                    lon = (0, adjust_lon_1.default)(this.long0 + Math.atan2(p.x, p.y), this.over);
                }
            }
            else {
                lon = (0, adjust_lon_1.default)(this.long0 + Math.atan2(p.x * Math.sin(c), rh * this.coslat0 * Math.cos(c) - p.y * this.sinlat0 * Math.sin(c)), this.over);
            }
            p.x = lon;
            p.y = lat;
            return p;
        }
        else {
            if (Math.abs(this.coslat0) <= values_1.EPSLN) {
                if (rh <= values_1.EPSLN) {
                    lat = this.lat0;
                    lon = this.long0;
                    p.x = lon;
                    p.y = lat;
                    // trace(p.toString());
                    return p;
                }
                p.x *= this.con;
                p.y *= this.con;
                ts = rh * this.cons / (2 * this.a * this.k0);
                lat = this.con * (0, phi2z_1.default)(this.e, ts);
                lon = this.con * (0, adjust_lon_1.default)(this.con * this.long0 + Math.atan2(p.x, -1 * p.y), this.over);
            }
            else {
                ce = 2 * Math.atan(rh * this.cosX0 / (2 * this.a * this.k0 * this.ms1));
                lon = this.long0;
                if (rh <= values_1.EPSLN) {
                    Chi = this.X0;
                }
                else {
                    Chi = Math.asin(Math.cos(ce) * this.sinX0 + p.y * Math.sin(ce) * this.cosX0 / rh);
                    lon = (0, adjust_lon_1.default)(this.long0 + Math.atan2(p.x * Math.sin(ce), rh * this.cosX0 * Math.cos(ce) - p.y * this.sinX0 * Math.sin(ce)), this.over);
                }
                lat = -1 * (0, phi2z_1.default)(this.e, Math.tan(0.5 * (values_1.HALF_PI + Chi)));
            }
        }
        p.x = lon;
        p.y = lat;
        // trace(p.toString());
        return p;
    }
    exports.names = ['stere', 'Stereographic_South_Pole', 'Polar_Stereographic_variant_A', 'Polar_Stereographic_variant_B', 'Polar_Stereographic'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names,
        ssfn_: ssfn_
    };
},
/* proj4/lib/projections/somerc.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    /**
     * @typedef {Object} LocalThis
     * @property {number} lambda0
     * @property {number} e
     * @property {number} R
     * @property {number} b0
     * @property {number} K
     */
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function init() {
        var phy0 = this.lat0;
        this.lambda0 = this.long0;
        var sinPhy0 = Math.sin(phy0);
        var semiMajorAxis = this.a;
        var invF = this.rf;
        var flattening = 1 / invF;
        var e2 = 2 * flattening - Math.pow(flattening, 2);
        var e = this.e = Math.sqrt(e2);
        this.R = this.k0 * semiMajorAxis * Math.sqrt(1 - e2) / (1 - e2 * Math.pow(sinPhy0, 2));
        this.alpha = Math.sqrt(1 + e2 / (1 - e2) * Math.pow(Math.cos(phy0), 4));
        this.b0 = Math.asin(sinPhy0 / this.alpha);
        var k1 = Math.log(Math.tan(Math.PI / 4 + this.b0 / 2));
        var k2 = Math.log(Math.tan(Math.PI / 4 + phy0 / 2));
        var k3 = Math.log((1 + e * sinPhy0) / (1 - e * sinPhy0));
        this.K = k1 - this.alpha * k2 + this.alpha * e / 2 * k3;
    }
    function forward(p) {
        var Sa1 = Math.log(Math.tan(Math.PI / 4 - p.y / 2));
        var Sa2 = this.e / 2 * Math.log((1 + this.e * Math.sin(p.y)) / (1 - this.e * Math.sin(p.y)));
        var S = -this.alpha * (Sa1 + Sa2) + this.K;
        // spheric latitude
        var b = 2 * (Math.atan(Math.exp(S)) - Math.PI / 4);
        // spheric longitude
        var I = this.alpha * (p.x - this.lambda0);
        // psoeudo equatorial rotation
        var rotI = Math.atan(Math.sin(I) / (Math.sin(this.b0) * Math.tan(b) + Math.cos(this.b0) * Math.cos(I)));
        var rotB = Math.asin(Math.cos(this.b0) * Math.sin(b) - Math.sin(this.b0) * Math.cos(b) * Math.cos(I));
        p.y = this.R / 2 * Math.log((1 + Math.sin(rotB)) / (1 - Math.sin(rotB))) + this.y0;
        p.x = this.R * rotI + this.x0;
        return p;
    }
    function inverse(p) {
        var Y = p.x - this.x0;
        var X = p.y - this.y0;
        var rotI = Y / this.R;
        var rotB = 2 * (Math.atan(Math.exp(X / this.R)) - Math.PI / 4);
        var b = Math.asin(Math.cos(this.b0) * Math.sin(rotB) + Math.sin(this.b0) * Math.cos(rotB) * Math.cos(rotI));
        var I = Math.atan(Math.sin(rotI) / (Math.cos(this.b0) * Math.cos(rotI) - Math.sin(this.b0) * Math.tan(rotB)));
        var lambda = this.lambda0 + I / this.alpha;
        var S = 0;
        var phy = b;
        var prevPhy = -1000;
        var iteration = 0;
        while (Math.abs(phy - prevPhy) > 0.0000001) {
            if (++iteration > 20) {
                // ...reportError("omercFwdInfinity");
                return;
            }
            // S = Math.log(Math.tan(Math.PI / 4 + phy / 2));
            S = 1 / this.alpha * (Math.log(Math.tan(Math.PI / 4 + b / 2)) - this.K) + this.e * Math.log(Math.tan(Math.PI / 4 + Math.asin(this.e * Math.sin(phy)) / 2));
            prevPhy = phy;
            phy = 2 * Math.atan(Math.exp(S)) - Math.PI / 2;
        }
        p.x = lambda;
        p.y = phy;
        return p;
    }
    exports.names = ['somerc'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/projections/omerc.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const tsfnz_1 = tslib_1.__importDefault(require(174) /* ../common/tsfnz */);
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    const phi2z_1 = tslib_1.__importDefault(require(175) /* ../common/phi2z */);
    const values_1 = require(156) /* ../constants/values */;
    const projections_1 = require(169) /* ../projections */;
    /**
     * @typedef {Object} LocalThis
     * @property {boolean} no_off
     * @property {boolean} no_rot
     * @property {number} rectified_grid_angle
     * @property {number} es
     * @property {number} A
     * @property {number} B
     * @property {number} E
     * @property {number} e
     * @property {number} lam0
     * @property {number} singam
     * @property {number} cosgam
     * @property {number} sinrot
     * @property {number} cosrot
     * @property {number} rB
     * @property {number} ArB
     * @property {number} BrA
     * @property {number} u_0
     * @property {number} v_pole_n
     * @property {number} v_pole_s
     */
    var TOL = 1e-7;
    function isTypeA(P) {
        var typeAProjections = ['Hotine_Oblique_Mercator', 'Hotine_Oblique_Mercator_variant_A', 'Hotine_Oblique_Mercator_Azimuth_Natural_Origin'];
        var projectionName = typeof P.projName === 'object' ? Object.keys(P.projName)[0] : P.projName;
        return 'no_uoff' in P || 'no_off' in P || typeAProjections.indexOf(projectionName) !== -1 || typeAProjections.indexOf((0, projections_1.getNormalizedProjName)(projectionName)) !== -1;
    }
    /**
     * Initialize the Oblique Mercator  projection
     * @this {import('../defs.js').ProjectionDefinition & LocalThis}
     */
    function init() {
        var con, com, cosph0, D, F, H, L, sinph0, p, J, gamma = 0, gamma0, lamc = 0, lam1 = 0, lam2 = 0, phi1 = 0, phi2 = 0, alpha_c = 0;
        // only Type A uses the no_off or no_uoff property
        // https://github.com/OSGeo/proj.4/issues/104
        this.no_off = isTypeA(this);
        this.no_rot = 'no_rot' in this;
        var alp = false;
        if ('alpha' in this) {
            alp = true;
        }
        var gam = false;
        if ('rectified_grid_angle' in this) {
            gam = true;
        }
        if (alp) {
            alpha_c = this.alpha;
        }
        if (gam) {
            gamma = this.rectified_grid_angle;
            if (!alp) {
                alpha_c = 0;
                alp = true;
            }
        }
        if (alp || gam) {
            lamc = this.longc;
        }
        else {
            lam1 = this.long1;
            phi1 = this.lat1;
            lam2 = this.long2;
            phi2 = this.lat2;
            if (Math.abs(phi1 - phi2) <= TOL || (con = Math.abs(phi1)) <= TOL
                || Math.abs(con - values_1.HALF_PI) <= TOL || Math.abs(Math.abs(this.lat0) - values_1.HALF_PI) <= TOL
                || Math.abs(Math.abs(phi2) - values_1.HALF_PI) <= TOL) {
                throw new Error();
            }
        }
        var one_es = 1.0 - this.es;
        com = Math.sqrt(one_es);
        if (Math.abs(this.lat0) > values_1.EPSLN) {
            sinph0 = Math.sin(this.lat0);
            cosph0 = Math.cos(this.lat0);
            con = 1 - this.es * sinph0 * sinph0;
            this.B = cosph0 * cosph0;
            this.B = Math.sqrt(1 + this.es * this.B * this.B / one_es);
            this.A = this.B * this.k0 * com / con;
            D = this.B * com / (cosph0 * Math.sqrt(con));
            F = D * D - 1;
            if (F <= 0) {
                F = 0;
            }
            else {
                F = Math.sqrt(F);
                if (this.lat0 < 0) {
                    F = -F;
                }
            }
            this.E = F += D;
            this.E *= Math.pow((0, tsfnz_1.default)(this.e, this.lat0, sinph0), this.B);
        }
        else {
            this.B = 1 / com;
            this.A = this.k0;
            this.E = D = F = 1;
        }
        if (alp || gam) {
            if (alp) {
                gamma0 = Math.asin(Math.sin(alpha_c) / D);
                if (!gam) {
                    gamma = alpha_c;
                }
            }
            else {
                gamma0 = gamma;
                alpha_c = Math.asin(D * Math.sin(gamma0));
            }
            this.lam0 = lamc - Math.asin(0.5 * (F - 1 / F) * Math.tan(gamma0)) / this.B;
        }
        else {
            H = Math.pow((0, tsfnz_1.default)(this.e, phi1, Math.sin(phi1)), this.B);
            L = Math.pow((0, tsfnz_1.default)(this.e, phi2, Math.sin(phi2)), this.B);
            F = this.E / H;
            p = (L - H) / (L + H);
            J = this.E * this.E;
            J = (J - L * H) / (J + L * H);
            con = lam1 - lam2;
            if (con < -Math.PI) {
                lam2 -= values_1.TWO_PI;
            }
            else if (con > Math.PI) {
                lam2 += values_1.TWO_PI;
            }
            this.lam0 = (0, adjust_lon_1.default)(0.5 * (lam1 + lam2) - Math.atan(J * Math.tan(0.5 * this.B * (lam1 - lam2)) / p) / this.B, this.over);
            gamma0 = Math.atan(2 * Math.sin(this.B * (0, adjust_lon_1.default)(lam1 - this.lam0, this.over)) / (F - 1 / F));
            gamma = alpha_c = Math.asin(D * Math.sin(gamma0));
        }
        this.singam = Math.sin(gamma0);
        this.cosgam = Math.cos(gamma0);
        this.sinrot = Math.sin(gamma);
        this.cosrot = Math.cos(gamma);
        this.rB = 1 / this.B;
        this.ArB = this.A * this.rB;
        this.BrA = 1 / this.ArB;
        if (this.no_off) {
            this.u_0 = 0;
        }
        else {
            this.u_0 = Math.abs(this.ArB * Math.atan(Math.sqrt(D * D - 1) / Math.cos(alpha_c)));
            if (this.lat0 < 0) {
                this.u_0 = -this.u_0;
            }
        }
        F = 0.5 * gamma0;
        this.v_pole_n = this.ArB * Math.log(Math.tan(values_1.FORTPI - F));
        this.v_pole_s = this.ArB * Math.log(Math.tan(values_1.FORTPI + F));
    }
    /* Oblique Mercator forward equations--mapping lat,long to x,y
        ---------------------------------------------------------- */
    function forward(p) {
        var coords = {};
        var S, T, U, V, W, temp, u, v;
        p.x = p.x - this.lam0;
        if (Math.abs(Math.abs(p.y) - values_1.HALF_PI) > values_1.EPSLN) {
            W = this.E / Math.pow((0, tsfnz_1.default)(this.e, p.y, Math.sin(p.y)), this.B);
            temp = 1 / W;
            S = 0.5 * (W - temp);
            T = 0.5 * (W + temp);
            V = Math.sin(this.B * p.x);
            U = (S * this.singam - V * this.cosgam) / T;
            if (Math.abs(Math.abs(U) - 1.0) < values_1.EPSLN) {
                throw new Error();
            }
            v = 0.5 * this.ArB * Math.log((1 - U) / (1 + U));
            temp = Math.cos(this.B * p.x);
            if (Math.abs(temp) < TOL) {
                u = this.A * p.x;
            }
            else {
                u = this.ArB * Math.atan2((S * this.cosgam + V * this.singam), temp);
            }
        }
        else {
            v = p.y > 0 ? this.v_pole_n : this.v_pole_s;
            u = this.ArB * p.y;
        }
        if (this.no_rot) {
            coords.x = u;
            coords.y = v;
        }
        else {
            u -= this.u_0;
            coords.x = v * this.cosrot + u * this.sinrot;
            coords.y = u * this.cosrot - v * this.sinrot;
        }
        coords.x = (this.a * coords.x + this.x0);
        coords.y = (this.a * coords.y + this.y0);
        return coords;
    }
    function inverse(p) {
        var u, v, Qp, Sp, Tp, Vp, Up;
        var coords = {};
        p.x = (p.x - this.x0) * (1.0 / this.a);
        p.y = (p.y - this.y0) * (1.0 / this.a);
        if (this.no_rot) {
            v = p.y;
            u = p.x;
        }
        else {
            v = p.x * this.cosrot - p.y * this.sinrot;
            u = p.y * this.cosrot + p.x * this.sinrot + this.u_0;
        }
        Qp = Math.exp(-this.BrA * v);
        Sp = 0.5 * (Qp - 1 / Qp);
        Tp = 0.5 * (Qp + 1 / Qp);
        Vp = Math.sin(this.BrA * u);
        Up = (Vp * this.cosgam + Sp * this.singam) / Tp;
        if (Math.abs(Math.abs(Up) - 1) < values_1.EPSLN) {
            coords.x = 0;
            coords.y = Up < 0 ? -values_1.HALF_PI : values_1.HALF_PI;
        }
        else {
            coords.y = this.E / Math.sqrt((1 + Up) / (1 - Up));
            coords.y = (0, phi2z_1.default)(this.e, Math.pow(coords.y, 1 / this.B));
            if (coords.y === Infinity) {
                throw new Error();
            }
            coords.x = -this.rB * Math.atan2((Sp * this.cosgam - Vp * this.singam), Math.cos(this.BrA * u));
        }
        coords.x += this.lam0;
        return coords;
    }
    exports.names = ['Hotine_Oblique_Mercator', 'Hotine Oblique Mercator', 'Hotine_Oblique_Mercator_variant_A', 'Hotine_Oblique_Mercator_Variant_B', 'Hotine_Oblique_Mercator_Azimuth_Natural_Origin', 'Hotine_Oblique_Mercator_Two_Point_Natural_Origin', 'Hotine_Oblique_Mercator_Azimuth_Center', 'Oblique_Mercator', 'omerc'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/projections/lcc.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const msfnz_1 = tslib_1.__importDefault(require(171) /* ../common/msfnz */);
    const tsfnz_1 = tslib_1.__importDefault(require(174) /* ../common/tsfnz */);
    const sign_1 = tslib_1.__importDefault(require(173) /* ../common/sign */);
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    const phi2z_1 = tslib_1.__importDefault(require(175) /* ../common/phi2z */);
    const values_1 = require(156) /* ../constants/values */;
    /**
     * @typedef {Object} LocalThis
     * @property {number} e
     * @property {number} ns
     * @property {number} f0
     * @property {number} rh
     */
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function init() {
        // double lat0;                    /* the reference latitude               */
        // double long0;                   /* the reference longitude              */
        // double lat1;                    /* first standard parallel              */
        // double lat2;                    /* second standard parallel             */
        // double r_maj;                   /* major axis                           */
        // double r_min;                   /* minor axis                           */
        // double false_east;              /* x offset in meters                   */
        // double false_north;             /* y offset in meters                   */
        // the above value can be set with proj4.defs
        // example: proj4.defs("EPSG:2154","+proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3 +x_0=700000 +y_0=6600000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs");
        if (!this.lat2) {
            this.lat2 = this.lat1;
        } // if lat2 is not defined
        if (!this.k0) {
            this.k0 = 1;
        }
        this.x0 = this.x0 || 0;
        this.y0 = this.y0 || 0;
        // Standard Parallels cannot be equal and on opposite sides of the equator
        if (Math.abs(this.lat1 + this.lat2) < values_1.EPSLN) {
            return;
        }
        var temp = this.b / this.a;
        this.e = Math.sqrt(1 - temp * temp);
        var sin1 = Math.sin(this.lat1);
        var cos1 = Math.cos(this.lat1);
        var ms1 = (0, msfnz_1.default)(this.e, sin1, cos1);
        var ts1 = (0, tsfnz_1.default)(this.e, this.lat1, sin1);
        var sin2 = Math.sin(this.lat2);
        var cos2 = Math.cos(this.lat2);
        var ms2 = (0, msfnz_1.default)(this.e, sin2, cos2);
        var ts2 = (0, tsfnz_1.default)(this.e, this.lat2, sin2);
        var ts0 = Math.abs(Math.abs(this.lat0) - values_1.HALF_PI) < values_1.EPSLN
            ? 0 // Handle poles by setting ts0 to 0
            : (0, tsfnz_1.default)(this.e, this.lat0, Math.sin(this.lat0));
        if (Math.abs(this.lat1 - this.lat2) > values_1.EPSLN) {
            this.ns = Math.log(ms1 / ms2) / Math.log(ts1 / ts2);
        }
        else {
            this.ns = sin1;
        }
        if (isNaN(this.ns)) {
            this.ns = sin1;
        }
        this.f0 = ms1 / (this.ns * Math.pow(ts1, this.ns));
        this.rh = this.a * this.f0 * Math.pow(ts0, this.ns);
        if (!this.title) {
            this.title = 'Lambert Conformal Conic';
        }
    }
    // Lambert Conformal conic forward equations--mapping lat,long to x,y
    // -----------------------------------------------------------------
    function forward(p) {
        var lon = p.x;
        var lat = p.y;
        // singular cases :
        if (Math.abs(2 * Math.abs(lat) - Math.PI) <= values_1.EPSLN) {
            lat = (0, sign_1.default)(lat) * (values_1.HALF_PI - 2 * values_1.EPSLN);
        }
        var con = Math.abs(Math.abs(lat) - values_1.HALF_PI);
        var ts, rh1;
        if (con > values_1.EPSLN) {
            ts = (0, tsfnz_1.default)(this.e, lat, Math.sin(lat));
            rh1 = this.a * this.f0 * Math.pow(ts, this.ns);
        }
        else {
            con = lat * this.ns;
            if (con <= 0) {
                return null;
            }
            rh1 = 0;
        }
        var theta = this.ns * (0, adjust_lon_1.default)(lon - this.long0, this.over);
        p.x = this.k0 * (rh1 * Math.sin(theta)) + this.x0;
        p.y = this.k0 * (this.rh - rh1 * Math.cos(theta)) + this.y0;
        return p;
    }
    // Lambert Conformal Conic inverse equations--mapping x,y to lat/long
    // -----------------------------------------------------------------
    function inverse(p) {
        var rh1, con, ts;
        var lat, lon;
        var x = (p.x - this.x0) / this.k0;
        var y = (this.rh - (p.y - this.y0) / this.k0);
        if (this.ns > 0) {
            rh1 = Math.sqrt(x * x + y * y);
            con = 1;
        }
        else {
            rh1 = -Math.sqrt(x * x + y * y);
            con = -1;
        }
        var theta = 0;
        if (rh1 !== 0) {
            theta = Math.atan2((con * x), (con * y));
        }
        if ((rh1 !== 0) || (this.ns > 0)) {
            con = 1 / this.ns;
            ts = Math.pow((rh1 / (this.a * this.f0)), con);
            lat = (0, phi2z_1.default)(this.e, ts);
            if (lat === -9999) {
                return null;
            }
        }
        else {
            lat = -values_1.HALF_PI;
        }
        lon = (0, adjust_lon_1.default)(theta / this.ns + this.long0, this.over);
        p.x = lon;
        p.y = lat;
        return p;
    }
    exports.names = [
        'Lambert Tangential Conformal Conic Projection',
        'Lambert_Conformal_Conic',
        'Lambert_Conformal_Conic_1SP',
        'Lambert_Conformal_Conic_2SP',
        'lcc',
        'Lambert Conic Conformal (1SP)',
        'Lambert Conic Conformal (2SP)'
    ];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/projections/krovak.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    function init() {
        this.a = 6377397.155;
        this.es = 0.006674372230614;
        this.e = Math.sqrt(this.es);
        if (!this.lat0) {
            this.lat0 = 0.863937979737193;
        }
        if (!this.long0) {
            this.long0 = 0.7417649320975901 - 0.308341501185665; // 42.5° from Ferro = 24.833° from Greenwich
        }
        /* if scale not set default to 0.9999 */
        if (!this.k0) {
            this.k0 = 0.9999;
        }
        this.s45 = 0.785398163397448; /* 45 */
        this.s90 = 2 * this.s45;
        this.fi0 = this.lat0;
        this.e2 = this.es;
        this.e = Math.sqrt(this.e2);
        this.alfa = Math.sqrt(1 + (this.e2 * Math.pow(Math.cos(this.fi0), 4)) / (1 - this.e2));
        this.uq = 1.04216856380474;
        this.u0 = Math.asin(Math.sin(this.fi0) / this.alfa);
        this.g = Math.pow((1 + this.e * Math.sin(this.fi0)) / (1 - this.e * Math.sin(this.fi0)), this.alfa * this.e / 2);
        this.k = Math.tan(this.u0 / 2 + this.s45) / Math.pow(Math.tan(this.fi0 / 2 + this.s45), this.alfa) * this.g;
        this.k1 = this.k0;
        this.n0 = this.a * Math.sqrt(1 - this.e2) / (1 - this.e2 * Math.pow(Math.sin(this.fi0), 2));
        this.s0 = 1.37008346281555;
        this.n = Math.sin(this.s0);
        this.ro0 = this.k1 * this.n0 / Math.tan(this.s0);
        this.ad = this.s90 - this.uq;
    }
    /* ellipsoid */
    /* calculate xy from lat/lon */
    /* Constants, identical to inverse transform function */
    function forward(p) {
        var gfi, u, deltav, s, d, eps, ro;
        var lon = p.x;
        var lat = p.y;
        var delta_lon = (0, adjust_lon_1.default)(lon - this.long0, this.over);
        /* Transformation */
        gfi = Math.pow(((1 + this.e * Math.sin(lat)) / (1 - this.e * Math.sin(lat))), (this.alfa * this.e / 2));
        u = 2 * (Math.atan(this.k * Math.pow(Math.tan(lat / 2 + this.s45), this.alfa) / gfi) - this.s45);
        deltav = -delta_lon * this.alfa;
        s = Math.asin(Math.cos(this.ad) * Math.sin(u) + Math.sin(this.ad) * Math.cos(u) * Math.cos(deltav));
        d = Math.asin(Math.cos(u) * Math.sin(deltav) / Math.cos(s));
        eps = this.n * d;
        ro = this.ro0 * Math.pow(Math.tan(this.s0 / 2 + this.s45), this.n) / Math.pow(Math.tan(s / 2 + this.s45), this.n);
        p.y = ro * Math.cos(eps) / 1;
        p.x = ro * Math.sin(eps) / 1;
        if (!this.czech) {
            p.y *= -1;
            p.x *= -1;
        }
        return (p);
    }
    /* calculate lat/lon from xy */
    function inverse(p) {
        var u, deltav, s, d, eps, ro, fi1;
        var ok;
        /* Transformation */
        /* revert y, x */
        var tmp = p.x;
        p.x = p.y;
        p.y = tmp;
        if (!this.czech) {
            p.y *= -1;
            p.x *= -1;
        }
        ro = Math.sqrt(p.x * p.x + p.y * p.y);
        eps = Math.atan2(p.y, p.x);
        d = eps / Math.sin(this.s0);
        s = 2 * (Math.atan(Math.pow(this.ro0 / ro, 1 / this.n) * Math.tan(this.s0 / 2 + this.s45)) - this.s45);
        u = Math.asin(Math.cos(this.ad) * Math.sin(s) - Math.sin(this.ad) * Math.cos(s) * Math.cos(d));
        deltav = Math.asin(Math.cos(s) * Math.sin(d) / Math.cos(u));
        p.x = this.long0 - deltav / this.alfa;
        fi1 = u;
        ok = 0;
        var iter = 0;
        do {
            p.y = 2 * (Math.atan(Math.pow(this.k, -1 / this.alfa) * Math.pow(Math.tan(u / 2 + this.s45), 1 / this.alfa) * Math.pow((1 + this.e * Math.sin(fi1)) / (1 - this.e * Math.sin(fi1)), this.e / 2)) - this.s45);
            if (Math.abs(fi1 - p.y) < 0.0000000001) {
                ok = 1;
            }
            fi1 = p.y;
            iter += 1;
        } while (ok === 0 && iter < 15);
        if (iter >= 15) {
            return null;
        }
        return (p);
    }
    exports.names = ['Krovak', 'Krovak Modified', 'Krovak (North Orientated)', 'Krovak Modified (North Orientated)', 'krovak'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/projections/cass.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const mlfn_1 = tslib_1.__importDefault(require(215) /* ../common/mlfn */);
    const e0fn_1 = tslib_1.__importDefault(require(216) /* ../common/e0fn */);
    const e1fn_1 = tslib_1.__importDefault(require(217) /* ../common/e1fn */);
    const e2fn_1 = tslib_1.__importDefault(require(218) /* ../common/e2fn */);
    const e3fn_1 = tslib_1.__importDefault(require(219) /* ../common/e3fn */);
    const gN_1 = tslib_1.__importDefault(require(220) /* ../common/gN */);
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    const adjust_lat_1 = tslib_1.__importDefault(require(221) /* ../common/adjust_lat */);
    const imlfn_1 = tslib_1.__importDefault(require(222) /* ../common/imlfn */);
    const values_1 = require(156) /* ../constants/values */;
    /**
     * @typedef {Object} LocalThis
     * @property {number} es
     * @property {number} e0
     * @property {number} e1
     * @property {number} e2
     * @property {number} e3
     * @property {number} ml0
     */
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function init() {
        if (!this.sphere) {
            this.e0 = (0, e0fn_1.default)(this.es);
            this.e1 = (0, e1fn_1.default)(this.es);
            this.e2 = (0, e2fn_1.default)(this.es);
            this.e3 = (0, e3fn_1.default)(this.es);
            this.ml0 = this.a * (0, mlfn_1.default)(this.e0, this.e1, this.e2, this.e3, this.lat0);
        }
    }
    /* Cassini forward equations--mapping lat,long to x,y
      ----------------------------------------------------------------------- */
    function forward(p) {
        /* Forward equations
            ----------------- */
        var x, y;
        var lam = p.x;
        var phi = p.y;
        lam = (0, adjust_lon_1.default)(lam - this.long0, this.over);
        if (this.sphere) {
            x = this.a * Math.asin(Math.cos(phi) * Math.sin(lam));
            y = this.a * (Math.atan2(Math.tan(phi), Math.cos(lam)) - this.lat0);
        }
        else {
            // ellipsoid
            var sinphi = Math.sin(phi);
            var cosphi = Math.cos(phi);
            var nl = (0, gN_1.default)(this.a, this.e, sinphi);
            var tl = Math.tan(phi) * Math.tan(phi);
            var al = lam * Math.cos(phi);
            var asq = al * al;
            var cl = this.es * cosphi * cosphi / (1 - this.es);
            var ml = this.a * (0, mlfn_1.default)(this.e0, this.e1, this.e2, this.e3, phi);
            x = nl * al * (1 - asq * tl * (1 / 6 - (8 - tl + 8 * cl) * asq / 120));
            y = ml - this.ml0 + nl * sinphi / cosphi * asq * (0.5 + (5 - tl + 6 * cl) * asq / 24);
        }
        p.x = x + this.x0;
        p.y = y + this.y0;
        return p;
    }
    /* Inverse equations
      ----------------- */
    function inverse(p) {
        p.x -= this.x0;
        p.y -= this.y0;
        var x = p.x / this.a;
        var y = p.y / this.a;
        var phi, lam;
        if (this.sphere) {
            var dd = y + this.lat0;
            phi = Math.asin(Math.sin(dd) * Math.cos(x));
            lam = Math.atan2(Math.tan(x), Math.cos(dd));
        }
        else {
            /* ellipsoid */
            var ml1 = this.ml0 / this.a + y;
            var phi1 = (0, imlfn_1.default)(ml1, this.e0, this.e1, this.e2, this.e3);
            if (Math.abs(Math.abs(phi1) - values_1.HALF_PI) <= values_1.EPSLN) {
                p.x = this.long0;
                p.y = values_1.HALF_PI;
                if (y < 0) {
                    p.y *= -1;
                }
                return p;
            }
            var nl1 = (0, gN_1.default)(this.a, this.e, Math.sin(phi1));
            var rl1 = nl1 * nl1 * nl1 / this.a / this.a * (1 - this.es);
            var tl1 = Math.pow(Math.tan(phi1), 2);
            var dl = x * this.a / nl1;
            var dsq = dl * dl;
            phi = phi1 - nl1 * Math.tan(phi1) / rl1 * dl * dl * (0.5 - (1 + 3 * tl1) * dl * dl / 24);
            lam = dl * (1 - dsq * (tl1 / 3 + (1 + 3 * tl1) * tl1 * dsq / 15)) / Math.cos(phi1);
        }
        p.x = (0, adjust_lon_1.default)(lam + this.long0, this.over);
        p.y = (0, adjust_lat_1.default)(phi);
        return p;
    }
    exports.names = ['Cassini', 'Cassini_Soldner', 'cass'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/common/mlfn.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(e0, e1, e2, e3, phi) {
        return (e0 * phi - e1 * Math.sin(2 * phi) + e2 * Math.sin(4 * phi) - e3 * Math.sin(6 * phi));
    }
},
/* proj4/lib/common/e0fn.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(x) {
        return (1 - 0.25 * x * (1 + x / 16 * (3 + 1.25 * x)));
    }
},
/* proj4/lib/common/e1fn.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(x) {
        return (0.375 * x * (1 + 0.25 * x * (1 + 0.46875 * x)));
    }
},
/* proj4/lib/common/e2fn.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(x) {
        return (0.05859375 * x * x * (1 + 0.75 * x));
    }
},
/* proj4/lib/common/e3fn.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(x) {
        return (x * x * x * (35 / 3072));
    }
},
/* proj4/lib/common/gN.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(a, e, sinphi) {
        var temp = e * sinphi;
        return a / Math.sqrt(1 - temp * temp);
    }
},
/* proj4/lib/common/adjust_lat.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    const tslib_1 = require(1) /* tslib */;
    const values_1 = require(156) /* ../constants/values */;
    const sign_1 = tslib_1.__importDefault(require(173) /* ./sign */);
    function default_1(x) {
        return (Math.abs(x) < values_1.HALF_PI) ? x : (x - ((0, sign_1.default)(x) * Math.PI));
    }
},
/* proj4/lib/common/imlfn.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(ml, e0, e1, e2, e3) {
        var phi;
        var dphi;
        phi = ml / e0;
        for (var i = 0; i < 15; i++) {
            dphi = (ml - (e0 * phi - e1 * Math.sin(2 * phi) + e2 * Math.sin(4 * phi) - e3 * Math.sin(6 * phi))) / (e0 - 2 * e1 * Math.cos(2 * phi) + 4 * e2 * Math.cos(4 * phi) - 6 * e3 * Math.cos(6 * phi));
            phi += dphi;
            if (Math.abs(dphi) <= 0.0000000001) {
                return phi;
            }
        }
        // ..reportError("IMLFN-CONV:Latitude failed to converge after 15 iterations");
        return NaN;
    }
},
/* proj4/lib/projections/laea.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const values_1 = require(156) /* ../constants/values */;
    const qsfnz_1 = tslib_1.__importDefault(require(224) /* ../common/qsfnz */);
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    const authset_1 = tslib_1.__importDefault(require(225) /* ../common/authset */);
    const authlat_1 = tslib_1.__importDefault(require(226) /* ../common/authlat */);
    /**
     * @typedef {Object} LocalThis
     * @property {number} mode
     * @property {Array<number>} apa
     * @property {number} dd
     * @property {number} e
     * @property {number} es
     * @property {number} mmf
     * @property {number} rq
     * @property {number} qp
     * @property {number} sinb1
     * @property {number} cosb1
     * @property {number} ymf
     * @property {number} xmf
     * @property {number} sinph0
     * @property {number} cosph0
     */
    /*
      reference
        "New Equal-Area Map Projections for Noncircular Regions", John P. Snyder,
        The American Cartographer, Vol 15, No. 4, October 1988, pp. 341-355.
      */
    exports.S_POLE = 1;
    exports.N_POLE = 2;
    exports.EQUIT = 3;
    exports.OBLIQ = 4;
    /**
     * Initialize the Lambert Azimuthal Equal Area projection
     * @this {import('../defs.js').ProjectionDefinition & LocalThis}
     */
    function init() {
        var t = Math.abs(this.lat0);
        if (Math.abs(t - values_1.HALF_PI) < values_1.EPSLN) {
            this.mode = this.lat0 < 0 ? exports.S_POLE : exports.N_POLE;
        }
        else if (Math.abs(t) < values_1.EPSLN) {
            this.mode = exports.EQUIT;
        }
        else {
            this.mode = exports.OBLIQ;
        }
        if (this.es > 0) {
            var sinphi;
            this.qp = (0, qsfnz_1.default)(this.e, 1);
            this.mmf = 0.5 / (1 - this.es);
            this.apa = (0, authset_1.default)(this.es);
            switch (this.mode) {
                case exports.N_POLE:
                    this.dd = 1;
                    break;
                case exports.S_POLE:
                    this.dd = 1;
                    break;
                case exports.EQUIT:
                    this.rq = Math.sqrt(0.5 * this.qp);
                    this.dd = 1 / this.rq;
                    this.xmf = 1;
                    this.ymf = 0.5 * this.qp;
                    break;
                case exports.OBLIQ:
                    this.rq = Math.sqrt(0.5 * this.qp);
                    sinphi = Math.sin(this.lat0);
                    this.sinb1 = (0, qsfnz_1.default)(this.e, sinphi) / this.qp;
                    this.cosb1 = Math.sqrt(1 - this.sinb1 * this.sinb1);
                    this.dd = Math.cos(this.lat0) / (Math.sqrt(1 - this.es * sinphi * sinphi) * this.rq * this.cosb1);
                    this.ymf = (this.xmf = this.rq) / this.dd;
                    this.xmf *= this.dd;
                    break;
            }
        }
        else {
            if (this.mode === exports.OBLIQ) {
                this.sinph0 = Math.sin(this.lat0);
                this.cosph0 = Math.cos(this.lat0);
            }
        }
    }
    /* Lambert Azimuthal Equal Area forward equations--mapping lat,long to x,y
      ----------------------------------------------------------------------- */
    function forward(p) {
        /* Forward equations
            ----------------- */
        var x, y, coslam, sinlam, sinphi, q, sinb, cosb, b, cosphi;
        var lam = p.x;
        var phi = p.y;
        lam = (0, adjust_lon_1.default)(lam - this.long0, this.over);
        if (this.sphere) {
            sinphi = Math.sin(phi);
            cosphi = Math.cos(phi);
            coslam = Math.cos(lam);
            if (this.mode === this.OBLIQ || this.mode === this.EQUIT) {
                y = (this.mode === this.EQUIT) ? 1 + cosphi * coslam : 1 + this.sinph0 * sinphi + this.cosph0 * cosphi * coslam;
                if (y <= values_1.EPSLN) {
                    return null;
                }
                y = Math.sqrt(2 / y);
                x = y * cosphi * Math.sin(lam);
                y *= (this.mode === this.EQUIT) ? sinphi : this.cosph0 * sinphi - this.sinph0 * cosphi * coslam;
            }
            else if (this.mode === this.N_POLE || this.mode === this.S_POLE) {
                if (this.mode === this.N_POLE) {
                    coslam = -coslam;
                }
                if (Math.abs(phi + this.lat0) < values_1.EPSLN) {
                    return null;
                }
                y = values_1.FORTPI - phi * 0.5;
                y = 2 * ((this.mode === this.S_POLE) ? Math.cos(y) : Math.sin(y));
                x = y * Math.sin(lam);
                y *= coslam;
            }
        }
        else {
            sinb = 0;
            cosb = 0;
            b = 0;
            coslam = Math.cos(lam);
            sinlam = Math.sin(lam);
            sinphi = Math.sin(phi);
            q = (0, qsfnz_1.default)(this.e, sinphi);
            if (this.mode === this.OBLIQ || this.mode === this.EQUIT) {
                sinb = q / this.qp;
                cosb = Math.sqrt(1 - sinb * sinb);
            }
            switch (this.mode) {
                case this.OBLIQ:
                    b = 1 + this.sinb1 * sinb + this.cosb1 * cosb * coslam;
                    break;
                case this.EQUIT:
                    b = 1 + cosb * coslam;
                    break;
                case this.N_POLE:
                    b = values_1.HALF_PI + phi;
                    q = this.qp - q;
                    break;
                case this.S_POLE:
                    b = phi - values_1.HALF_PI;
                    q = this.qp + q;
                    break;
            }
            if (Math.abs(b) < values_1.EPSLN) {
                return null;
            }
            switch (this.mode) {
                case this.OBLIQ:
                case this.EQUIT:
                    b = Math.sqrt(2 / b);
                    if (this.mode === this.OBLIQ) {
                        y = this.ymf * b * (this.cosb1 * sinb - this.sinb1 * cosb * coslam);
                    }
                    else {
                        y = (b = Math.sqrt(2 / (1 + cosb * coslam))) * sinb * this.ymf;
                    }
                    x = this.xmf * b * cosb * sinlam;
                    break;
                case this.N_POLE:
                case this.S_POLE:
                    if (q >= 0) {
                        x = (b = Math.sqrt(q)) * sinlam;
                        y = coslam * ((this.mode === this.S_POLE) ? b : -b);
                    }
                    else {
                        x = y = 0;
                    }
                    break;
            }
        }
        p.x = this.a * x + this.x0;
        p.y = this.a * y + this.y0;
        return p;
    }
    /* Inverse equations
      ----------------- */
    function inverse(p) {
        p.x -= this.x0;
        p.y -= this.y0;
        var x = p.x / this.a;
        var y = p.y / this.a;
        var lam, phi, cCe, sCe, q, rho, ab;
        if (this.sphere) {
            var cosz = 0, rh, sinz = 0;
            rh = Math.sqrt(x * x + y * y);
            phi = rh * 0.5;
            if (phi > 1) {
                return null;
            }
            phi = 2 * Math.asin(phi);
            if (this.mode === this.OBLIQ || this.mode === this.EQUIT) {
                sinz = Math.sin(phi);
                cosz = Math.cos(phi);
            }
            switch (this.mode) {
                case this.EQUIT:
                    phi = (Math.abs(rh) <= values_1.EPSLN) ? 0 : Math.asin(y * sinz / rh);
                    x *= sinz;
                    y = cosz * rh;
                    break;
                case this.OBLIQ:
                    phi = (Math.abs(rh) <= values_1.EPSLN) ? this.lat0 : Math.asin(cosz * this.sinph0 + y * sinz * this.cosph0 / rh);
                    x *= sinz * this.cosph0;
                    y = (cosz - Math.sin(phi) * this.sinph0) * rh;
                    break;
                case this.N_POLE:
                    y = -y;
                    phi = values_1.HALF_PI - phi;
                    break;
                case this.S_POLE:
                    phi -= values_1.HALF_PI;
                    break;
            }
            lam = (y === 0 && (this.mode === this.EQUIT || this.mode === this.OBLIQ)) ? 0 : Math.atan2(x, y);
        }
        else {
            ab = 0;
            if (this.mode === this.OBLIQ || this.mode === this.EQUIT) {
                x /= this.dd;
                y *= this.dd;
                rho = Math.sqrt(x * x + y * y);
                if (rho < values_1.EPSLN) {
                    p.x = this.long0;
                    p.y = this.lat0;
                    return p;
                }
                sCe = 2 * Math.asin(0.5 * rho / this.rq);
                cCe = Math.cos(sCe);
                x *= (sCe = Math.sin(sCe));
                if (this.mode === this.OBLIQ) {
                    ab = cCe * this.sinb1 + y * sCe * this.cosb1 / rho;
                    q = this.qp * ab;
                    y = rho * this.cosb1 * cCe - y * this.sinb1 * sCe;
                }
                else {
                    ab = y * sCe / rho;
                    q = this.qp * ab;
                    y = rho * cCe;
                }
            }
            else if (this.mode === this.N_POLE || this.mode === this.S_POLE) {
                if (this.mode === this.N_POLE) {
                    y = -y;
                }
                q = (x * x + y * y);
                if (!q) {
                    p.x = this.long0;
                    p.y = this.lat0;
                    return p;
                }
                ab = 1 - q / this.qp;
                if (this.mode === this.S_POLE) {
                    ab = -ab;
                }
            }
            lam = Math.atan2(x, y);
            phi = (0, authlat_1.default)(Math.asin(ab), this.apa);
        }
        p.x = (0, adjust_lon_1.default)(this.long0 + lam, this.over);
        p.y = phi;
        return p;
    }
    exports.names = ['Lambert Azimuthal Equal Area', 'Lambert_Azimuthal_Equal_Area', 'laea'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names,
        S_POLE: exports.S_POLE,
        N_POLE: exports.N_POLE,
        EQUIT: exports.EQUIT,
        OBLIQ: exports.OBLIQ
    };
},
/* proj4/lib/common/qsfnz.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(eccent, sinphi) {
        var con;
        if (eccent > 1.0e-7) {
            con = eccent * sinphi;
            return ((1 - eccent * eccent) * (sinphi / (1 - con * con) - (0.5 / eccent) * Math.log((1 - con) / (1 + con))));
        }
        else {
            return (2 * sinphi);
        }
    }
},
/* proj4/lib/common/authset.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = authset;
    var P00 = 0.33333333333333333333;
    var P01 = 0.17222222222222222222;
    var P02 = 0.10257936507936507936;
    var P10 = 0.06388888888888888888;
    var P11 = 0.06640211640211640211;
    var P20 = 0.01641501294219154443;
    function authset(es) {
        var t;
        var APA = [];
        APA[0] = es * P00;
        t = es * es;
        APA[0] += t * P01;
        APA[1] = t * P10;
        t *= es;
        APA[0] += t * P02;
        APA[1] += t * P11;
        APA[2] = t * P20;
        return APA;
    }
},
/* proj4/lib/common/authlat.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = authlat;
    function authlat(beta, APA) {
        var t = beta + beta;
        return (beta + APA[0] * Math.sin(t) + APA[1] * Math.sin(t + t) + APA[2] * Math.sin(t + t + t));
    }
},
/* proj4/lib/projections/aea.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    exports.phi1z = phi1z;
    const tslib_1 = require(1) /* tslib */;
    const msfnz_1 = tslib_1.__importDefault(require(171) /* ../common/msfnz */);
    const qsfnz_1 = tslib_1.__importDefault(require(224) /* ../common/qsfnz */);
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    const asinz_1 = tslib_1.__importDefault(require(228) /* ../common/asinz */);
    const values_1 = require(156) /* ../constants/values */;
    /**
     * @typedef {Object} LocalThis
     * @property {number} temp
     * @property {number} es
     * @property {number} e3
     * @property {number} sin_po
     * @property {number} cos_po
     * @property {number} t1
     * @property {number} con
     * @property {number} ms1
     * @property {number} qs1
     * @property {number} t2
     * @property {number} ms2
     * @property {number} qs2
     * @property {number} t3
     * @property {number} qs0
     * @property {number} ns0
     * @property {number} c
     * @property {number} rh
     * @property {number} sin_phi
     * @property {number} cos_phi
     */
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function init() {
        if (Math.abs(this.lat1 + this.lat2) < values_1.EPSLN) {
            return;
        }
        this.temp = this.b / this.a;
        this.es = 1 - Math.pow(this.temp, 2);
        this.e3 = Math.sqrt(this.es);
        this.sin_po = Math.sin(this.lat1);
        this.cos_po = Math.cos(this.lat1);
        this.t1 = this.sin_po;
        this.con = this.sin_po;
        this.ms1 = (0, msfnz_1.default)(this.e3, this.sin_po, this.cos_po);
        this.qs1 = (0, qsfnz_1.default)(this.e3, this.sin_po);
        this.sin_po = Math.sin(this.lat2);
        this.cos_po = Math.cos(this.lat2);
        this.t2 = this.sin_po;
        this.ms2 = (0, msfnz_1.default)(this.e3, this.sin_po, this.cos_po);
        this.qs2 = (0, qsfnz_1.default)(this.e3, this.sin_po);
        this.sin_po = Math.sin(this.lat0);
        this.cos_po = Math.cos(this.lat0);
        this.t3 = this.sin_po;
        this.qs0 = (0, qsfnz_1.default)(this.e3, this.sin_po);
        if (Math.abs(this.lat1 - this.lat2) > values_1.EPSLN) {
            this.ns0 = (this.ms1 * this.ms1 - this.ms2 * this.ms2) / (this.qs2 - this.qs1);
        }
        else {
            this.ns0 = this.con;
        }
        this.c = this.ms1 * this.ms1 + this.ns0 * this.qs1;
        this.rh = this.a * Math.sqrt(this.c - this.ns0 * this.qs0) / this.ns0;
    }
    /* Albers Conical Equal Area forward equations--mapping lat,long to x,y
      ------------------------------------------------------------------- */
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function forward(p) {
        var lon = p.x;
        var lat = p.y;
        this.sin_phi = Math.sin(lat);
        this.cos_phi = Math.cos(lat);
        var qs = (0, qsfnz_1.default)(this.e3, this.sin_phi);
        var rh1 = this.a * Math.sqrt(this.c - this.ns0 * qs) / this.ns0;
        var theta = this.ns0 * (0, adjust_lon_1.default)(lon - this.long0, this.over);
        var x = rh1 * Math.sin(theta) + this.x0;
        var y = this.rh - rh1 * Math.cos(theta) + this.y0;
        p.x = x;
        p.y = y;
        return p;
    }
    function inverse(p) {
        var rh1, qs, con, theta, lon, lat;
        p.x -= this.x0;
        p.y = this.rh - p.y + this.y0;
        if (this.ns0 >= 0) {
            rh1 = Math.sqrt(p.x * p.x + p.y * p.y);
            con = 1;
        }
        else {
            rh1 = -Math.sqrt(p.x * p.x + p.y * p.y);
            con = -1;
        }
        theta = 0;
        if (rh1 !== 0) {
            theta = Math.atan2(con * p.x, con * p.y);
        }
        con = rh1 * this.ns0 / this.a;
        if (this.sphere) {
            lat = Math.asin((this.c - con * con) / (2 * this.ns0));
        }
        else {
            qs = (this.c - con * con) / this.ns0;
            lat = this.phi1z(this.e3, qs);
        }
        lon = (0, adjust_lon_1.default)(theta / this.ns0 + this.long0, this.over);
        p.x = lon;
        p.y = lat;
        return p;
    }
    /* Function to compute phi1, the latitude for the inverse of the
       Albers Conical Equal-Area projection.
    ------------------------------------------- */
    function phi1z(eccent, qs) {
        var sinphi, cosphi, con, com, dphi;
        var phi = (0, asinz_1.default)(0.5 * qs);
        if (eccent < values_1.EPSLN) {
            return phi;
        }
        var eccnts = eccent * eccent;
        for (var i = 1; i <= 25; i++) {
            sinphi = Math.sin(phi);
            cosphi = Math.cos(phi);
            con = eccent * sinphi;
            com = 1 - con * con;
            dphi = 0.5 * com * com / cosphi * (qs / (1 - eccnts) - sinphi / com + 0.5 / eccent * Math.log((1 - con) / (1 + con)));
            phi = phi + dphi;
            if (Math.abs(dphi) <= 1e-7) {
                return phi;
            }
        }
        return null;
    }
    exports.names = ['Albers_Conic_Equal_Area', 'Albers_Equal_Area', 'Albers', 'aea'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names,
        phi1z: phi1z
    };
},
/* proj4/lib/common/asinz.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(x) {
        if (Math.abs(x) > 1) {
            x = (x > 1) ? 1 : -1;
        }
        return Math.asin(x);
    }
},
/* proj4/lib/projections/gnom.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    const asinz_1 = tslib_1.__importDefault(require(228) /* ../common/asinz */);
    const values_1 = require(156) /* ../constants/values */;
    /**
     * @typedef {Object} LocalThis
     * @property {number} sin_p14
     * @property {number} cos_p14
     * @property {number} infinity_dist
     * @property {number} rc
     */
    /**
      reference:
        Wolfram Mathworld "Gnomonic Projection"
        http://mathworld.wolfram.com/GnomonicProjection.html
        Accessed: 12th November 2009
       @this {import('../defs.js').ProjectionDefinition & LocalThis}
     */
    function init() {
        /* Place parameters in static storage for common use
            ------------------------------------------------- */
        this.sin_p14 = Math.sin(this.lat0);
        this.cos_p14 = Math.cos(this.lat0);
        // Approximation for projecting points to the horizon (infinity)
        this.infinity_dist = 1000 * this.a;
        this.rc = 1;
    }
    /* Gnomonic forward equations--mapping lat,long to x,y
        --------------------------------------------------- */
    function forward(p) {
        var sinphi, cosphi; /* sin and cos value        */
        var dlon; /* delta longitude value      */
        var coslon; /* cos of longitude        */
        var ksp; /* scale factor          */
        var g;
        var x, y;
        var lon = p.x;
        var lat = p.y;
        /* Forward equations
            ----------------- */
        dlon = (0, adjust_lon_1.default)(lon - this.long0, this.over);
        sinphi = Math.sin(lat);
        cosphi = Math.cos(lat);
        coslon = Math.cos(dlon);
        g = this.sin_p14 * sinphi + this.cos_p14 * cosphi * coslon;
        ksp = 1;
        if ((g > 0) || (Math.abs(g) <= values_1.EPSLN)) {
            x = this.x0 + this.a * ksp * cosphi * Math.sin(dlon) / g;
            y = this.y0 + this.a * ksp * (this.cos_p14 * sinphi - this.sin_p14 * cosphi * coslon) / g;
        }
        else {
            // Point is in the opposing hemisphere and is unprojectable
            // We still need to return a reasonable point, so we project
            // to infinity, on a bearing
            // equivalent to the northern hemisphere equivalent
            // This is a reasonable approximation for short shapes and lines that
            // straddle the horizon.
            x = this.x0 + this.infinity_dist * cosphi * Math.sin(dlon);
            y = this.y0 + this.infinity_dist * (this.cos_p14 * sinphi - this.sin_p14 * cosphi * coslon);
        }
        p.x = x;
        p.y = y;
        return p;
    }
    function inverse(p) {
        var rh; /* Rho */
        var sinc, cosc;
        var c;
        var lon, lat;
        /* Inverse equations
            ----------------- */
        p.x = (p.x - this.x0) / this.a;
        p.y = (p.y - this.y0) / this.a;
        p.x /= this.k0;
        p.y /= this.k0;
        if ((rh = Math.sqrt(p.x * p.x + p.y * p.y))) {
            c = Math.atan2(rh, this.rc);
            sinc = Math.sin(c);
            cosc = Math.cos(c);
            lat = (0, asinz_1.default)(cosc * this.sin_p14 + (p.y * sinc * this.cos_p14) / rh);
            lon = Math.atan2(p.x * sinc, rh * this.cos_p14 * cosc - p.y * this.sin_p14 * sinc);
            lon = (0, adjust_lon_1.default)(this.long0 + lon, this.over);
        }
        else {
            lat = this.phic0;
            lon = 0;
        }
        p.x = lon;
        p.y = lat;
        return p;
    }
    exports.names = ['gnom'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/projections/cea.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    const qsfnz_1 = tslib_1.__importDefault(require(224) /* ../common/qsfnz */);
    const msfnz_1 = tslib_1.__importDefault(require(171) /* ../common/msfnz */);
    const iqsfnz_1 = tslib_1.__importDefault(require(231) /* ../common/iqsfnz */);
    /**
     * @typedef {Object} LocalThis
     * @property {number} e
     */
    /**
      reference:
        "Cartographic Projection Procedures for the UNIX Environment-
        A User's Manual" by Gerald I. Evenden,
        USGS Open File Report 90-284and Release 4 Interim Reports (2003)
      @this {import('../defs.js').ProjectionDefinition & LocalThis}
    */
    function init() {
        // no-op
        if (!this.sphere) {
            this.k0 = (0, msfnz_1.default)(this.e, Math.sin(this.lat_ts), Math.cos(this.lat_ts));
        }
    }
    /* Cylindrical Equal Area forward equations--mapping lat,long to x,y
        ------------------------------------------------------------ */
    function forward(p) {
        var lon = p.x;
        var lat = p.y;
        var x, y;
        /* Forward equations
            ----------------- */
        var dlon = (0, adjust_lon_1.default)(lon - this.long0, this.over);
        if (this.sphere) {
            x = this.x0 + this.a * dlon * Math.cos(this.lat_ts);
            y = this.y0 + this.a * Math.sin(lat) / Math.cos(this.lat_ts);
        }
        else {
            var qs = (0, qsfnz_1.default)(this.e, Math.sin(lat));
            x = this.x0 + this.a * this.k0 * dlon;
            y = this.y0 + this.a * qs * 0.5 / this.k0;
        }
        p.x = x;
        p.y = y;
        return p;
    }
    /* Cylindrical Equal Area inverse equations--mapping x,y to lat/long
        ------------------------------------------------------------ */
    function inverse(p) {
        p.x -= this.x0;
        p.y -= this.y0;
        var lon, lat;
        if (this.sphere) {
            lon = (0, adjust_lon_1.default)(this.long0 + (p.x / this.a) / Math.cos(this.lat_ts), this.over);
            lat = Math.asin((p.y / this.a) * Math.cos(this.lat_ts));
        }
        else {
            lat = (0, iqsfnz_1.default)(this.e, 2 * p.y * this.k0 / this.a);
            lon = (0, adjust_lon_1.default)(this.long0 + p.x / (this.a * this.k0), this.over);
        }
        p.x = lon;
        p.y = lat;
        return p;
    }
    exports.names = ['cea'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/common/iqsfnz.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    const values_1 = require(156) /* ../constants/values */;
    function default_1(eccent, q) {
        var temp = 1 - (1 - eccent * eccent) / (2 * eccent) * Math.log((1 - eccent) / (1 + eccent));
        if (Math.abs(Math.abs(q) - temp) < 1.0E-6) {
            if (q < 0) {
                return (-1 * values_1.HALF_PI);
            }
            else {
                return values_1.HALF_PI;
            }
        }
        // var phi = 0.5* q/(1-eccent*eccent);
        var phi = Math.asin(0.5 * q);
        var dphi;
        var sin_phi;
        var cos_phi;
        var con;
        for (var i = 0; i < 30; i++) {
            sin_phi = Math.sin(phi);
            cos_phi = Math.cos(phi);
            con = eccent * sin_phi;
            dphi = Math.pow(1 - con * con, 2) / (2 * cos_phi) * (q / (1 - eccent * eccent) - sin_phi / (1 - con * con) + 0.5 / eccent * Math.log((1 - con) / (1 + con)));
            phi += dphi;
            if (Math.abs(dphi) <= 0.0000000001) {
                return phi;
            }
        }
        // console.log("IQSFN-CONV:Latitude failed to converge after 30 iterations");
        return NaN;
    }
},
/* proj4/lib/projections/eqc.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    const adjust_lat_1 = tslib_1.__importDefault(require(221) /* ../common/adjust_lat */);
    function init() {
        this.x0 = this.x0 || 0;
        this.y0 = this.y0 || 0;
        this.lat0 = this.lat0 || 0;
        this.long0 = this.long0 || 0;
        this.lat_ts = this.lat_ts || 0;
        this.title = this.title || 'Equidistant Cylindrical (Plate Carre)';
        this.rc = Math.cos(this.lat_ts);
    }
    // forward equations--mapping lat,long to x,y
    // -----------------------------------------------------------------
    function forward(p) {
        var lon = p.x;
        var lat = p.y;
        var dlon = (0, adjust_lon_1.default)(lon - this.long0, this.over);
        var dlat = (0, adjust_lat_1.default)(lat - this.lat0);
        p.x = this.x0 + (this.a * dlon * this.rc);
        p.y = this.y0 + (this.a * dlat);
        return p;
    }
    // inverse equations--mapping x,y to lat/long
    // -----------------------------------------------------------------
    function inverse(p) {
        var x = p.x;
        var y = p.y;
        p.x = (0, adjust_lon_1.default)(this.long0 + ((x - this.x0) / (this.a * this.rc)), this.over);
        p.y = (0, adjust_lat_1.default)(this.lat0 + ((y - this.y0) / (this.a)));
        return p;
    }
    exports.names = ['Equirectangular', 'Equidistant_Cylindrical', 'Equidistant_Cylindrical_Spherical', 'eqc'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/projections/poly.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const e0fn_1 = tslib_1.__importDefault(require(216) /* ../common/e0fn */);
    const e1fn_1 = tslib_1.__importDefault(require(217) /* ../common/e1fn */);
    const e2fn_1 = tslib_1.__importDefault(require(218) /* ../common/e2fn */);
    const e3fn_1 = tslib_1.__importDefault(require(219) /* ../common/e3fn */);
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    const adjust_lat_1 = tslib_1.__importDefault(require(221) /* ../common/adjust_lat */);
    const mlfn_1 = tslib_1.__importDefault(require(215) /* ../common/mlfn */);
    const values_1 = require(156) /* ../constants/values */;
    const gN_1 = tslib_1.__importDefault(require(220) /* ../common/gN */);
    /**
     * @typedef {Object} LocalThis
     * @property {number} temp
     * @property {number} es
     * @property {number} e
     * @property {number} e0
     * @property {number} e1
     * @property {number} e2
     * @property {number} e3
     * @property {number} ml0
     */
    var MAX_ITER = 20;
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function init() {
        /* Place parameters in static storage for common use
            ------------------------------------------------- */
        this.temp = this.b / this.a;
        this.es = 1 - Math.pow(this.temp, 2); // devait etre dans tmerc.js mais n y est pas donc je commente sinon retour de valeurs nulles
        this.e = Math.sqrt(this.es);
        this.e0 = (0, e0fn_1.default)(this.es);
        this.e1 = (0, e1fn_1.default)(this.es);
        this.e2 = (0, e2fn_1.default)(this.es);
        this.e3 = (0, e3fn_1.default)(this.es);
        this.ml0 = this.a * (0, mlfn_1.default)(this.e0, this.e1, this.e2, this.e3, this.lat0); // si que des zeros le calcul ne se fait pas
    }
    /* Polyconic forward equations--mapping lat,long to x,y
        --------------------------------------------------- */
    function forward(p) {
        var lon = p.x;
        var lat = p.y;
        var x, y, el;
        var dlon = (0, adjust_lon_1.default)(lon - this.long0, this.over);
        el = dlon * Math.sin(lat);
        if (this.sphere) {
            if (Math.abs(lat) <= values_1.EPSLN) {
                x = this.a * dlon;
                y = -1 * this.a * this.lat0;
            }
            else {
                x = this.a * Math.sin(el) / Math.tan(lat);
                y = this.a * ((0, adjust_lat_1.default)(lat - this.lat0) + (1 - Math.cos(el)) / Math.tan(lat));
            }
        }
        else {
            if (Math.abs(lat) <= values_1.EPSLN) {
                x = this.a * dlon;
                y = -1 * this.ml0;
            }
            else {
                var nl = (0, gN_1.default)(this.a, this.e, Math.sin(lat)) / Math.tan(lat);
                x = nl * Math.sin(el);
                y = this.a * (0, mlfn_1.default)(this.e0, this.e1, this.e2, this.e3, lat) - this.ml0 + nl * (1 - Math.cos(el));
            }
        }
        p.x = x + this.x0;
        p.y = y + this.y0;
        return p;
    }
    /* Inverse equations
      ----------------- */
    function inverse(p) {
        var lon, lat, x, y, i;
        var al, bl;
        var phi, dphi;
        x = p.x - this.x0;
        y = p.y - this.y0;
        if (this.sphere) {
            if (Math.abs(y + this.a * this.lat0) <= values_1.EPSLN) {
                lon = (0, adjust_lon_1.default)(x / this.a + this.long0, this.over);
                lat = 0;
            }
            else {
                al = this.lat0 + y / this.a;
                bl = x * x / this.a / this.a + al * al;
                phi = al;
                var tanphi;
                for (i = MAX_ITER; i; --i) {
                    tanphi = Math.tan(phi);
                    dphi = -1 * (al * (phi * tanphi + 1) - phi - 0.5 * (phi * phi + bl) * tanphi) / ((phi - al) / tanphi - 1);
                    phi += dphi;
                    if (Math.abs(dphi) <= values_1.EPSLN) {
                        lat = phi;
                        break;
                    }
                }
                lon = (0, adjust_lon_1.default)(this.long0 + (Math.asin(x * Math.tan(phi) / this.a)) / Math.sin(lat), this.over);
            }
        }
        else {
            if (Math.abs(y + this.ml0) <= values_1.EPSLN) {
                lat = 0;
                lon = (0, adjust_lon_1.default)(this.long0 + x / this.a, this.over);
            }
            else {
                al = (this.ml0 + y) / this.a;
                bl = x * x / this.a / this.a + al * al;
                phi = al;
                var cl, mln, mlnp, ma;
                var con;
                for (i = MAX_ITER; i; --i) {
                    con = this.e * Math.sin(phi);
                    cl = Math.sqrt(1 - con * con) * Math.tan(phi);
                    mln = this.a * (0, mlfn_1.default)(this.e0, this.e1, this.e2, this.e3, phi);
                    mlnp = this.e0 - 2 * this.e1 * Math.cos(2 * phi) + 4 * this.e2 * Math.cos(4 * phi) - 6 * this.e3 * Math.cos(6 * phi);
                    ma = mln / this.a;
                    dphi = (al * (cl * ma + 1) - ma - 0.5 * cl * (ma * ma + bl)) / (this.es * Math.sin(2 * phi) * (ma * ma + bl - 2 * al * ma) / (4 * cl) + (al - ma) * (cl * mlnp - 2 / Math.sin(2 * phi)) - mlnp);
                    phi -= dphi;
                    if (Math.abs(dphi) <= values_1.EPSLN) {
                        lat = phi;
                        break;
                    }
                }
                // lat=phi4z(this.e,this.e0,this.e1,this.e2,this.e3,al,bl,0,0);
                cl = Math.sqrt(1 - this.es * Math.pow(Math.sin(lat), 2)) * Math.tan(lat);
                lon = (0, adjust_lon_1.default)(this.long0 + Math.asin(x * cl / this.a) / Math.sin(lat), this.over);
            }
        }
        p.x = lon;
        p.y = lat;
        return p;
    }
    exports.names = ['Polyconic', 'American_Polyconic', 'poly'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/projections/nzmg.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const values_1 = require(156) /* ../constants/values */;
    /*
      reference
        Department of Land and Survey Technical Circular 1973/32
          http://www.linz.govt.nz/docs/miscellaneous/nz-map-definition.pdf
        OSG Technical Report 4.1
          http://www.linz.govt.nz/docs/miscellaneous/nzmg.pdf
      */
    /**
     * iterations: Number of iterations to refine inverse transform.
     *     0 -> km accuracy
     *     1 -> m accuracy -- suitable for most mapping applications
     *     2 -> mm accuracy
     */
    exports.iterations = 1;
    function init() {
        this.A = [];
        this.A[1] = 0.6399175073;
        this.A[2] = -0.1358797613;
        this.A[3] = 0.063294409;
        this.A[4] = -0.02526853;
        this.A[5] = 0.0117879;
        this.A[6] = -0.0055161;
        this.A[7] = 0.0026906;
        this.A[8] = -0.001333;
        this.A[9] = 0.00067;
        this.A[10] = -0.00034;
        this.B_re = [];
        this.B_im = [];
        this.B_re[1] = 0.7557853228;
        this.B_im[1] = 0;
        this.B_re[2] = 0.249204646;
        this.B_im[2] = 0.003371507;
        this.B_re[3] = -0.001541739;
        this.B_im[3] = 0.041058560;
        this.B_re[4] = -0.10162907;
        this.B_im[4] = 0.01727609;
        this.B_re[5] = -0.26623489;
        this.B_im[5] = -0.36249218;
        this.B_re[6] = -0.6870983;
        this.B_im[6] = -1.1651967;
        this.C_re = [];
        this.C_im = [];
        this.C_re[1] = 1.3231270439;
        this.C_im[1] = 0;
        this.C_re[2] = -0.577245789;
        this.C_im[2] = -0.007809598;
        this.C_re[3] = 0.508307513;
        this.C_im[3] = -0.112208952;
        this.C_re[4] = -0.15094762;
        this.C_im[4] = 0.18200602;
        this.C_re[5] = 1.01418179;
        this.C_im[5] = 1.64497696;
        this.C_re[6] = 1.9660549;
        this.C_im[6] = 2.5127645;
        this.D = [];
        this.D[1] = 1.5627014243;
        this.D[2] = 0.5185406398;
        this.D[3] = -0.03333098;
        this.D[4] = -0.1052906;
        this.D[5] = -0.0368594;
        this.D[6] = 0.007317;
        this.D[7] = 0.01220;
        this.D[8] = 0.00394;
        this.D[9] = -0.0013;
    }
    /**
        New Zealand Map Grid Forward  - long/lat to x/y
        long/lat in radians
      */
    function forward(p) {
        var n;
        var lon = p.x;
        var lat = p.y;
        var delta_lat = lat - this.lat0;
        var delta_lon = lon - this.long0;
        // 1. Calculate d_phi and d_psi    ...                          // and d_lambda
        // For this algorithm, delta_latitude is in seconds of arc x 10-5, so we need to scale to those units. Longitude is radians.
        var d_phi = delta_lat / values_1.SEC_TO_RAD * 1E-5;
        var d_lambda = delta_lon;
        var d_phi_n = 1; // d_phi^0
        var d_psi = 0;
        for (n = 1; n <= 10; n++) {
            d_phi_n = d_phi_n * d_phi;
            d_psi = d_psi + this.A[n] * d_phi_n;
        }
        // 2. Calculate theta
        var th_re = d_psi;
        var th_im = d_lambda;
        // 3. Calculate z
        var th_n_re = 1;
        var th_n_im = 0; // theta^0
        var th_n_re1;
        var th_n_im1;
        var z_re = 0;
        var z_im = 0;
        for (n = 1; n <= 6; n++) {
            th_n_re1 = th_n_re * th_re - th_n_im * th_im;
            th_n_im1 = th_n_im * th_re + th_n_re * th_im;
            th_n_re = th_n_re1;
            th_n_im = th_n_im1;
            z_re = z_re + this.B_re[n] * th_n_re - this.B_im[n] * th_n_im;
            z_im = z_im + this.B_im[n] * th_n_re + this.B_re[n] * th_n_im;
        }
        // 4. Calculate easting and northing
        p.x = (z_im * this.a) + this.x0;
        p.y = (z_re * this.a) + this.y0;
        return p;
    }
    /**
        New Zealand Map Grid Inverse  -  x/y to long/lat
      */
    function inverse(p) {
        var n;
        var x = p.x;
        var y = p.y;
        var delta_x = x - this.x0;
        var delta_y = y - this.y0;
        // 1. Calculate z
        var z_re = delta_y / this.a;
        var z_im = delta_x / this.a;
        // 2a. Calculate theta - first approximation gives km accuracy
        var z_n_re = 1;
        var z_n_im = 0; // z^0
        var z_n_re1;
        var z_n_im1;
        var th_re = 0;
        var th_im = 0;
        for (n = 1; n <= 6; n++) {
            z_n_re1 = z_n_re * z_re - z_n_im * z_im;
            z_n_im1 = z_n_im * z_re + z_n_re * z_im;
            z_n_re = z_n_re1;
            z_n_im = z_n_im1;
            th_re = th_re + this.C_re[n] * z_n_re - this.C_im[n] * z_n_im;
            th_im = th_im + this.C_im[n] * z_n_re + this.C_re[n] * z_n_im;
        }
        // 2b. Iterate to refine the accuracy of the calculation
        //        0 iterations gives km accuracy
        //        1 iteration gives m accuracy -- good enough for most mapping applications
        //        2 iterations bives mm accuracy
        for (var i = 0; i < this.iterations; i++) {
            var th_n_re = th_re;
            var th_n_im = th_im;
            var th_n_re1;
            var th_n_im1;
            var num_re = z_re;
            var num_im = z_im;
            for (n = 2; n <= 6; n++) {
                th_n_re1 = th_n_re * th_re - th_n_im * th_im;
                th_n_im1 = th_n_im * th_re + th_n_re * th_im;
                th_n_re = th_n_re1;
                th_n_im = th_n_im1;
                num_re = num_re + (n - 1) * (this.B_re[n] * th_n_re - this.B_im[n] * th_n_im);
                num_im = num_im + (n - 1) * (this.B_im[n] * th_n_re + this.B_re[n] * th_n_im);
            }
            th_n_re = 1;
            th_n_im = 0;
            var den_re = this.B_re[1];
            var den_im = this.B_im[1];
            for (n = 2; n <= 6; n++) {
                th_n_re1 = th_n_re * th_re - th_n_im * th_im;
                th_n_im1 = th_n_im * th_re + th_n_re * th_im;
                th_n_re = th_n_re1;
                th_n_im = th_n_im1;
                den_re = den_re + n * (this.B_re[n] * th_n_re - this.B_im[n] * th_n_im);
                den_im = den_im + n * (this.B_im[n] * th_n_re + this.B_re[n] * th_n_im);
            }
            // Complex division
            var den2 = den_re * den_re + den_im * den_im;
            th_re = (num_re * den_re + num_im * den_im) / den2;
            th_im = (num_im * den_re - num_re * den_im) / den2;
        }
        // 3. Calculate d_phi              ...                                    // and d_lambda
        var d_psi = th_re;
        var d_lambda = th_im;
        var d_psi_n = 1; // d_psi^0
        var d_phi = 0;
        for (n = 1; n <= 9; n++) {
            d_psi_n = d_psi_n * d_psi;
            d_phi = d_phi + this.D[n] * d_psi_n;
        }
        // 4. Calculate latitude and longitude
        // d_phi is calcuated in second of arc * 10^-5, so we need to scale back to radians. d_lambda is in radians.
        var lat = this.lat0 + (d_phi * values_1.SEC_TO_RAD * 1E5);
        var lon = this.long0 + d_lambda;
        p.x = lon;
        p.y = lat;
        return p;
    }
    exports.names = ['New_Zealand_Map_Grid', 'nzmg'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/projections/mill.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    /*
      reference
        "New Equal-Area Map Projections for Noncircular Regions", John P. Snyder,
        The American Cartographer, Vol 15, No. 4, October 1988, pp. 341-355.
      */
    /* Initialize the Miller Cylindrical projection
      ------------------------------------------- */
    function init() {
        // no-op
    }
    /* Miller Cylindrical forward equations--mapping lat,long to x,y
        ------------------------------------------------------------ */
    function forward(p) {
        var lon = p.x;
        var lat = p.y;
        /* Forward equations
            ----------------- */
        var dlon = (0, adjust_lon_1.default)(lon - this.long0, this.over);
        var x = this.x0 + this.a * dlon;
        var y = this.y0 + this.a * Math.log(Math.tan((Math.PI / 4) + (lat / 2.5))) * 1.25;
        p.x = x;
        p.y = y;
        return p;
    }
    /* Miller Cylindrical inverse equations--mapping x,y to lat/long
        ------------------------------------------------------------ */
    function inverse(p) {
        p.x -= this.x0;
        p.y -= this.y0;
        var lon = (0, adjust_lon_1.default)(this.long0 + p.x / this.a, this.over);
        var lat = 2.5 * (Math.atan(Math.exp(0.8 * p.y / this.a)) - Math.PI / 4);
        p.x = lon;
        p.y = lat;
        return p;
    }
    exports.names = ['Miller_Cylindrical', 'mill'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/projections/sinu.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    const adjust_lat_1 = tslib_1.__importDefault(require(221) /* ../common/adjust_lat */);
    const pj_enfn_1 = tslib_1.__importDefault(require(192) /* ../common/pj_enfn */);
    var MAX_ITER = 20;
    const pj_mlfn_1 = tslib_1.__importDefault(require(193) /* ../common/pj_mlfn */);
    const pj_inv_mlfn_1 = tslib_1.__importDefault(require(194) /* ../common/pj_inv_mlfn */);
    const values_1 = require(156) /* ../constants/values */;
    const asinz_1 = tslib_1.__importDefault(require(228) /* ../common/asinz */);
    /**
     * @typedef {Object} LocalThis
     * @property {Array<number>} en
     * @property {number} n
     * @property {number} m
     * @property {number} C_y
     * @property {number} C_x
     * @property {number} es
     */
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function init() {
        /* Place parameters in static storage for common use
          ------------------------------------------------- */
        this.long0 = this.long0 || 0;
        if (!this.sphere) {
            this.en = (0, pj_enfn_1.default)(this.es);
        }
        else {
            this.n = 1;
            this.m = 0;
            this.es = 0;
            this.C_y = Math.sqrt((this.m + 1) / this.n);
            this.C_x = this.C_y / (this.m + 1);
        }
    }
    /* Sinusoidal forward equations--mapping lat,long to x,y
      ----------------------------------------------------- */
    function forward(p) {
        var x, y;
        var lon = p.x;
        var lat = p.y;
        /* Forward equations
          ----------------- */
        lon = (0, adjust_lon_1.default)(lon - this.long0, this.over);
        if (this.sphere) {
            if (!this.m) {
                lat = this.n !== 1 ? Math.asin(this.n * Math.sin(lat)) : lat;
            }
            else {
                var k = this.n * Math.sin(lat);
                for (var i = MAX_ITER; i; --i) {
                    var V = (this.m * lat + Math.sin(lat) - k) / (this.m + Math.cos(lat));
                    lat -= V;
                    if (Math.abs(V) < values_1.EPSLN) {
                        break;
                    }
                }
            }
            x = this.a * this.C_x * lon * (this.m + Math.cos(lat));
            y = this.a * this.C_y * lat;
        }
        else {
            var s = Math.sin(lat);
            var c = Math.cos(lat);
            y = this.a * (0, pj_mlfn_1.default)(lat, s, c, this.en);
            x = this.a * lon * c / Math.sqrt(1 - this.es * s * s);
        }
        p.x = x;
        p.y = y;
        return p;
    }
    function inverse(p) {
        var lat, temp, lon, s;
        p.x -= this.x0;
        lon = p.x / this.a;
        p.y -= this.y0;
        lat = p.y / this.a;
        if (this.sphere) {
            lat /= this.C_y;
            lon = lon / (this.C_x * (this.m + Math.cos(lat)));
            if (this.m) {
                lat = (0, asinz_1.default)((this.m * lat + Math.sin(lat)) / this.n);
            }
            else if (this.n !== 1) {
                lat = (0, asinz_1.default)(Math.sin(lat) / this.n);
            }
            lon = (0, adjust_lon_1.default)(lon + this.long0, this.over);
            lat = (0, adjust_lat_1.default)(lat);
        }
        else {
            lat = (0, pj_inv_mlfn_1.default)(p.y / this.a, this.es, this.en);
            s = Math.abs(lat);
            if (s < values_1.HALF_PI) {
                s = Math.sin(lat);
                temp = this.long0 + p.x * Math.sqrt(1 - this.es * s * s) / (this.a * Math.cos(lat));
                // temp = this.long0 + p.x / (this.a * Math.cos(lat));
                lon = (0, adjust_lon_1.default)(temp, this.over);
            }
            else if ((s - values_1.EPSLN) < values_1.HALF_PI) {
                lon = this.long0;
            }
        }
        p.x = lon;
        p.y = lat;
        return p;
    }
    exports.names = ['Sinusoidal', 'sinu'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/projections/eck6.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    const sinu_1 = require(236) /* ./sinu */;
    /**
     * Eckert VI projection — spherical sinusoidal variant with m=1, n=1+π/2.
     * Always forces spherical computation regardless of the ellipsoid.
     *
     * @typedef {Object} LocalThis
     * @property {number} m
     * @property {number} n
     * @property {number} C_y
     * @property {number} C_x
     * @property {number} es
     */
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function init() {
        /* Force spherical handling */
        this.sphere = true;
        this.b = this.a;
        this.m = 1.0;
        this.n = 2.570796326794896619231321691; /* 1 + π/2 */
        this.es = 0;
        this.C_y = Math.sqrt((this.m + 1.0) / this.n);
        this.C_x = this.C_y / (this.m + 1.0);
    }
    exports.forward = sinu_1.forward;
    exports.inverse = sinu_1.inverse;
    exports.names = ['Eckert_VI', 'eck6'];
    exports.default = {
        init: init,
        forward: exports.forward,
        inverse: exports.inverse,
        names: exports.names
    };
},
/* proj4/lib/projections/moll.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    const values_1 = require(156) /* ../constants/values */;
    /** @this {import('../defs.js').ProjectionDefinition} */
    function init() {
        this.x0 = this.x0 !== undefined ? this.x0 : 0;
        this.y0 = this.y0 !== undefined ? this.y0 : 0;
        this.long0 = this.long0 !== undefined ? this.long0 : 0;
    }
    /* Mollweide forward equations--mapping lat,long to x,y
        ---------------------------------------------------- */
    function forward(p) {
        /* Forward equations
            ----------------- */
        var lon = p.x;
        var lat = p.y;
        var delta_lon = (0, adjust_lon_1.default)(lon - this.long0, this.over);
        var theta = lat;
        var con = Math.PI * Math.sin(lat);
        /* Iterate using the Newton-Raphson method to find theta
            ----------------------------------------------------- */
        while (true) {
            var delta_theta = -(theta + Math.sin(theta) - con) / (1 + Math.cos(theta));
            theta += delta_theta;
            if (Math.abs(delta_theta) < values_1.EPSLN) {
                break;
            }
        }
        theta /= 2;
        /* If the latitude is 90 deg, force the x coordinate to be "0 + false easting"
             this is done here because of precision problems with "cos(theta)"
             -------------------------------------------------------------------------- */
        if (Math.PI / 2 - Math.abs(lat) < values_1.EPSLN) {
            delta_lon = 0;
        }
        var x = 0.900316316158 * this.a * delta_lon * Math.cos(theta) + this.x0;
        var y = 1.4142135623731 * this.a * Math.sin(theta) + this.y0;
        p.x = x;
        p.y = y;
        return p;
    }
    function inverse(p) {
        var theta;
        var arg;
        /* Inverse equations
            ----------------- */
        p.x -= this.x0;
        p.y -= this.y0;
        arg = p.y / (1.4142135623731 * this.a);
        /* Because of division by zero problems, 'arg' can not be 1.  Therefore
             a number very close to one is used instead.
             ------------------------------------------------------------------- */
        if (Math.abs(arg) > 0.999999999999) {
            arg = 0.999999999999;
        }
        theta = Math.asin(arg);
        var lon = (0, adjust_lon_1.default)(this.long0 + (p.x / (0.900316316158 * this.a * Math.cos(theta))), this.over);
        if (lon < (-Math.PI)) {
            lon = -Math.PI;
        }
        if (lon > Math.PI) {
            lon = Math.PI;
        }
        arg = (2 * theta + Math.sin(2 * theta)) / Math.PI;
        if (Math.abs(arg) > 1) {
            arg = 1;
        }
        var lat = Math.asin(arg);
        p.x = lon;
        p.y = lat;
        return p;
    }
    exports.names = ['Mollweide', 'moll'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/projections/eqdc.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const e0fn_1 = tslib_1.__importDefault(require(216) /* ../common/e0fn */);
    const e1fn_1 = tslib_1.__importDefault(require(217) /* ../common/e1fn */);
    const e2fn_1 = tslib_1.__importDefault(require(218) /* ../common/e2fn */);
    const e3fn_1 = tslib_1.__importDefault(require(219) /* ../common/e3fn */);
    const msfnz_1 = tslib_1.__importDefault(require(171) /* ../common/msfnz */);
    const mlfn_1 = tslib_1.__importDefault(require(215) /* ../common/mlfn */);
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    const adjust_lat_1 = tslib_1.__importDefault(require(221) /* ../common/adjust_lat */);
    const imlfn_1 = tslib_1.__importDefault(require(222) /* ../common/imlfn */);
    const values_1 = require(156) /* ../constants/values */;
    /**
     * @typedef {Object} LocalThis
     * @property {number} temp
     * @property {number} es
     * @property {number} e
     * @property {number} e0
     * @property {number} e1
     * @property {number} e2
     * @property {number} e3
     * @property {number} sin_phi
     * @property {number} cos_phi
     * @property {number} ms1
     * @property {number} ml1
     * @property {number} ms2
     * @property {number} ml2
     * @property {number} ns
     * @property {number} g
     * @property {number} ml0
     * @property {number} rh
     */
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function init() {
        /* Place parameters in static storage for common use
            ------------------------------------------------- */
        // Standard Parallels cannot be equal and on opposite sides of the equator
        if (Math.abs(this.lat1 + this.lat2) < values_1.EPSLN) {
            return;
        }
        this.lat2 = this.lat2 || this.lat1;
        this.temp = this.b / this.a;
        this.es = 1 - Math.pow(this.temp, 2);
        this.e = Math.sqrt(this.es);
        this.e0 = (0, e0fn_1.default)(this.es);
        this.e1 = (0, e1fn_1.default)(this.es);
        this.e2 = (0, e2fn_1.default)(this.es);
        this.e3 = (0, e3fn_1.default)(this.es);
        this.sin_phi = Math.sin(this.lat1);
        this.cos_phi = Math.cos(this.lat1);
        this.ms1 = (0, msfnz_1.default)(this.e, this.sin_phi, this.cos_phi);
        this.ml1 = (0, mlfn_1.default)(this.e0, this.e1, this.e2, this.e3, this.lat1);
        if (Math.abs(this.lat1 - this.lat2) < values_1.EPSLN) {
            this.ns = this.sin_phi;
        }
        else {
            this.sin_phi = Math.sin(this.lat2);
            this.cos_phi = Math.cos(this.lat2);
            this.ms2 = (0, msfnz_1.default)(this.e, this.sin_phi, this.cos_phi);
            this.ml2 = (0, mlfn_1.default)(this.e0, this.e1, this.e2, this.e3, this.lat2);
            this.ns = (this.ms1 - this.ms2) / (this.ml2 - this.ml1);
        }
        this.g = this.ml1 + this.ms1 / this.ns;
        this.ml0 = (0, mlfn_1.default)(this.e0, this.e1, this.e2, this.e3, this.lat0);
        this.rh = this.a * (this.g - this.ml0);
    }
    /* Equidistant Conic forward equations--mapping lat,long to x,y
      ----------------------------------------------------------- */
    function forward(p) {
        var lon = p.x;
        var lat = p.y;
        var rh1;
        /* Forward equations
            ----------------- */
        if (this.sphere) {
            rh1 = this.a * (this.g - lat);
        }
        else {
            var ml = (0, mlfn_1.default)(this.e0, this.e1, this.e2, this.e3, lat);
            rh1 = this.a * (this.g - ml);
        }
        var theta = this.ns * (0, adjust_lon_1.default)(lon - this.long0, this.over);
        var x = this.x0 + rh1 * Math.sin(theta);
        var y = this.y0 + this.rh - rh1 * Math.cos(theta);
        p.x = x;
        p.y = y;
        return p;
    }
    /* Inverse equations
      ----------------- */
    function inverse(p) {
        p.x -= this.x0;
        p.y = this.rh - p.y + this.y0;
        var con, rh1, lat, lon;
        if (this.ns >= 0) {
            rh1 = Math.sqrt(p.x * p.x + p.y * p.y);
            con = 1;
        }
        else {
            rh1 = -Math.sqrt(p.x * p.x + p.y * p.y);
            con = -1;
        }
        var theta = 0;
        if (rh1 !== 0) {
            theta = Math.atan2(con * p.x, con * p.y);
        }
        if (this.sphere) {
            lon = (0, adjust_lon_1.default)(this.long0 + theta / this.ns, this.over);
            lat = (0, adjust_lat_1.default)(this.g - rh1 / this.a);
            p.x = lon;
            p.y = lat;
            return p;
        }
        else {
            var ml = this.g - rh1 / this.a;
            lat = (0, imlfn_1.default)(ml, this.e0, this.e1, this.e2, this.e3);
            lon = (0, adjust_lon_1.default)(this.long0 + theta / this.ns, this.over);
            p.x = lon;
            p.y = lat;
            return p;
        }
    }
    exports.names = ['Equidistant_Conic', 'eqdc'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/projections/vandg.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    const values_1 = require(156) /* ../constants/values */;
    const asinz_1 = tslib_1.__importDefault(require(228) /* ../common/asinz */);
    /**
     * @typedef {Object} LocalThis
     * @property {number} R - Radius of the Earth
     */
    /**
     * Initialize the Van Der Grinten projection
     * @this {import('../defs.js').ProjectionDefinition & LocalThis}
     */
    function init() {
        // this.R = 6370997; //Radius of earth
        this.R = this.a;
    }
    function forward(p) {
        var lon = p.x;
        var lat = p.y;
        /* Forward equations
          ----------------- */
        var dlon = (0, adjust_lon_1.default)(lon - this.long0, this.over);
        var x, y;
        if (Math.abs(lat) <= values_1.EPSLN) {
            x = this.x0 + this.R * dlon;
            y = this.y0;
        }
        var theta = (0, asinz_1.default)(2 * Math.abs(lat / Math.PI));
        if ((Math.abs(dlon) <= values_1.EPSLN) || (Math.abs(Math.abs(lat) - values_1.HALF_PI) <= values_1.EPSLN)) {
            x = this.x0;
            if (lat >= 0) {
                y = this.y0 + Math.PI * this.R * Math.tan(0.5 * theta);
            }
            else {
                y = this.y0 + Math.PI * this.R * -Math.tan(0.5 * theta);
            }
            //  return(OK);
        }
        var al = 0.5 * Math.abs((Math.PI / dlon) - (dlon / Math.PI));
        var asq = al * al;
        var sinth = Math.sin(theta);
        var costh = Math.cos(theta);
        var g = costh / (sinth + costh - 1);
        var gsq = g * g;
        var m = g * (2 / sinth - 1);
        var msq = m * m;
        var con = Math.PI * this.R * (al * (g - msq) + Math.sqrt(asq * (g - msq) * (g - msq) - (msq + asq) * (gsq - msq))) / (msq + asq);
        if (dlon < 0) {
            con = -con;
        }
        x = this.x0 + con;
        // con = Math.abs(con / (Math.PI * this.R));
        var q = asq + g;
        con = Math.PI * this.R * (m * q - al * Math.sqrt((msq + asq) * (asq + 1) - q * q)) / (msq + asq);
        if (lat >= 0) {
            // y = this.y0 + Math.PI * this.R * Math.sqrt(1 - con * con - 2 * al * con);
            y = this.y0 + con;
        }
        else {
            // y = this.y0 - Math.PI * this.R * Math.sqrt(1 - con * con - 2 * al * con);
            y = this.y0 - con;
        }
        p.x = x;
        p.y = y;
        return p;
    }
    /* Van Der Grinten inverse equations--mapping x,y to lat/long
      --------------------------------------------------------- */
    function inverse(p) {
        var lon, lat;
        var xx, yy, xys, c1, c2, c3;
        var a1;
        var m1;
        var con;
        var th1;
        var d;
        /* inverse equations
          ----------------- */
        p.x -= this.x0;
        p.y -= this.y0;
        con = Math.PI * this.R;
        xx = p.x / con;
        yy = p.y / con;
        xys = xx * xx + yy * yy;
        c1 = -Math.abs(yy) * (1 + xys);
        c2 = c1 - 2 * yy * yy + xx * xx;
        c3 = -2 * c1 + 1 + 2 * yy * yy + xys * xys;
        d = yy * yy / c3 + (2 * c2 * c2 * c2 / c3 / c3 / c3 - 9 * c1 * c2 / c3 / c3) / 27;
        a1 = (c1 - c2 * c2 / 3 / c3) / c3;
        m1 = 2 * Math.sqrt(-a1 / 3);
        con = ((3 * d) / a1) / m1;
        if (Math.abs(con) > 1) {
            if (con >= 0) {
                con = 1;
            }
            else {
                con = -1;
            }
        }
        th1 = Math.acos(con) / 3;
        if (p.y >= 0) {
            lat = (-m1 * Math.cos(th1 + Math.PI / 3) - c2 / 3 / c3) * Math.PI;
        }
        else {
            lat = -(-m1 * Math.cos(th1 + Math.PI / 3) - c2 / 3 / c3) * Math.PI;
        }
        if (Math.abs(xx) < values_1.EPSLN) {
            lon = this.long0;
        }
        else {
            lon = (0, adjust_lon_1.default)(this.long0 + Math.PI * (xys - 1 + Math.sqrt(1 + 2 * (xx * xx - yy * yy) + xys * xys)) / 2 / xx, this.over);
        }
        p.x = lon;
        p.y = lat;
        return p;
    }
    exports.names = ['Van_der_Grinten_I', 'VanDerGrinten', 'Van_der_Grinten', 'vandg'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/projections/aeqd.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    const values_1 = require(156) /* ../constants/values */;
    const mlfn_1 = tslib_1.__importDefault(require(215) /* ../common/mlfn */);
    const e0fn_1 = tslib_1.__importDefault(require(216) /* ../common/e0fn */);
    const e1fn_1 = tslib_1.__importDefault(require(217) /* ../common/e1fn */);
    const e2fn_1 = tslib_1.__importDefault(require(218) /* ../common/e2fn */);
    const e3fn_1 = tslib_1.__importDefault(require(219) /* ../common/e3fn */);
    const asinz_1 = tslib_1.__importDefault(require(228) /* ../common/asinz */);
    const imlfn_1 = tslib_1.__importDefault(require(222) /* ../common/imlfn */);
    const vincenty_1 = require(242) /* ../common/vincenty */;
    /**
     * @typedef {Object} LocalThis
     * @property {number} es
     * @property {number} sin_p12
     * @property {number} cos_p12
     * @property {number} a
     * @property {number} f
     */
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function init() {
        this.sin_p12 = Math.sin(this.lat0);
        this.cos_p12 = Math.cos(this.lat0);
        // flattening for ellipsoid
        this.f = this.es / (1 + Math.sqrt(1 - this.es));
    }
    function forward(p) {
        var lon = p.x;
        var lat = p.y;
        var sinphi = Math.sin(p.y);
        var cosphi = Math.cos(p.y);
        var dlon = (0, adjust_lon_1.default)(lon - this.long0, this.over);
        var e0, e1, e2, e3, Mlp, Ml, c, kp, cos_c, vars, azi1;
        if (this.sphere) {
            if (Math.abs(this.sin_p12 - 1) <= values_1.EPSLN) {
                // North Pole case
                p.x = this.x0 + this.a * (values_1.HALF_PI - lat) * Math.sin(dlon);
                p.y = this.y0 - this.a * (values_1.HALF_PI - lat) * Math.cos(dlon);
                return p;
            }
            else if (Math.abs(this.sin_p12 + 1) <= values_1.EPSLN) {
                // South Pole case
                p.x = this.x0 + this.a * (values_1.HALF_PI + lat) * Math.sin(dlon);
                p.y = this.y0 + this.a * (values_1.HALF_PI + lat) * Math.cos(dlon);
                return p;
            }
            else {
                // default case
                cos_c = this.sin_p12 * sinphi + this.cos_p12 * cosphi * Math.cos(dlon);
                c = Math.acos(cos_c);
                kp = c ? c / Math.sin(c) : 1;
                p.x = this.x0 + this.a * kp * cosphi * Math.sin(dlon);
                p.y = this.y0 + this.a * kp * (this.cos_p12 * sinphi - this.sin_p12 * cosphi * Math.cos(dlon));
                return p;
            }
        }
        else {
            e0 = (0, e0fn_1.default)(this.es);
            e1 = (0, e1fn_1.default)(this.es);
            e2 = (0, e2fn_1.default)(this.es);
            e3 = (0, e3fn_1.default)(this.es);
            if (Math.abs(this.sin_p12 - 1) <= values_1.EPSLN) {
                // North Pole case
                Mlp = this.a * (0, mlfn_1.default)(e0, e1, e2, e3, values_1.HALF_PI);
                Ml = this.a * (0, mlfn_1.default)(e0, e1, e2, e3, lat);
                p.x = this.x0 + (Mlp - Ml) * Math.sin(dlon);
                p.y = this.y0 - (Mlp - Ml) * Math.cos(dlon);
                return p;
            }
            else if (Math.abs(this.sin_p12 + 1) <= values_1.EPSLN) {
                // South Pole case
                Mlp = this.a * (0, mlfn_1.default)(e0, e1, e2, e3, values_1.HALF_PI);
                Ml = this.a * (0, mlfn_1.default)(e0, e1, e2, e3, lat);
                p.x = this.x0 + (Mlp + Ml) * Math.sin(dlon);
                p.y = this.y0 + (Mlp + Ml) * Math.cos(dlon);
                return p;
            }
            else {
                // Default case
                if (Math.abs(lon) < values_1.EPSLN && Math.abs(lat - this.lat0) < values_1.EPSLN) {
                    p.x = p.y = 0;
                    return p;
                }
                vars = (0, vincenty_1.vincentyInverse)(this.lat0, this.long0, lat, lon, this.a, this.f);
                azi1 = vars.azi1;
                p.x = vars.s12 * Math.sin(azi1);
                p.y = vars.s12 * Math.cos(azi1);
                return p;
            }
        }
    }
    function inverse(p) {
        p.x -= this.x0;
        p.y -= this.y0;
        var rh, z, sinz, cosz, lon, lat, con, e0, e1, e2, e3, Mlp, M, azi1, s12, vars;
        if (this.sphere) {
            rh = Math.sqrt(p.x * p.x + p.y * p.y);
            if (rh > (2 * values_1.HALF_PI * this.a)) {
                return;
            }
            z = rh / this.a;
            sinz = Math.sin(z);
            cosz = Math.cos(z);
            lon = this.long0;
            if (Math.abs(rh) <= values_1.EPSLN) {
                lat = this.lat0;
            }
            else {
                lat = (0, asinz_1.default)(cosz * this.sin_p12 + (p.y * sinz * this.cos_p12) / rh);
                con = Math.abs(this.lat0) - values_1.HALF_PI;
                if (Math.abs(con) <= values_1.EPSLN) {
                    if (this.lat0 >= 0) {
                        lon = (0, adjust_lon_1.default)(this.long0 + Math.atan2(p.x, -p.y), this.over);
                    }
                    else {
                        lon = (0, adjust_lon_1.default)(this.long0 - Math.atan2(-p.x, p.y), this.over);
                    }
                }
                else {
                    lon = (0, adjust_lon_1.default)(this.long0 + Math.atan2(p.x * sinz, rh * this.cos_p12 * cosz - p.y * this.sin_p12 * sinz), this.over);
                }
            }
            p.x = lon;
            p.y = lat;
            return p;
        }
        else {
            e0 = (0, e0fn_1.default)(this.es);
            e1 = (0, e1fn_1.default)(this.es);
            e2 = (0, e2fn_1.default)(this.es);
            e3 = (0, e3fn_1.default)(this.es);
            if (Math.abs(this.sin_p12 - 1) <= values_1.EPSLN) {
                // North pole case
                Mlp = this.a * (0, mlfn_1.default)(e0, e1, e2, e3, values_1.HALF_PI);
                rh = Math.sqrt(p.x * p.x + p.y * p.y);
                M = Mlp - rh;
                lat = (0, imlfn_1.default)(M / this.a, e0, e1, e2, e3);
                lon = (0, adjust_lon_1.default)(this.long0 + Math.atan2(p.x, -1 * p.y), this.over);
                p.x = lon;
                p.y = lat;
                return p;
            }
            else if (Math.abs(this.sin_p12 + 1) <= values_1.EPSLN) {
                // South pole case
                Mlp = this.a * (0, mlfn_1.default)(e0, e1, e2, e3, values_1.HALF_PI);
                rh = Math.sqrt(p.x * p.x + p.y * p.y);
                M = rh - Mlp;
                lat = (0, imlfn_1.default)(M / this.a, e0, e1, e2, e3);
                lon = (0, adjust_lon_1.default)(this.long0 + Math.atan2(p.x, p.y), this.over);
                p.x = lon;
                p.y = lat;
                return p;
            }
            else {
                // default case
                azi1 = Math.atan2(p.x, p.y);
                s12 = Math.sqrt(p.x * p.x + p.y * p.y);
                vars = (0, vincenty_1.vincentyDirect)(this.lat0, this.long0, azi1, s12, this.a, this.f);
                p.x = vars.lon2;
                p.y = vars.lat2;
                return p;
            }
        }
    }
    exports.names = ['Azimuthal_Equidistant', 'aeqd'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/common/vincenty.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.vincentyInverse = vincentyInverse;
    exports.vincentyDirect = vincentyDirect;
    /**
     * Calculates the inverse geodesic problem using Vincenty's formulae.
     * Computes the forward azimuth and ellipsoidal distance between two points
     * specified by latitude and longitude on the surface of an ellipsoid.
     *
     * @param {number} lat1 Latitude of the first point in radians.
     * @param {number} lon1 Longitude of the first point in radians.
     * @param {number} lat2 Latitude of the second point in radians.
     * @param {number} lon2 Longitude of the second point in radians.
     * @param {number} a Semi-major axis of the ellipsoid (meters).
     * @param {number} f Flattening of the ellipsoid.
     * @returns {{ azi1: number, s12: number }} An object containing:
     *   - azi1: Forward azimuth from the first point to the second point (radians).
     *   - s12: Ellipsoidal distance between the two points (meters).
     */
    function vincentyInverse(lat1, lon1, lat2, lon2, a, f) {
        const L = lon2 - lon1;
        const U1 = Math.atan((1 - f) * Math.tan(lat1));
        const U2 = Math.atan((1 - f) * Math.tan(lat2));
        const sinU1 = Math.sin(U1), cosU1 = Math.cos(U1);
        const sinU2 = Math.sin(U2), cosU2 = Math.cos(U2);
        let lambda = L, lambdaP, iterLimit = 100;
        let sinLambda, cosLambda, sinSigma, cosSigma, sigma, sinAlpha, cos2Alpha, cos2SigmaM, C;
        let uSq, A, B, deltaSigma, s;
        do {
            sinLambda = Math.sin(lambda);
            cosLambda = Math.cos(lambda);
            sinSigma = Math.sqrt((cosU2 * sinLambda) * (cosU2 * sinLambda)
                + (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda)
                    * (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda));
            if (sinSigma === 0) {
                return { azi1: 0, s12: 0 }; // coincident points
            }
            cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda;
            sigma = Math.atan2(sinSigma, cosSigma);
            sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;
            cos2Alpha = 1 - sinAlpha * sinAlpha;
            cos2SigmaM = (cos2Alpha !== 0) ? (cosSigma - 2 * sinU1 * sinU2 / cos2Alpha) : 0;
            C = f / 16 * cos2Alpha * (4 + f * (4 - 3 * cos2Alpha));
            lambdaP = lambda;
            lambda = L + (1 - C) * f * sinAlpha
                * (sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));
        } while (Math.abs(lambda - lambdaP) > 1e-12 && --iterLimit > 0);
        if (iterLimit === 0) {
            return { azi1: NaN, s12: NaN }; // formula failed to converge
        }
        uSq = cos2Alpha * (a * a - (a * (1 - f)) * (a * (1 - f))) / ((a * (1 - f)) * (a * (1 - f)));
        A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
        B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));
        deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)
            - B / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM * cos2SigmaM)));
        s = (a * (1 - f)) * A * (sigma - deltaSigma);
        // Forward azimuth
        const azi1 = Math.atan2(cosU2 * sinLambda, cosU1 * sinU2 - sinU1 * cosU2 * cosLambda);
        return { azi1, s12: s };
    }
    /**
     * Solves the direct geodetic problem using Vincenty's formulae.
     * Given a starting point, initial azimuth, and distance, computes the destination point on the ellipsoid.
     *
     * @param {number} lat1 Latitude of the starting point in radians.
     * @param {number} lon1 Longitude of the starting point in radians.
     * @param {number} azi1 Initial azimuth (forward azimuth) in radians.
     * @param {number} s12 Distance to travel from the starting point in meters.
     * @param {number} a Semi-major axis of the ellipsoid in meters.
     * @param {number} f Flattening of the ellipsoid.
     * @returns {{lat2: number, lon2: number}} The latitude and longitude (in radians) of the destination point.
     */
    function vincentyDirect(lat1, lon1, azi1, s12, a, f) {
        const U1 = Math.atan((1 - f) * Math.tan(lat1));
        const sinU1 = Math.sin(U1), cosU1 = Math.cos(U1);
        const sinAlpha1 = Math.sin(azi1), cosAlpha1 = Math.cos(azi1);
        const sigma1 = Math.atan2(sinU1, cosU1 * cosAlpha1);
        const sinAlpha = cosU1 * sinAlpha1;
        const cos2Alpha = 1 - sinAlpha * sinAlpha;
        const uSq = cos2Alpha * (a * a - (a * (1 - f)) * (a * (1 - f))) / ((a * (1 - f)) * (a * (1 - f)));
        const A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
        const B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));
        let sigma = s12 / ((a * (1 - f)) * A), sigmaP, iterLimit = 100;
        let cos2SigmaM, sinSigma, cosSigma, deltaSigma;
        do {
            cos2SigmaM = Math.cos(2 * sigma1 + sigma);
            sinSigma = Math.sin(sigma);
            cosSigma = Math.cos(sigma);
            deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)
                - B / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM * cos2SigmaM)));
            sigmaP = sigma;
            sigma = s12 / ((a * (1 - f)) * A) + deltaSigma;
        } while (Math.abs(sigma - sigmaP) > 1e-12 && --iterLimit > 0);
        if (iterLimit === 0) {
            return { lat2: NaN, lon2: NaN };
        }
        const tmp = sinU1 * sinSigma - cosU1 * cosSigma * cosAlpha1;
        const lat2 = Math.atan2(sinU1 * cosSigma + cosU1 * sinSigma * cosAlpha1, (1 - f) * Math.sqrt(sinAlpha * sinAlpha + tmp * tmp));
        const lambda = Math.atan2(sinSigma * sinAlpha1, cosU1 * cosSigma - sinU1 * sinSigma * cosAlpha1);
        const C = f / 16 * cos2Alpha * (4 + f * (4 - 3 * cos2Alpha));
        const L = lambda - (1 - C) * f * sinAlpha
            * (sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));
        const lon2 = lon1 + L;
        return { lat2, lon2 };
    }
},
/* proj4/lib/projections/ortho.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    const asinz_1 = tslib_1.__importDefault(require(228) /* ../common/asinz */);
    const values_1 = require(156) /* ../constants/values */;
    /**
     * @typedef {Object} LocalThis
     * @property {number} sin_p14
     * @property {number} cos_p14
     */
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function init() {
        // double temp;      /* temporary variable    */
        /* Place parameters in static storage for common use
            ------------------------------------------------- */
        this.sin_p14 = Math.sin(this.lat0 || 0);
        this.cos_p14 = Math.cos(this.lat0 || 0);
    }
    /* Orthographic forward equations--mapping lat,long to x,y
        --------------------------------------------------- */
    function forward(p) {
        var sinphi, cosphi; /* sin and cos value        */
        var dlon; /* delta longitude value      */
        var coslon; /* cos of longitude        */
        var ksp; /* scale factor          */
        var g, x, y;
        var lon = p.x;
        var lat = p.y;
        /* Forward equations
            ----------------- */
        dlon = (0, adjust_lon_1.default)(lon - (this.long0 || 0), this.over);
        sinphi = Math.sin(lat);
        cosphi = Math.cos(lat);
        coslon = Math.cos(dlon);
        g = this.sin_p14 * sinphi + this.cos_p14 * cosphi * coslon;
        ksp = 1;
        if ((g > 0) || (Math.abs(g) <= values_1.EPSLN)) {
            x = this.a * ksp * cosphi * Math.sin(dlon);
            y = (this.y0 || 0) + this.a * ksp * (this.cos_p14 * sinphi - this.sin_p14 * cosphi * coslon);
        }
        p.x = x;
        p.y = y;
        return p;
    }
    function inverse(p) {
        var rh; /* height above ellipsoid      */
        var z; /* angle          */
        var sinz, cosz; /* sin of z and cos of z      */
        var con;
        var lon, lat;
        var long0, lat0;
        /* Inverse equations
            ----------------- */
        p.x -= this.x0 || 0;
        p.y -= this.y0 || 0;
        rh = Math.sqrt(p.x * p.x + p.y * p.y);
        z = (0, asinz_1.default)(rh / this.a);
        sinz = Math.sin(z);
        cosz = Math.cos(z);
        long0 = this.long0 || 0;
        lat0 = this.lat0 || 0;
        lon = long0;
        if (Math.abs(rh) <= values_1.EPSLN) {
            lat = lat0;
            p.x = lon;
            p.y = lat;
            return p;
        }
        lat = (0, asinz_1.default)(cosz * this.sin_p14 + (p.y * sinz * this.cos_p14) / rh);
        con = Math.abs(lat0) - values_1.HALF_PI;
        if (Math.abs(con) <= values_1.EPSLN) {
            if (lat0 >= 0) {
                lon = (0, adjust_lon_1.default)(long0 + Math.atan2(p.x, -p.y), this.over);
            }
            else {
                lon = (0, adjust_lon_1.default)(long0 - Math.atan2(-p.x, p.y), this.over);
            }
            p.x = lon;
            p.y = lat;
            return p;
        }
        lon = (0, adjust_lon_1.default)(long0 + Math.atan2((p.x * sinz), rh * this.cos_p14 * cosz - p.y * this.sin_p14 * sinz), this.over);
        p.x = lon;
        p.y = lat;
        return p;
    }
    exports.names = ['ortho'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/projections/qsc.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const values_1 = require(156) /* ../constants/values */;
    /**
     * @typedef {Object} LocalThis
     * @property {number} face
     * @property {number} x0
     * @property {number} y0
     * @property {number} es
     * @property {number} one_minus_f
     * @property {number} one_minus_f_squared
     */
    /* constants */
    var FACE_ENUM = {
        FRONT: 1,
        RIGHT: 2,
        BACK: 3,
        LEFT: 4,
        TOP: 5,
        BOTTOM: 6
    };
    var AREA_ENUM = {
        AREA_0: 1,
        AREA_1: 2,
        AREA_2: 3,
        AREA_3: 4
    };
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function init() {
        this.x0 = this.x0 || 0;
        this.y0 = this.y0 || 0;
        this.lat0 = this.lat0 || 0;
        this.long0 = this.long0 || 0;
        this.lat_ts = this.lat_ts || 0;
        this.title = this.title || 'Quadrilateralized Spherical Cube';
        /* Determine the cube face from the center of projection. */
        if (this.lat0 >= values_1.HALF_PI - values_1.FORTPI / 2.0) {
            this.face = FACE_ENUM.TOP;
        }
        else if (this.lat0 <= -(values_1.HALF_PI - values_1.FORTPI / 2.0)) {
            this.face = FACE_ENUM.BOTTOM;
        }
        else if (Math.abs(this.long0) <= values_1.FORTPI) {
            this.face = FACE_ENUM.FRONT;
        }
        else if (Math.abs(this.long0) <= values_1.HALF_PI + values_1.FORTPI) {
            this.face = this.long0 > 0.0 ? FACE_ENUM.RIGHT : FACE_ENUM.LEFT;
        }
        else {
            this.face = FACE_ENUM.BACK;
        }
        /* Fill in useful values for the ellipsoid <-> sphere shift
         * described in [LK12]. */
        if (this.es !== 0) {
            this.one_minus_f = 1 - (this.a - this.b) / this.a;
            this.one_minus_f_squared = this.one_minus_f * this.one_minus_f;
        }
    }
    // QSC forward equations--mapping lat,long to x,y
    // -----------------------------------------------------------------
    function forward(p) {
        var xy = { x: 0, y: 0 };
        var lat, lon;
        var theta, phi;
        var t, mu;
        /* nu; */
        var area = { value: 0 };
        // move lon according to projection's lon
        p.x -= this.long0;
        /* Convert the geodetic latitude to a geocentric latitude.
         * This corresponds to the shift from the ellipsoid to the sphere
         * described in [LK12]. */
        if (this.es !== 0) { // if (P->es != 0) {
            lat = Math.atan(this.one_minus_f_squared * Math.tan(p.y));
        }
        else {
            lat = p.y;
        }
        /* Convert the input lat, lon into theta, phi as used by QSC.
         * This depends on the cube face and the area on it.
         * For the top and bottom face, we can compute theta and phi
         * directly from phi, lam. For the other faces, we must use
         * unit sphere cartesian coordinates as an intermediate step. */
        lon = p.x; // lon = lp.lam;
        if (this.face === FACE_ENUM.TOP) {
            phi = values_1.HALF_PI - lat;
            if (lon >= values_1.FORTPI && lon <= values_1.HALF_PI + values_1.FORTPI) {
                area.value = AREA_ENUM.AREA_0;
                theta = lon - values_1.HALF_PI;
            }
            else if (lon > values_1.HALF_PI + values_1.FORTPI || lon <= -(values_1.HALF_PI + values_1.FORTPI)) {
                area.value = AREA_ENUM.AREA_1;
                theta = (lon > 0.0 ? lon - values_1.SPI : lon + values_1.SPI);
            }
            else if (lon > -(values_1.HALF_PI + values_1.FORTPI) && lon <= -values_1.FORTPI) {
                area.value = AREA_ENUM.AREA_2;
                theta = lon + values_1.HALF_PI;
            }
            else {
                area.value = AREA_ENUM.AREA_3;
                theta = lon;
            }
        }
        else if (this.face === FACE_ENUM.BOTTOM) {
            phi = values_1.HALF_PI + lat;
            if (lon >= values_1.FORTPI && lon <= values_1.HALF_PI + values_1.FORTPI) {
                area.value = AREA_ENUM.AREA_0;
                theta = -lon + values_1.HALF_PI;
            }
            else if (lon < values_1.FORTPI && lon >= -values_1.FORTPI) {
                area.value = AREA_ENUM.AREA_1;
                theta = -lon;
            }
            else if (lon < -values_1.FORTPI && lon >= -(values_1.HALF_PI + values_1.FORTPI)) {
                area.value = AREA_ENUM.AREA_2;
                theta = -lon - values_1.HALF_PI;
            }
            else {
                area.value = AREA_ENUM.AREA_3;
                theta = (lon > 0.0 ? -lon + values_1.SPI : -lon - values_1.SPI);
            }
        }
        else {
            var q, r, s;
            var sinlat, coslat;
            var sinlon, coslon;
            if (this.face === FACE_ENUM.RIGHT) {
                lon = qsc_shift_lon_origin(lon, +values_1.HALF_PI);
            }
            else if (this.face === FACE_ENUM.BACK) {
                lon = qsc_shift_lon_origin(lon, +values_1.SPI);
            }
            else if (this.face === FACE_ENUM.LEFT) {
                lon = qsc_shift_lon_origin(lon, -values_1.HALF_PI);
            }
            sinlat = Math.sin(lat);
            coslat = Math.cos(lat);
            sinlon = Math.sin(lon);
            coslon = Math.cos(lon);
            q = coslat * coslon;
            r = coslat * sinlon;
            s = sinlat;
            if (this.face === FACE_ENUM.FRONT) {
                phi = Math.acos(q);
                theta = qsc_fwd_equat_face_theta(phi, s, r, area);
            }
            else if (this.face === FACE_ENUM.RIGHT) {
                phi = Math.acos(r);
                theta = qsc_fwd_equat_face_theta(phi, s, -q, area);
            }
            else if (this.face === FACE_ENUM.BACK) {
                phi = Math.acos(-q);
                theta = qsc_fwd_equat_face_theta(phi, s, -r, area);
            }
            else if (this.face === FACE_ENUM.LEFT) {
                phi = Math.acos(-r);
                theta = qsc_fwd_equat_face_theta(phi, s, q, area);
            }
            else {
                /* Impossible */
                phi = theta = 0;
                area.value = AREA_ENUM.AREA_0;
            }
        }
        /* Compute mu and nu for the area of definition.
         * For mu, see Eq. (3-21) in [OL76], but note the typos:
         * compare with Eq. (3-14). For nu, see Eq. (3-38). */
        mu = Math.atan((12 / values_1.SPI) * (theta + Math.acos(Math.sin(theta) * Math.cos(values_1.FORTPI)) - values_1.HALF_PI));
        t = Math.sqrt((1 - Math.cos(phi)) / (Math.cos(mu) * Math.cos(mu)) / (1 - Math.cos(Math.atan(1 / Math.cos(theta)))));
        /* Apply the result to the real area. */
        if (area.value === AREA_ENUM.AREA_1) {
            mu += values_1.HALF_PI;
        }
        else if (area.value === AREA_ENUM.AREA_2) {
            mu += values_1.SPI;
        }
        else if (area.value === AREA_ENUM.AREA_3) {
            mu += 1.5 * values_1.SPI;
        }
        /* Now compute x, y from mu and nu */
        xy.x = t * Math.cos(mu);
        xy.y = t * Math.sin(mu);
        xy.x = xy.x * this.a + this.x0;
        xy.y = xy.y * this.a + this.y0;
        p.x = xy.x;
        p.y = xy.y;
        return p;
    }
    // QSC inverse equations--mapping x,y to lat/long
    // -----------------------------------------------------------------
    function inverse(p) {
        var lp = { lam: 0, phi: 0 };
        var mu, nu, cosmu, tannu;
        var tantheta, theta, cosphi, phi;
        var t;
        var area = { value: 0 };
        /* de-offset */
        p.x = (p.x - this.x0) / this.a;
        p.y = (p.y - this.y0) / this.a;
        /* Convert the input x, y to the mu and nu angles as used by QSC.
         * This depends on the area of the cube face. */
        nu = Math.atan(Math.sqrt(p.x * p.x + p.y * p.y));
        mu = Math.atan2(p.y, p.x);
        if (p.x >= 0.0 && p.x >= Math.abs(p.y)) {
            area.value = AREA_ENUM.AREA_0;
        }
        else if (p.y >= 0.0 && p.y >= Math.abs(p.x)) {
            area.value = AREA_ENUM.AREA_1;
            mu -= values_1.HALF_PI;
        }
        else if (p.x < 0.0 && -p.x >= Math.abs(p.y)) {
            area.value = AREA_ENUM.AREA_2;
            mu = (mu < 0.0 ? mu + values_1.SPI : mu - values_1.SPI);
        }
        else {
            area.value = AREA_ENUM.AREA_3;
            mu += values_1.HALF_PI;
        }
        /* Compute phi and theta for the area of definition.
         * The inverse projection is not described in the original paper, but some
         * good hints can be found here (as of 2011-12-14):
         * http://fits.gsfc.nasa.gov/fitsbits/saf.93/saf.9302
         * (search for "Message-Id: <9302181759.AA25477 at fits.cv.nrao.edu>") */
        t = (values_1.SPI / 12) * Math.tan(mu);
        tantheta = Math.sin(t) / (Math.cos(t) - (1 / Math.sqrt(2)));
        theta = Math.atan(tantheta);
        cosmu = Math.cos(mu);
        tannu = Math.tan(nu);
        cosphi = 1 - cosmu * cosmu * tannu * tannu * (1 - Math.cos(Math.atan(1 / Math.cos(theta))));
        if (cosphi < -1) {
            cosphi = -1;
        }
        else if (cosphi > +1) {
            cosphi = +1;
        }
        /* Apply the result to the real area on the cube face.
         * For the top and bottom face, we can compute phi and lam directly.
         * For the other faces, we must use unit sphere cartesian coordinates
         * as an intermediate step. */
        if (this.face === FACE_ENUM.TOP) {
            phi = Math.acos(cosphi);
            lp.phi = values_1.HALF_PI - phi;
            if (area.value === AREA_ENUM.AREA_0) {
                lp.lam = theta + values_1.HALF_PI;
            }
            else if (area.value === AREA_ENUM.AREA_1) {
                lp.lam = (theta < 0.0 ? theta + values_1.SPI : theta - values_1.SPI);
            }
            else if (area.value === AREA_ENUM.AREA_2) {
                lp.lam = theta - values_1.HALF_PI;
            }
            else /* area.value == AREA_ENUM.AREA_3 */ {
                lp.lam = theta;
            }
        }
        else if (this.face === FACE_ENUM.BOTTOM) {
            phi = Math.acos(cosphi);
            lp.phi = phi - values_1.HALF_PI;
            if (area.value === AREA_ENUM.AREA_0) {
                lp.lam = -theta + values_1.HALF_PI;
            }
            else if (area.value === AREA_ENUM.AREA_1) {
                lp.lam = -theta;
            }
            else if (area.value === AREA_ENUM.AREA_2) {
                lp.lam = -theta - values_1.HALF_PI;
            }
            else /* area.value == AREA_ENUM.AREA_3 */ {
                lp.lam = (theta < 0.0 ? -theta - values_1.SPI : -theta + values_1.SPI);
            }
        }
        else {
            /* Compute phi and lam via cartesian unit sphere coordinates. */
            var q, r, s;
            q = cosphi;
            t = q * q;
            if (t >= 1) {
                s = 0;
            }
            else {
                s = Math.sqrt(1 - t) * Math.sin(theta);
            }
            t += s * s;
            if (t >= 1) {
                r = 0;
            }
            else {
                r = Math.sqrt(1 - t);
            }
            /* Rotate q,r,s into the correct area. */
            if (area.value === AREA_ENUM.AREA_1) {
                t = r;
                r = -s;
                s = t;
            }
            else if (area.value === AREA_ENUM.AREA_2) {
                r = -r;
                s = -s;
            }
            else if (area.value === AREA_ENUM.AREA_3) {
                t = r;
                r = s;
                s = -t;
            }
            /* Rotate q,r,s into the correct cube face. */
            if (this.face === FACE_ENUM.RIGHT) {
                t = q;
                q = -r;
                r = t;
            }
            else if (this.face === FACE_ENUM.BACK) {
                q = -q;
                r = -r;
            }
            else if (this.face === FACE_ENUM.LEFT) {
                t = q;
                q = r;
                r = -t;
            }
            /* Now compute phi and lam from the unit sphere coordinates. */
            lp.phi = Math.acos(-s) - values_1.HALF_PI;
            lp.lam = Math.atan2(r, q);
            if (this.face === FACE_ENUM.RIGHT) {
                lp.lam = qsc_shift_lon_origin(lp.lam, -values_1.HALF_PI);
            }
            else if (this.face === FACE_ENUM.BACK) {
                lp.lam = qsc_shift_lon_origin(lp.lam, -values_1.SPI);
            }
            else if (this.face === FACE_ENUM.LEFT) {
                lp.lam = qsc_shift_lon_origin(lp.lam, +values_1.HALF_PI);
            }
        }
        /* Apply the shift from the sphere to the ellipsoid as described
         * in [LK12]. */
        if (this.es !== 0) {
            var invert_sign;
            var tanphi, xa;
            invert_sign = (lp.phi < 0 ? 1 : 0);
            tanphi = Math.tan(lp.phi);
            xa = this.b / Math.sqrt(tanphi * tanphi + this.one_minus_f_squared);
            lp.phi = Math.atan(Math.sqrt(this.a * this.a - xa * xa) / (this.one_minus_f * xa));
            if (invert_sign) {
                lp.phi = -lp.phi;
            }
        }
        lp.lam += this.long0;
        p.x = lp.lam;
        p.y = lp.phi;
        return p;
    }
    /* Helper function for forward projection: compute the theta angle
     * and determine the area number. */
    function qsc_fwd_equat_face_theta(phi, y, x, area) {
        var theta;
        if (phi < values_1.EPSLN) {
            area.value = AREA_ENUM.AREA_0;
            theta = 0.0;
        }
        else {
            theta = Math.atan2(y, x);
            if (Math.abs(theta) <= values_1.FORTPI) {
                area.value = AREA_ENUM.AREA_0;
            }
            else if (theta > values_1.FORTPI && theta <= values_1.HALF_PI + values_1.FORTPI) {
                area.value = AREA_ENUM.AREA_1;
                theta -= values_1.HALF_PI;
            }
            else if (theta > values_1.HALF_PI + values_1.FORTPI || theta <= -(values_1.HALF_PI + values_1.FORTPI)) {
                area.value = AREA_ENUM.AREA_2;
                theta = (theta >= 0.0 ? theta - values_1.SPI : theta + values_1.SPI);
            }
            else {
                area.value = AREA_ENUM.AREA_3;
                theta += values_1.HALF_PI;
            }
        }
        return theta;
    }
    /* Helper function: shift the longitude. */
    function qsc_shift_lon_origin(lon, offset) {
        var slon = lon + offset;
        if (slon < -values_1.SPI) {
            slon += values_1.TWO_PI;
        }
        else if (slon > +values_1.SPI) {
            slon -= values_1.TWO_PI;
        }
        return slon;
    }
    exports.names = ['Quadrilateralized Spherical Cube', 'Quadrilateralized_Spherical_Cube', 'qsc'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/projections/robin.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const values_1 = require(156) /* ../constants/values */;
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    var COEFS_X = [
        [1.0000, 2.2199e-17, -7.15515e-05, 3.1103e-06],
        [0.9986, -0.000482243, -2.4897e-05, -1.3309e-06],
        [0.9954, -0.00083103, -4.48605e-05, -9.86701e-07],
        [0.9900, -0.00135364, -5.9661e-05, 3.6777e-06],
        [0.9822, -0.00167442, -4.49547e-06, -5.72411e-06],
        [0.9730, -0.00214868, -9.03571e-05, 1.8736e-08],
        [0.9600, -0.00305085, -9.00761e-05, 1.64917e-06],
        [0.9427, -0.00382792, -6.53386e-05, -2.6154e-06],
        [0.9216, -0.00467746, -0.00010457, 4.81243e-06],
        [0.8962, -0.00536223, -3.23831e-05, -5.43432e-06],
        [0.8679, -0.00609363, -0.000113898, 3.32484e-06],
        [0.8350, -0.00698325, -6.40253e-05, 9.34959e-07],
        [0.7986, -0.00755338, -5.00009e-05, 9.35324e-07],
        [0.7597, -0.00798324, -3.5971e-05, -2.27626e-06],
        [0.7186, -0.00851367, -7.01149e-05, -8.6303e-06],
        [0.6732, -0.00986209, -0.000199569, 1.91974e-05],
        [0.6213, -0.010418, 8.83923e-05, 6.24051e-06],
        [0.5722, -0.00906601, 0.000182, 6.24051e-06],
        [0.5322, -0.00677797, 0.000275608, 6.24051e-06]
    ];
    var COEFS_Y = [
        [-5.20417e-18, 0.0124, 1.21431e-18, -8.45284e-11],
        [0.0620, 0.0124, -1.26793e-09, 4.22642e-10],
        [0.1240, 0.0124, 5.07171e-09, -1.60604e-09],
        [0.1860, 0.0123999, -1.90189e-08, 6.00152e-09],
        [0.2480, 0.0124002, 7.10039e-08, -2.24e-08],
        [0.3100, 0.0123992, -2.64997e-07, 8.35986e-08],
        [0.3720, 0.0124029, 9.88983e-07, -3.11994e-07],
        [0.4340, 0.0123893, -3.69093e-06, -4.35621e-07],
        [0.4958, 0.0123198, -1.02252e-05, -3.45523e-07],
        [0.5571, 0.0121916, -1.54081e-05, -5.82288e-07],
        [0.6176, 0.0119938, -2.41424e-05, -5.25327e-07],
        [0.6769, 0.011713, -3.20223e-05, -5.16405e-07],
        [0.7346, 0.0113541, -3.97684e-05, -6.09052e-07],
        [0.7903, 0.0109107, -4.89042e-05, -1.04739e-06],
        [0.8435, 0.0103431, -6.4615e-05, -1.40374e-09],
        [0.8936, 0.00969686, -6.4636e-05, -8.547e-06],
        [0.9394, 0.00840947, -0.000192841, -4.2106e-06],
        [0.9761, 0.00616527, -0.000256, -4.2106e-06],
        [1.0000, 0.00328947, -0.000319159, -4.2106e-06]
    ];
    var FXC = 0.8487;
    var FYC = 1.3523;
    var C1 = values_1.R2D / 5; // rad to 5-degree interval
    var RC1 = 1 / C1;
    var NODES = 18;
    var poly3_val = function (coefs, x) {
        return coefs[0] + x * (coefs[1] + x * (coefs[2] + x * coefs[3]));
    };
    var poly3_der = function (coefs, x) {
        return coefs[1] + x * (2 * coefs[2] + x * 3 * coefs[3]);
    };
    function newton_rapshon(f_df, start, max_err, iters) {
        var x = start;
        for (; iters; --iters) {
            var upd = f_df(x);
            x -= upd;
            if (Math.abs(upd) < max_err) {
                break;
            }
        }
        return x;
    }
    function init() {
        this.x0 = this.x0 || 0;
        this.y0 = this.y0 || 0;
        this.long0 = this.long0 || 0;
        this.es = 0;
        this.title = this.title || 'Robinson';
    }
    function forward(ll) {
        var lon = (0, adjust_lon_1.default)(ll.x - this.long0, this.over);
        var dphi = Math.abs(ll.y);
        var i = Math.floor(dphi * C1);
        if (i < 0) {
            i = 0;
        }
        else if (i >= NODES) {
            i = NODES - 1;
        }
        dphi = values_1.R2D * (dphi - RC1 * i);
        var xy = {
            x: poly3_val(COEFS_X[i], dphi) * lon,
            y: poly3_val(COEFS_Y[i], dphi)
        };
        if (ll.y < 0) {
            xy.y = -xy.y;
        }
        xy.x = xy.x * this.a * FXC + this.x0;
        xy.y = xy.y * this.a * FYC + this.y0;
        return xy;
    }
    function inverse(xy) {
        var ll = {
            x: (xy.x - this.x0) / (this.a * FXC),
            y: Math.abs(xy.y - this.y0) / (this.a * FYC)
        };
        if (ll.y >= 1) { // pathologic case
            ll.x /= COEFS_X[NODES][0];
            ll.y = xy.y < 0 ? -values_1.HALF_PI : values_1.HALF_PI;
        }
        else {
            // find table interval
            var i = Math.floor(ll.y * NODES);
            if (i < 0) {
                i = 0;
            }
            else if (i >= NODES) {
                i = NODES - 1;
            }
            for (;;) {
                if (COEFS_Y[i][0] > ll.y) {
                    --i;
                }
                else if (COEFS_Y[i + 1][0] <= ll.y) {
                    ++i;
                }
                else {
                    break;
                }
            }
            // linear interpolation in 5 degree interval
            var coefs = COEFS_Y[i];
            var t = 5 * (ll.y - coefs[0]) / (COEFS_Y[i + 1][0] - coefs[0]);
            // find t so that poly3_val(coefs, t) = ll.y
            t = newton_rapshon(function (x) {
                return (poly3_val(coefs, x) - ll.y) / poly3_der(coefs, x);
            }, t, values_1.EPSLN, 100);
            ll.x /= poly3_val(COEFS_X[i], t);
            ll.y = (5 * i + t) * values_1.D2R;
            if (xy.y < 0) {
                ll.y = -ll.y;
            }
        }
        ll.x = (0, adjust_lon_1.default)(ll.x + this.long0, this.over);
        return ll;
    }
    exports.names = ['Robinson', 'robin'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/projections/geocent.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const datumUtils_1 = require(184) /* ../datumUtils */;
    function init() {
        this.name = 'geocent';
    }
    function forward(p) {
        var point = (0, datumUtils_1.geodeticToGeocentric)(p, this.es, this.a);
        return point;
    }
    function inverse(p) {
        var point = (0, datumUtils_1.geocentricToGeodetic)(p, this.es, this.a, this.b);
        return point;
    }
    exports.names = ['Geocentric', 'geocentric', 'geocent', 'Geocent'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/projections/tpers.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const values_1 = require(156) /* ../constants/values */;
    const hypot_1 = tslib_1.__importDefault(require(197) /* ../common/hypot */);
    /**
     * @typedef {Object} LocalThis
     * @property {number} mode
     * @property {number} sinph0
     * @property {number} cosph0
     * @property {number} pn1
     * @property {number} h
     * @property {number} rp
     * @property {number} p
     * @property {number} h1
     * @property {number} pfact
     * @property {number} es
     * @property {number} tilt
     * @property {number} azi
     * @property {number} cg
     * @property {number} sg
     * @property {number} cw
     * @property {number} sw
     */
    var mode = {
        N_POLE: 0,
        S_POLE: 1,
        EQUIT: 2,
        OBLIQ: 3
    };
    var params = {
        h: { def: 100000, num: true }, // default is Karman line, no default in PROJ.7
        azi: { def: 0, num: true, degrees: true }, // default is North
        tilt: { def: 0, num: true, degrees: true }, // default is Nadir
        long0: { def: 0, num: true }, // default is Greenwich, conversion to rad is automatic
        lat0: { def: 0, num: true } // default is Equator, conversion to rad is automatic
    };
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function init() {
        Object.keys(params).forEach(function (p) {
            if (typeof this[p] === 'undefined') {
                this[p] = params[p].def;
            }
            else if (params[p].num && isNaN(this[p])) {
                throw new Error('Invalid parameter value, must be numeric ' + p + ' = ' + this[p]);
            }
            else if (params[p].num) {
                this[p] = parseFloat(this[p]);
            }
            if (params[p].degrees) {
                this[p] = this[p] * values_1.D2R;
            }
        }.bind(this));
        if (Math.abs((Math.abs(this.lat0) - values_1.HALF_PI)) < values_1.EPSLN) {
            this.mode = this.lat0 < 0 ? mode.S_POLE : mode.N_POLE;
        }
        else if (Math.abs(this.lat0) < values_1.EPSLN) {
            this.mode = mode.EQUIT;
        }
        else {
            this.mode = mode.OBLIQ;
            this.sinph0 = Math.sin(this.lat0);
            this.cosph0 = Math.cos(this.lat0);
        }
        this.pn1 = this.h / this.a; // Normalize relative to the Earth's radius
        if (this.pn1 <= 0 || this.pn1 > 1e10) {
            throw new Error('Invalid height');
        }
        this.p = 1 + this.pn1;
        this.rp = 1 / this.p;
        this.h1 = 1 / this.pn1;
        this.pfact = (this.p + 1) * this.h1;
        this.es = 0;
        var omega = this.tilt;
        var gamma = this.azi;
        this.cg = Math.cos(gamma);
        this.sg = Math.sin(gamma);
        this.cw = Math.cos(omega);
        this.sw = Math.sin(omega);
    }
    function forward(p) {
        p.x -= this.long0;
        var sinphi = Math.sin(p.y);
        var cosphi = Math.cos(p.y);
        var coslam = Math.cos(p.x);
        var x, y;
        switch (this.mode) {
            case mode.OBLIQ:
                y = this.sinph0 * sinphi + this.cosph0 * cosphi * coslam;
                break;
            case mode.EQUIT:
                y = cosphi * coslam;
                break;
            case mode.S_POLE:
                y = -sinphi;
                break;
            case mode.N_POLE:
                y = sinphi;
                break;
        }
        y = this.pn1 / (this.p - y);
        x = y * cosphi * Math.sin(p.x);
        switch (this.mode) {
            case mode.OBLIQ:
                y *= this.cosph0 * sinphi - this.sinph0 * cosphi * coslam;
                break;
            case mode.EQUIT:
                y *= sinphi;
                break;
            case mode.N_POLE:
                y *= -(cosphi * coslam);
                break;
            case mode.S_POLE:
                y *= cosphi * coslam;
                break;
        }
        // Tilt
        var yt, ba;
        yt = y * this.cg + x * this.sg;
        ba = 1 / (yt * this.sw * this.h1 + this.cw);
        x = (x * this.cg - y * this.sg) * this.cw * ba;
        y = yt * ba;
        p.x = x * this.a;
        p.y = y * this.a;
        return p;
    }
    function inverse(p) {
        p.x /= this.a;
        p.y /= this.a;
        var r = { x: p.x, y: p.y };
        // Un-Tilt
        var bm, bq, yt;
        yt = 1 / (this.pn1 - p.y * this.sw);
        bm = this.pn1 * p.x * yt;
        bq = this.pn1 * p.y * this.cw * yt;
        p.x = bm * this.cg + bq * this.sg;
        p.y = bq * this.cg - bm * this.sg;
        var rh = (0, hypot_1.default)(p.x, p.y);
        if (Math.abs(rh) < values_1.EPSLN) {
            r.x = 0;
            r.y = p.y;
        }
        else {
            var cosz, sinz;
            sinz = 1 - rh * rh * this.pfact;
            sinz = (this.p - Math.sqrt(sinz)) / (this.pn1 / rh + rh / this.pn1);
            cosz = Math.sqrt(1 - sinz * sinz);
            switch (this.mode) {
                case mode.OBLIQ:
                    r.y = Math.asin(cosz * this.sinph0 + p.y * sinz * this.cosph0 / rh);
                    p.y = (cosz - this.sinph0 * Math.sin(r.y)) * rh;
                    p.x *= sinz * this.cosph0;
                    break;
                case mode.EQUIT:
                    r.y = Math.asin(p.y * sinz / rh);
                    p.y = cosz * rh;
                    p.x *= sinz;
                    break;
                case mode.N_POLE:
                    r.y = Math.asin(cosz);
                    p.y = -p.y;
                    break;
                case mode.S_POLE:
                    r.y = -Math.asin(cosz);
                    break;
            }
            r.x = Math.atan2(p.x, p.y);
        }
        p.x = r.x + this.long0;
        p.y = r.y;
        return p;
    }
    exports.names = ['Tilted_Perspective', 'tpers'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/projections/geos.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    const tslib_1 = require(1) /* tslib */;
    const hypot_1 = tslib_1.__importDefault(require(197) /* ../common/hypot */);
    /**
     * @typedef {Object} LocalThis
     * @property {1 | 0} flip_axis
     * @property {number} h
     * @property {number} radius_g_1
     * @property {number} radius_g
     * @property {number} radius_p
     * @property {number} radius_p2
     * @property {number} radius_p_inv2
     * @property {'ellipse'|'sphere'} shape
     * @property {number} C
     * @property {string} sweep
     * @property {number} es
     */
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function init() {
        this.flip_axis = (this.sweep === 'x' ? 1 : 0);
        this.h = Number(this.h);
        this.radius_g_1 = this.h / this.a;
        if (this.radius_g_1 <= 0 || this.radius_g_1 > 1e10) {
            throw new Error();
        }
        this.radius_g = 1.0 + this.radius_g_1;
        this.C = this.radius_g * this.radius_g - 1.0;
        if (this.es !== 0.0) {
            var one_es = 1.0 - this.es;
            var rone_es = 1 / one_es;
            this.radius_p = Math.sqrt(one_es);
            this.radius_p2 = one_es;
            this.radius_p_inv2 = rone_es;
            this.shape = 'ellipse'; // Use as a condition in the forward and inverse functions.
        }
        else {
            this.radius_p = 1.0;
            this.radius_p2 = 1.0;
            this.radius_p_inv2 = 1.0;
            this.shape = 'sphere'; // Use as a condition in the forward and inverse functions.
        }
        if (!this.title) {
            this.title = 'Geostationary Satellite View';
        }
    }
    function forward(p) {
        var lon = p.x;
        var lat = p.y;
        var tmp, v_x, v_y, v_z;
        lon = lon - this.long0;
        if (this.shape === 'ellipse') {
            lat = Math.atan(this.radius_p2 * Math.tan(lat));
            var r = this.radius_p / (0, hypot_1.default)(this.radius_p * Math.cos(lat), Math.sin(lat));
            v_x = r * Math.cos(lon) * Math.cos(lat);
            v_y = r * Math.sin(lon) * Math.cos(lat);
            v_z = r * Math.sin(lat);
            if (((this.radius_g - v_x) * v_x - v_y * v_y - v_z * v_z * this.radius_p_inv2) < 0.0) {
                p.x = Number.NaN;
                p.y = Number.NaN;
                return p;
            }
            tmp = this.radius_g - v_x;
            if (this.flip_axis) {
                p.x = this.radius_g_1 * Math.atan(v_y / (0, hypot_1.default)(v_z, tmp));
                p.y = this.radius_g_1 * Math.atan(v_z / tmp);
            }
            else {
                p.x = this.radius_g_1 * Math.atan(v_y / tmp);
                p.y = this.radius_g_1 * Math.atan(v_z / (0, hypot_1.default)(v_y, tmp));
            }
        }
        else if (this.shape === 'sphere') {
            tmp = Math.cos(lat);
            v_x = Math.cos(lon) * tmp;
            v_y = Math.sin(lon) * tmp;
            v_z = Math.sin(lat);
            tmp = this.radius_g - v_x;
            if (this.flip_axis) {
                p.x = this.radius_g_1 * Math.atan(v_y / (0, hypot_1.default)(v_z, tmp));
                p.y = this.radius_g_1 * Math.atan(v_z / tmp);
            }
            else {
                p.x = this.radius_g_1 * Math.atan(v_y / tmp);
                p.y = this.radius_g_1 * Math.atan(v_z / (0, hypot_1.default)(v_y, tmp));
            }
        }
        p.x = p.x * this.a;
        p.y = p.y * this.a;
        return p;
    }
    function inverse(p) {
        var v_x = -1.0;
        var v_y = 0.0;
        var v_z = 0.0;
        var a, b, det, k;
        p.x = p.x / this.a;
        p.y = p.y / this.a;
        if (this.shape === 'ellipse') {
            if (this.flip_axis) {
                v_z = Math.tan(p.y / this.radius_g_1);
                v_y = Math.tan(p.x / this.radius_g_1) * (0, hypot_1.default)(1.0, v_z);
            }
            else {
                v_y = Math.tan(p.x / this.radius_g_1);
                v_z = Math.tan(p.y / this.radius_g_1) * (0, hypot_1.default)(1.0, v_y);
            }
            var v_zp = v_z / this.radius_p;
            a = v_y * v_y + v_zp * v_zp + v_x * v_x;
            b = 2 * this.radius_g * v_x;
            det = (b * b) - 4 * a * this.C;
            if (det < 0.0) {
                p.x = Number.NaN;
                p.y = Number.NaN;
                return p;
            }
            k = (-b - Math.sqrt(det)) / (2.0 * a);
            v_x = this.radius_g + k * v_x;
            v_y *= k;
            v_z *= k;
            p.x = Math.atan2(v_y, v_x);
            p.y = Math.atan(v_z * Math.cos(p.x) / v_x);
            p.y = Math.atan(this.radius_p_inv2 * Math.tan(p.y));
        }
        else if (this.shape === 'sphere') {
            if (this.flip_axis) {
                v_z = Math.tan(p.y / this.radius_g_1);
                v_y = Math.tan(p.x / this.radius_g_1) * Math.sqrt(1.0 + v_z * v_z);
            }
            else {
                v_y = Math.tan(p.x / this.radius_g_1);
                v_z = Math.tan(p.y / this.radius_g_1) * Math.sqrt(1.0 + v_y * v_y);
            }
            a = v_y * v_y + v_z * v_z + v_x * v_x;
            b = 2 * this.radius_g * v_x;
            det = (b * b) - 4 * a * this.C;
            if (det < 0.0) {
                p.x = Number.NaN;
                p.y = Number.NaN;
                return p;
            }
            k = (-b - Math.sqrt(det)) / (2.0 * a);
            v_x = this.radius_g + k * v_x;
            v_y *= k;
            v_z *= k;
            p.x = Math.atan2(v_y, v_x);
            p.y = Math.atan(v_z * Math.cos(p.x) / v_x);
        }
        p.x = p.x + this.long0;
        return p;
    }
    exports.names = ['Geostationary Satellite View', 'Geostationary_Satellite', 'geos'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/projections/eqearth.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    const qsfnz_1 = tslib_1.__importDefault(require(224) /* ../common/qsfnz */);
    const authset_1 = tslib_1.__importDefault(require(225) /* ../common/authset */);
    const authlat_1 = tslib_1.__importDefault(require(226) /* ../common/authlat */);
    var A1 = 1.340264, A2 = -0.081106, A3 = 0.000893, A4 = 0.003796, M = Math.sqrt(3) / 2.0;
    /**
     * @typedef {Object} LocalThis
     * @property {number} es
     * @property {number} e
     * @property {Array<number>} apa
     * @property {number} qp
     * @property {number} rqda
     */
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function init() {
        this.long0 = this.long0 !== undefined ? this.long0 : 0;
        this.x0 = this.x0 !== undefined ? this.x0 : 0;
        this.y0 = this.y0 !== undefined ? this.y0 : 0;
        if (this.es !== 0) {
            this.apa = (0, authset_1.default)(this.es);
            this.qp = (0, qsfnz_1.default)(this.e, 1);
            this.rqda = Math.sqrt(0.5 * this.qp);
        }
    }
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function forward(p) {
        var lam = (0, adjust_lon_1.default)(p.x - this.long0, this.over);
        var phi = p.y;
        var sinphi = Math.sin(phi);
        if (this.es !== 0) {
            sinphi = (0, qsfnz_1.default)(this.e, sinphi) / this.qp;
        }
        var paramLat = Math.asin(M * sinphi), paramLatSq = paramLat * paramLat, paramLatPow6 = paramLatSq * paramLatSq * paramLatSq;
        p.x = lam * Math.cos(paramLat)
            / (M * (A1 + 3 * A2 * paramLatSq + paramLatPow6 * (7 * A3 + 9 * A4 * paramLatSq)));
        p.y = paramLat * (A1 + A2 * paramLatSq + paramLatPow6 * (A3 + A4 * paramLatSq));
        if (this.es !== 0) {
            p.x *= this.rqda;
            p.y *= this.rqda;
        }
        p.x = this.a * p.x + this.x0;
        p.y = this.a * p.y + this.y0;
        return p;
    }
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function inverse(p) {
        p.x = (p.x - this.x0) / this.a;
        p.y = (p.y - this.y0) / this.a;
        if (this.es !== 0) {
            p.x /= this.rqda;
            p.y /= this.rqda;
        }
        var EPS = 1e-9, NITER = 12, paramLat = p.y, paramLatSq, paramLatPow6, fy, fpy, dlat, i;
        for (i = 0; i < NITER; ++i) {
            paramLatSq = paramLat * paramLat;
            paramLatPow6 = paramLatSq * paramLatSq * paramLatSq;
            fy = paramLat * (A1 + A2 * paramLatSq + paramLatPow6 * (A3 + A4 * paramLatSq)) - p.y;
            fpy = A1 + 3 * A2 * paramLatSq + paramLatPow6 * (7 * A3 + 9 * A4 * paramLatSq);
            paramLat -= dlat = fy / fpy;
            if (Math.abs(dlat) < EPS) {
                break;
            }
        }
        paramLatSq = paramLat * paramLat;
        paramLatPow6 = paramLatSq * paramLatSq * paramLatSq;
        p.x = M * p.x * (A1 + 3 * A2 * paramLatSq + paramLatPow6 * (7 * A3 + 9 * A4 * paramLatSq))
            / Math.cos(paramLat);
        p.y = Math.asin(Math.sin(paramLat) / M);
        if (this.es !== 0) {
            p.y = (0, authlat_1.default)(p.y, this.apa);
        }
        p.x = (0, adjust_lon_1.default)(p.x + this.long0, this.over);
        return p;
    }
    exports.names = ['eqearth', 'Equal Earth', 'Equal_Earth'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/projections/bonne.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    const tslib_1 = require(1) /* tslib */;
    const adjust_lat_1 = tslib_1.__importDefault(require(221) /* ../common/adjust_lat */);
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    const hypot_1 = tslib_1.__importDefault(require(197) /* ../common/hypot */);
    const pj_enfn_1 = tslib_1.__importDefault(require(192) /* ../common/pj_enfn */);
    const pj_inv_mlfn_1 = tslib_1.__importDefault(require(194) /* ../common/pj_inv_mlfn */);
    const pj_mlfn_1 = tslib_1.__importDefault(require(193) /* ../common/pj_mlfn */);
    const values_1 = require(156) /* ../constants/values */;
    /**
     * @typedef {Object} LocalThis
     * @property {number} phi1
     * @property {number} cphi1
     * @property {number} es
     * @property {Array<number>} en
     * @property {number} m1
     * @property {number} am1
     */
    var EPS10 = 1e-10;
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function init() {
        var c;
        this.phi1 = this.lat1;
        if (Math.abs(this.phi1) < EPS10) {
            throw new Error();
        }
        if (this.es) {
            this.en = (0, pj_enfn_1.default)(this.es);
            this.m1 = (0, pj_mlfn_1.default)(this.phi1, this.am1 = Math.sin(this.phi1), c = Math.cos(this.phi1), this.en);
            this.am1 = c / (Math.sqrt(1 - this.es * this.am1 * this.am1) * this.am1);
            this.inverse = e_inv;
            this.forward = e_fwd;
        }
        else {
            if (Math.abs(this.phi1) + EPS10 >= values_1.HALF_PI) {
                this.cphi1 = 0;
            }
            else {
                this.cphi1 = 1 / Math.tan(this.phi1);
            }
            this.inverse = s_inv;
            this.forward = s_fwd;
        }
    }
    function e_fwd(p) {
        var lam = (0, adjust_lon_1.default)(p.x - (this.long0 || 0), this.over);
        var phi = p.y;
        var rh, E, c;
        rh = this.am1 + this.m1 - (0, pj_mlfn_1.default)(phi, E = Math.sin(phi), c = Math.cos(phi), this.en);
        E = c * lam / (rh * Math.sqrt(1 - this.es * E * E));
        p.x = rh * Math.sin(E);
        p.y = this.am1 - rh * Math.cos(E);
        p.x = this.a * p.x + (this.x0 || 0);
        p.y = this.a * p.y + (this.y0 || 0);
        return p;
    }
    function e_inv(p) {
        p.x = (p.x - (this.x0 || 0)) / this.a;
        p.y = (p.y - (this.y0 || 0)) / this.a;
        var s, rh, lam, phi;
        rh = (0, hypot_1.default)(p.x, p.y = this.am1 - p.y);
        phi = (0, pj_inv_mlfn_1.default)(this.am1 + this.m1 - rh, this.es, this.en);
        if ((s = Math.abs(phi)) < values_1.HALF_PI) {
            s = Math.sin(phi);
            lam = rh * Math.atan2(p.x, p.y) * Math.sqrt(1 - this.es * s * s) / Math.cos(phi);
        }
        else if (Math.abs(s - values_1.HALF_PI) <= EPS10) {
            lam = 0;
        }
        else {
            throw new Error();
        }
        p.x = (0, adjust_lon_1.default)(lam + (this.long0 || 0), this.over);
        p.y = (0, adjust_lat_1.default)(phi);
        return p;
    }
    function s_fwd(p) {
        var lam = (0, adjust_lon_1.default)(p.x - (this.long0 || 0), this.over);
        var phi = p.y;
        var E, rh;
        rh = this.cphi1 + this.phi1 - phi;
        if (Math.abs(rh) > EPS10) {
            p.x = rh * Math.sin(E = lam * Math.cos(phi) / rh);
            p.y = this.cphi1 - rh * Math.cos(E);
        }
        else {
            p.x = p.y = 0;
        }
        p.x = this.a * p.x + (this.x0 || 0);
        p.y = this.a * p.y + (this.y0 || 0);
        return p;
    }
    function s_inv(p) {
        p.x = (p.x - (this.x0 || 0)) / this.a;
        p.y = (p.y - (this.y0 || 0)) / this.a;
        var lam, phi;
        var rh = (0, hypot_1.default)(p.x, p.y = this.cphi1 - p.y);
        phi = this.cphi1 + this.phi1 - rh;
        if (Math.abs(phi) > values_1.HALF_PI) {
            throw new Error();
        }
        if (Math.abs(Math.abs(phi) - values_1.HALF_PI) <= EPS10) {
            lam = 0;
        }
        else {
            lam = rh * Math.atan2(p.x, p.y) / Math.cos(phi);
        }
        p.x = (0, adjust_lon_1.default)(lam + (this.long0 || 0), this.over);
        p.y = (0, adjust_lat_1.default)(phi);
        return p;
    }
    exports.names = ['bonne', 'Bonne (Werner lat_1=90)'];
    exports.default = {
        init: init,
        names: exports.names
    };
},
/* proj4/lib/projections/ob_tran.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const adjust_lon_1 = tslib_1.__importDefault(require(172) /* ../common/adjust_lon */);
    const values_1 = require(156) /* ../constants/values */;
    const Proj_1 = tslib_1.__importDefault(require(151) /* ../Proj */);
    const longlat_1 = require(176) /* ./longlat */;
    /**
        Original projection implementation:
            https://github.com/OSGeo/PROJ/blob/46c47e9adf6376ae06afabe5d24a0016a05ced82/src/projections/ob_tran.cpp
    
        Documentation:
            https://proj.org/operations/projections/ob_tran.html
    
        References/Formulas:
            https://pubs.usgs.gov/pp/1395/report.pdf
    
        Examples:
            +proj=ob_tran +o_proj=moll +o_lat_p=45 +o_lon_p=-90
            +proj=ob_tran +o_proj=moll +o_lat_p=45 +o_lon_p=-90 +lon_0=60
            +proj=ob_tran +o_proj=moll +o_lat_p=45 +o_lon_p=-90 +lon_0=-90
    */
    const projectionType = {
        OBLIQUE: {
            forward: forwardOblique,
            inverse: inverseOblique
        },
        TRANSVERSE: {
            forward: forwardTransverse,
            inverse: inverseTransverse
        }
    };
    /**
     * @typedef {Object} LocalThis
     * @property {number} lamp
     * @property {number} cphip
     * @property {number} sphip
     * @property {Object} projectionType
     * @property {string | undefined} o_proj
     * @property {string | undefined} o_lon_p
     * @property {string | undefined} o_lat_p
     * @property {string | undefined} o_alpha
     * @property {string | undefined} o_lon_c
     * @property {string | undefined} o_lat_c
     * @property {string | undefined} o_lon_1
     * @property {string | undefined} o_lat_1
     * @property {string | undefined} o_lon_2
     * @property {string | undefined} o_lat_2
     * @property {number | undefined} oLongP
     * @property {number | undefined} oLatP
     * @property {number | undefined} oAlpha
     * @property {number | undefined} oLongC
     * @property {number | undefined} oLatC
     * @property {number | undefined} oLong1
     * @property {number | undefined} oLat1
     * @property {number | undefined} oLong2
     * @property {number | undefined} oLat2
     * @property {boolean} isIdentity
     * @property {import('..').Converter} obliqueProjection
     *
     */
    /**
     *    Parameters can be from the following sets:
     *       New pole --> o_lat_p, o_lon_p
     *       Rotate about point --> o_alpha, o_lon_c, o_lat_c
     *       New equator points --> lon_1, lat_1, lon_2, lat_2
     *
     *    Per the original source code, the parameter sets are
     *    checked in the order of the object below.
     */
    const paramSets = {
        ROTATE: {
            o_alpha: 'oAlpha',
            o_lon_c: 'oLongC',
            o_lat_c: 'oLatC'
        },
        NEW_POLE: {
            o_lat_p: 'oLatP',
            o_lon_p: 'oLongP'
        },
        NEW_EQUATOR: {
            o_lon_1: 'oLong1',
            o_lat_1: 'oLat1',
            o_lon_2: 'oLong2',
            o_lat_2: 'oLat2'
        }
    };
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function init() {
        this.x0 = this.x0 || 0;
        this.y0 = this.y0 || 0;
        this.long0 = this.long0 || 0;
        this.title = this.title || 'General Oblique Transformation';
        this.isIdentity = longlat_1.names.includes(this.o_proj);
        /** Verify required parameters exist */
        if (!this.o_proj) {
            throw new Error('Missing parameter: o_proj');
        }
        if (this.o_proj === `ob_tran`) {
            throw new Error('Invalid value for o_proj: ' + this.o_proj);
        }
        const newProjStr = this.projStr.replace('+proj=ob_tran', '').replace('+o_proj=', '+proj=').trim();
        /** @type {import('../defs.js').ProjectionDefinition} */
        const oProj = (0, Proj_1.default)(newProjStr);
        if (!oProj) {
            throw new Error('Invalid parameter: o_proj. Unknown projection ' + this.o_proj);
        }
        oProj.long0 = 0; // we handle long0 before/after forward/inverse
        this.obliqueProjection = oProj;
        let matchedSet;
        const paramSetsKeys = Object.keys(paramSets);
        /**
         * parse strings, convert to radians, throw on NaN
         * @param {string} name
         * @returns {number | undefined}
         */
        const parseParam = (name) => {
            if (typeof this[name] === `undefined`) {
                return undefined;
            }
            const val = parseFloat(this[name]) * values_1.D2R;
            if (isNaN(val)) {
                throw new Error('Invalid value for ' + name + ': ' + this[name]);
            }
            return val;
        };
        for (let i = 0; i < paramSetsKeys.length; i++) {
            const setKey = paramSetsKeys[i];
            const set = paramSets[setKey];
            const params = Object.entries(set);
            const setHasParams = params.some(([p]) => typeof this[p] !== 'undefined');
            if (!setHasParams) {
                continue;
            }
            matchedSet = set;
            for (let ii = 0; ii < params.length; ii++) {
                const [inputParam, param] = params[ii];
                const val = parseParam(inputParam);
                if (typeof val === 'undefined') {
                    throw new Error('Missing parameter: ' + inputParam + '.');
                }
                this[param] = val;
            }
            break;
        }
        if (!matchedSet) {
            throw new Error('No valid parameters provided for ob_tran projection.');
        }
        const { lamp, phip } = createRotation(this, matchedSet);
        this.lamp = lamp;
        if (Math.abs(phip) > values_1.EPSLN) {
            this.cphip = Math.cos(phip);
            this.sphip = Math.sin(phip);
            this.projectionType = projectionType.OBLIQUE;
        }
        else {
            this.projectionType = projectionType.TRANSVERSE;
        }
    }
    // ob_tran forward equations--mapping (lat,long) to (x,y)
    // transverse (90 degrees from normal orientation) - forwardTransverse
    // or oblique (arbitrary angle) used based on parameters - forwardOblique
    // -----------------------------------------------------------------
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function forward(p) {
        return this.projectionType.forward(this, p);
    }
    // inverse equations--mapping (x,y) to (lat,long)
    // transverse: inverseTransverse
    // oblique: inverseOblique
    // -----------------------------------------------------------------
    /** @this {import('../defs.js').ProjectionDefinition & LocalThis} */
    function inverse(p) {
        return this.projectionType.inverse(this, p);
    }
    /**
     * @param {import('../defs.js').ProjectionDefinition & LocalThis} params - Initialized projection definition
     * @param {Object} how - Transformation method
     * @returns {{phip: number, lamp: number}}
     */
    function createRotation(params, how) {
        let phip, lamp;
        if (how === paramSets.ROTATE) {
            let lamc = params.oLongC;
            let phic = params.oLatC;
            let alpha = params.oAlpha;
            if (Math.abs(Math.abs(phic) - values_1.HALF_PI) <= values_1.EPSLN) {
                throw new Error('Invalid value for o_lat_c: ' + params.o_lat_c + ' should be < 90°');
            }
            lamp = lamc + Math.atan2(-1 * Math.cos(alpha), -1 * Math.sin(alpha) * Math.sin(phic));
            phip = Math.asin(Math.cos(phic) * Math.sin(alpha));
        }
        else if (how === paramSets.NEW_POLE) {
            lamp = params.oLongP;
            phip = params.oLatP;
        }
        else {
            let lam1 = params.oLong1;
            let phi1 = params.oLat1;
            let lam2 = params.oLong2;
            let phi2 = params.oLat2;
            let con = Math.abs(phi1);
            if (Math.abs(phi1) > values_1.HALF_PI - values_1.EPSLN) {
                throw new Error('Invalid value for o_lat_1: ' + params.o_lat_1 + ' should be < 90°');
            }
            if (Math.abs(phi2) > values_1.HALF_PI - values_1.EPSLN) {
                throw new Error('Invalid value for o_lat_2: ' + params.o_lat_2 + ' should be < 90°');
            }
            if (Math.abs(phi1 - phi2) < values_1.EPSLN) {
                throw new Error('Invalid value for o_lat_1 and o_lat_2: o_lat_1 should be different from o_lat_2');
            }
            if (con < values_1.EPSLN) {
                throw new Error('Invalid value for o_lat_1: o_lat_1 should be different from zero');
            }
            lamp = Math.atan2((Math.cos(phi1) * Math.sin(phi2) * Math.cos(lam1))
                - (Math.sin(phi1) * Math.cos(phi2) * Math.cos(lam2)), (Math.sin(phi1) * Math.cos(phi2) * Math.sin(lam2))
                - (Math.cos(phi1) * Math.sin(phi2) * Math.sin(lam1)));
            phip = Math.atan(-1 * Math.cos(lamp - lam1) / Math.tan(phi1));
        }
        return { lamp, phip };
    }
    /**
     * Forward (lng, lat) to (x, y) for oblique case
     * @param {import('../defs.js').ProjectionDefinition & LocalThis} self
     * @param {{x: number, y: number}} lp - lambda, phi
     */
    function forwardOblique(self, lp) {
        let { x: lam, y: phi } = lp;
        lam = (0, adjust_lon_1.default)(lam - self.long0, self.over);
        const coslam = Math.cos(lam);
        const sinphi = Math.sin(phi);
        const cosphi = Math.cos(phi);
        lp.x = (0, adjust_lon_1.default)(Math.atan2(cosphi * Math.sin(lam), (self.sphip * cosphi * coslam) + (self.cphip * sinphi)) + self.lamp);
        lp.y = Math.asin((self.sphip * sinphi) - (self.cphip * cosphi * coslam));
        const result = self.obliqueProjection.forward(lp);
        if (self.isIdentity) {
            result.x *= values_1.R2D;
            result.y *= values_1.R2D;
        }
        return result;
    }
    /**
     * Forward (lng, lat) to (x, y) for transverse case
     * @param {import('../defs.js').ProjectionDefinition & LocalThis} self
     * @param {{x: number, y: number}} lp - lambda, phi
     */
    function forwardTransverse(self, lp) {
        let { x: lam, y: phi } = lp;
        lam = (0, adjust_lon_1.default)(lam - self.long0, self.over);
        const cosphi = Math.cos(phi);
        const coslam = Math.cos(lam);
        lp.x = (0, adjust_lon_1.default)(Math.atan2(cosphi * Math.sin(lam), Math.sin(phi)) + self.lamp);
        lp.y = Math.asin(-1 * cosphi * coslam);
        const result = self.obliqueProjection.forward(lp);
        if (self.isIdentity) {
            result.x *= values_1.R2D;
            result.y *= values_1.R2D;
        }
        return result;
    }
    /**
     * Inverse (x, y) to (lng, lat) for oblique case
     * @param {import('../defs.js').ProjectionDefinition & LocalThis} self
     * @param {{x: number, y: number}} lp - lambda, phi
     */
    function inverseOblique(self, lp) {
        if (self.isIdentity) {
            lp.x *= values_1.D2R;
            lp.y *= values_1.D2R;
        }
        const innerLp = self.obliqueProjection.inverse(lp);
        let { x: lam, y: phi } = innerLp;
        if (lam < Number.MAX_VALUE) {
            lam -= self.lamp;
            const coslam = Math.cos(lam);
            const sinphi = Math.sin(phi);
            const cosphi = Math.cos(phi);
            lp.x = Math.atan2(cosphi * Math.sin(lam), (self.sphip * cosphi * coslam) - (self.cphip * sinphi));
            lp.y = Math.asin((self.sphip * sinphi) + (self.cphip * cosphi * coslam));
        }
        lp.x = (0, adjust_lon_1.default)(lp.x + self.long0);
        return lp;
    }
    /**
     * Inverse (x, y) to (lng, lat) for transverse case
     * @param {import('../defs.js').ProjectionDefinition & LocalThis} self
     * @param {{x: number, y: number}} lp - lambda, phi
     */
    function inverseTransverse(self, lp) {
        if (self.isIdentity) {
            lp.x *= values_1.D2R;
            lp.y *= values_1.D2R;
        }
        const innerLp = self.obliqueProjection.inverse(lp);
        let { x: lam, y: phi } = innerLp;
        if (lam < Number.MAX_VALUE) {
            const cosphi = Math.cos(phi);
            lam -= self.lamp;
            lp.x = Math.atan2(cosphi * Math.sin(lam), -1 * Math.sin(phi));
            lp.y = Math.asin(cosphi * Math.cos(lam));
        }
        lp.x = (0, adjust_lon_1.default)(lp.x + self.long0);
        return lp;
    }
    exports.names = ['General Oblique Transformation', 'General_Oblique_Transformation', 'ob_tran'];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* models/annotations/arrow_head.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const marking_1 = require(253) /* ../graphics/marking */;
    const property_mixins_1 = require(95) /* ../../core/property_mixins */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    class ArrowHeadView extends marking_1.MarkingView {
    }
    exports.ArrowHeadView = ArrowHeadView;
    class ArrowHead extends marking_1.Marking {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(() => ({
                size: [p.NumberSpec, 25],
            }));
        }
    }
    exports.ArrowHead = ArrowHead;
    class OpenHeadView extends ArrowHeadView {
        clip(ctx, i) {
            this.visuals.line.set_vectorize(ctx, i);
            const size_i = this.size.get(i);
            ctx.moveTo(0.5 * size_i, size_i);
            ctx.lineTo(0.5 * size_i, -2);
            ctx.lineTo(-0.5 * size_i, -2);
            ctx.lineTo(-0.5 * size_i, size_i);
            ctx.lineTo(0, 0);
            ctx.lineTo(0.5 * size_i, size_i);
        }
        paint(ctx, i) {
            const size_i = this.size.get(i);
            ctx.beginPath();
            ctx.moveTo(0.5 * size_i, size_i);
            ctx.lineTo(0, 0);
            ctx.lineTo(-0.5 * size_i, size_i);
            this.visuals.line.apply(ctx, i);
        }
    }
    exports.OpenHeadView = OpenHeadView;
    class OpenHead extends ArrowHead {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = OpenHeadView;
            this.mixins(property_mixins_1.LineVector);
        }
    }
    exports.OpenHead = OpenHead;
    class NormalHeadView extends ArrowHeadView {
        clip(ctx, i) {
            this.visuals.line.set_vectorize(ctx, i);
            const size_i = this.size.get(i);
            ctx.moveTo(0.5 * size_i, size_i);
            ctx.lineTo(0.5 * size_i, -2);
            ctx.lineTo(-0.5 * size_i, -2);
            ctx.lineTo(-0.5 * size_i, size_i);
            ctx.lineTo(0.5 * size_i, size_i);
        }
        paint(ctx, i) {
            const size_i = this.size.get(i);
            ctx.beginPath();
            ctx.moveTo(0.5 * size_i, size_i);
            ctx.lineTo(0, 0);
            ctx.lineTo(-0.5 * size_i, size_i);
            ctx.closePath();
            this.visuals.fill.apply(ctx, i);
            this.visuals.hatch.apply(ctx, i);
            this.visuals.line.apply(ctx, i);
        }
    }
    exports.NormalHeadView = NormalHeadView;
    class NormalHead extends ArrowHead {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = NormalHeadView;
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
            this.override({
                fill_color: "black",
            });
        }
    }
    exports.NormalHead = NormalHead;
    class VeeHeadView extends ArrowHeadView {
        clip(ctx, i) {
            this.visuals.line.set_vectorize(ctx, i);
            const size_i = this.size.get(i);
            ctx.moveTo(0.5 * size_i, size_i);
            ctx.lineTo(0.5 * size_i, -2);
            ctx.lineTo(-0.5 * size_i, -2);
            ctx.lineTo(-0.5 * size_i, size_i);
            ctx.lineTo(0, 0.5 * size_i);
            ctx.lineTo(0.5 * size_i, size_i);
        }
        paint(ctx, i) {
            const size_i = this.size.get(i);
            ctx.beginPath();
            ctx.moveTo(0.5 * size_i, size_i);
            ctx.lineTo(0, 0);
            ctx.lineTo(-0.5 * size_i, size_i);
            ctx.lineTo(0, 0.5 * size_i);
            ctx.closePath();
            this.visuals.fill.apply(ctx, i);
            this.visuals.hatch.apply(ctx, i);
            this.visuals.line.apply(ctx, i);
        }
    }
    exports.VeeHeadView = VeeHeadView;
    class VeeHead extends ArrowHead {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = VeeHeadView;
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
            this.override({
                fill_color: "black",
            });
        }
    }
    exports.VeeHead = VeeHead;
    class TeeHeadView extends ArrowHeadView {
        paint(ctx, i) {
            const size_i = this.size.get(i);
            ctx.beginPath();
            ctx.moveTo(0.5 * size_i, 0);
            ctx.lineTo(-0.5 * size_i, 0);
            this.visuals.line.apply(ctx, i);
        }
        clip(_ctx, _i) { }
    }
    exports.TeeHeadView = TeeHeadView;
    class TeeHead extends ArrowHead {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = TeeHeadView;
            this.mixins(property_mixins_1.LineVector);
        }
    }
    exports.TeeHead = TeeHead;
},
/* models/graphics/marking.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const model_1 = require(52) /* ../../model */;
    const dom_view_1 = require(64) /* ../../core/dom_view */;
    const visuals = tslib_1.__importStar(require(99) /* ../../core/visuals */);
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    class MarkingView extends dom_view_1.DOMComponentView {
        visuals;
        size;
        initialize() {
            super.initialize();
            this.visuals = new visuals.Visuals(this);
        }
        request_paint() {
            this.parent.request_paint();
        }
        get canvas() {
            return this.parent.canvas;
        }
        set_data(source, indices) {
            const self = this;
            for (const prop of this.model) {
                if (!(prop instanceof p.VectorSpec || prop instanceof p.ScalarSpec)) {
                    continue;
                }
                const uniform = prop.uniform(source).select(indices);
                self[`${prop.attr}`] = uniform;
            }
        }
    }
    exports.MarkingView = MarkingView;
    class Marking extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({}) => ({}));
        }
    }
    exports.Marking = Marking;
},
/* models/annotations/base_color_bar.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(96) /* ./annotation */;
    const title_1 = require(255) /* ./title */;
    const cartesian_frame_1 = require(268) /* ../canvas/cartesian_frame */;
    const axis_1 = require(272) /* ../axes/axis */;
    const linear_axis_1 = require(277) /* ../axes/linear_axis */;
    const ticker_1 = require(274) /* ../tickers/ticker */;
    const tickers_1 = require(283) /* ../tickers */;
    const tick_formatter_1 = require(275) /* ../formatters/tick_formatter */;
    const formatters_1 = require(326) /* ../formatters */;
    const labeling_1 = require(276) /* ../policies/labeling */;
    const scales_1 = require(339) /* ../scales */;
    const ranges_1 = require(341) /* ../ranges */;
    const base_text_1 = require(258) /* ../text/base_text */;
    const enums_1 = require(21) /* ../../core/enums */;
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    const layout_1 = require(135) /* ../../core/layout */;
    const alignments_1 = require(138) /* ../../core/layout/alignments */;
    const border_1 = require(342) /* ../../core/layout/border */;
    const side_panel_1 = require(257) /* ../../core/layout/side_panel */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const bbox_1 = require(62) /* ../../core/util/bbox */;
    const types_1 = require(8) /* ../../core/util/types */;
    const MINOR_DIM = 25;
    const MAJOR_DIM_MIN_SCALAR = 0.3;
    const MAJOR_DIM_MAX_SCALAR = 0.8;
    class BaseColorBarView extends annotation_1.AnnotationView {
        _frame;
        _frame_view;
        _axis;
        _axis_view;
        _title;
        _title_view;
        _ticker;
        _formatter;
        _inner_layout;
        _major_range;
        _major_scale;
        _minor_range;
        _minor_scale;
        _orientation;
        get orientation() {
            return this._orientation;
        }
        children_views() {
            return [...super.children_views(), this._axis_view, this._title_view];
        }
        initialize() {
            super.initialize();
            const { ticker, formatter } = this.model;
            this._ticker = ticker != "auto" ? ticker : this._create_ticker();
            this._formatter = formatter != "auto" ? formatter : this._create_formatter();
            this._major_range = this._create_major_range();
            this._major_scale = this._create_major_scale();
            this._minor_range = new ranges_1.Range1d({ start: 0, end: 1 });
            this._minor_scale = new scales_1.LinearScale();
            // configure some frame, update when the layout is known
            this._frame = new cartesian_frame_1.CartesianFrame({
                x_scale: this._major_scale,
                y_scale: this._minor_scale,
                x_range: this._major_range,
                y_range: this._minor_range,
            });
            this._axis = this._create_axis();
            this._apply_axis_properties();
            this._title = new title_1.Title();
            this._apply_title_properties();
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const self = this;
            const parent = {
                get parent() {
                    return self.parent;
                },
                get root() {
                    return self.root;
                },
                get frame() {
                    return self._frame_view;
                },
                get frame_view() {
                    return self._frame_view;
                },
                get canvas_view() {
                    return self.parent.canvas_view;
                },
                request_layout() {
                    // force re-layout; not ideal but ColorBar's layout doesn't fully
                    // participate in has_size_changed to detect if layout is needed
                    self.layout.dirty = true;
                    self.parent.request_layout();
                },
                request_paint() {
                    self.parent.request_paint(self);
                },
                notify_finished_after_paint() {
                    self.parent.notify_finished_after_paint();
                },
            };
            this._frame_view = await (0, build_views_1.build_view)(this._frame, { parent });
            this._axis_view = await (0, build_views_1.build_view)(this._axis, { parent });
            this._title_view = await (0, build_views_1.build_view)(this._title, { parent });
        }
        _apply_axis_properties() {
            const attrs = {
                ticker: this._ticker,
                formatter: this._formatter,
                major_label_standoff: this.model.label_standoff,
                axis_line_color: null,
                major_tick_in: this.model.major_tick_in,
                major_tick_out: this.model.major_tick_out,
                minor_tick_in: this.model.minor_tick_in,
                minor_tick_out: this.model.minor_tick_out,
                major_label_overrides: this.model.major_label_overrides,
                major_label_policy: this.model.major_label_policy,
                // TODO: this needs strict typing
                ...mixins.attrs_of(this.model, "major_label_", mixins.Text, true),
                ...mixins.attrs_of(this.model, "major_tick_", mixins.Line, true),
                ...mixins.attrs_of(this.model, "minor_tick_", mixins.Line, true),
            };
            this._axis.setv(attrs);
        }
        _apply_title_properties() {
            const attrs = {
                text: this.model.title ?? "",
                standoff: this.model.title_standoff,
                // TODO: this needs strict typing
                ...mixins.attrs_of(this.model, "title_", mixins.Text, false),
            };
            this._title.setv(attrs);
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => {
                this._apply_title_properties();
                this._apply_axis_properties();
                // TODO?: this.plot_view.invalidate_layout()
            });
            this.connect(this._ticker.change, () => this.request_paint());
            this.connect(this._formatter.change, () => this.request_paint());
        }
        _update_frame() {
            const [x_scale, y_scale, x_range, y_range] = (() => {
                if (this.orientation == "horizontal") {
                    return [this._major_scale, this._minor_scale, this._major_range, this._minor_range];
                }
                else {
                    return [this._minor_scale, this._major_scale, this._minor_range, this._major_range];
                }
            })();
            this._frame.setv({ x_scale, y_scale, x_range, y_range });
        }
        update_layout() {
            const { location, width: w, height: h, padding, margin } = this.model;
            const [valign, halign] = (() => {
                if ((0, types_1.isString)(location)) {
                    switch (location) {
                        case "top_left":
                            return ["start", "start"];
                        case "top":
                        case "top_center":
                            return ["start", "center"];
                        case "top_right":
                            return ["start", "end"];
                        case "bottom_left":
                            return ["end", "start"];
                        case "bottom":
                        case "bottom_center":
                            return ["end", "center"];
                        case "bottom_right":
                            return ["end", "end"];
                        case "left":
                        case "center_left":
                            return ["center", "start"];
                        case "center":
                        case "center_center":
                            return ["center", "center"];
                        case "right":
                        case "center_right":
                            return ["center", "end"];
                    }
                }
                else {
                    return ["end", "start"];
                } // "bottom_left"
            })();
            const orientation = this._orientation = (() => {
                const { orientation } = this.model;
                if (orientation == "auto") {
                    if (this.panel != null) {
                        return this.panel.is_horizontal ? "horizontal" : "vertical";
                    }
                    else {
                        if (halign == "start" || halign == "end" || ( /*halign == "center" &&*/valign == "center")) {
                            return "vertical";
                        }
                        else {
                            return "horizontal";
                        }
                    }
                }
                else {
                    return orientation;
                }
            })();
            this._update_frame();
            const center_panel = new alignments_1.NodeLayout();
            const top_panel = new alignments_1.VStack();
            const bottom_panel = new alignments_1.VStack();
            const left_panel = new alignments_1.HStack();
            const right_panel = new alignments_1.HStack();
            center_panel.absolute = true;
            top_panel.absolute = true;
            bottom_panel.absolute = true;
            left_panel.absolute = true;
            right_panel.absolute = true;
            center_panel.on_resize((bbox) => this._frame_view.set_geometry(bbox));
            const layout = new border_1.BorderLayout();
            this._inner_layout = layout;
            layout.absolute = true;
            layout.center_panel = center_panel;
            layout.top_panel = top_panel;
            layout.bottom_panel = bottom_panel;
            layout.left_panel = left_panel;
            layout.right_panel = right_panel;
            const padding_box = { left: padding, right: padding, top: padding, bottom: padding };
            const margin_box = (() => {
                if (this.panel == null) {
                    if ((0, types_1.isString)(location)) {
                        return { left: margin, right: margin, top: margin, bottom: margin };
                    }
                    else {
                        const [left, bottom] = location;
                        return { left, right: margin, top: margin, bottom };
                    }
                }
                else {
                    /**
                     * XXX: alignment is broken in Grid, which is used to govern positioning of a ColorBar
                     * in side panels. Earlier attempts at fixing this failed and resulted in a multitude
                     * or regressions in various places in the layout. So instead of this, let's assume that
                     * the positioning is always at "start" regardless of configuration, and fix this here
                     * by manually computing "center" and "end" alignment.
                     */
                    if ((0, types_1.isString)(location)) {
                        layout.fixup_geometry = (outer, inner) => {
                            const origin = outer;
                            if (orientation == "horizontal") {
                                const { top, width, height } = outer;
                                if (halign == "end") {
                                    const { right } = this.layout.bbox;
                                    outer = new bbox_1.BBox({ right, top, width, height });
                                }
                                else if (halign == "center") {
                                    const { hcenter } = this.layout.bbox;
                                    outer = new bbox_1.BBox({ hcenter: Math.round(hcenter), top, width, height });
                                }
                            }
                            else {
                                const { left, width, height } = outer;
                                if (valign == "end") {
                                    const { bottom } = this.layout.bbox;
                                    outer = new bbox_1.BBox({ left, bottom, width, height });
                                }
                                else if (valign == "center") {
                                    const { vcenter } = this.layout.bbox;
                                    outer = new bbox_1.BBox({ left, vcenter: Math.round(vcenter), width, height });
                                }
                            }
                            if (inner != null) {
                                const dh = outer.left - origin.left;
                                const dv = outer.top - origin.top;
                                const { left, top, width, height } = inner;
                                inner = new bbox_1.BBox({ left: left + dh, top: top + dv, width, height });
                            }
                            return [outer, inner];
                        };
                        return undefined;
                    }
                    else {
                        const [left, bottom] = location;
                        layout.fixup_geometry = (outer, inner) => {
                            const origin = outer;
                            const grid = this.layout.bbox;
                            const { width, height } = outer;
                            outer = new bbox_1.BBox({ left: grid.left + left, bottom: grid.bottom - bottom, width, height });
                            if (inner != null) {
                                const dh = outer.left - origin.left;
                                const dv = outer.top - origin.top;
                                const { left, top, width, height } = inner;
                                inner = new bbox_1.BBox({ left: left + dh, top: top + dv, width, height });
                            }
                            return [outer, inner];
                        };
                        return { left, right: 0, top: 0, bottom };
                    }
                }
            })();
            layout.padding = padding_box;
            let major_policy;
            let major_size;
            let min_major_size;
            let max_major_size;
            if (this.panel != null) {
                major_policy = "max";
                major_size = undefined;
                min_major_size = undefined;
                max_major_size = undefined;
            }
            else {
                if ((orientation == "horizontal" ? w : h) == "auto") {
                    major_policy = "fixed";
                    const major_size_factor = this._get_major_size_factor();
                    if (major_size_factor != null) {
                        major_size = major_size_factor * MINOR_DIM;
                    }
                    min_major_size = { percent: MAJOR_DIM_MIN_SCALAR };
                    max_major_size = { percent: MAJOR_DIM_MAX_SCALAR };
                }
                else {
                    major_policy = "fit";
                    major_size = undefined;
                }
            }
            if (orientation == "horizontal") {
                const width = w == "auto" ? undefined : w;
                const height = h == "auto" ? MINOR_DIM : h;
                layout.set_sizing({
                    width_policy: major_policy, height_policy: "min",
                    width: major_size, min_width: min_major_size, max_width: max_major_size,
                    halign, valign, margin: margin_box,
                });
                layout.center_panel.set_sizing({ width_policy: w == "auto" ? "fit" : "fixed", height_policy: "fixed", width, height });
            }
            else {
                const width = w == "auto" ? MINOR_DIM : w;
                const height = h == "auto" ? undefined : h;
                layout.set_sizing({
                    width_policy: "min", height_policy: major_policy,
                    height: major_size, min_height: min_major_size, max_height: max_major_size,
                    halign, valign, margin: margin_box,
                });
                layout.center_panel.set_sizing({ width_policy: "fixed", height_policy: h == "auto" ? "fit" : "fixed", width, height });
            }
            top_panel.set_sizing({ width_policy: "fit", height_policy: "min" });
            bottom_panel.set_sizing({ width_policy: "fit", height_policy: "min" });
            left_panel.set_sizing({ width_policy: "min", height_policy: "fit" });
            right_panel.set_sizing({ width_policy: "min", height_policy: "fit" });
            const { _title_view } = this;
            if (orientation == "horizontal") {
                _title_view.panel = new side_panel_1.SidePanel("above");
                _title_view.update_layout();
                top_panel.children.push(_title_view.layout);
            }
            else {
                _title_view.panel = new side_panel_1.SidePanel("left");
                _title_view.update_layout();
                left_panel.children.push(_title_view.layout);
            }
            const { panel } = this;
            const side = (() => {
                if (panel != null && orientation == panel.orientation) {
                    return panel.side;
                }
                else {
                    return orientation == "horizontal" ? "below" : "right";
                }
            })();
            const stack = (() => {
                switch (side) {
                    case "above":
                        return top_panel;
                    case "below":
                        return bottom_panel;
                    case "left":
                        return left_panel;
                    case "right":
                        return right_panel;
                }
            })();
            const { _axis_view } = this;
            _axis_view.panel = new side_panel_1.SidePanel(side);
            _axis_view.update_layout();
            if (_axis_view.layout != null) {
                stack.children.push(_axis_view.layout);
            }
            if (this.panel != null) {
                const outer = new layout_1.Grid([{ layout, row: 0, col: 0 }]);
                outer.absolute = true;
                if (orientation == "horizontal") {
                    outer.set_sizing({ width_policy: "max", height_policy: "min" });
                }
                else {
                    outer.set_sizing({ width_policy: "min", height_policy: "max" });
                }
                this.layout = outer;
            }
            else {
                this.layout = this._inner_layout;
            }
            const { visible } = this.model;
            this.layout.sizing.visible = visible;
        }
        _create_axis() {
            return new linear_axis_1.LinearAxis();
        }
        _create_formatter() {
            return new formatters_1.BasicTickFormatter();
        }
        _create_major_range() {
            return new ranges_1.Range1d({ start: 0, end: 1 });
        }
        _create_major_scale() {
            return new scales_1.LinearScale();
        }
        _create_ticker() {
            return new tickers_1.BasicTicker();
        }
        _get_major_size_factor() {
            return null;
        }
        _paint(ctx) {
            ctx.save();
            this._paint_bbox(ctx, this._inner_layout.bbox);
            this._paint_colors(ctx, this._inner_layout.center_panel.bbox);
            this._title_view.paint(ctx);
            this._axis_view.paint(ctx);
            ctx.restore();
        }
        _paint_bbox(ctx, bbox) {
            const { x, y } = bbox;
            let { width, height } = bbox;
            // XXX: shrink outline region by 1px to make right and bottom lines visible
            // if they are on the edge of the canvas.
            if (x + width >= this.parent.canvas_view.bbox.width) {
                width -= 1;
            }
            if (y + height >= this.parent.canvas_view.bbox.height) {
                height -= 1;
            }
            ctx.save();
            ctx.beginPath();
            ctx.rect(x, y, width, height);
            this.visuals.background_fill.apply(ctx);
            this.visuals.background_hatch.apply(ctx);
            this.visuals.border_line.apply(ctx);
            ctx.restore();
        }
    }
    exports.BaseColorBarView = BaseColorBarView;
    class BaseColorBar extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.mixins([
                ["major_label_", mixins.Text],
                ["title_", mixins.Text],
                ["major_tick_", mixins.Line],
                ["minor_tick_", mixins.Line],
                ["border_", mixins.Line],
                ["bar_", mixins.Line],
                ["background_", mixins.Fill],
                ["background_", mixins.Hatch],
            ]);
            this.define(({ Float, Str, Tuple, Or, Ref, Auto, Nullable }) => ({
                location: [Or(enums_1.Anchor, Tuple(Float, Float)), "top_right"],
                orientation: [Or(enums_1.Orientation, Auto), "auto"],
                title: [Nullable(Or(Str, Ref(base_text_1.BaseText))), null],
                title_standoff: [Float, 2],
                width: [Or(Float, Auto), "auto"],
                height: [Or(Float, Auto), "auto"],
                ticker: [Or(Ref(ticker_1.Ticker), Auto), "auto"],
                formatter: [Or(Ref(tick_formatter_1.TickFormatter), Auto), "auto"],
                major_label_overrides: [axis_1.LabelOverrides, new Map()],
                major_label_policy: [Ref(labeling_1.LabelingPolicy), () => new labeling_1.NoOverlap()],
                label_standoff: [Float, 5],
                margin: [Float, 30],
                padding: [Float, 10],
                major_tick_in: [Float, 5],
                major_tick_out: [Float, 0],
                minor_tick_in: [Float, 0],
                minor_tick_out: [Float, 0],
            }));
            this.override({
                background_fill_color: "#ffffff",
                background_fill_alpha: 0.95,
                bar_line_color: null,
                border_line_color: null,
                major_label_text_font_size: "11px",
                major_tick_line_color: "#ffffff",
                minor_tick_line_color: null,
                title_text_font_size: "13px",
                title_text_font_style: "italic",
            });
        }
    }
    exports.BaseColorBar = BaseColorBar;
},
/* models/annotations/title.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const text_annotation_1 = require(256) /* ./text_annotation */;
    const enums_1 = require(21) /* ../../core/enums */;
    const resolve = tslib_1.__importStar(require(127) /* ../common/resolve */);
    class TitleView extends text_annotation_1.TextAnnotationView {
        _get_position() {
            const hmargin = this.model.offset;
            const vmargin = this.model.standoff / 2;
            const { align, vertical_align } = this.model;
            let sx, sy;
            const { bbox } = this.layout;
            switch (this.panel.side) {
                case "above":
                case "below": {
                    switch (vertical_align) {
                        case "top":
                            sy = bbox.top + vmargin;
                            break;
                        case "middle":
                            sy = bbox.vcenter;
                            break;
                        case "bottom":
                            sy = bbox.bottom - vmargin;
                            break;
                    }
                    switch (align) {
                        case "left":
                            sx = bbox.left + hmargin;
                            break;
                        case "center":
                            sx = bbox.hcenter;
                            break;
                        case "right":
                            sx = bbox.right - hmargin;
                            break;
                    }
                    break;
                }
                case "left": {
                    switch (vertical_align) {
                        case "top":
                            sx = bbox.left + vmargin;
                            break;
                        case "middle":
                            sx = bbox.hcenter;
                            break;
                        case "bottom":
                            sx = bbox.right - vmargin;
                            break;
                    }
                    switch (align) {
                        case "left":
                            sy = bbox.bottom - hmargin;
                            break;
                        case "center":
                            sy = bbox.vcenter;
                            break;
                        case "right":
                            sy = bbox.top + hmargin;
                            break;
                    }
                    break;
                }
                case "right": {
                    switch (vertical_align) {
                        case "top":
                            sx = bbox.right - vmargin;
                            break;
                        case "middle":
                            sx = bbox.hcenter;
                            break;
                        case "bottom":
                            sx = bbox.left + vmargin;
                            break;
                    }
                    switch (align) {
                        case "left":
                            sy = bbox.top + hmargin;
                            break;
                        case "center":
                            sy = bbox.vcenter;
                            break;
                        case "right":
                            sy = bbox.bottom - hmargin;
                            break;
                    }
                    break;
                }
            }
            return { sx, sy };
        }
        get anchor() {
            const { align, vertical_align } = this.model;
            return resolve.text_anchor("auto", align, vertical_align);
        }
        get origin() {
            return this._get_position();
        }
        get angle() {
            return this.panel.get_label_angle_heuristic("parallel");
        }
        _get_size() {
            const offset = (value) => {
                return value == 0 ? 0 : value + this.model.standoff;
            };
            const { width, height } = super._get_size();
            if (this.panel.is_horizontal) {
                return { width, height: offset(height) };
            }
            else {
                return { width: offset(width), height };
            }
        }
    }
    exports.TitleView = TitleView;
    class Title extends text_annotation_1.TextAnnotation {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = TitleView;
            this.define(({ Float }) => ({
                vertical_align: [enums_1.VerticalAlign, "bottom"],
                align: [enums_1.TextAlign, "left"],
                offset: [Float, 0],
                standoff: [Float, 10],
            }));
            this.override({
                text_font_size: "13px",
                text_font_style: "bold",
                text_line_height: 1.0,
            });
        }
    }
    exports.Title = Title;
},
/* models/annotations/text_annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(96) /* ./annotation */;
    const side_panel_1 = require(257) /* ../../core/layout/side_panel */;
    const base_text_1 = require(258) /* ../text/base_text */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const types_1 = require(8) /* ../../core/util/types */;
    const utils_1 = require(259) /* ../text/utils */;
    const kinds_1 = require(124) /* ../common/kinds */;
    const resolve = tslib_1.__importStar(require(127) /* ../common/resolve */);
    const bbox_1 = require(62) /* ../../core/util/bbox */;
    const painting_1 = require(267) /* ../common/painting */;
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    class TextAnnotationView extends annotation_1.AnnotationView {
        _text_view;
        children_views() {
            return [...super.children_views(), this._text_view];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._init_text();
        }
        async _init_text() {
            const { text } = this.model;
            const _text = (0, types_1.isString)(text) ? (0, utils_1.parse_delimited_string)(text) : text;
            this._text_view = await (0, build_views_1.build_view)(_text, { parent: this });
        }
        update_layout() {
            const { panel } = this;
            if (panel != null) {
                this.layout = new side_panel_1.SideLayout(panel, () => this.get_size(), false);
            }
            else {
                this.layout = undefined;
            }
        }
        connect_signals() {
            super.connect_signals();
            const { text } = this.model.properties;
            this.on_change(text, async () => {
                this._text_view.remove();
                await this._init_text();
            });
            this.connect(this.model.change, () => this.request_paint());
        }
        has_finished() {
            if (!super.has_finished()) {
                return false;
            }
            if (!this._text_view.has_finished()) {
                return false;
            }
            return true;
        }
        get displayed() {
            return super.displayed && this._text_view.model.text != "" && this.visuals.text.doit;
        }
        get padding() {
            return resolve.padding(this.model.padding);
        }
        get border_radius() {
            return resolve.border_radius(this.model.border_radius);
        }
        _text_box;
        _rect;
        _get_size() {
            if (!this.displayed) {
                return { width: 0, height: 0 };
            }
            const graphics = this._text_view.graphics();
            graphics.angle = this.angle;
            graphics.align = "auto";
            graphics.visuals = this.visuals.text.values();
            const size = graphics.size();
            const { padding } = this;
            const width = size.width + padding.left + padding.right;
            const height = size.height + padding.top + padding.bottom;
            return { width, height };
        }
        compute_geometry() {
            super.compute_geometry();
            const text_box = this._text_view.graphics();
            text_box.position = { sx: 0, sy: 0, x_anchor: "left", y_anchor: "top" };
            text_box.angle = 0; // needs reset because text_box is self-referential
            text_box.align = "auto";
            text_box.visuals = this.visuals.text.values();
            const size = text_box.size();
            const { sx, sy } = this.origin;
            const { anchor, padding, border_radius, angle } = this;
            const width = size.width + padding.left + padding.right;
            const height = size.height + padding.top + padding.bottom;
            this._text_box = text_box;
            this._rect = { sx, sy, width, height, angle, anchor, padding, border_radius };
        }
        _paint(ctx) {
            const { sx, sy, width, height, angle, anchor, padding, border_radius } = this._rect;
            const label = this._text_box;
            const dx = anchor.x * width;
            const dy = anchor.y * height;
            ctx.translate(sx, sy);
            ctx.rotate(angle);
            ctx.translate(-dx, -dy);
            const { background_fill, background_hatch, border_line, text } = this.visuals;
            if (background_fill.doit || background_hatch.doit || border_line.doit) {
                ctx.beginPath();
                const bbox = new bbox_1.BBox({ x: 0, y: 0, width, height });
                (0, painting_1.round_rect)(ctx, bbox, border_radius);
                background_fill.apply(ctx);
                background_hatch.apply(ctx);
                border_line.apply(ctx);
            }
            if (text.doit) {
                const { left, top } = padding;
                ctx.translate(left, top);
                label.paint(ctx);
                ctx.translate(-left, -top);
            }
            ctx.translate(dx, dy);
            ctx.rotate(-angle);
            ctx.translate(-sx, -sy);
        }
    }
    exports.TextAnnotationView = TextAnnotationView;
    class TextAnnotation extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.mixins([
                mixins.Text,
                ["border_", mixins.Line],
                ["background_", mixins.Fill],
                ["background_", mixins.Hatch],
            ]);
            this.define(({ Str, Or, Ref }) => ({
                text: [Or(Str, Ref(base_text_1.BaseText)), ""],
                padding: [kinds_1.Padding, 0],
                border_radius: [kinds_1.BorderRadius, 0],
            }));
            this.override({
                border_line_color: null,
                background_fill_color: null,
            });
        }
    }
    exports.TextAnnotation = TextAnnotation;
},
/* core/layout/side_panel.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(136) /* ./types */;
    const layoutable_1 = require(137) /* ./layoutable */;
    const types_2 = require(8) /* ../util/types */;
    // This table lays out the rules for configuring the baseline, alignment, etc. of
    // title text, based on it's location and orientation
    //
    // side    orient        baseline   align     angle   normal-dist
    // ------------------------------------------------------------------------------
    // above   parallel      bottom     center    0       height
    //         normal        middle     left      -90     width
    //         horizontal    bottom     center    0       height
    //         [angle > 0]   middle     left              width * sin + height * cos
    //         [angle < 0]   middle     right             width * sin + height * cos
    //
    // below   parallel      top        center    0       height
    //         normal        middle     right     90      width
    //         horizontal    top        center    0       height
    //         [angle > 0]   middle     right             width * sin + height * cos
    //         [angle < 0]   middle     left              width * sin + height * cos
    //
    // left    parallel      bottom     center    90      height
    //         normal        middle     right     0       width
    //         horizontal    middle     right     0       width
    //         [angle > 0]   middle     right             width * cos + height * sin
    //         [angle < 0]   middle     right             width * cos + height + sin
    //
    // right   parallel      bottom     center   -90      height
    //         normal        middle     left     0        width
    //         horizontal    middle     left     0        width
    //         [angle > 0]   middle     left              width * cos + height * sin
    //         [angle < 0]   middle     left              width * cos + height + sin
    const pi2 = Math.PI / 2;
    const _angle_lookup = {
        above: {
            parallel: 0,
            normal: -pi2,
            horizontal: 0,
            vertical: -pi2,
        },
        below: {
            parallel: 0,
            normal: pi2,
            horizontal: 0,
            vertical: pi2,
        },
        left: {
            parallel: -pi2,
            normal: 0,
            horizontal: 0,
            vertical: -pi2,
        },
        right: {
            parallel: pi2,
            normal: 0,
            horizontal: 0,
            vertical: pi2,
        },
    };
    const _vertical_align_lookup = {
        above: {
            parallel: "bottom",
            normal: "center",
            horizontal: "bottom",
            vertical: "center",
        },
        below: {
            parallel: "top",
            normal: "center",
            horizontal: "top",
            vertical: "center",
        },
        left: {
            parallel: "bottom",
            normal: "center",
            horizontal: "center",
            vertical: "bottom",
        },
        right: {
            parallel: "bottom",
            normal: "center",
            horizontal: "center",
            vertical: "bottom",
        },
    };
    const _align_lookup = {
        above: {
            parallel: "center",
            normal: "left",
            horizontal: "center",
            vertical: "left",
        },
        below: {
            parallel: "center",
            normal: "left",
            horizontal: "center",
            vertical: "left",
        },
        left: {
            parallel: "center",
            normal: "right",
            horizontal: "right",
            vertical: "center",
        },
        right: {
            parallel: "center",
            normal: "left",
            horizontal: "left",
            vertical: "center",
        },
    };
    const _align_lookup_negative = {
        above: "right",
        below: "left",
        left: "right",
        right: "left",
    };
    const _align_lookup_positive = {
        above: "left",
        below: "right",
        left: "right",
        right: "left",
    };
    class SidePanel {
        side;
        face;
        dimension;
        orientation;
        is_horizontal;
        is_vertical;
        normals;
        constructor(side, face) {
            this.side = side;
            this.face = (() => {
                if (face != null && face != "auto") {
                    return face;
                }
                else {
                    switch (this.side) {
                        case "left":
                        case "above":
                            return "front";
                        case "right":
                        case "below":
                            return "back";
                    }
                }
            })();
            this.dimension = this.side == "above" || this.side == "below" ? 0 : 1;
            this.orientation = this.dimension == 0 ? "horizontal" : "vertical";
            this.is_horizontal = this.dimension == 0;
            this.is_vertical = this.dimension == 1;
            this.normals = (() => {
                const sign = this.face == "front" ? -1 : 1;
                switch (this.side) {
                    case "left": return [sign, 0];
                    case "right": return [sign, 0];
                    case "above": return [0, sign];
                    case "below": return [0, sign];
                }
            })();
        }
        get face_adjusted_side() {
            const { side, face } = this;
            switch (side) {
                case "left":
                case "right":
                    return face == "front" ? "left" : "right";
                case "above":
                case "below":
                    return face == "front" ? "above" : "below";
            }
        }
        get_label_text_heuristics(orient) {
            const side = this.face_adjusted_side;
            if ((0, types_2.isString)(orient)) {
                return {
                    vertical_align: _vertical_align_lookup[side][orient],
                    align: _align_lookup[side][orient],
                };
            }
            else if (orient === 0) {
                return {
                    vertical_align: _vertical_align_lookup[side].horizontal,
                    align: _align_lookup[side].horizontal,
                };
            }
            else {
                return {
                    vertical_align: "center",
                    align: (orient < 0 ? _align_lookup_negative : _align_lookup_positive)[side],
                };
            }
        }
        get_label_angle_heuristic(orient) {
            if ((0, types_2.isString)(orient)) {
                const side = this.face_adjusted_side;
                return _angle_lookup[side][orient];
            }
            else {
                return -orient;
            }
        }
    }
    exports.SidePanel = SidePanel;
    class SideLayout extends layoutable_1.ContentLayoutable {
        panel;
        get_size;
        rotate;
        constructor(panel, get_size, rotate = false) {
            super();
            this.panel = panel;
            this.get_size = get_size;
            this.rotate = rotate;
            if (this.panel.is_horizontal) {
                this.set_sizing({ width_policy: "max", height_policy: "fixed" });
            }
            else {
                this.set_sizing({ width_policy: "fixed", height_policy: "max" });
            }
        }
        _content_size() {
            const { width, height } = this.get_size();
            if (!this.rotate || this.panel.is_horizontal) {
                return new types_1.Sizeable({ width, height });
            }
            else {
                return new types_1.Sizeable({ width: height, height: width });
            }
        }
        has_size_changed() {
            const { width, height } = this._content_size();
            if (this.panel.is_horizontal) {
                return this.bbox.height != height;
            }
            else {
                return this.bbox.width != width;
            }
        }
    }
    exports.SideLayout = SideLayout;
},
/* models/text/base_text.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    const view_1 = require(65) /* ../../core/view */;
    class BaseTextView extends view_1.View {
    }
    exports.BaseTextView = BaseTextView;
    class BaseText extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Str }) => ({
                text: [Str],
            }));
        }
    }
    exports.BaseText = BaseText;
},
/* models/text/utils.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.parse_delimited_string = parse_delimited_string;
    const math_text_1 = require(260) /* ./math_text */;
    const plain_text_1 = require(266) /* ./plain_text */;
    const array_1 = require(10) /* ../../core/util/array */;
    const delimiters = [
        { start: "$$", end: "$$", inline: false },
        { start: "\\\[", end: "\\\]", inline: false },
        { start: "\\\(", end: "\\\)", inline: true },
    ];
    function add_backslash(m) {
        return m.split("").map(s => `\\${s}`).join("");
    }
    function parse_delimited_string(text) {
        const matches = [];
        for (const delim of delimiters) {
            const start = add_backslash(delim.start);
            const end = add_backslash(delim.end);
            const re = new RegExp(`${start}([^]*?)${end}`, "gm");
            for (const match of text.matchAll(re)) {
                const { index } = match;
                const [outer, inner] = match;
                matches.push({ index, outer, inner, delim });
            }
        }
        if (matches.length > 0) {
            if (matches.length == 1) {
                const [match] = matches;
                const start = match.index;
                const end = match.outer.length;
                if (start == 0 && end == text.length) {
                    const tex_string = match.inner;
                    return new math_text_1.TeX({ text: tex_string, inline: match.delim.inline });
                }
            }
            let tex_string = "";
            let end = 0;
            for (const match of (0, array_1.sort_by)(matches, (match) => match.index)) {
                const start = match.index;
                if (end <= start) {
                    tex_string += start != 0 ? `\\text{${text.slice(end, start)}}${match.inner}` : `${match.inner}`;
                    end = start + match.outer.length;
                }
            }
            tex_string += end < text.length ? `\\text{${text.slice(end)}}` : "";
            return new math_text_1.TeX({ text: tex_string, inline: false });
        }
        else {
            return new plain_text_1.PlainText({ text });
        }
    }
},
/* models/text/math_text.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const object_1 = require(9) /* ../../core/util/object */;
    const types_1 = require(8) /* ../../core/util/types */;
    const image_1 = require(261) /* ../../core/util/image */;
    const color_1 = require(23) /* ../../core/util/color */;
    const graphics_1 = require(262) /* ../../core/graphics */;
    const text_1 = require(263) /* ../../core/util/text */;
    const string_1 = require(41) /* ../../core/util/string */;
    const affine_1 = require(73) /* ../../core/util/affine */;
    const bbox_1 = require(62) /* ../../core/util/bbox */;
    const base_text_1 = require(258) /* ./base_text */;
    const providers_1 = require(264) /* ./providers */;
    /**
     * Helper class for rendering MathText into Canvas
     */
    class MathTextView extends base_text_1.BaseTextView {
        graphics() {
            return this;
        }
        valign;
        angle;
        _position = { sx: 0, sy: 0 };
        // Align does nothing, needed to maintain compatibility with TextBox,
        // to align you need to use TeX Macros.
        // http://docs.mathjax.org/en/latest/input/tex/macros/index.html?highlight=align
        align = "left";
        // Same for infer_text_height
        infer_text_height() {
            return "ascent_descent";
        }
        _x_anchor = "left";
        _y_anchor = "center";
        _base_font_size = 13; // the same as :host's font-size (13px)
        set base_font_size(v) {
            if (v != null) {
                this._base_font_size = v;
            }
        }
        get base_font_size() {
            return this._base_font_size;
        }
        font_size_scale = 1.0;
        font;
        color;
        svg_image = null;
        svg_element;
        _rect() {
            const { width, height } = this._size();
            const { x, y } = this._computed_position();
            const bbox = new bbox_1.BBox({ x, y, width, height });
            return bbox.rect;
        }
        set position(p) {
            this._position = p;
        }
        get position() {
            return this._position;
        }
        get text() {
            return this.model.text;
        }
        get provider() {
            return providers_1.default_provider;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            if (this.provider.status == "not_started") {
                await this.provider.fetch();
            }
        }
        connect_signals() {
            super.connect_signals();
            this.on_change(this.model.properties.text, () => this.load_image());
        }
        set visuals(v) {
            const color = v.color;
            const alpha = v.alpha;
            const style = v.font_style;
            let size = v.font_size;
            const face = v.font;
            const { font_size_scale, _base_font_size } = this;
            const res = (0, text_1.parse_css_font_size)(size);
            if (res != null) {
                let { value, unit } = res;
                value *= font_size_scale;
                if (unit == "em" && _base_font_size != 0) {
                    value *= _base_font_size;
                    unit = "px";
                }
                size = `${value}${unit}`;
            }
            const font = `${style} ${size} ${face}`;
            this.font = font;
            this.color = (0, color_1.color2css)(color, alpha);
            const align = v.align;
            //this._visual_align = align
            this._x_anchor = align;
            const baseline = v.baseline;
            this._y_anchor = (() => {
                switch (baseline) {
                    case "top": return "top";
                    case "middle": return "center";
                    case "bottom": return "bottom";
                    default: return "baseline";
                }
            })();
        }
        /**
         * Calculates position of element after considering
         * anchor and dimensions
         */
        _computed_position() {
            const { width, height } = this._size();
            const { sx, sy, x_anchor = this._x_anchor, y_anchor = this._y_anchor } = this.position;
            const metrics = (0, text_1.font_metrics)(this.font);
            const x = sx - (() => {
                if ((0, types_1.isNumber)(x_anchor)) {
                    return x_anchor * width;
                }
                else {
                    switch (x_anchor) {
                        case "left": return 0;
                        case "center": return 0.5 * width;
                        case "right": return width;
                    }
                }
            })();
            const y = sy - (() => {
                if ((0, types_1.isNumber)(y_anchor)) {
                    return y_anchor * height;
                }
                else {
                    switch (y_anchor) {
                        case "top":
                            if (metrics.height > height) {
                                return (height - (-this.valign - metrics.descent) - metrics.height);
                            }
                            else {
                                return 0;
                            }
                        case "center": return 0.5 * height;
                        case "bottom":
                            if (metrics.height > height) {
                                return (height + metrics.descent + this.valign);
                            }
                            else {
                                return height;
                            }
                        case "baseline": return 0.5 * height;
                    }
                }
            })();
            return { x, y };
        }
        /**
         * Uses the width, height and given angle to calculate the size
        */
        size() {
            const { width, height } = this._size();
            const { angle } = this;
            if (angle == null || angle == 0) {
                return { width, height };
            }
            else {
                const c = Math.cos(Math.abs(angle));
                const s = Math.sin(Math.abs(angle));
                return {
                    width: Math.abs(width * c + height * s),
                    height: Math.abs(width * s + height * c),
                };
            }
        }
        get_image_dimensions() {
            const fmetrics = (0, text_1.font_metrics)(this.font);
            // XXX: perhaps use getComputedStyle()?
            const svg_styles = this.svg_element.getAttribute("style")?.split(";");
            if (svg_styles != null) {
                const rules_map = new Map();
                svg_styles.forEach(property => {
                    const [rule, value] = property.split(":");
                    if (rule.trim() != "") {
                        rules_map.set(rule.trim(), value.trim());
                    }
                });
                const v_align = (0, text_1.parse_css_length)(rules_map.get("vertical-align"));
                if (v_align?.unit == "ex") {
                    this.valign = v_align.value * fmetrics.x_height;
                }
                else if (v_align?.unit == "px") {
                    this.valign = v_align.value;
                }
            }
            const ex = (() => {
                const width = this.svg_element.getAttribute("width");
                const height = this.svg_element.getAttribute("height");
                return {
                    width: width != null && width.endsWith("ex") ? parseFloat(width) : 1,
                    height: height != null && height.endsWith("ex") ? parseFloat(height) : 1,
                };
            })();
            return {
                width: fmetrics.x_height * ex.width,
                height: fmetrics.x_height * ex.height,
            };
        }
        get truncated_text() {
            return this.model.text.length > 6
                ? `${this.model.text.substring(0, 6)}...`
                : this.model.text;
        }
        width;
        height;
        _size() {
            if (this.svg_image == null) {
                if (this.provider.status == "failed" || this.provider.status == "not_started") {
                    return {
                        width: (0, graphics_1.text_width)(this.truncated_text, this.font),
                        height: (0, text_1.font_metrics)(this.font).height,
                    };
                }
                else {
                    return { width: this._base_font_size, height: this._base_font_size };
                }
            }
            const fmetrics = (0, text_1.font_metrics)(this.font);
            let { width, height } = this.get_image_dimensions();
            height = Math.max(height, fmetrics.height);
            const w_scale = this.width?.unit == "%" ? this.width.value : 1;
            const h_scale = this.height?.unit == "%" ? this.height.value : 1;
            return { width: width * w_scale, height: height * h_scale };
        }
        bbox() {
            const { p0, p1, p2, p3 } = this.rect();
            const left = Math.min(p0.x, p1.x, p2.x, p3.x);
            const top = Math.min(p0.y, p1.y, p2.y, p3.y);
            const right = Math.max(p0.x, p1.x, p2.x, p3.x);
            const bottom = Math.max(p0.y, p1.y, p2.y, p3.y);
            return new bbox_1.BBox({ left, right, top, bottom });
        }
        rect() {
            const rect = this._rect();
            const { angle } = this;
            if (angle == null || angle == 0) {
                return rect;
            }
            else {
                const { sx, sy } = this.position;
                const tr = new affine_1.AffineTransform();
                tr.translate(sx, sy);
                tr.rotate(angle);
                tr.translate(-sx, -sy);
                return tr.apply_rect(rect);
            }
        }
        paint_rect(ctx) {
            const { p0, p1, p2, p3 } = this.rect();
            ctx.save();
            ctx.strokeStyle = "red";
            ctx.lineWidth = 1;
            ctx.beginPath();
            const { round } = Math;
            ctx.moveTo(round(p0.x), round(p0.y));
            ctx.lineTo(round(p1.x), round(p1.y));
            ctx.lineTo(round(p2.x), round(p2.y));
            ctx.lineTo(round(p3.x), round(p3.y));
            ctx.closePath();
            ctx.stroke();
            ctx.restore();
        }
        paint_bbox(ctx) {
            const { x, y, width, height } = this.bbox();
            ctx.save();
            ctx.strokeStyle = "blue";
            ctx.lineWidth = 1;
            ctx.beginPath();
            const { round } = Math;
            ctx.moveTo(round(x), round(y));
            ctx.lineTo(round(x), round(y + height));
            ctx.lineTo(round(x + width), round(y + height));
            ctx.lineTo(round(x + width), round(y));
            ctx.closePath();
            ctx.stroke();
            ctx.restore();
        }
        async request_image() {
            if (this.provider.MathJax == null) {
                return;
            }
            const mathjax_element = this._process_text();
            if (mathjax_element == null) {
                this._has_finished = true;
                return;
            }
            const svg_element = mathjax_element.children[0];
            this.svg_element = svg_element;
            svg_element.setAttribute("font", this.font);
            svg_element.setAttribute("stroke", this.color);
            const svg = svg_element.outerHTML;
            const src = `data:image/svg+xml;utf-8,${encodeURIComponent(svg)}`;
            this.svg_image = await (0, image_1.load_image)(src);
        }
        async load_image() {
            await this.request_image();
            this.parent.request_layout();
        }
        /**
         * Takes a Canvas' Context2d and if the image has already
         * been loaded draws the image in it otherwise draws the model's text.
        */
        paint(ctx) {
            if (this.svg_image == null) {
                if (this.provider.status == "not_started" || this.provider.status == "loading") {
                    this.provider.ready.connect(() => this.load_image());
                }
                if (this.provider.status == "loaded") {
                    void this.load_image();
                }
            }
            ctx.save();
            const { sx, sy } = this.position;
            const { angle } = this;
            if (angle != null && angle != 0) {
                ctx.translate(sx, sy);
                ctx.rotate(angle);
                ctx.translate(-sx, -sy);
            }
            const { x, y } = this._computed_position();
            if (this.svg_image != null) {
                const { width, height } = this.get_image_dimensions();
                ctx.drawImage(this.svg_image, x, y, width, height);
            }
            else if (this.provider.status == "failed" || this.provider.status == "not_started") {
                ctx.fillStyle = this.color;
                ctx.font = this.font;
                ctx.textAlign = "left";
                ctx.textBaseline = "alphabetic";
                ctx.fillText(this.truncated_text, x, y + (0, text_1.font_metrics)(this.font).ascent);
            }
            ctx.restore();
            if (!this._has_finished && (this.provider.status == "failed" || this.svg_image != null)) {
                this._has_finished = true;
                this.parent.notify_finished_after_paint();
            }
        }
    }
    exports.MathTextView = MathTextView;
    class MathText extends base_text_1.BaseText {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.MathText = MathText;
    class AsciiView extends MathTextView {
        // TODO: Color ascii
        get styled_text() {
            return this.text;
        }
        _process_text() {
            return undefined; // TODO: this.provider.MathJax?.ascii2svg(text)
        }
        _size() {
            return {
                width: (0, graphics_1.text_width)(this.text, this.font),
                height: (0, text_1.font_metrics)(this.font).height,
            };
        }
        paint(ctx) {
            ctx.save();
            const { sx, sy } = this.position;
            const { angle } = this;
            if (angle != null && angle != 0) {
                ctx.translate(sx, sy);
                ctx.rotate(angle);
                ctx.translate(-sx, -sy);
            }
            const { x, y } = this._computed_position();
            ctx.fillStyle = this.color;
            ctx.font = this.font;
            ctx.textAlign = "left";
            ctx.textBaseline = "alphabetic";
            ctx.fillText(this.text, x, y + (0, text_1.font_metrics)(this.font).ascent);
            ctx.restore();
            this._has_finished = true;
            this.parent.notify_finished_after_paint();
        }
    }
    exports.AsciiView = AsciiView;
    class Ascii extends MathText {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = AsciiView;
        }
    }
    exports.Ascii = Ascii;
    class MathMLView extends MathTextView {
        get styled_text() {
            let styled = this.text.trim();
            let matches = styled.match(/<math(.*?[^?])?>/s);
            if (matches == null) {
                return this.text.trim();
            }
            styled = (0, string_1.insert_text_on_position)(styled, styled.indexOf(matches[0]) + matches[0].length, `<mstyle displaystyle="true" mathcolor="${(0, color_1.color2hexrgb)(this.color)}" ${this.font.includes("bold") ? 'mathvariant="bold"' : ""}>`);
            matches = styled.match(/<\/[^>]*?math.*?>/s);
            if (matches == null) {
                return this.text.trim();
            }
            return (0, string_1.insert_text_on_position)(styled, styled.indexOf(matches[0]), "</mstyle>");
        }
        _process_text() {
            const fmetrics = (0, text_1.font_metrics)(this.font);
            return this.provider.MathJax?.mathml2svg(this.styled_text, {
                em: this.base_font_size,
                ex: fmetrics.x_height,
            });
        }
    }
    exports.MathMLView = MathMLView;
    class MathML extends MathText {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = MathMLView;
        }
    }
    exports.MathML = MathML;
    class TeXView extends MathTextView {
        get styled_text() {
            const [r, g, b] = (0, color_1.color2rgba)(this.color);
            return `\\color[RGB]{${r}, ${g}, ${b}} ${this.font.includes("bold") ? `\\boldsymbol{${this.text}}` : this.text}`;
        }
        _process_text() {
            // TODO: allow plot/document level configuration of macros
            const fmetrics = (0, text_1.font_metrics)(this.font);
            return this.provider.MathJax?.tex2svg(this.styled_text, {
                display: !this.model.inline,
                em: this.base_font_size,
                ex: fmetrics.x_height,
            }, (0, object_1.to_object)(this.model.macros));
        }
    }
    exports.TeXView = TeXView;
    class TeX extends MathText {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = TeXView;
            this.define(({ Bool, Float, Str, Dict, Tuple, Or }) => ({
                macros: [Dict(Or(Str, Tuple(Str, Float))), {}],
                inline: [Bool, false],
            }));
        }
    }
    exports.TeX = TeX;
},
/* core/util/image.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.load_image = load_image;
    const logging_1 = require(11) /* ../logging */;
    async function load_image(url, options) {
        return new ImageLoader(url, options).promise;
    }
    class ImageLoader {
        image = new Image();
        promise;
        constructor(src, config = {}) {
            const { attempts = 1, timeout = 1 } = config;
            const url = (() => {
                if (src instanceof ArrayBuffer) {
                    const blob = new Blob([src], { type: "image/png" }); // TODO mime
                    return URL.createObjectURL(blob); // TODO revoke
                }
                else {
                    return src;
                }
            })();
            this.promise = new Promise((resolve, _reject) => {
                this.image.crossOrigin = "anonymous";
                let retries = 0;
                this.image.onerror = () => {
                    if (++retries == attempts) {
                        const message = `unable to load ${url} image after ${attempts} attempts`;
                        logging_1.logger.warn(message);
                        if (this.image.crossOrigin != null) {
                            logging_1.logger.warn(`attempting to load ${url} without a cross origin policy`);
                            this.image.crossOrigin = null;
                            retries = 0;
                        }
                        else {
                            config.failed?.();
                            return; // XXX reject(new Error(message))
                        }
                    }
                    setTimeout(() => this.image.src = url, timeout);
                };
                this.image.onload = () => {
                    this._finished = true;
                    config.loaded?.(this.image);
                    resolve(this.image);
                };
                this.image.src = url;
            });
        }
        _finished = false;
        get finished() {
            return this._finished;
        }
    }
    exports.ImageLoader = ImageLoader;
},
/* core/graphics.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const bbox_1 = require(62) /* ./util/bbox */;
    const text_1 = require(263) /* ./util/text */;
    const array_1 = require(10) /* ./util/array */;
    const types_1 = require(8) /* ./util/types */;
    const affine_1 = require(73) /* ./util/affine */;
    const color_1 = require(23) /* ./util/color */;
    exports.text_width = (() => {
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");
        let current_font = "";
        return (text, font) => {
            if (font != current_font) {
                current_font = font;
                ctx.font = font;
            }
            return ctx.measureText(text).width;
        };
    })();
    class GraphicsBox {
        _position = { sx: 0, sy: 0 };
        angle;
        width;
        height;
        padding;
        font_size_scale = 1.0;
        text_height_metric;
        align = "left";
        _base_font_size = 13; // the same as :host's font-size (13px)
        _x_anchor = "left";
        _y_anchor = "center";
        set base_font_size(v) {
            if (v != null) {
                this._base_font_size = v;
            }
        }
        get base_font_size() {
            return this._base_font_size;
        }
        set position(p) {
            this._position = p;
        }
        get position() {
            return this._position;
        }
        infer_text_height() {
            return "ascent_descent";
        }
        bbox() {
            const { p0, p1, p2, p3 } = this.rect();
            const left = Math.min(p0.x, p1.x, p2.x, p3.x);
            const top = Math.min(p0.y, p1.y, p2.y, p3.y);
            const right = Math.max(p0.x, p1.x, p2.x, p3.x);
            const bottom = Math.max(p0.y, p1.y, p2.y, p3.y);
            return new bbox_1.BBox({ left, right, top, bottom });
        }
        size() {
            const { width, height } = this._size();
            const { angle } = this;
            if (angle == null || angle == 0) {
                return { width, height };
            }
            else {
                const c = Math.cos(Math.abs(angle));
                const s = Math.sin(Math.abs(angle));
                return {
                    width: Math.abs(width * c + height * s),
                    height: Math.abs(width * s + height * c),
                };
            }
        }
        rect() {
            const rect = this._rect();
            const { angle } = this;
            if (angle == null || angle == 0) {
                return rect;
            }
            else {
                const { sx, sy } = this.position;
                const tr = new affine_1.AffineTransform();
                tr.translate(sx, sy);
                tr.rotate(angle);
                tr.translate(-sx, -sy);
                return tr.apply_rect(rect);
            }
        }
        paint_rect(ctx) {
            const { p0, p1, p2, p3 } = this.rect();
            ctx.save();
            ctx.strokeStyle = "red";
            ctx.lineWidth = 1;
            ctx.beginPath();
            const { round } = Math;
            ctx.moveTo(round(p0.x), round(p0.y));
            ctx.lineTo(round(p1.x), round(p1.y));
            ctx.lineTo(round(p2.x), round(p2.y));
            ctx.lineTo(round(p3.x), round(p3.y));
            ctx.closePath();
            ctx.stroke();
            ctx.restore();
        }
        paint_bbox(ctx) {
            const { x, y, width, height } = this.bbox();
            ctx.save();
            ctx.strokeStyle = "blue";
            ctx.lineWidth = 1;
            ctx.beginPath();
            const { round } = Math;
            ctx.moveTo(round(x), round(y));
            ctx.lineTo(round(x), round(y + height));
            ctx.lineTo(round(x + width), round(y + height));
            ctx.lineTo(round(x + width), round(y));
            ctx.closePath();
            ctx.stroke();
            ctx.restore();
        }
    }
    exports.GraphicsBox = GraphicsBox;
    class TextBox extends GraphicsBox {
        text;
        color;
        outline_color;
        outline_width;
        font;
        line_height;
        //padding: Padding
        _visual_align = "left";
        set visuals(v) {
            const color = v.color;
            const alpha = v.alpha;
            const outline_color = v.outline_color;
            const outline_width = v.outline_width;
            const style = v.font_style;
            let size = v.font_size;
            const face = v.font;
            const { font_size_scale, base_font_size } = this;
            const res = (0, text_1.parse_css_font_size)(size);
            if (res != null) {
                let { value, unit } = res;
                value *= font_size_scale;
                if (unit == "em" && base_font_size != 0) {
                    value *= base_font_size;
                    unit = "px";
                }
                size = `${value}${unit}`;
            }
            const font = `${style} ${size} ${face}`;
            this.font = font;
            this.color = (0, color_1.color2css)(color, alpha);
            this.outline_color = (0, color_1.color2css)(outline_color, alpha);
            this.outline_width = outline_width;
            this.line_height = v.line_height;
            const align = v.align;
            this._visual_align = align;
            this._x_anchor = align;
            const baseline = v.baseline;
            this._y_anchor = (() => {
                switch (baseline) {
                    case "top": return "top";
                    case "middle": return "center";
                    case "bottom": return "bottom";
                    default: return "baseline";
                }
            })();
        }
        constructor({ text }) {
            super();
            this.text = text;
        }
        infer_text_height() {
            if (this.text.includes("\n")) {
                return "ascent_descent";
            }
            else {
                function is_math_like(text) {
                    for (const c of new Set(text)) {
                        if ("0" <= c && c <= "9") {
                            continue;
                        }
                        switch (c) {
                            case ",":
                            case ".":
                            case "+":
                            case "-":
                            case "\u2212":
                            case "e":
                                continue;
                            default:
                                return false;
                        }
                    }
                    return true;
                }
                if (is_math_like(this.text)) {
                    return "cap";
                }
                else {
                    return "ascent_descent";
                }
            }
        }
        _text_line(fmetrics) {
            const metric = this.text_height_metric ?? this.infer_text_height();
            const ascent = (() => {
                switch (metric) {
                    case "x":
                    case "x_descent":
                        return fmetrics.x_height;
                    case "cap":
                    case "cap_descent":
                        return fmetrics.cap_height;
                    case "ascent":
                    case "ascent_descent":
                        return fmetrics.ascent;
                }
            })();
            const descent = (() => {
                switch (metric) {
                    case "x":
                    case "cap":
                    case "ascent":
                        return 0;
                    case "x_descent":
                    case "cap_descent":
                    case "ascent_descent":
                        return fmetrics.descent;
                }
            })();
            return { height: ascent + descent, ascent, descent };
        }
        get nlines() {
            const lines = this.text.split("\n");
            return lines.length;
        }
        _size() {
            const { font } = this;
            const fmetrics = (0, text_1.font_metrics)(font);
            const line_spacing = (this.line_height - 1) * fmetrics.height; // TODO: max(trailing(L[n-1]), leading(L[n]))
            const empty = this.text == "";
            const lines = this.text.split("\n");
            const nlines = lines.length;
            const widths = lines.map((line) => (0, exports.text_width)(line, font));
            const text_line = this._text_line(fmetrics);
            const text_height = text_line.height * nlines;
            /*
            const heights: number[] = []
            const ascents: number[] = []
            const descents: number[] = []
        
            for (const line of lines) {
              const metrics = [...line].map((c) => glyph_metrics(c, font))
              const max_ascent = Math.max(max(metrics.map((m) => m.ascent)), fmetrics.cap_height)
              const max_descent = max(metrics.map((m) => m.descent))
              ascents.push(max_ascent)
              descents.push(max_descent)
              heights.push(max_ascent + max_descent)
            }
        
            const text_height = sum(heights)
            */
            const w_scale = this.width?.unit == "%" ? this.width.value : 1;
            const h_scale = this.height?.unit == "%" ? this.height.value : 1;
            const width = (0, array_1.max)(widths) * w_scale;
            const height = empty ? 0 : (text_height + line_spacing * (nlines - 1)) * h_scale;
            return { width, height, metrics: fmetrics };
        }
        _computed_position(size, metrics, nlines) {
            const { width, height } = size;
            const { sx, sy, x_anchor = this._x_anchor, y_anchor = this._y_anchor } = this.position;
            const x = sx - (() => {
                if ((0, types_1.isNumber)(x_anchor)) {
                    return x_anchor * width;
                }
                else {
                    switch (x_anchor) {
                        case "left": return 0;
                        case "center": return 0.5 * width;
                        case "right": return width;
                    }
                }
            })();
            const y = sy - (() => {
                if ((0, types_1.isNumber)(y_anchor)) {
                    return y_anchor * height;
                }
                else {
                    switch (y_anchor) {
                        case "top": return 0;
                        case "center": return 0.5 * height;
                        case "bottom": return height;
                        case "baseline": {
                            if (nlines == 1) {
                                const metric = this.text_height_metric ?? this.infer_text_height();
                                switch (metric) {
                                    case "x":
                                    case "x_descent":
                                        return metrics.x_height;
                                    case "cap":
                                    case "cap_descent":
                                        return metrics.cap_height;
                                    case "ascent":
                                    case "ascent_descent":
                                        return metrics.ascent;
                                }
                            }
                            else {
                                return 0.5 * height;
                            }
                        }
                    }
                }
            })();
            return { x, y };
        }
        _rect() {
            const { width, height, metrics } = this._size();
            const nlines = this.text.split("\n").length;
            const { x, y } = this._computed_position({ width, height }, metrics, nlines);
            const bbox = new bbox_1.BBox({ x, y, width, height });
            return bbox.rect;
        }
        paint(ctx) {
            const { font } = this;
            const fmetrics = (0, text_1.font_metrics)(font);
            const line_spacing = (this.line_height - 1) * fmetrics.height; // TODO: see above
            const lines = this.text.split("\n");
            const nlines = lines.length;
            const widths = lines.map((line) => (0, exports.text_width)(line, font));
            const text_line = this._text_line(fmetrics);
            const text_height = text_line.height * nlines;
            /*
            const heights: number[] = []
            const ascents: number[] = []
            const descents: number[] = []
        
            for (const line of lines) {
              const metrics = [...line].map((c) => glyph_metrics(c, font))
              const max_ascent = Math.max(max(metrics.map((m) => m.ascent)), fmetrics.cap_height)
              const max_descent = max(metrics.map((m) => m.descent))
              ascents.push(max_ascent)
              descents.push(max_descent)
              heights.push(max_ascent + max_descent)
            }
            */
            const w_scale = this.width?.unit == "%" ? this.width.value : 1;
            const h_scale = this.height?.unit == "%" ? this.height.value : 1;
            const width = (0, array_1.max)(widths) * w_scale;
            const height = (text_height + line_spacing * (nlines - 1)) * h_scale;
            ctx.save();
            ctx.fillStyle = this.color;
            ctx.strokeStyle = this.outline_color;
            ctx.lineWidth = this.outline_width;
            ctx.font = this.font;
            ctx.textAlign = "left";
            ctx.textBaseline = "alphabetic";
            const { sx, sy } = this.position;
            const { align } = this;
            const { angle } = this;
            if (angle != null && angle != 0) {
                ctx.translate(sx, sy);
                ctx.rotate(angle);
                ctx.translate(-sx, -sy);
            }
            let { x, y } = this._computed_position({ width, height }, fmetrics, nlines);
            if (align == "justify") {
                for (let i = 0; i < nlines; i++) {
                    let xij = x;
                    const line = lines[i];
                    const words = line.split(" ");
                    const nwords = words.length;
                    const word_widths = words.map((word) => (0, exports.text_width)(word, font));
                    const word_spacing = (width - (0, array_1.sum)(word_widths)) / (nwords - 1);
                    for (let j = 0; j < nwords; j++) {
                        ctx.fillText(words[j], xij, y);
                        ctx.strokeText(words[j], xij, y);
                        xij += word_widths[j] + word_spacing;
                    }
                    y += /*heights[i]*/ text_line.height + line_spacing;
                }
            }
            else {
                for (let i = 0; i < nlines; i++) {
                    const xi = x + (() => {
                        switch (align == "auto" ? this._visual_align : align) {
                            case "left": return 0;
                            case "center": return 0.5 * (width - widths[i]);
                            case "right": return width - widths[i];
                        }
                    })();
                    const linei = lines[i];
                    const yi = y + /*ascents[i]*/ text_line.ascent;
                    ctx.fillText(linei, xi, yi);
                    ctx.strokeText(linei, xi, yi);
                    y += /*heights[i]*/ text_line.height + line_spacing;
                }
            }
            ctx.restore();
        }
    }
    exports.TextBox = TextBox;
    class BaseExpo extends GraphicsBox {
        base;
        expo;
        constructor(base, expo) {
            super();
            this.base = base;
            this.expo = expo;
        }
        get children() {
            return [this.base, this.expo];
        }
        set base_font_size(v) {
            super.base_font_size = v;
            this.base.base_font_size = v;
            this.expo.base_font_size = v;
        }
        set position(p) {
            this._position = p;
            const bs = this.base.size();
            const es = this.expo.size();
            const shift = this._shift_scale() * bs.height;
            const height = Math.max(bs.height, shift + es.height);
            this.base.position = {
                sx: 0, x_anchor: "left",
                sy: height, y_anchor: "bottom",
            };
            this.expo.position = {
                sx: bs.width, x_anchor: "left",
                sy: shift, y_anchor: "bottom",
            };
        }
        get position() {
            return this._position;
        }
        set visuals(v) {
            this.expo.font_size_scale = 0.7;
            this.base.visuals = v;
            this.expo.visuals = v;
        }
        _shift_scale() {
            if (this.base instanceof TextBox && this.base.nlines == 1) {
                const { x_height, cap_height } = (0, text_1.font_metrics)(this.base.font);
                return x_height / cap_height;
            }
            else {
                return 2 / 3;
            }
        }
        infer_text_height() {
            return this.base.infer_text_height();
        }
        _rect() {
            const bb = this.base.bbox();
            const eb = this.expo.bbox();
            const bbox = bb.union(eb);
            const { x, y } = this._computed_position();
            return bbox.translate(x, y).rect;
        }
        _size() {
            const bs = this.base.size();
            const es = this.expo.size();
            return {
                width: bs.width + es.width,
                height: Math.max(bs.height, this._shift_scale() * bs.height + es.height),
            };
        }
        paint(ctx) {
            ctx.save();
            const { angle } = this;
            if (angle != null && angle != 0) {
                const { sx, sy } = this.position;
                ctx.translate(sx, sy);
                ctx.rotate(angle);
                ctx.translate(-sx, -sy);
            }
            const { x, y } = this._computed_position();
            ctx.translate(x, y);
            this.base.paint(ctx);
            this.expo.paint(ctx);
            ctx.restore();
        }
        // paint_rect ...
        paint_bbox(ctx) {
            super.paint_bbox(ctx);
            const { x, y } = this._computed_position();
            ctx.save();
            ctx.translate(x, y);
            for (const child of this.children) {
                child.paint_bbox(ctx);
            }
            ctx.restore();
        }
        _computed_position() {
            const { width, height } = this._size();
            const { sx, sy, x_anchor = this._x_anchor, y_anchor = this._y_anchor } = this.position;
            const x = sx - (() => {
                if ((0, types_1.isNumber)(x_anchor)) {
                    return x_anchor * width;
                }
                else {
                    switch (x_anchor) {
                        case "left": return 0;
                        case "center": return 0.5 * width;
                        case "right": return width;
                    }
                }
            })();
            const y = sy - (() => {
                if ((0, types_1.isNumber)(y_anchor)) {
                    return y_anchor * height;
                }
                else {
                    switch (y_anchor) {
                        case "top": return 0;
                        case "center": return 0.5 * height;
                        case "bottom": return height;
                        case "baseline": return 0.5 * height; /* TODO */
                    }
                }
            })();
            return { x, y };
        }
    }
    exports.BaseExpo = BaseExpo;
    class GraphicsBoxes {
        items;
        constructor(items) {
            this.items = items;
        }
        set base_font_size(v) {
            for (const item of this.items) {
                item.base_font_size = v;
            }
        }
        get length() {
            return this.items.length;
        }
        set visuals(v) {
            for (const item of this.items) {
                item.visuals = v;
            }
            const metric_map = { x: 0, cap: 1, ascent: 2, x_descent: 3, cap_descent: 4, ascent_descent: 5 };
            const common = (0, array_1.max_by)(this.items.map((item) => item.infer_text_height()), (metric) => metric_map[metric]);
            for (const item of this.items) {
                item.text_height_metric = common;
            }
        }
        set angle(a) {
            for (const item of this.items) {
                item.angle = a;
            }
        }
        max_size() {
            let width = 0;
            let height = 0;
            for (const item of this.items) {
                const size = item.size();
                width = Math.max(width, size.width);
                height = Math.max(height, size.height);
            }
            return { width, height };
        }
    }
    exports.GraphicsBoxes = GraphicsBoxes;
},
/* core/util/text.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.font_metrics = font_metrics;
    exports.parse_css_font_size = parse_css_font_size;
    exports.parse_css_length = parse_css_length;
    const assert_1 = require(13) /* ./assert */;
    const dom_1 = require(61) /* ../dom */;
    const _offscreen_context = (() => {
        // Support Firefox ESR, etc., see https://github.com/bokeh/bokeh/issues/14006.
        const canvas_el = typeof OffscreenCanvas !== "undefined" ? new OffscreenCanvas(0, 0) : (0, dom_1.canvas)({ width: 0, height: 0 });
        const ctx = canvas_el.getContext("2d");
        (0, assert_1.assert)(ctx != null, "can't obtain 2d context");
        return ctx;
    })();
    function _font_metrics(font) {
        const ctx = _offscreen_context;
        ctx.font = font;
        const cap_metrics = ctx.measureText("M");
        const x_metrics = ctx.measureText("x");
        const metrics = ctx.measureText("ÅŚg|");
        // Support Firefox ESR, etc., see https://github.com/bokeh/bokeh/issues/13969.
        const ascent = typeof metrics.fontBoundingBoxAscent !== "undefined" ? metrics.fontBoundingBoxAscent : metrics.actualBoundingBoxAscent;
        const descent = typeof metrics.fontBoundingBoxDescent !== "undefined" ? metrics.fontBoundingBoxDescent : metrics.actualBoundingBoxDescent;
        return {
            height: ascent + descent,
            ascent,
            descent,
            cap_height: cap_metrics.actualBoundingBoxAscent,
            x_height: x_metrics.actualBoundingBoxAscent,
        };
    }
    const _metrics_cache = new Map();
    function font_metrics(font) {
        let metrics = _metrics_cache.get(font);
        if (metrics == null) {
            const loaded = document.fonts.check(font);
            metrics = { font: _font_metrics(font) };
            if (loaded) {
                _metrics_cache.set(font, metrics);
            }
        }
        return metrics.font;
    }
    function parse_css_font_size(size) {
        const match = size.match(/^\s*(\d+(\.\d+)?)(\w+)\s*$/);
        if (match != null) {
            const [, value, , unit] = match;
            const number = Number(value);
            if (isFinite(number)) {
                return { value: number, unit };
            }
        }
        return null;
    }
    function parse_css_length(size) {
        const match = size.match(/^\s*(-?\d+(\.\d+)?)(\w+)\s*$/);
        if (match != null) {
            const [, value, , unit] = match;
            const number = Number(value);
            if (isFinite(number)) {
                return { value: number, unit };
            }
        }
        return null;
    }
},
/* models/text/providers.js */ function _(require, module, exports, __esModule, __esExport) {
    var __createBinding = (this && this.__createBinding) || (Object.create ? (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        var desc = Object.getOwnPropertyDescriptor(m, k);
        if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
            desc = { enumerable: true, get: function () { return m[k]; } };
        }
        Object.defineProperty(o, k2, desc);
    }) : (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        o[k2] = m[k];
    }));
    var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function (o, v) {
        o["default"] = v;
    });
    var __importStar = (this && this.__importStar) || (function () {
        var ownKeys = function (o) {
            ownKeys = Object.getOwnPropertyNames || function (o) {
                var ar = [];
                for (var k in o)
                    if (Object.prototype.hasOwnProperty.call(o, k))
                        ar[ar.length] = k;
                return ar;
            };
            return ownKeys(o);
        };
        return function (mod) {
            if (mod && mod.__esModule)
                return mod;
            var result = {};
            if (mod != null)
                for (var k = ownKeys(mod), i = 0; i < k.length; i++)
                    if (k[i] !== "default")
                        __createBinding(result, mod, k[i]);
            __setModuleDefault(result, mod);
            return result;
        };
    })();
    __esModule();
    const signaling_1 = require(17) /* ../../core/signaling */;
    const modules_1 = require(265) /* ../../core/util/modules */;
    class MathJaxProvider {
        ready = new signaling_1.Signal0(this, "ready");
        status = "not_started";
    }
    exports.MathJaxProvider = MathJaxProvider;
    class NoProvider extends MathJaxProvider {
        get MathJax() {
            return null;
        }
        async fetch() {
            this.status = "failed";
        }
    }
    exports.NoProvider = NoProvider;
    class CDNProvider extends MathJaxProvider {
        get MathJax() {
            return typeof MathJax !== "undefined" ? MathJax : null;
        }
        async fetch() {
            const script = document.createElement("script");
            script.src = "https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js";
            script.onload = () => {
                this.status = "loaded";
                this.ready.emit();
            };
            script.onerror = () => {
                this.status = "failed";
            };
            this.status = "loading";
            document.head.appendChild(script);
        }
    }
    exports.CDNProvider = CDNProvider;
    class BundleProvider extends MathJaxProvider {
        _mathjax;
        get MathJax() {
            return this._mathjax;
        }
        async fetch() {
            this.status = "loading";
            try {
                const mathjax = await (0, modules_1.load_module)(Promise.resolve().then(() => __importStar(require(806) /* ./mathjax */)));
                this.status = mathjax == null ? "failed" : "loaded";
                this._mathjax = mathjax;
                this.ready.emit();
            }
            catch (error) {
                this.status = "failed";
            }
        }
    }
    exports.BundleProvider = BundleProvider;
    exports.default_provider = new BundleProvider();
},
/* core/util/modules.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.load_module = load_module;
    function is_ModuleError(error) {
        return error instanceof Error && "code" in error;
    }
    /** T is of import("some/module/path") type */
    async function load_module(module) {
        try {
            return await module;
        }
        catch (e) {
            // XXX: this exposes the underlying module system and hinders
            // interoperability with other module systems and bundlers
            if (is_ModuleError(e) && e.code === "MODULE_NOT_FOUND") {
                return null;
            }
            else {
                throw e;
            }
        }
    }
},
/* models/text/plain_text.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const base_text_1 = require(258) /* ./base_text */;
    const graphics_1 = require(262) /* ../../core/graphics */;
    class PlainTextView extends base_text_1.BaseTextView {
        initialize() {
            super.initialize();
            this._has_finished = true;
        }
        graphics() {
            return new graphics_1.TextBox({ text: this.model.text });
        }
    }
    exports.PlainTextView = PlainTextView;
    class PlainText extends base_text_1.BaseText {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = PlainTextView;
        }
    }
    exports.PlainText = PlainText;
},
/* models/common/painting.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.round_rect = round_rect;
    function round_rect(ctx, bbox, border_radius) {
        /**
         * Create a path for a rect with rounded corners.
         *
         * From https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-roundrect.
         */
        let { top_left, top_right, bottom_right, bottom_left } = border_radius;
        if (top_left != 0 || top_right != 0 || bottom_right != 0 || bottom_left != 0) {
            const { left, right, top, bottom, width, height } = bbox;
            const scale = Math.min(width / (top_left + top_right), height / (top_right + bottom_right), width / (bottom_right + bottom_left), height / (top_left + bottom_left));
            if (scale < 1.0) {
                top_left *= scale;
                top_right *= scale;
                bottom_right *= scale;
                bottom_left *= scale;
            }
            ctx.moveTo(left + top_left, top);
            ctx.lineTo(right - top_right, top);
            if (top_right != 0) {
                ctx.arcTo(right, top, right, top + top_right, top_right);
            }
            ctx.lineTo(right, bottom - bottom_right);
            if (bottom_right != 0) {
                ctx.arcTo(right, bottom, right - bottom_right, bottom, bottom_right);
            }
            ctx.lineTo(left + bottom_left, bottom);
            if (bottom_left != 0) {
                ctx.arcTo(left, bottom, left, bottom - bottom_left, bottom_left);
            }
            ctx.lineTo(left, top + top_left);
            if (top_left != 0) {
                ctx.arcTo(left, top, left + top_left, top, top_left);
            }
            ctx.closePath();
        }
        else {
            const { left, top, width, height } = bbox;
            ctx.rect(left, top, width, height);
        }
    }
},
/* models/canvas/cartesian_frame.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const canvas_panel_1 = require(269) /* ./canvas_panel */;
    const categorical_scale_1 = require(116) /* ../scales/categorical_scale */;
    const log_scale_1 = require(115) /* ../scales/log_scale */;
    const scale_1 = require(108) /* ../scales/scale */;
    const linear_scale_1 = require(113) /* ../scales/linear_scale */;
    const range_1 = require(110) /* ../ranges/range */;
    const range1d_1 = require(111) /* ../ranges/range1d */;
    const data_range1d_1 = require(118) /* ../ranges/data_range1d */;
    const factor_range_1 = require(121) /* ../ranges/factor_range */;
    const object_1 = require(9) /* ../../core/util/object */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    const css = tslib_1.__importStar(require(271) /* ../../styles/cartesian_frame.css */);
    class CartesianFrameView extends canvas_panel_1.CanvasPanelView {
        initialize() {
            super.initialize();
            this._configure_scales();
        }
        remove() {
            this._unregister_frame();
            super.remove();
        }
        stylesheets() {
            return [...super.stylesheets(), css.default];
        }
        connect_signals() {
            super.connect_signals();
            const { x_range, y_range, x_scale, y_scale, extra_x_ranges, extra_y_ranges, extra_x_scales, extra_y_scales } = this.model.properties;
            this.on_change([x_range, y_range, x_scale, y_scale, extra_x_ranges, extra_y_ranges, extra_x_scales, extra_y_scales], () => {
                this._configure_scales();
            });
        }
        _x_target;
        _y_target;
        _x_ranges = new Map();
        _y_ranges = new Map();
        _x_scales = new Map();
        _y_scales = new Map();
        _x_scale;
        _y_scale;
        _get_ranges(range, extra_ranges) {
            return new Map([...(0, object_1.entries)(extra_ranges), ["default", range]]);
        }
        _get_scales(scale, extra_scales, ranges, frame_range) {
            const in_scales = new Map([...(0, object_1.entries)(extra_scales), ["default", scale]]);
            const scales = new Map();
            for (const [name, range] of ranges) {
                const factor_range = range instanceof factor_range_1.FactorRange;
                const categorical_scale = scale instanceof categorical_scale_1.CategoricalScale;
                if (factor_range != categorical_scale) {
                    throw new Error(`'${range.type}' is incompatible '${scale.type}'`);
                }
                if (scale instanceof log_scale_1.LogScale && range instanceof data_range1d_1.DataRange1d) {
                    range.scale_hint = "log";
                }
                const base_scale = in_scales.get(name) ?? scale;
                const derived_scale = base_scale.clone();
                derived_scale.setv({ source_range: range, target_range: frame_range });
                scales.set(name, derived_scale);
            }
            return scales;
        }
        _configure_ranges() {
            // data to/from screen space transform (left-bottom <-> left-top origin)
            const { bbox } = this;
            this._x_target = new range1d_1.Range1d({ start: bbox.left, end: bbox.right });
            this._y_target = new range1d_1.Range1d({ start: bbox.bottom, end: bbox.top });
        }
        _configure_scales() {
            const { x_range, y_range, extra_x_ranges, extra_y_ranges } = this.model;
            const { x_scale, y_scale, extra_x_scales, extra_y_scales } = this.model;
            (0, assert_1.assert)(x_scale.properties.source_range.is_unset && x_scale.properties.target_range.is_unset);
            (0, assert_1.assert)(y_scale.properties.source_range.is_unset && y_scale.properties.target_range.is_unset);
            this._configure_ranges();
            this._unregister_frame();
            this._x_ranges = this._get_ranges(x_range, extra_x_ranges);
            this._y_ranges = this._get_ranges(y_range, extra_y_ranges);
            this._register_frame();
            this._x_scales = this._get_scales(x_scale, extra_x_scales, this._x_ranges, this._x_target);
            this._y_scales = this._get_scales(y_scale, extra_y_scales, this._y_ranges, this._y_target);
            this._x_scale = this._x_scales.get("default");
            this._y_scale = this._y_scales.get("default");
            this.mark_finished();
        }
        _update_scales() {
            this._configure_ranges();
            for (const [, scale] of this._x_scales) {
                scale.target_range = this._x_target;
            }
            for (const [, scale] of this._y_scales) {
                scale.target_range = this._y_target;
            }
        }
        _register_frame() {
            for (const range of this.ranges.values()) {
                range.frames.add(this);
            }
        }
        _unregister_frame() {
            for (const range of this.ranges.values()) {
                range.frames.delete(this);
            }
        }
        set_geometry(bbox) {
            super.set_geometry(bbox);
            this._update_scales();
        }
        get x_range() {
            return this.model.x_range;
        }
        get y_range() {
            return this.model.y_range;
        }
        get x_target() {
            return this._x_target;
        }
        get y_target() {
            return this._y_target;
        }
        get x_ranges() {
            return this._x_ranges;
        }
        get y_ranges() {
            return this._y_ranges;
        }
        get ranges() {
            return new Set([...this.x_ranges.values(), ...this.y_ranges.values()]);
        }
        get x_scales() {
            return this._x_scales;
        }
        get y_scales() {
            return this._y_scales;
        }
        get scales() {
            return new Set([...this.x_scales.values(), ...this.y_scales.values()]);
        }
        get x_scale() {
            return this._x_scale;
        }
        get y_scale() {
            return this._y_scale;
        }
    }
    exports.CartesianFrameView = CartesianFrameView;
    class CartesianFrame extends canvas_panel_1.CanvasPanel {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = CartesianFrameView;
            this.define(({ Bool, Float, Dict, Ref }) => ({
                x_range: [Ref(range_1.Range), () => new data_range1d_1.DataRange1d()],
                y_range: [Ref(range_1.Range), () => new data_range1d_1.DataRange1d()],
                x_scale: [Ref(scale_1.Scale), () => new linear_scale_1.LinearScale()],
                y_scale: [Ref(scale_1.Scale), () => new linear_scale_1.LinearScale()],
                extra_x_ranges: [Dict(Ref(range_1.Range)), {}],
                extra_y_ranges: [Dict(Ref(range_1.Range)), {}],
                extra_x_scales: [Dict(Ref(scale_1.Scale)), {}],
                extra_y_scales: [Dict(Ref(scale_1.Scale)), {}],
                match_aspect: [Bool, false],
                aspect_scale: [Float, 1],
            }));
        }
    }
    exports.CartesianFrame = CartesianFrame;
},
/* models/canvas/canvas_panel.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const styled_element_1 = require(56) /* ../ui/styled_element */;
    const dom_1 = require(61) /* ../../core/dom */;
    const bbox_1 = require(62) /* ../../core/util/bbox */;
    const enums_1 = require(21) /* ../../core/enums */;
    const kinds_1 = require(22) /* ../../core/kinds */;
    const types_1 = require(8) /* ../../core/util/types */;
    const css = tslib_1.__importStar(require(270) /* ../../styles/canvas_panel.css */);
    class CanvasPanelView extends styled_element_1.StyledElementView {
        _bbox = new bbox_1.BBox();
        get bbox() {
            return this._bbox;
        }
        position = new dom_1.InlineStyleSheet("", "position");
        stylesheets() {
            return [...super.stylesheets(), css.default, this.position];
        }
        rendering_target() {
            if (this.model.inner) {
                return this.parent.frame_view.shadow_el;
            }
            else {
                return this.parent.canvas_view.events_el;
            }
        }
        render() {
            super.render();
            this.class_list.add(css[this.model.place]);
        }
        set_geometry(bbox) {
            this._bbox = bbox;
            this._update_position();
            this.mark_finished();
        }
        /**
         * Updates the position of the associated DOM element.
         */
        _update_position() {
            const { bbox, position } = this;
            if (!bbox.is_valid) {
                position.replace(`
      :host {
        display: none;
      }
      `);
            }
        }
        // TODO remove this when bbox handling is unified
        resolve_symbol(node) {
            const target = this;
            const value = target.bbox.resolve(node.symbol);
            const { offset } = node;
            if ((0, types_1.isNumber)(value)) {
                return value + offset;
            }
            else {
                const { x, y } = value;
                return { x: x + offset, y: y + offset };
            }
        }
    }
    exports.CanvasPanelView = CanvasPanelView;
    class CanvasPanel extends styled_element_1.StyledElement {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = CanvasPanelView;
            this.define({
                place: [enums_1.Place],
                inner: [kinds_1.Bool, false],
            });
        }
    }
    exports.CanvasPanel = CanvasPanel;
},
/* styles/canvas_panel.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.above = "bk-above";
    exports.below = "bk-below";
    exports.left = "bk-left";
    exports.right = "bk-right";
    exports.center = "bk-center";
    exports.default = `:host{position:relative;pointer-events:none;}:host{align-items:start;justify-items:start;}:host(.bk-above),:host(.bk-below){display:grid;grid-auto-flow:row;grid-template-rows:auto;grid-template-columns:100%;}:host(.bk-left),:host(.bk-right){display:grid;grid-auto-flow:column;grid-template-rows:100%;grid-template-columns:auto;}:host(.bk-above){grid-area:above;}:host(.bk-below){grid-area:below;}:host(.bk-left){grid-area:left;}:host(.bk-right){grid-area:right;}:host(.bk-center){grid-area:center;}:host(.bk-center){overflow:hidden;}`;
},
/* styles/cartesian_frame.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = `:host{display:grid;grid-template-areas:".    above  .    " "left center right" ".    below  .    ";grid-template-rows:max-content 1fr max-content;grid-template-columns:max-content 1fr max-content;}`;
},
/* models/axes/axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const guide_renderer_1 = require(273) /* ../renderers/guide_renderer */;
    const ticker_1 = require(274) /* ../tickers/ticker */;
    const tick_formatter_1 = require(275) /* ../formatters/tick_formatter */;
    const labeling_1 = require(276) /* ../policies/labeling */;
    const bokeh_events_1 = require(80) /* ../../core/bokeh_events */;
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    const enums_1 = require(21) /* ../../core/enums */;
    const types_1 = require(25) /* ../../core/types */;
    const side_panel_1 = require(257) /* ../../core/layout/side_panel */;
    const array_1 = require(10) /* ../../core/util/array */;
    const object_1 = require(9) /* ../../core/util/object */;
    const types_2 = require(8) /* ../../core/util/types */;
    const graphics_1 = require(262) /* ../../core/graphics */;
    const factor_range_1 = require(121) /* ../ranges/factor_range */;
    const base_text_1 = require(258) /* ../text/base_text */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const logging_1 = require(11) /* ../../core/logging */;
    const types_3 = require(8) /* ../../core/util/types */;
    const bbox_1 = require(62) /* ../../core/util/bbox */;
    const utils_1 = require(259) /* ../text/utils */;
    const kinds_1 = require(22) /* ../../core/kinds */;
    exports.LabelOverrides = (0, kinds_1.Or)((0, kinds_1.Dict)((0, kinds_1.Or)(kinds_1.Str, (0, kinds_1.Ref)(base_text_1.BaseText))), (0, kinds_1.Mapping)((0, kinds_1.Or)(kinds_1.Str, kinds_1.Float), (0, kinds_1.Or)(kinds_1.Str, (0, kinds_1.Ref)(base_text_1.BaseText))));
    const { abs } = Math;
    class AxisView extends guide_renderer_1.GuideRendererView {
        get panel() {
            return this._panel;
        }
        set panel(panel) {
            this._panel = new side_panel_1.SidePanel(panel.side, this.model.face);
        }
        /*private*/ _axis_label_view = null;
        /*private*/ _major_label_views = new Map();
        get bbox() {
            if (this.model.fixed_location != null) {
                return new bbox_1.BBox();
            }
            else if (this.layout != null) {
                return this.layout.bbox;
            }
            else if (this.is_renderable) {
                const { extents } = this;
                const depth = Math.round(extents.tick + extents.tick_label + extents.axis_label);
                let { sx0, sy0, sx1, sy1 } = this.rule_scoords;
                const { dimension, face } = this;
                if (dimension == 0) {
                    if (face == "front") {
                        sy0 -= depth;
                    }
                    else {
                        sy1 += depth;
                    }
                }
                else {
                    if (face == "front") {
                        sx0 -= depth;
                    }
                    else {
                        sx1 += depth;
                    }
                }
                return bbox_1.BBox.from_lrtb({ left: sx0, top: sy0, right: sx1, bottom: sy1 });
            }
            else {
                return new bbox_1.BBox();
            }
        }
        children_views() {
            return [...super.children_views(), this._axis_label_view, ...this._major_label_views.values()];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._init_axis_label();
            await this._init_major_labels();
        }
        async _init_axis_label() {
            const { axis_label } = this.model;
            if (axis_label != null) {
                const _axis_label = (0, types_3.isString)(axis_label) ? (0, utils_1.parse_delimited_string)(axis_label) : axis_label;
                this._axis_label_view = await (0, build_views_1.build_view)(_axis_label, { parent: this });
            }
            else {
                this._axis_label_view = null;
            }
        }
        async _init_major_labels() {
            for (const [label, label_text] of (0, object_1.dict)(this.model.major_label_overrides)) {
                const _label_text = (0, types_3.isString)(label_text) ? (0, utils_1.parse_delimited_string)(label_text) : label_text;
                this._major_label_views.set(label, await (0, build_views_1.build_view)(_label_text, { parent: this }));
            }
        }
        update_layout() {
            this.layout = new side_panel_1.SideLayout(this.panel, () => this.get_size(), true);
            this.layout.on_resize(() => {
                this._coordinates = undefined;
            });
        }
        get_size() {
            const { visible, fixed_location } = this.model;
            if (visible && fixed_location == null && this.is_renderable) {
                const { extents } = this;
                const height = Math.round(extents.tick + extents.tick_label + extents.axis_label);
                return { width: 0, height };
            }
            else {
                return { width: 0, height: 0 };
            }
        }
        get is_renderable() {
            const [range, cross_range] = this.ranges;
            return super.is_renderable && range.is_valid && cross_range.is_valid && range.span > 0 && cross_range.span > 0 && !isNaN(this.loc);
        }
        interactive_hit(sx, sy) {
            return this.bbox.contains(sx, sy);
        }
        on_hit(sx, sy) {
            const value = this._hit_value(sx, sy);
            if (value != null) {
                this.model.trigger_event(new bokeh_events_1.AxisClick(this.model, value));
                return true;
            }
            return false;
        }
        _paint(ctx) {
            const { tick_coords, extents } = this;
            this._draw_background(ctx, extents);
            this._draw_rule(ctx, extents);
            this._draw_major_ticks(ctx, extents, tick_coords);
            this._draw_minor_ticks(ctx, extents, tick_coords);
            this._draw_major_labels(ctx, extents, tick_coords);
            this._draw_axis_label(ctx, extents, tick_coords);
        }
        connect_signals() {
            super.connect_signals();
            const { axis_label, major_label_overrides } = this.model.properties;
            this.on_change(axis_label, async () => {
                this._axis_label_view?.remove();
                await this._init_axis_label();
            });
            this.on_change(major_label_overrides, async () => {
                for (const label_view of this._major_label_views.values()) {
                    label_view.remove();
                }
                await this._init_major_labels();
            });
            this.connect(this.model.change, () => this.plot_view.request_layout());
            this.connect(this.model.ticker.change, () => this.plot_view.request_layout());
            this.connect(this.model.formatter.change, () => this.plot_view.request_layout());
        }
        get needs_clip() {
            return this.model.fixed_location != null;
        }
        // drawing sub functions -----------------------------------------------------
        _draw_background(ctx, _extents) {
            if (!this.visuals.background_fill.doit && !this.visuals.background_hatch.doit) {
                return;
            }
            ctx.beginPath();
            const { x, y, width, height } = this.bbox;
            ctx.rect(x, y, width, height);
            this.visuals.background_fill.apply(ctx);
            this.visuals.background_hatch.apply(ctx);
        }
        _draw_rule(ctx, _extents) {
            if (!this.visuals.axis_line.doit) {
                return;
            }
            const { sx0, sy0, sx1, sy1 } = this.rule_scoords;
            ctx.beginPath();
            ctx.moveTo(sx0, sy0);
            ctx.lineTo(sx1, sy1);
            this.visuals.axis_line.apply(ctx);
        }
        _draw_major_ticks(ctx, _extents, tick_coords) {
            const tin = this.model.major_tick_in;
            const tout = this.model.major_tick_out;
            const visuals = this.visuals.major_tick_line;
            this._draw_ticks(ctx, tick_coords.major, tin, tout, visuals);
        }
        _draw_minor_ticks(ctx, _extents, tick_coords) {
            const tin = this.model.minor_tick_in;
            const tout = this.model.minor_tick_out;
            const visuals = this.visuals.minor_tick_line;
            this._draw_ticks(ctx, tick_coords.minor, tin, tout, visuals);
        }
        _draw_major_labels(ctx, extents, tick_coords) {
            const coords = tick_coords.major;
            const labels = this.compute_labels(coords[this.dimension]);
            const orient = this.model.major_label_orientation;
            const standoff = extents.tick + this.model.major_label_standoff;
            const visuals = this.visuals.major_label_text;
            this._draw_oriented_labels(ctx, labels, coords, orient, standoff, visuals);
        }
        _axis_label_extent() {
            if (this._axis_label_view == null) {
                return 0;
            }
            const axis_label_graphics = this._axis_label_view.graphics();
            const padding = 3;
            const orient = this.model.axis_label_orientation;
            axis_label_graphics.visuals = this.visuals.axis_label_text.values();
            axis_label_graphics.angle = this.panel.get_label_angle_heuristic(orient);
            axis_label_graphics.base_font_size = this.plot_view.base_font_size;
            const size = axis_label_graphics.size();
            const extent = this.dimension == 0 ? size.height : size.width;
            const standoff_offset = (() => {
                switch (this.model.axis_label_standoff_mode) {
                    case "tick_labels":
                        return 0;
                    case "axis":
                        return (0, array_1.sum)(this._tick_label_extents()) + this._tick_extent();
                }
            })();
            const standoff = this.model.axis_label_standoff - standoff_offset;
            return extent > 0 ? standoff + extent + padding : 0;
        }
        _draw_axis_label(ctx, extents, _tick_coords) {
            if (this._axis_label_view == null) {
                return;
            }
            const [sx, sy /* TODO, x_anchor, y_anchor*/] = (() => {
                const { bbox } = this;
                const { side, face } = this.panel;
                const [range] = this.ranges;
                const { axis_label_align } = this.model;
                switch (side) {
                    case "above":
                    case "below": {
                        const [sx, x_anchor] = (() => {
                            switch (axis_label_align) {
                                case "start": return !range.is_reversed ? [bbox.left, "left"] : [bbox.right, "right"];
                                case "center": return [bbox.hcenter, "center"];
                                case "end": return !range.is_reversed ? [bbox.right, "right"] : [bbox.left, "left"];
                            }
                        })();
                        const [sy, y_anchor] = face == "front" ? [bbox.bottom, "bottom"] : [bbox.top, "top"];
                        return [sx, sy, x_anchor, y_anchor];
                    }
                    case "left":
                    case "right": {
                        const [sy, y_anchor] = (() => {
                            switch (axis_label_align) {
                                case "start": return !range.is_reversed ? [bbox.bottom, "bottom"] : [bbox.top, "top"];
                                case "center": return [bbox.vcenter, "center"];
                                case "end": return !range.is_reversed ? [bbox.top, "top"] : [bbox.bottom, "bottom"];
                            }
                        })();
                        const [sx, x_anchor] = face == "front" ? [bbox.right, "right"] : [bbox.left, "left"];
                        return [sx, sy, x_anchor, y_anchor];
                    }
                }
            })();
            const [nx, ny] = this.normals;
            const orient = this.model.axis_label_orientation;
            const standoff_mode = this.model.axis_label_standoff_mode;
            const standoff_offset = (() => {
                switch (standoff_mode) {
                    case "tick_labels":
                        return extents.tick + extents.tick_label;
                    case "axis":
                        return 0;
                }
            })();
            const standoff = this.model.axis_label_standoff + standoff_offset;
            const { vertical_align, align } = this.panel.get_label_text_heuristics(orient);
            const position = {
                sx: sx + nx * standoff,
                sy: sy + ny * standoff,
                x_anchor: align,
                y_anchor: vertical_align,
            };
            const axis_label_graphics = this._axis_label_view.graphics();
            axis_label_graphics.visuals = this.visuals.axis_label_text.values();
            axis_label_graphics.angle = this.panel.get_label_angle_heuristic(orient);
            axis_label_graphics.base_font_size = this.plot_view.base_font_size;
            axis_label_graphics.position = position;
            axis_label_graphics.align = align;
            axis_label_graphics.paint(ctx);
        }
        _draw_ticks(ctx, coords, tin, tout, visuals) {
            if (!visuals.doit) {
                return;
            }
            const [sxs, sys] = this.scoords(coords);
            const [nx, ny] = this.normals;
            const [nxin, nyin] = [nx * -tin, ny * -tin];
            const [nxout, nyout] = [nx * tout, ny * tout];
            visuals.set_value(ctx);
            ctx.beginPath();
            for (let i = 0; i < sxs.length; i++) {
                const sx0 = Math.round(sxs[i] + nxout);
                const sy0 = Math.round(sys[i] + nyout);
                const sx1 = Math.round(sxs[i] + nxin);
                const sy1 = Math.round(sys[i] + nyin);
                ctx.moveTo(sx0, sy0);
                ctx.lineTo(sx1, sy1);
            }
            ctx.stroke();
        }
        _draw_oriented_labels(ctx, labels, coords, orient, standoff, visuals) {
            if (!visuals.doit || labels.length == 0) {
                return;
            }
            const [sxs, sys] = this.scoords(coords);
            const [nx, ny] = this.normals;
            const nxd = nx * standoff;
            const nyd = ny * standoff;
            const { vertical_align, align } = this.panel.get_label_text_heuristics(orient);
            const angle = this.panel.get_label_angle_heuristic(orient);
            labels.visuals = visuals.values();
            labels.angle = angle;
            labels.base_font_size = this.plot_view.base_font_size;
            for (let i = 0; i < labels.length; i++) {
                const label = labels.items[i];
                label.position = {
                    sx: sxs[i] + nxd,
                    sy: sys[i] + nyd,
                    x_anchor: align,
                    y_anchor: vertical_align,
                };
                if (label instanceof graphics_1.TextBox) {
                    label.align = align;
                }
            }
            const n = labels.length;
            const indices = types_1.Indices.all_set(n);
            const { items } = labels;
            const bboxes = items.map((l) => l.bbox());
            const dist = (() => {
                const [range] = this.ranges;
                if (!range.is_reversed) {
                    return this.dimension == 0 ? (i, j) => bboxes[j].left - bboxes[i].right
                        : (i, j) => bboxes[i].top - bboxes[j].bottom;
                }
                else {
                    return this.dimension == 0 ? (i, j) => bboxes[i].left - bboxes[j].right
                        : (i, j) => bboxes[j].top - bboxes[i].bottom;
                }
            })();
            const { major_label_policy } = this.model;
            const selected = major_label_policy.filter(indices, bboxes, dist);
            const ids = [...selected];
            if (ids.length != 0) {
                const cbox = this.canvas.bbox;
                const correct_x = (k) => {
                    const bbox = bboxes[k];
                    if (bbox.left < 0) {
                        const offset = -bbox.left;
                        const { position } = items[k];
                        items[k].position = { ...position, sx: position.sx + offset };
                    }
                    else if (bbox.right > cbox.width) {
                        const offset = bbox.right - cbox.width;
                        const { position } = items[k];
                        items[k].position = { ...position, sx: position.sx - offset };
                    }
                };
                const correct_y = (k) => {
                    const bbox = bboxes[k];
                    if (bbox.top < 0) {
                        const offset = -bbox.top;
                        const { position } = items[k];
                        items[k].position = { ...position, sy: position.sy + offset };
                    }
                    else if (bbox.bottom > cbox.height) {
                        const offset = bbox.bottom - cbox.height;
                        const { position } = items[k];
                        items[k].position = { ...position, sy: position.sy - offset };
                    }
                };
                const i = ids[0];
                const j = ids[ids.length - 1];
                if (this.dimension == 0) {
                    correct_x(i);
                    correct_x(j);
                }
                else {
                    correct_y(i);
                    correct_y(j);
                }
            }
            for (const i of selected) {
                const label = items[i];
                label.paint(ctx);
            }
        }
        // extents sub functions -----------------------------------------------------
        /*protected*/ _tick_extent() {
            const { major, minor } = this.tick_coords;
            const i = this.dimension;
            return Math.max(major[i].length == 0 ? 0 : this.model.major_tick_out, minor[i].length == 0 ? 0 : this.model.minor_tick_out);
        }
        _tick_label_extents() {
            const coords = this.tick_coords.major;
            const labels = this.compute_labels(coords[this.dimension]);
            const orient = this.model.major_label_orientation;
            const standoff = this.model.major_label_standoff;
            const visuals = this.visuals.major_label_text;
            return [this._oriented_labels_extent(labels, orient, standoff, visuals)];
        }
        get extents() {
            const tick_labels = this._tick_label_extents();
            return {
                tick: this._tick_extent(),
                tick_labels,
                tick_label: (0, array_1.sum)(tick_labels),
                axis_label: this._axis_label_extent(),
            };
        }
        _oriented_labels_extent(labels, orient, standoff, visuals) {
            if (labels.length == 0 || !visuals.doit) {
                return 0;
            }
            const angle = this.panel.get_label_angle_heuristic(orient);
            labels.visuals = visuals.values();
            labels.angle = angle;
            labels.base_font_size = this.plot_view.base_font_size;
            const size = labels.max_size();
            const extent = this.dimension == 0 ? size.height : size.width;
            const padding = 3;
            return extent > 0 ? standoff + extent + padding : 0;
        }
        // {{{ TODO: state
        get normals() {
            return this.panel.normals;
        }
        get dimension() {
            return this.panel.dimension;
        }
        compute_labels(ticks) {
            const labels = this.model.formatter.format_graphics(ticks, this);
            const { _major_label_views } = this;
            const visited = new Set();
            for (let i = 0; i < ticks.length; i++) {
                const override = _major_label_views.get(ticks[i]);
                if (override != null) {
                    visited.add(override);
                    labels[i] = override.graphics();
                }
            }
            // XXX: make sure unused overrides don't prevent document idle
            for (const label_view of this._major_label_views.values()) {
                if (!visited.has(label_view)) {
                    label_view._has_finished = true;
                }
            }
            return new graphics_1.GraphicsBoxes(labels);
        }
        scoords(coords) {
            /**
             * Compute screen coordinates with respect to the bbox.
             */
            const [x, y] = coords;
            const [sxs, sys] = this.coordinates.map_to_screen(x, y);
            if (this.model.fixed_location != null) {
                return [[...sxs], [...sys]];
            }
            else {
                const { bbox } = this;
                const { face } = this.panel;
                if (this.panel.is_vertical) {
                    const sx = face == "front" ? bbox.right : bbox.left;
                    return [(0, array_1.repeat)(sx, sxs.length), [...sys]];
                }
                else {
                    const sy = face == "front" ? bbox.bottom : bbox.top;
                    return [[...sxs], (0, array_1.repeat)(sy, sys.length)];
                }
            }
        }
        get ranges() {
            const i = this.dimension;
            const j = 1 - i;
            const { ranges } = this.coordinates;
            return [ranges[i], ranges[j]];
        }
        get computed_bounds() {
            const [range] = this.ranges;
            const user_bounds = this.model.bounds;
            const range_bounds = [range.min, range.max];
            if (user_bounds == "auto") {
                return [range.min, range.max];
            }
            else {
                let start;
                let end;
                const [user_start, user_end] = user_bounds;
                const [range_start, range_end] = range_bounds;
                const { min, max } = Math;
                if (abs(user_start - user_end) > abs(range_start - range_end)) {
                    start = max(min(user_start, user_end), range_start);
                    end = min(max(user_start, user_end), range_end);
                }
                else {
                    start = min(user_start, user_end);
                    end = max(user_start, user_end);
                }
                return [start, end];
            }
        }
        get rule_coords() {
            const i = this.dimension;
            const j = 1 - i;
            const [range] = this.ranges;
            const [start, end] = this.computed_bounds;
            const xs = new Array(2);
            const ys = new Array(2);
            const coords = [xs, ys];
            coords[i][0] = Math.max(start, range.min);
            coords[i][1] = Math.min(end, range.max);
            if (coords[i][0] > coords[i][1]) {
                coords[i][0] = coords[i][1] = NaN;
            }
            coords[j][0] = this.loc;
            coords[j][1] = this.loc;
            return coords;
        }
        get rule_scoords() {
            const [[sx0, sx1], [sy0, sy1]] = this.scoords(this.rule_coords);
            return {
                sx0: Math.round(sx0),
                sy0: Math.round(sy0),
                sx1: Math.round(sx1),
                sy1: Math.round(sy1),
            };
        }
        get tick_coords() {
            const i = this.dimension;
            const j = 1 - i;
            const [range] = this.ranges;
            const [start, end] = this.computed_bounds;
            const ticks = this.model.ticker.get_ticks(start, end, range, this.loc);
            const majors = ticks.major;
            const minors = ticks.minor;
            const xs = [];
            const ys = [];
            const coords = [xs, ys];
            const minor_xs = [];
            const minor_ys = [];
            const minor_coords = [minor_xs, minor_ys];
            const [range_min, range_max] = [range.min, range.max];
            for (let ii = 0; ii < majors.length; ii++) {
                if (majors[ii] < range_min || majors[ii] > range_max) {
                    continue;
                }
                coords[i].push(majors[ii]);
                coords[j].push(this.loc);
            }
            for (let ii = 0; ii < minors.length; ii++) {
                if (minors[ii] < range_min || minors[ii] > range_max) {
                    continue;
                }
                minor_coords[i].push(minors[ii]);
                minor_coords[j].push(this.loc);
            }
            return {
                major: coords,
                minor: minor_coords,
            };
        }
        _warned_bad_loc = false;
        get loc() {
            const { fixed_location } = this.model;
            if (fixed_location != null) {
                if ((0, types_2.isNumber)(fixed_location)) {
                    return fixed_location;
                }
                const [, cross_range] = this.ranges;
                if (cross_range instanceof factor_range_1.FactorRange) {
                    return cross_range.synthetic(fixed_location);
                }
                if (!this._warned_bad_loc) {
                    this._warned_bad_loc = true;
                    logging_1.logger.warn("cannot determine location of axis based on its fixed_location");
                }
                return NaN;
            }
            const [, cross_range] = this.ranges;
            switch (this.panel.side) {
                case "left":
                case "below":
                    return cross_range.start;
                case "right":
                case "above":
                    return cross_range.end;
            }
        }
        get face() {
            return this.panel.face;
        }
        // }}}
        has_finished() {
            if (!super.has_finished()) {
                return false;
            }
            if (this._axis_label_view != null) {
                if (!this._axis_label_view.has_finished()) {
                    return false;
                }
            }
            for (const label_view of this._major_label_views.values()) {
                if (!label_view.has_finished()) {
                    return false;
                }
            }
            return true;
        }
    }
    exports.AxisView = AxisView;
    class Axis extends guide_renderer_1.GuideRenderer {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.mixins([
                ["axis_", mixins.Line],
                ["major_tick_", mixins.Line],
                ["minor_tick_", mixins.Line],
                ["major_label_", mixins.Text],
                ["axis_label_", mixins.Text],
                ["background_", mixins.Fill],
                ["background_", mixins.Hatch],
            ]);
            this.define(({ Any, Int, Float, Str, Ref, Tuple, Or, Nullable, Auto, Enum }) => ({
                dimension: [Or(Enum(0, 1), Auto), "auto"],
                face: [Or(enums_1.Face, Auto), "auto"],
                bounds: [Or(Tuple(Float, Float), Auto), "auto"],
                ticker: [Ref(ticker_1.Ticker)],
                formatter: [Ref(tick_formatter_1.TickFormatter)],
                axis_label: [Nullable(Or(Str, Ref(base_text_1.BaseText))), null],
                axis_label_standoff: [Int, 5],
                axis_label_standoff_mode: [enums_1.AxisLabelStandoffMode, "tick_labels"],
                axis_label_orientation: [Or(enums_1.LabelOrientation, Float), "parallel"],
                axis_label_align: [enums_1.Align, "center"],
                major_label_standoff: [Int, 5],
                major_label_orientation: [Or(enums_1.LabelOrientation, Float), "horizontal"],
                major_label_overrides: [exports.LabelOverrides, new Map()],
                major_label_policy: [Ref(labeling_1.LabelingPolicy), () => new labeling_1.AllLabels()],
                major_tick_in: [Float, 2],
                major_tick_out: [Float, 6],
                minor_tick_in: [Float, 0],
                minor_tick_out: [Float, 4],
                fixed_location: [Nullable(Or(Float, Any)), null],
            }));
            this.override({
                axis_line_color: "black",
                major_tick_line_color: "black",
                minor_tick_line_color: "black",
                major_label_text_font_size: "11px",
                major_label_text_align: "center", // XXX: remove
                major_label_text_baseline: "alphabetic", // XXX: remove
                axis_label_text_font_size: "13px",
                axis_label_text_font_style: "italic",
                background_fill_color: null,
            });
        }
    }
    exports.Axis = Axis;
},
/* models/renderers/guide_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const renderer_1 = require(98) /* ./renderer */;
    class GuideRendererView extends renderer_1.RendererView {
    }
    exports.GuideRendererView = GuideRendererView;
    class GuideRenderer extends renderer_1.Renderer {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.override({
                level: "guide",
            });
        }
    }
    exports.GuideRenderer = GuideRenderer;
},
/* models/tickers/ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    class Ticker extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Ticker = Ticker;
},
/* models/formatters/tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    const graphics_1 = require(262) /* ../../core/graphics */;
    class TickFormatter extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        format_graphics(ticks, opts) {
            return this.doFormat(ticks, opts).map((text) => new graphics_1.TextBox({ text }));
        }
        compute(tick, opts) {
            return this.doFormat([tick], opts ?? { loc: 0 })[0];
        }
        v_compute(tick, opts) {
            return this.doFormat(tick, opts ?? { loc: 0 });
        }
    }
    exports.TickFormatter = TickFormatter;
},
/* models/policies/labeling.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    const object_1 = require(9) /* ../../core/util/object */;
    const string_1 = require(41) /* ../../core/util/string */;
    const types_1 = require(8) /* ../../core/util/types */;
    const types_2 = require(25) /* ../../core/types */;
    class LabelingPolicy extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.LabelingPolicy = LabelingPolicy;
    class AllLabels extends LabelingPolicy {
        constructor(attrs) {
            super(attrs);
        }
        filter(indices, _bboxes, _distance) {
            return indices;
        }
    }
    exports.AllLabels = AllLabels;
    class NoOverlap extends LabelingPolicy {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Float }) => ({
                min_distance: [Float, 5],
            }));
        }
        filter(indices, _bboxes, distance) {
            const { min_distance } = this;
            let k = null;
            for (const i of indices) {
                if (k != null && distance(k, i) < min_distance) {
                    indices.unset(i);
                }
                else {
                    k = i;
                }
            }
            return indices;
        }
    }
    exports.NoOverlap = NoOverlap;
    class CustomLabelingPolicy extends LabelingPolicy {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Unknown, Str, Dict }) => ({
                args: [Dict(Unknown), {}],
                code: [Str, ""],
            }));
        }
        get names() {
            return (0, object_1.keys)(this.args);
        }
        get values() {
            return (0, object_1.values)(this.args);
        }
        get func() {
            const code = (0, string_1.use_strict)(this.code);
            return new types_2.GeneratorFunction("indices", "bboxes", "distance", ...this.names, code);
        }
        filter(indices, bboxes, distance) {
            const obj = Object.create(null);
            const generator = this.func.call(obj, indices, bboxes, distance, ...this.values);
            let result = generator.next();
            if ((result.done ?? false) && result.value !== undefined) {
                const { value } = result;
                if (value instanceof types_2.Indices) {
                    return value;
                }
                else if (value === undefined) {
                    return indices;
                }
                else if ((0, types_1.isIterable)(value)) {
                    return types_2.Indices.from_indices(indices.size, value);
                }
                else {
                    return types_2.Indices.all_unset(indices.size);
                }
            }
            else {
                const array = [];
                do {
                    array.push(result.value);
                    result = generator.next();
                } while (!(result.done ?? false));
                return types_2.Indices.from_indices(indices.size, array);
            }
        }
    }
    exports.CustomLabelingPolicy = CustomLabelingPolicy;
},
/* models/axes/linear_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_axis_1 = require(278) /* ./continuous_axis */;
    const basic_tick_formatter_1 = require(279) /* ../formatters/basic_tick_formatter */;
    const basic_ticker_1 = require(280) /* ../tickers/basic_ticker */;
    class LinearAxisView extends continuous_axis_1.ContinuousAxisView {
    }
    exports.LinearAxisView = LinearAxisView;
    class LinearAxis extends continuous_axis_1.ContinuousAxis {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = LinearAxisView;
            this.override({
                ticker: () => new basic_ticker_1.BasicTicker(),
                formatter: () => new basic_tick_formatter_1.BasicTickFormatter(),
            });
        }
    }
    exports.LinearAxis = LinearAxis;
},
/* models/axes/continuous_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const axis_1 = require(272) /* ./axis */;
    class ContinuousAxisView extends axis_1.AxisView {
        _hit_value(sx, sy) {
            const [range] = this.ranges;
            const { start, end, span } = range;
            switch (this.dimension) {
                case 0: {
                    const { x0, width } = this.bbox;
                    return span * (sx - x0) / width + start;
                }
                case 1: {
                    const { y0, height } = this.bbox;
                    return end - span * (sy - y0) / height;
                }
            }
        }
    }
    exports.ContinuousAxisView = ContinuousAxisView;
    class ContinuousAxis extends axis_1.Axis {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ContinuousAxis = ContinuousAxis;
},
/* models/formatters/basic_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.unicode_replace = unicode_replace;
    const tick_formatter_1 = require(275) /* ./tick_formatter */;
    const string_1 = require(41) /* ../../core/util/string */;
    function unicode_replace(input) {
        let output = "";
        for (const c of input) {
            if (c == "-") {
                output += "\u2212";
            }
            else {
                output += c;
            }
        }
        return output;
    }
    class BasicTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Bool, Int, Auto, Or }) => ({
                precision: [Or(Int, Auto), "auto"],
                use_scientific: [Bool, true],
                power_limit_high: [Int, 5],
                power_limit_low: [Int, -3],
            }));
        }
        get scientific_limit_low() {
            return 10.0 ** this.power_limit_low;
        }
        get scientific_limit_high() {
            return 10.0 ** this.power_limit_high;
        }
        _need_sci(ticks) {
            if (!this.use_scientific) {
                return false;
            }
            const { scientific_limit_high } = this;
            const { scientific_limit_low } = this;
            const zeroish = ticks.length < 2 ? 0 : Math.abs(ticks[1] - ticks[0]) / 10000;
            for (const tick of ticks) {
                const tick_abs = Math.abs(tick);
                if (tick_abs <= zeroish) {
                    continue;
                }
                if (tick_abs >= scientific_limit_high || tick_abs <= scientific_limit_low) {
                    return true;
                }
            }
            return false;
        }
        _format_with_precision(ticks, need_sci, precision) {
            if (need_sci) {
                return ticks.map((tick) => unicode_replace(tick.toExponential(precision)));
            }
            else {
                return ticks.map((tick) => unicode_replace((0, string_1.to_fixed)(tick, precision)));
            }
        }
        _auto_precision(ticks, need_sci) {
            const labels = new Array(ticks.length);
            let last_precision = 3;
            const asc = last_precision <= 15;
            outer: for (let x = last_precision; asc ? x <= 15 : x >= 1; asc ? x++ : x--) {
                if (need_sci) {
                    labels[0] = ticks[0].toExponential(x);
                    for (let i = 1; i < ticks.length; i++) {
                        labels[i] = ticks[i].toExponential(x);
                        if (labels[i] == labels[i - 1]) {
                            continue outer;
                        }
                    }
                    last_precision = x;
                    break;
                }
                else {
                    labels[0] = (0, string_1.to_fixed)(ticks[0], x);
                    for (let i = 1; i < ticks.length; i++) {
                        labels[i] = (0, string_1.to_fixed)(ticks[i], x);
                        if (labels[i] == labels[i - 1]) {
                            continue outer;
                        }
                    }
                    last_precision = x;
                    break;
                }
            }
            return last_precision;
        }
        doFormat(ticks, _opts) {
            if (ticks.length == 0) {
                return [];
            }
            const need_sci = this._need_sci(ticks);
            const precision = this.precision == "auto" ? this._auto_precision(ticks, need_sci) : this.precision;
            return this._format_with_precision(ticks, need_sci, precision);
        }
    }
    exports.BasicTickFormatter = BasicTickFormatter;
},
/* models/tickers/basic_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const adaptive_ticker_1 = require(281) /* ./adaptive_ticker */;
    class BasicTicker extends adaptive_ticker_1.AdaptiveTicker {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.BasicTicker = BasicTicker;
},
/* models/tickers/adaptive_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_ticker_1 = require(282) /* ./continuous_ticker */;
    const array_1 = require(10) /* ../../core/util/array */;
    const math_1 = require(12) /* ../../core/util/math */;
    class AdaptiveTicker extends continuous_ticker_1.ContinuousTicker {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Float, List, Nullable }) => ({
                base: [Float, 10.0],
                mantissas: [List(Float), [1, 2, 5]],
                min_interval: [Float, 0.0],
                max_interval: [Nullable(Float), null],
            }));
        }
        get_min_interval() {
            return this.min_interval;
        }
        get_max_interval() {
            return this.max_interval ?? Infinity;
        }
        // These arguments control the range of possible intervals. The interval I
        // returned by get_interval() will be the one that most closely matches the
        // desired number of ticks, subject to the following constraints:
        // I = (M * B^N), where
        // M is a member of mantissas,
        // B is base,
        // and N is an integer;
        // and min_interval <= I <= max_interval.
        get extended_mantissas() {
            const prefix_mantissa = (0, array_1.nth)(this.mantissas, -1) / this.base;
            const suffix_mantissa = (0, array_1.nth)(this.mantissas, 0) * this.base;
            return [prefix_mantissa, ...this.mantissas, suffix_mantissa];
        }
        get base_factor() {
            return this.get_min_interval() == 0.0 ? 1.0 : this.get_min_interval();
        }
        get_interval(data_low, data_high, desired_n_ticks) {
            const data_range = data_high - data_low;
            const ideal_interval = this.get_ideal_interval(data_low, data_high, desired_n_ticks);
            const interval_exponent = Math.floor((0, math_1.log)(ideal_interval / this.base_factor, this.base));
            const ideal_magnitude = this.base ** interval_exponent * this.base_factor;
            // An untested optimization.
            //   const ideal_mantissa = ideal_interval / ideal_magnitude
            //   index = sorted_index(this.extended_mantissas, ideal_mantissa)
            //   candidate_mantissas = this.extended_mantissas[index..index + 1]
            const candidate_mantissas = this.extended_mantissas;
            const errors = candidate_mantissas.map((mantissa) => {
                return Math.abs(desired_n_ticks - (data_range / (mantissa * ideal_magnitude)));
            });
            const best_mantissa = candidate_mantissas[(0, array_1.argmin)(errors)];
            const interval = best_mantissa * ideal_magnitude;
            return (0, math_1.clamp)(interval, this.get_min_interval(), this.get_max_interval());
        }
    }
    exports.AdaptiveTicker = AdaptiveTicker;
},
/* models/tickers/continuous_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const ticker_1 = require(274) /* ./ticker */;
    const array_1 = require(10) /* ../../core/util/array */;
    const logging_1 = require(11) /* ../../core/logging */;
    class ContinuousTicker extends ticker_1.Ticker {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Int, NonNegative }) => ({
                num_minor_ticks: [NonNegative(Int), 5],
                desired_num_ticks: [NonNegative(Int), 6],
            }));
        }
        get_ticks(data_low, data_high, _range, cross_loc) {
            try {
                return this.get_ticks_no_defaults(data_low, data_high, cross_loc, this.desired_num_ticks, this.num_minor_ticks);
            }
            catch (error) {
                logging_1.logger.warn(`Caught an error calculating the ticks for ${this.desired_num_ticks} desired_num_ticks`, `and ${this.num_minor_ticks} num_minor_ticks. The default values are used instead.`);
                this.desired_num_ticks = 6;
                this.num_minor_ticks = 5;
                return this.get_ticks_no_defaults(data_low, data_high, cross_loc, this.desired_num_ticks, this.num_minor_ticks);
            }
        }
        // The version of get_ticks() that does the work (and the version that
        // should be overridden in subclasses).
        get_ticks_no_defaults(data_low, data_high, _cross_loc, desired_n_ticks, num_minor_ticks) {
            const interval = this.get_interval(data_low, data_high, desired_n_ticks);
            const start_factor = Math.floor(data_low / interval);
            const end_factor = Math.ceil(data_high / interval);
            let factors;
            if (!isFinite(start_factor) || !isFinite(end_factor)) {
                factors = [];
            }
            else {
                factors = (0, array_1.range)(start_factor, end_factor + 1);
            }
            const ticks = factors
                .map((factor) => factor * interval)
                .filter((tick) => data_low <= tick && tick <= data_high);
            const minor_ticks = [];
            if (num_minor_ticks > 0 && ticks.length > 0) {
                const minor_interval = interval / num_minor_ticks;
                const minor_offsets = (0, array_1.range)(0, num_minor_ticks).map((i) => i * minor_interval);
                for (const x of minor_offsets.slice(1)) {
                    const mt = ticks[0] - x;
                    if (data_low <= mt && mt <= data_high) {
                        minor_ticks.push(mt);
                    }
                }
                for (const tick of ticks) {
                    for (const x of minor_offsets) {
                        const mt = tick + x;
                        if (data_low <= mt && mt <= data_high) {
                            minor_ticks.push(mt);
                        }
                    }
                }
            }
            return {
                major: ticks,
                minor: minor_ticks,
            };
        }
        // Returns the interval size that would produce exactly the number of
        // desired ticks. (In general we won't use exactly this interval, because
        // we want the ticks to be round numbers.)
        get_ideal_interval(data_low, data_high, desired_n_ticks) {
            const data_range = data_high - data_low;
            return data_range / desired_n_ticks;
        }
    }
    exports.ContinuousTicker = ContinuousTicker;
},
/* models/tickers/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var adaptive_ticker_1 = require(281) /* ./adaptive_ticker */;
    __esExport("AdaptiveTicker", adaptive_ticker_1.AdaptiveTicker);
    var basic_ticker_1 = require(280) /* ./basic_ticker */;
    __esExport("BasicTicker", basic_ticker_1.BasicTicker);
    var categorical_ticker_1 = require(284) /* ./categorical_ticker */;
    __esExport("CategoricalTicker", categorical_ticker_1.CategoricalTicker);
    var composite_ticker_1 = require(285) /* ./composite_ticker */;
    __esExport("CompositeTicker", composite_ticker_1.CompositeTicker);
    var continuous_ticker_1 = require(282) /* ./continuous_ticker */;
    __esExport("ContinuousTicker", continuous_ticker_1.ContinuousTicker);
    var customjs_ticker_1 = require(286) /* ./customjs_ticker */;
    __esExport("CustomJSTicker", customjs_ticker_1.CustomJSTicker);
    var datetime_ticker_1 = require(287) /* ./datetime_ticker */;
    __esExport("DatetimeTicker", datetime_ticker_1.DatetimeTicker);
    var days_ticker_1 = require(288) /* ./days_ticker */;
    __esExport("DaysTicker", days_ticker_1.DaysTicker);
    var fixed_ticker_1 = require(293) /* ./fixed_ticker */;
    __esExport("FixedTicker", fixed_ticker_1.FixedTicker);
    var log_ticker_1 = require(294) /* ./log_ticker */;
    __esExport("LogTicker", log_ticker_1.LogTicker);
    var mercator_ticker_1 = require(295) /* ./mercator_ticker */;
    __esExport("MercatorTicker", mercator_ticker_1.MercatorTicker);
    var months_ticker_1 = require(291) /* ./months_ticker */;
    __esExport("MonthsTicker", months_ticker_1.MonthsTicker);
    var single_interval_ticker_1 = require(289) /* ./single_interval_ticker */;
    __esExport("SingleIntervalTicker", single_interval_ticker_1.SingleIntervalTicker);
    var ticker_1 = require(274) /* ./ticker */;
    __esExport("Ticker", ticker_1.Ticker);
    var timedelta_ticker_1 = require(296) /* ./timedelta_ticker */;
    __esExport("TimedeltaTicker", timedelta_ticker_1.TimedeltaTicker);
    var years_ticker_1 = require(292) /* ./years_ticker */;
    __esExport("YearsTicker", years_ticker_1.YearsTicker);
    var binned_ticker_1 = require(297) /* ./binned_ticker */;
    __esExport("BinnedTicker", binned_ticker_1.BinnedTicker);
},
/* models/tickers/categorical_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const ticker_1 = require(274) /* ./ticker */;
    class CategoricalTicker extends ticker_1.Ticker {
        constructor(attrs) {
            super(attrs);
        }
        get_ticks(start, end, range, _cross_loc) {
            const majors = this._collect(range.factors, range, start, end);
            const tops = this._collect(range.mapper.tops ?? [], range, start, end);
            const mids = this._collect(range.mapper.mids ?? [], range, start, end);
            return { major: majors, minor: [], tops, mids };
        }
        _collect(factors, range, start, end) {
            const result = [];
            for (const factor of factors) {
                const coord = range.synthetic(factor);
                if (coord > start && coord < end) {
                    result.push(factor);
                }
            }
            return result;
        }
    }
    exports.CategoricalTicker = CategoricalTicker;
},
/* models/tickers/composite_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_ticker_1 = require(282) /* ./continuous_ticker */;
    const array_1 = require(10) /* ../../core/util/array */;
    class CompositeTicker extends continuous_ticker_1.ContinuousTicker {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ NonEmptyList, Ref }) => ({
                tickers: [NonEmptyList(Ref(continuous_ticker_1.ContinuousTicker))],
            }));
        }
        // The tickers should be in order of increasing interval size; specifically,
        // if S comes before T, then it should be the case that
        // S.get_max_interval() < T.get_min_interval().
        // FIXME Enforce this automatically.
        get min_intervals() {
            return this.tickers.map((ticker) => ticker.get_min_interval());
        }
        get max_intervals() {
            return this.tickers.map((ticker) => ticker.get_max_interval());
        }
        get_min_interval() {
            return this.min_intervals[0];
        }
        get_max_interval() {
            return this.max_intervals[0];
        }
        get_best_ticker(data_low, data_high, desired_n_ticks) {
            const data_range = data_high - data_low;
            if (data_range == 0) {
                return this.tickers[0];
            }
            const ideal_interval = this.get_ideal_interval(data_low, data_high, desired_n_ticks);
            const ticker_ndxs = [
                (0, array_1.sorted_index)(this.min_intervals, ideal_interval) - 1,
                (0, array_1.sorted_index)(this.max_intervals, ideal_interval),
            ];
            const intervals = [
                this.min_intervals[ticker_ndxs[0]],
                this.max_intervals[ticker_ndxs[1]],
            ];
            const errors = intervals.map((interval) => {
                return Math.abs(desired_n_ticks - (data_range / interval));
            });
            let best_ticker;
            if ((0, array_1.is_empty)(errors.filter((e) => !isNaN(e)))) {
                // this can happen if the data isn't loaded yet, we just default to the first scale
                best_ticker = this.tickers[0];
            }
            else {
                const best_index = (0, array_1.argmin)(errors);
                const best_ticker_ndx = ticker_ndxs[best_index];
                best_ticker = this.tickers[best_ticker_ndx];
            }
            return best_ticker;
        }
        get_interval(data_low, data_high, desired_n_ticks) {
            const best_ticker = this.get_best_ticker(data_low, data_high, desired_n_ticks);
            return best_ticker.get_interval(data_low, data_high, desired_n_ticks);
        }
        get_ticks_no_defaults(data_low, data_high, cross_loc, desired_n_ticks, num_minor_ticks) {
            const best_ticker = this.get_best_ticker(data_low, data_high, desired_n_ticks);
            return best_ticker.get_ticks_no_defaults(data_low, data_high, cross_loc, desired_n_ticks, num_minor_ticks);
        }
    }
    exports.CompositeTicker = CompositeTicker;
},
/* models/tickers/customjs_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const ticker_1 = require(274) /* ./ticker */;
    const factor_range_1 = require(121) /* ../ranges/factor_range */;
    const object_1 = require(9) /* ../../core/util/object */;
    const string_1 = require(41) /* ../../core/util/string */;
    class CustomJSTicker extends ticker_1.Ticker {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Unknown, Str, Dict }) => ({
                args: [Dict(Unknown), {}],
                major_code: [Str, ""],
                minor_code: [Str, ""],
            }));
        }
        get names() {
            return (0, object_1.keys)(this.args);
        }
        get values() {
            return (0, object_1.values)(this.args);
        }
        get_ticks(start, end, range, cross_loc) {
            const major_cb_data = { start, end, range, cross_loc };
            const major_ticks = this.major_ticks(major_cb_data);
            // CustomJSTicker for categorical axes only support a single level of major ticks
            if (range instanceof factor_range_1.FactorRange) {
                return { major: major_ticks, minor: [], tops: [], mids: [] };
            }
            const minor_cb_data = { major_ticks, ...major_cb_data };
            const minor_ticks = this.minor_ticks(minor_cb_data);
            return {
                major: major_ticks,
                minor: minor_ticks,
            };
        }
        major_ticks(cb_data) {
            if (this.major_code == "") {
                return [];
            }
            const code = (0, string_1.use_strict)(this.major_code);
            const func = new Function("cb_data", ...this.names, code);
            return func(cb_data, ...this.values);
        }
        minor_ticks(cb_data) {
            if (this.minor_code == "") {
                return [];
            }
            const code = (0, string_1.use_strict)(this.minor_code);
            const func = new Function("cb_data", ...this.names, code);
            return func(cb_data, ...this.values);
        }
    }
    exports.CustomJSTicker = CustomJSTicker;
},
/* models/tickers/datetime_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const array_1 = require(10) /* ../../core/util/array */;
    const adaptive_ticker_1 = require(281) /* ./adaptive_ticker */;
    const composite_ticker_1 = require(285) /* ./composite_ticker */;
    const days_ticker_1 = require(288) /* ./days_ticker */;
    const months_ticker_1 = require(291) /* ./months_ticker */;
    const years_ticker_1 = require(292) /* ./years_ticker */;
    const util_1 = require(290) /* ./util */;
    class DatetimeTicker extends composite_ticker_1.CompositeTicker {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.override({
                num_minor_ticks: 0,
                tickers: () => [
                    // Sub-second.
                    new adaptive_ticker_1.AdaptiveTicker({
                        mantissas: [1, 2, 5],
                        base: 10,
                        min_interval: 0,
                        max_interval: 500 * util_1.ONE_MILLI,
                        num_minor_ticks: 0,
                    }),
                    // Seconds, minutes.
                    new adaptive_ticker_1.AdaptiveTicker({
                        mantissas: [1, 2, 5, 10, 15, 20, 30],
                        base: 60,
                        min_interval: util_1.ONE_SECOND,
                        max_interval: 30 * util_1.ONE_MINUTE,
                        num_minor_ticks: 0,
                    }),
                    // Hours.
                    new adaptive_ticker_1.AdaptiveTicker({
                        mantissas: [1, 2, 4, 6, 8, 12],
                        base: 24.0,
                        min_interval: util_1.ONE_HOUR,
                        max_interval: 12 * util_1.ONE_HOUR,
                        num_minor_ticks: 0,
                    }),
                    // Days.
                    new days_ticker_1.DaysTicker({ days: (0, array_1.range)(1, 32) }),
                    new days_ticker_1.DaysTicker({ days: (0, array_1.range)(1, 31, 3) }),
                    new days_ticker_1.DaysTicker({ days: [1, 8, 15, 22] }),
                    new days_ticker_1.DaysTicker({ days: [1, 15] }),
                    // Months.
                    new months_ticker_1.MonthsTicker({ months: (0, array_1.range)(0, 12, 1) }),
                    new months_ticker_1.MonthsTicker({ months: (0, array_1.range)(0, 12, 2) }),
                    new months_ticker_1.MonthsTicker({ months: (0, array_1.range)(0, 12, 4) }),
                    new months_ticker_1.MonthsTicker({ months: (0, array_1.range)(0, 12, 6) }),
                    // Years
                    new years_ticker_1.YearsTicker({}),
                ],
            });
        }
    }
    exports.DatetimeTicker = DatetimeTicker;
},
/* models/tickers/days_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const single_interval_ticker_1 = require(289) /* ./single_interval_ticker */;
    const util_1 = require(290) /* ./util */;
    const array_1 = require(10) /* ../../core/util/array */;
    // Given a start and end time in millis, returns the shortest array of
    // consecutive months (as Dates) that surrounds both times.
    function date_range_by_month(start_time, end_time) {
        const start_date = (0, util_1.last_month_no_later_than)(new Date(start_time));
        const end_date = (0, util_1.last_month_no_later_than)(new Date(end_time));
        // XXX This is not a reliable technique in general, but it should be
        // safe when the day of the month is 1.  (The problem case is this:
        // Mar 31 -> Apr 31, which becomes May 1.)
        end_date.setUTCMonth(end_date.getUTCMonth() + 1);
        const dates = [];
        const date = start_date;
        while (true) {
            dates.push((0, util_1.copy_date)(date));
            date.setUTCMonth(date.getUTCMonth() + 1);
            if (date > end_date) {
                break;
            }
        }
        return dates;
    }
    class DaysTicker extends single_interval_ticker_1.BaseSingleIntervalTicker {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Int, List }) => ({
                days: [List(Int), []],
            }));
            this.internal(({ Float }) => ({
                interval: [Float, (obj) => {
                        const { days } = obj;
                        return (days.length > 1 ? days[1] - days[0] : 31) * util_1.ONE_DAY;
                    }],
            }));
            this.override({
                num_minor_ticks: 0,
            });
        }
        get_ticks_no_defaults(data_low, data_high, _cross_loc, _desired_n_ticks) {
            const month_dates = date_range_by_month(data_low, data_high);
            const days = this.days;
            const days_of_month = (month_date, interval) => {
                const current_month = month_date.getUTCMonth();
                const dates = [];
                for (const day of days) {
                    const day_date = (0, util_1.copy_date)(month_date);
                    day_date.setUTCDate(day);
                    // We can't use all of the values in this.days, because they may not
                    // fall within the current month.  In fact, if, e.g., our month is 28 days
                    // and we're marking every third day, we don't want day 28 to show up
                    // because it'll be right next to the 1st of the next month.  So we
                    // make sure we have a bit of room before we include a day.
                    // TODO (bev) The above description does not exactly work because JS Date
                    // is broken and will happily consider "Feb 28 + 3*ONE_DAY" to have month "2"
                    const future_date = new Date(day_date.getTime() + (interval / 2));
                    if (future_date.getUTCMonth() == current_month) {
                        dates.push(day_date);
                    }
                }
                return dates;
            };
            const day_dates = (0, array_1.concat)(month_dates.map((date) => days_of_month(date, this.interval)));
            const all_ticks = day_dates.map((day_date) => day_date.getTime());
            const ticks_in_range = all_ticks.filter((tick) => data_low <= tick && tick <= data_high);
            return {
                major: ticks_in_range,
                minor: [],
            };
        }
    }
    exports.DaysTicker = DaysTicker;
},
/* models/tickers/single_interval_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_ticker_1 = require(282) /* ./continuous_ticker */;
    class BaseSingleIntervalTicker extends continuous_ticker_1.ContinuousTicker {
        constructor(attrs) {
            super(attrs);
        }
        get_interval(_data_low, _data_high, _n_desired_ticks) {
            return this.interval;
        }
        get_min_interval() {
            return this.interval;
        }
        get_max_interval() {
            return this.interval;
        }
    }
    exports.BaseSingleIntervalTicker = BaseSingleIntervalTicker;
    class SingleIntervalTicker extends BaseSingleIntervalTicker {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Float }) => ({
                interval: [Float],
            }));
        }
    }
    exports.SingleIntervalTicker = SingleIntervalTicker;
},
/* models/tickers/util.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.copy_date = copy_date;
    exports.last_month_no_later_than = last_month_no_later_than;
    exports.last_year_no_later_than = last_year_no_later_than;
    // TODO Clear out debugging code, etc.
    // TODO Organize helper functions.
    // TODO The years ticker doesn't always use the roundest numbers; it should
    // probably use a special ticker.
    // TODO Add tests.
    // TODO There used to be a TODO: restore memoization.  So.... do that?
    // TODO Instead of a get_ticks() method, there used to be an auto_ticks()
    // function that took a lot of fancy arguments, but those arguments weren't
    // used anywhere.  Should we restore them?
    // Some time constants, in milliseconds.
    exports.ONE_NANO = 0.000001;
    exports.ONE_MICRO = 0.001;
    exports.ONE_MILLI = 1.0;
    exports.ONE_SECOND = 1000.0;
    exports.ONE_MINUTE = 60.0 * exports.ONE_SECOND;
    exports.ONE_HOUR = 60 * exports.ONE_MINUTE;
    exports.ONE_DAY = 24 * exports.ONE_HOUR;
    exports.ONE_MONTH = 30 * exports.ONE_DAY; // An approximation, obviously.
    exports.ONE_YEAR = 365 * exports.ONE_DAY;
    // ---------------------------------------------------------------------------
    // Date/time utility functions
    // ---------------------------------------------------------------------------
    // Makes a copy of a date object.
    function copy_date(date) {
        return new Date(date.getTime());
    }
    // Rounds a date down to the month.
    function last_month_no_later_than(date) {
        const new_date = copy_date(date);
        new_date.setUTCDate(1);
        new_date.setUTCHours(0);
        new_date.setUTCMinutes(0);
        new_date.setUTCSeconds(0);
        new_date.setUTCMilliseconds(0);
        return new_date;
    }
    // Rounds a date down to the year.
    function last_year_no_later_than(date) {
        const new_date = last_month_no_later_than(date);
        new_date.setUTCMonth(0);
        return new_date;
    }
},
/* models/tickers/months_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const single_interval_ticker_1 = require(289) /* ./single_interval_ticker */;
    const util_1 = require(290) /* ./util */;
    const array_1 = require(10) /* ../../core/util/array */;
    // Given a start and end time in millis, returns the shortest array of
    // consecutive years (as Dates) that surrounds both times.
    function date_range_by_year(start_time, end_time) {
        const start_date = (0, util_1.last_year_no_later_than)(new Date(start_time));
        const end_date = (0, util_1.last_year_no_later_than)(new Date(end_time));
        end_date.setUTCFullYear(end_date.getUTCFullYear() + 1);
        const dates = [];
        const date = start_date;
        while (true) {
            dates.push((0, util_1.copy_date)(date));
            date.setUTCFullYear(date.getUTCFullYear() + 1);
            if (date > end_date) {
                break;
            }
        }
        return dates;
    }
    class MonthsTicker extends single_interval_ticker_1.BaseSingleIntervalTicker {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Int, List }) => ({
                months: [List(Int), []],
            }));
            this.internal(({ Float }) => ({
                interval: [Float, (obj) => {
                        const { months } = obj;
                        return (months.length > 1 ? months[1] - months[0] : 12) * util_1.ONE_MONTH;
                    }],
            }));
        }
        get_ticks_no_defaults(data_low, data_high, _cross_loc, _desired_n_ticks) {
            const year_dates = date_range_by_year(data_low, data_high);
            const { months } = this;
            const month_dates = (0, array_1.concat)(year_dates.map((year_date) => {
                return months.map((month) => {
                    const month_date = (0, util_1.copy_date)(year_date);
                    month_date.setUTCMonth(month);
                    return month_date;
                });
            }));
            const all_ticks = month_dates.map((month_date) => month_date.getTime());
            const ticks_in_range = all_ticks.filter((tick) => data_low <= tick && tick <= data_high);
            return {
                major: ticks_in_range,
                minor: [],
            };
        }
    }
    exports.MonthsTicker = MonthsTicker;
},
/* models/tickers/years_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const basic_ticker_1 = require(280) /* ./basic_ticker */;
    const single_interval_ticker_1 = require(289) /* ./single_interval_ticker */;
    const util_1 = require(290) /* ./util */;
    class YearsTicker extends single_interval_ticker_1.BaseSingleIntervalTicker {
        constructor(attrs) {
            super(attrs);
        }
        interval = util_1.ONE_YEAR;
        basic_ticker = new basic_ticker_1.BasicTicker({ num_minor_ticks: 0 });
        get_ticks_no_defaults(data_low, data_high, cross_loc, desired_n_ticks, num_minor_ticks) {
            const start_year = (0, util_1.last_year_no_later_than)(new Date(data_low)).getUTCFullYear();
            const end_year = (0, util_1.last_year_no_later_than)(new Date(data_high)).getUTCFullYear();
            const years = this.basic_ticker.get_ticks_no_defaults(start_year, end_year, cross_loc, desired_n_ticks, num_minor_ticks).major;
            const all_ticks = years.map((year) => Date.UTC(year, 0, 1));
            const ticks_in_range = all_ticks.filter((tick) => data_low <= tick && tick <= data_high);
            return {
                major: ticks_in_range,
                minor: [],
            };
        }
    }
    exports.YearsTicker = YearsTicker;
},
/* models/tickers/fixed_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_ticker_1 = require(282) /* ./continuous_ticker */;
    class FixedTicker extends continuous_ticker_1.ContinuousTicker {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Float, Arrayable }) => ({
                ticks: [Arrayable(Float), []],
                minor_ticks: [Arrayable(Float), []],
            }));
        }
        get_ticks_no_defaults(_data_low, _data_high, _cross_loc, _desired_n_ticks) {
            return {
                major: [...this.ticks],
                minor: [...this.minor_ticks],
            };
        }
        // XXX: whatever, because FixedTicker needs to fulfill the interface somehow
        get_interval(_data_low, _data_high, _desired_n_ticks) {
            return 0;
        }
        get_min_interval() {
            return 0;
        }
        get_max_interval() {
            return 0;
        }
    }
    exports.FixedTicker = FixedTicker;
},
/* models/tickers/log_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const adaptive_ticker_1 = require(281) /* ./adaptive_ticker */;
    const array_1 = require(10) /* ../../core/util/array */;
    class LogTicker extends adaptive_ticker_1.AdaptiveTicker {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.override({
                mantissas: [1, 5],
            });
        }
        get_ticks_no_defaults(data_low, data_high, _cross_loc, desired_n_ticks) {
            const num_minor_ticks = this.num_minor_ticks;
            const minor_ticks = [];
            const base = this.base;
            const log_low = Math.log(data_low) / Math.log(base);
            const log_high = Math.log(data_high) / Math.log(base);
            const log_interval = log_high - log_low;
            let ticks;
            if (!isFinite(log_interval) || log_interval == 0) {
                ticks = [];
            }
            else if (log_interval < 2) { // treat as linear ticker
                const interval = this.get_interval(data_low, data_high, desired_n_ticks);
                const start_factor = Math.floor(data_low / interval);
                const end_factor = Math.ceil(data_high / interval);
                ticks = (0, array_1.range)(start_factor, end_factor + 1)
                    .filter((factor) => factor != 0)
                    .map((factor) => factor * interval)
                    .filter((tick) => data_low <= tick && tick <= data_high);
                if (num_minor_ticks > 0 && ticks.length > 0) {
                    const minor_interval = interval / num_minor_ticks;
                    const minor_offsets = (0, array_1.range)(0, num_minor_ticks).map((i) => i * minor_interval);
                    for (const x of minor_offsets.slice(1)) {
                        minor_ticks.push(ticks[0] - x);
                    }
                    for (const tick of ticks) {
                        for (const x of minor_offsets) {
                            minor_ticks.push(tick + x);
                        }
                    }
                }
            }
            else {
                const d = 0.000001;
                const low_pad = 1.0 - Math.sign(log_low) * d;
                const high_pad = 1.0 + Math.sign(log_high) * d;
                const startlog = Math.ceil(log_low * low_pad);
                const endlog = Math.floor(log_high * high_pad);
                const interval = Math.ceil((endlog - startlog) / 9.0);
                const base_tick_options = (0, array_1.range)(startlog - 1, endlog + 1, 1).map((i) => base ** i);
                const tick_options = base_tick_options.filter((tick) => data_low <= tick && tick <= data_high);
                ticks = tick_options.filter((_, i) => i % interval === 0);
                if (num_minor_ticks > 0 && ticks.length > 0) {
                    const minor_interval = base ** interval / num_minor_ticks;
                    const minor_offsets = (0, array_1.range)(1, num_minor_ticks + 1).map((i) => i * minor_interval);
                    const max_offset = Math.max(...minor_offsets);
                    for (const x of minor_offsets) {
                        minor_ticks.push(ticks[0] * (x / max_offset));
                    }
                    for (const tick of ticks) {
                        for (const x of minor_offsets) {
                            minor_ticks.push(tick * x);
                        }
                    }
                }
            }
            return {
                major: ticks.filter((tick) => data_low <= tick && tick <= data_high),
                minor: minor_ticks.filter((tick) => data_low <= tick && tick <= data_high),
            };
        }
    }
    exports.LogTicker = LogTicker;
},
/* models/tickers/mercator_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const basic_ticker_1 = require(280) /* ./basic_ticker */;
    const enums_1 = require(21) /* ../../core/enums */;
    const projections_1 = require(148) /* ../../core/util/projections */;
    class MercatorTicker extends basic_ticker_1.BasicTicker {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Nullable }) => ({
                dimension: [Nullable(enums_1.LatLon), null],
            }));
        }
        get_ticks_no_defaults(data_low, data_high, cross_loc, desired_n_ticks, num_minor_ticks) {
            if (this.dimension == null) {
                throw new Error(`${this}.dimension wasn't configured`);
            }
            [data_low, data_high] = (0, projections_1.clip_mercator)(data_low, data_high, this.dimension);
            if (this.dimension == "lon") {
                return this._get_ticks_lon(data_low, data_high, cross_loc, desired_n_ticks, num_minor_ticks);
            }
            else {
                return this._get_ticks_lat(data_low, data_high, cross_loc, desired_n_ticks, num_minor_ticks);
            }
        }
        _get_ticks_lon(data_low, data_high, cross_loc, desired_n_ticks, num_minor_ticks) {
            const [proj_low] = projections_1.wgs84_mercator.invert(data_low, cross_loc);
            const [proj_high, proj_cross_loc] = projections_1.wgs84_mercator.invert(data_high, cross_loc);
            const proj_ticks = super.get_ticks_no_defaults(proj_low, proj_high, cross_loc, desired_n_ticks, num_minor_ticks);
            const major = [];
            for (const tick of proj_ticks.major) {
                if ((0, projections_1.in_bounds)(tick, "lon")) {
                    const [lon] = projections_1.wgs84_mercator.compute(tick, proj_cross_loc);
                    major.push(lon);
                }
            }
            const minor = [];
            for (const tick of proj_ticks.minor) {
                if ((0, projections_1.in_bounds)(tick, "lon")) {
                    const [lon] = projections_1.wgs84_mercator.compute(tick, proj_cross_loc);
                    minor.push(lon);
                }
            }
            return { major, minor };
        }
        _get_ticks_lat(data_low, data_high, cross_loc, desired_n_ticks, num_minor_ticks) {
            const [, proj_low] = projections_1.wgs84_mercator.invert(cross_loc, data_low);
            const [proj_cross_loc, proj_high] = projections_1.wgs84_mercator.invert(cross_loc, data_high);
            const proj_ticks = super.get_ticks_no_defaults(proj_low, proj_high, cross_loc, desired_n_ticks, num_minor_ticks);
            const major = [];
            for (const tick of proj_ticks.major) {
                if ((0, projections_1.in_bounds)(tick, "lat")) {
                    const [, lat] = projections_1.wgs84_mercator.compute(proj_cross_loc, tick);
                    major.push(lat);
                }
            }
            const minor = [];
            for (const tick of proj_ticks.minor) {
                if ((0, projections_1.in_bounds)(tick, "lat")) {
                    const [, lat] = projections_1.wgs84_mercator.compute(proj_cross_loc, tick);
                    minor.push(lat);
                }
            }
            return { major, minor };
        }
    }
    exports.MercatorTicker = MercatorTicker;
},
/* models/tickers/timedelta_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const adaptive_ticker_1 = require(281) /* ./adaptive_ticker */;
    const composite_ticker_1 = require(285) /* ./composite_ticker */;
    const util_1 = require(290) /* ./util */;
    class TimedeltaTicker extends composite_ticker_1.CompositeTicker {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.override({
                num_minor_ticks: 0,
                tickers: () => [
                    // Sub-second.
                    new adaptive_ticker_1.AdaptiveTicker({
                        mantissas: [1, 2, 5],
                        base: 10,
                        min_interval: 0,
                        max_interval: 500 * util_1.ONE_MILLI,
                        num_minor_ticks: 0,
                    }),
                    // Seconds, minutes.
                    new adaptive_ticker_1.AdaptiveTicker({
                        mantissas: [1, 2, 5, 10, 15, 20, 30],
                        base: 60,
                        min_interval: util_1.ONE_SECOND,
                        max_interval: 30 * util_1.ONE_MINUTE,
                        num_minor_ticks: 0,
                    }),
                    // Hours.
                    new adaptive_ticker_1.AdaptiveTicker({
                        mantissas: [1, 2, 4, 6, 8, 12],
                        base: 24.0,
                        min_interval: util_1.ONE_HOUR,
                        max_interval: 12 * util_1.ONE_HOUR,
                        num_minor_ticks: 0,
                    }),
                    // Days.
                    new adaptive_ticker_1.AdaptiveTicker({
                        mantissas: [1, 2, 5],
                        base: 10,
                        min_interval: util_1.ONE_DAY,
                        max_interval: null,
                        num_minor_ticks: 0,
                    }),
                ],
            });
        }
    }
    exports.TimedeltaTicker = TimedeltaTicker;
},
/* models/tickers/binned_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const ticker_1 = require(274) /* ./ticker */;
    const scanning_color_mapper_1 = require(298) /* ../mappers/scanning_color_mapper */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    class BinnedTicker extends ticker_1.Ticker {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Float, Ref, Or, Auto }) => ({
                mapper: [Ref(scanning_color_mapper_1.ScanningColorMapper)],
                num_major_ticks: [Or(Float, Auto), 8],
            }));
        }
        get_ticks(data_low, data_high, _range, _cross_loc) {
            const { binning } = this.mapper.metrics;
            const k_low = Math.max(0, (0, arrayable_1.left_edge_index)(data_low, binning));
            const k_high = Math.min((0, arrayable_1.left_edge_index)(data_high, binning) + 1, binning.length - 1);
            const _major = [];
            for (let k = k_low; k <= k_high; k++) {
                _major.push(binning[k]);
            }
            const { num_major_ticks } = this;
            const major = [];
            const n = num_major_ticks == "auto" ? _major.length : num_major_ticks;
            const step = Math.max(1, Math.floor(_major.length / n));
            for (let i = 0; i < _major.length; i += step) {
                major.push(_major[i]);
            }
            return {
                major,
                minor: [],
            };
        }
    }
    exports.BinnedTicker = BinnedTicker;
},
/* models/mappers/scanning_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_color_mapper_1 = require(299) /* ./continuous_color_mapper */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    class ScanningColorMapper extends continuous_color_mapper_1.ContinuousColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        index_to_value(index) {
            const scan_data = this._scan_data;
            return scan_data.binning[index];
        }
        value_to_index(value, palette_length) {
            const scan_data = this._scan_data;
            if (value < scan_data.binning[0]) {
                return -1;
            }
            else if (value > scan_data.binning[scan_data.binning.length - 1]) {
                return palette_length;
            }
            else {
                return (0, arrayable_1.left_edge_index)(value, scan_data.binning);
            }
        }
    }
    exports.ScanningColorMapper = ScanningColorMapper;
},
/* models/mappers/continuous_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const color_mapper_1 = require(300) /* ./color_mapper */;
    const glyph_renderer_1 = require(302) /* ../renderers/glyph_renderer */;
    const array_1 = require(10) /* ../../core/util/array */;
    const types_1 = require(8) /* ../../core/util/types */;
    class ContinuousColorMapper extends color_mapper_1.ColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Float, Str, Ref, Color, Or, Tuple, List, Nullable }) => {
                return {
                    high: [Nullable(Float), null],
                    low: [Nullable(Float), null],
                    high_color: [Nullable(Color), null],
                    low_color: [Nullable(Color), null],
                    domain: [List(Tuple(Ref(glyph_renderer_1.GlyphRenderer), Or(Str, List(Str)))), []],
                };
            });
        }
        connect_signals() {
            super.connect_signals();
            const connect_renderers = () => {
                // TODO: if already connected this will bail. However, it won't remove old connections.
                for (const [renderer] of this.domain) {
                    this.connect(renderer.view.change, () => this.update_data());
                    this.connect(renderer.data_source.selected.change, () => this.update_data());
                }
            };
            const { high, low, high_color, low_color, palette, nan_color } = this.properties;
            this.on_change([high, low, high_color, low_color, palette, nan_color], () => this.update_data());
            this.connect(this.properties.domain.change, () => connect_renderers());
            connect_renderers();
        }
        update_data() {
            const { domain, palette } = this;
            const all_data = [...this._collect(domain)];
            this._scan_data = this.scan(all_data, palette.length);
            this.metrics_change.emit();
            this.change.emit();
        }
        MatricsType;
        get metrics() {
            if (this._scan_data == null) {
                this.update_data();
            }
            return this._scan_data;
        }
        *_collect(domain) {
            for (const [renderer, fields] of domain) {
                for (const field of (0, types_1.isArray)(fields) ? fields : [fields]) {
                    if (renderer.view.properties.indices.is_unset) {
                        continue;
                    }
                    const column = renderer.data_source.get_column(field);
                    if (column == null) {
                        continue;
                    }
                    let array = renderer.view.indices.select(column);
                    const masked = renderer.view.masked;
                    const selected = renderer.data_source.selected.indices;
                    let subset;
                    if (masked != null && selected.length > 0) {
                        subset = (0, array_1.intersection)([...masked], selected);
                    }
                    else if (masked != null) {
                        subset = [...masked];
                    }
                    else if (selected.length > 0) {
                        subset = selected;
                    }
                    if (subset != null) {
                        array = (0, array_1.map)(subset, (i) => array[i]);
                    }
                    if (array.length > 0 && !(0, types_1.isNumber)(array[0])) {
                        for (const subarray of array) {
                            yield* subarray;
                        }
                    }
                    else {
                        yield* array;
                    }
                }
            }
        }
        _scan_data = null;
        _v_compute(data, values, palette, colors) {
            const { nan_color } = colors;
            let { low_color, high_color } = colors;
            if (low_color == null) {
                low_color = palette[0];
            }
            if (high_color == null) {
                high_color = palette[palette.length - 1];
            }
            const { domain } = this;
            const all_data = !(0, array_1.is_empty)(domain) ? [...this._collect(domain)] : data;
            this._scan_data = this.scan(all_data, palette.length);
            this.metrics_change.emit();
            for (let i = 0, end = data.length; i < end; i++) {
                const d = data[i];
                if (isNaN(d)) {
                    values[i] = nan_color;
                }
                else {
                    values[i] = this.cmap(d, palette, low_color, high_color);
                }
            }
        }
        _colors(conv) {
            return {
                ...super._colors(conv),
                low_color: this.low_color != null ? conv(this.low_color) : undefined,
                high_color: this.high_color != null ? conv(this.high_color) : undefined,
            };
        }
        cmap(value, palette, low_color, high_color) {
            const index = this.value_to_index(value, palette.length);
            if (index < 0) {
                return low_color;
            }
            else if (index >= palette.length) {
                return high_color;
            }
            else {
                return palette[index];
            }
        }
    }
    exports.ContinuousColorMapper = ContinuousColorMapper;
},
/* models/mappers/color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.convert_to_uint32_color = convert_to_uint32_color;
    exports.convert_to_uint32_palette = convert_to_uint32_palette;
    const mapper_1 = require(301) /* ./mapper */;
    const signaling_1 = require(17) /* ../../core/signaling */;
    const types_1 = require(25) /* ../../core/types */;
    const color_1 = require(23) /* ../../core/util/color */;
    const platform_1 = require(28) /* ../../core/util/platform */;
    const ndarray_1 = require(31) /* ../../core/util/ndarray */;
    function convert_to_uint32_color(color) {
        return (0, color_1.encode_rgba)((0, color_1.color2rgba)(color));
    }
    function convert_to_uint32_palette(palette) {
        const new_palette = new Uint32Array(palette.length);
        for (let i = 0, end = palette.length; i < end; i++) {
            new_palette[i] = convert_to_uint32_color(palette[i]);
        }
        return new_palette;
    }
    class ColorMapper extends mapper_1.Mapper {
        metrics_change = new signaling_1.Signal0(this, "metrics_change");
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Color, List }) => ({
                palette: [List(Color)],
                nan_color: [Color, "gray"],
            }));
        }
        v_compute(xs) {
            const values = new Uint32Array(xs.length);
            this._v_compute(xs, values, convert_to_uint32_palette(this.palette), this._colors(convert_to_uint32_color));
            return new ndarray_1.Uint32NDArray(values);
        }
        get rgba_mapper() {
            const self = this;
            const palette = convert_to_uint32_palette(this.palette);
            const colors = this._colors(convert_to_uint32_color);
            return {
                v_compute(xs) {
                    const length_divisor = (0, ndarray_1.is_NDArray)(xs) && xs.dimension == 3 ? xs.shape[2] : 1;
                    const values = new types_1.ColorArray(xs.length / length_divisor);
                    self._v_compute(xs, values, palette, colors);
                    (0, platform_1.to_big_endian)(values);
                    return new Uint8ClampedArray(values.buffer);
                },
            };
        }
        _colors(conv) {
            return { nan_color: conv(this.nan_color) };
        }
    }
    exports.ColorMapper = ColorMapper;
},
/* models/mappers/mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const transform_1 = require(109) /* ../transforms/transform */;
    class Mapper extends transform_1.Transform {
        constructor(attrs) {
            super(attrs);
        }
        compute(_x) {
            // If it's just a single value, then a mapper doesn't really make sense.
            throw new Error("mapping single values is not supported");
        }
    }
    exports.Mapper = Mapper;
},
/* models/renderers/glyph_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const data_renderer_1 = require(303) /* ./data_renderer */;
    const line_1 = require(304) /* ../glyphs/line */;
    const step_1 = require(312) /* ../glyphs/step */;
    const patch_1 = require(313) /* ../glyphs/patch */;
    const harea_step_1 = require(314) /* ../glyphs/harea_step */;
    const harea_1 = require(317) /* ../glyphs/harea */;
    const varea_step_1 = require(318) /* ../glyphs/varea_step */;
    const varea_1 = require(319) /* ../glyphs/varea */;
    const glyph_1 = require(306) /* ../glyphs/glyph */;
    const columnar_data_source_1 = require(142) /* ../sources/columnar_data_source */;
    const cds_view_1 = require(320) /* ../sources/cds_view */;
    const types_1 = require(25) /* ../../core/types */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const object_1 = require(9) /* ../../core/util/object */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const eq_1 = require(27) /* ../../core/util/eq */;
    const factor_range_1 = require(121) /* ../ranges/factor_range */;
    const decoration_1 = require(309) /* ../graphics/decoration */;
    const selection_defaults = {
        fill: {},
        line: {},
    };
    const decimated_defaults = {
        fill: { fill_alpha: 0.3, fill_color: "grey" },
        line: { line_alpha: 0.3, line_color: "grey" },
    };
    const nonselection_defaults = {
        fill: { fill_alpha: 0.2 },
        line: {},
    };
    const muted_defaults = {
        fill: { fill_alpha: 0.2 },
        line: {},
    };
    class GlyphRendererView extends data_renderer_1.DataRendererView {
        cds_view;
        glyph;
        selection_glyph;
        nonselection_glyph;
        hover_glyph;
        muted_glyph;
        decimated_glyph;
        get glyph_view() {
            return this.glyph;
        }
        children_views() {
            return [
                ...super.children_views(),
                this.cds_view,
                this.glyph,
                this.selection_glyph,
                this.nonselection_glyph,
                this.hover_glyph,
                this.muted_glyph,
                this.decimated_glyph,
            ];
        }
        all_indices;
        decimated;
        last_dtrender;
        get data_source() {
            return this.model.properties.data_source;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            this.cds_view = await (0, build_views_1.build_view)(this.model.view, { parent: this });
            const base_glyph = this.model.glyph;
            this.glyph = await this.build_glyph_view(base_glyph);
            const has_fill = "fill" in this.glyph.visuals;
            const has_line = "line" in this.glyph.visuals;
            const glyph_attrs = { ...base_glyph.attributes };
            delete glyph_attrs.id;
            function mk_glyph(defaults) {
                const attrs = (0, object_1.clone)(glyph_attrs);
                if (has_fill) {
                    (0, object_1.extend)(attrs, defaults.fill);
                }
                if (has_line) {
                    (0, object_1.extend)(attrs, defaults.line);
                }
                return new base_glyph.constructor(attrs);
            }
            function glyph_from_mode(defaults, glyph) {
                if (glyph instanceof glyph_1.Glyph) {
                    return glyph;
                }
                else if (glyph == "auto") {
                    return mk_glyph(defaults);
                }
                return mk_glyph({ fill: {}, line: {} });
            }
            let { selection_glyph, nonselection_glyph, hover_glyph, muted_glyph } = this.model;
            selection_glyph = glyph_from_mode(selection_defaults, selection_glyph);
            this.selection_glyph = await this.build_glyph_view(selection_glyph);
            nonselection_glyph = glyph_from_mode(nonselection_defaults, nonselection_glyph);
            this.nonselection_glyph = await this.build_glyph_view(nonselection_glyph);
            if (hover_glyph != null) {
                this.hover_glyph = await this.build_glyph_view(hover_glyph);
            }
            muted_glyph = glyph_from_mode(muted_defaults, muted_glyph);
            this.muted_glyph = await this.build_glyph_view(muted_glyph);
            const decimated_glyph = glyph_from_mode(decimated_defaults, "auto");
            this.decimated_glyph = await this.build_glyph_view(decimated_glyph);
            this.selection_glyph.set_base(this.glyph);
            this.nonselection_glyph.set_base(this.glyph);
            this.hover_glyph?.set_base(this.glyph);
            this.muted_glyph.set_base(this.glyph);
            this.decimated_glyph.set_base(this.glyph);
            await this.set_data();
        }
        async build_glyph_view(glyph) {
            return (0, build_views_1.build_view)(glyph, { parent: this });
        }
        _previous_inspected;
        connect_signals() {
            super.connect_signals();
            const render = () => this.request_paint();
            const update = () => this.update_data();
            this.connect(this.model.change, render);
            this.connect(this.glyph.model.change, update);
            this.connect(this.selection_glyph.model.change, update);
            this.connect(this.nonselection_glyph.model.change, update);
            if (this.hover_glyph != null) {
                this.connect(this.hover_glyph.model.change, update);
            }
            this.connect(this.muted_glyph.model.change, update);
            this.connect(this.decimated_glyph.model.change, update);
            this.connect(this.model.data_source.change, update);
            this.connect(this.model.data_source.streaming, update);
            this.connect(this.model.data_source.patching, (indices) => this.update_data(indices));
            this.connect(this.model.data_source.selected.change, render);
            this.connect(this.model.data_source._select, render);
            if (this.hover_glyph != null) {
                this.connect(this.model.data_source.inspect, () => {
                    // XXX: hoping for the best, assuming no in-place mutation
                    const { inspected } = this.model.data_source;
                    const current_inspected = {
                        indices: inspected.indices,
                        line_indices: inspected.line_indices,
                        multiline_indices: inspected.multiline_indices,
                        image_indices: inspected.image_indices,
                        selected_glyphs: inspected.selected_glyphs,
                    };
                    if (!(0, eq_1.is_equal)(this._previous_inspected, current_inspected)) {
                        this._previous_inspected = current_inspected;
                        render();
                    }
                });
            }
            this.connect(this.model.properties.view.change, async () => {
                this.cds_view.remove();
                this.cds_view = await (0, build_views_1.build_view)(this.model.view, { parent: this });
                await update();
            });
            this.connect(this.model.view.properties.indices.change, update);
            this.connect(this.model.view.properties.masked.change, async () => await this.set_visuals());
            this.connect(this.model.properties.visible.change, () => this.plot_view.invalidate_dataranges = true);
            const { x_ranges, y_ranges } = this.plot_view.frame;
            for (const [, range] of x_ranges) {
                if (range instanceof factor_range_1.FactorRange) {
                    this.connect(range.invalidate_synthetic, update);
                }
            }
            for (const [, range] of y_ranges) {
                if (range instanceof factor_range_1.FactorRange) {
                    this.connect(range.invalidate_synthetic, update);
                }
            }
            const { transformchange, exprchange } = this.model.glyph;
            this.connect(transformchange, update);
            this.connect(exprchange, update);
        }
        _update_masked_indices() {
            const masked = this.glyph.mask_data();
            this.model.view.masked = masked;
            return masked;
        }
        async update_data(indices) {
            await this.set_data(indices);
            this.request_paint();
        }
        // in case of partial updates like patching, the list of indices that actually
        // changed may be passed as the "indices" parameter to afford any optional optimizations
        async set_data(indices) {
            const source = this.model.data_source;
            this.all_indices = this.model.view.indices;
            const { all_indices } = this;
            await this.glyph.set_data(source, all_indices, indices);
            await this.decimated_glyph.set_data(source, all_indices, indices);
            await this.selection_glyph.set_data(source, all_indices, indices);
            await this.nonselection_glyph.set_data(source, all_indices, indices);
            await this.hover_glyph?.set_data(source, all_indices, indices);
            await this.muted_glyph.set_data(source, all_indices, indices);
            await this.set_visuals();
            this._update_masked_indices();
            const { lod_factor } = this.plot_model;
            const n = this.all_indices.count;
            this.decimated = new types_1.Indices(n);
            for (let i = 0; i < n; i += lod_factor) {
                this.decimated.set(i);
            }
            this.plot_view.invalidate_dataranges = true;
        }
        async set_visuals() {
            const source = this.model.data_source;
            const { all_indices } = this;
            this.glyph.set_visuals(source, all_indices);
            this.glyph.after_visuals();
            await this.glyph.after_lazy_visuals();
            this.decimated_glyph.set_visuals(source, all_indices);
            this.decimated_glyph.after_visuals();
            await this.decimated_glyph.after_lazy_visuals();
            this.selection_glyph.set_visuals(source, all_indices);
            this.selection_glyph.after_visuals();
            await this.selection_glyph.after_lazy_visuals();
            this.nonselection_glyph.set_visuals(source, all_indices);
            this.nonselection_glyph.after_visuals();
            await this.nonselection_glyph.after_lazy_visuals();
            this.hover_glyph?.set_visuals(source, all_indices);
            this.hover_glyph?.after_visuals();
            await this.hover_glyph?.after_lazy_visuals();
            this.muted_glyph.set_visuals(source, all_indices);
            this.muted_glyph.after_visuals();
            await this.muted_glyph.after_lazy_visuals();
        }
        map_data() {
            this.glyph.map_data();
            this.decimated_glyph.map_data();
            this.selection_glyph.map_data();
            this.nonselection_glyph.map_data();
            this.hover_glyph?.map_data();
            this.muted_glyph.map_data();
        }
        get bbox() {
            return this.glyph.bbox;
        }
        get has_webgl() {
            return this.glyph.has_webgl();
        }
        _paint(ctx) {
            const { has_webgl } = this;
            this.map_data();
            // all_indices is in full data space, indices is converted to subset space by mask_data (that may use the spatial index)
            const all_indices = this.all_indices.ones();
            let indices = this._update_masked_indices().ones();
            // selected is in full set space
            const { selected } = this.model.data_source;
            const selected_full_indices = (() => {
                if (selected.is_empty()) {
                    return [];
                }
                else {
                    if ((this.glyph instanceof line_1.LineView || this.glyph instanceof step_1.StepView) && selected.selected_glyph === this.glyph.model) {
                        return this.model.view.convert_indices_from_subset(indices);
                    }
                    else {
                        return selected.indices;
                    }
                }
            })();
            // inspected is in full set space
            const { inspected } = this.model.data_source;
            this._previous_inspected = {
                indices: inspected.indices,
                line_indices: inspected.line_indices,
                multiline_indices: inspected.multiline_indices,
                image_indices: inspected.image_indices,
                selected_glyphs: inspected.selected_glyphs,
            };
            const inspected_full_indices = new Set((() => {
                if (inspected.is_empty()) {
                    return [];
                }
                else {
                    if (inspected.selected_glyph != null) {
                        return this.model.view.convert_indices_from_subset(indices);
                    }
                    else if (inspected.indices.length > 0) {
                        return inspected.indices;
                    }
                    else {
                        // TODO: return inspected.multiline_indices.keys()
                        return Object.keys(inspected.multiline_indices).map((i) => parseInt(i));
                    }
                }
            })());
            // inspected is transformed to subset space
            const inspected_subset_indices = (() => {
                if (inspected_full_indices.size === 0) {
                    return [];
                }
                return (0, arrayable_1.filter)(indices, (i) => inspected_full_indices.has(all_indices[i]));
            })();
            const { lod_threshold } = this.plot_model;
            let glyph;
            let nonselection_glyph;
            let selection_glyph;
            if ((this.model.document != null ? this.model.document.interactive_duration() > 0 : false)
                && !has_webgl && lod_threshold != null && all_indices.length > lod_threshold) {
                // Render decimated during interaction if too many elements and not using GL
                indices = [...this.decimated];
                glyph = this.decimated_glyph;
                nonselection_glyph = this.decimated_glyph;
                selection_glyph = this.selection_glyph;
            }
            else {
                glyph = this.model.muted ? this.muted_glyph : this.glyph;
                nonselection_glyph = this.nonselection_glyph;
                selection_glyph = this.selection_glyph;
            }
            if (this.hover_glyph != null && inspected_subset_indices.length != 0) {
                // TODO: keep working on Indices instead of converting back and forth
                const set = new Set(indices);
                for (const i of inspected_subset_indices) {
                    set.delete(i);
                }
                indices = [...set];
            }
            ctx.save();
            // Render with no selection
            if (selected_full_indices.length == 0) {
                if (this.glyph instanceof line_1.LineView || this.glyph instanceof step_1.StepView) {
                    if (this.hover_glyph != null && inspected_subset_indices.length != 0) {
                        this.hover_glyph.paint(ctx, this.model.view.convert_indices_from_subset(inspected_subset_indices));
                    }
                    else {
                        glyph.paint(ctx, all_indices);
                    }
                }
                else if (this.glyph instanceof patch_1.PatchView ||
                    this.glyph instanceof harea_1.HAreaView ||
                    this.glyph instanceof varea_1.VAreaView ||
                    this.glyph instanceof varea_step_1.VAreaStepView ||
                    this.glyph instanceof harea_step_1.HAreaStepView) {
                    if (inspected.selected_glyphs.length == 0 || this.hover_glyph == null) {
                        glyph.paint(ctx, all_indices);
                    }
                    else {
                        for (const sglyph of inspected.selected_glyphs) {
                            if (sglyph == this.glyph.model) {
                                this.hover_glyph.paint(ctx, all_indices);
                            }
                        }
                    }
                }
                else {
                    glyph.paint(ctx, indices);
                    if (this.hover_glyph != null && inspected_subset_indices.length != 0) {
                        this.hover_glyph.paint(ctx, inspected_subset_indices);
                    }
                }
                // Render with selection
            }
            else {
                // reset the selection mask
                const selected_mask = new Set(selected_full_indices);
                // intersect/different selection with render mask
                const selected_subset_indices = new Array();
                const nonselected_subset_indices = new Array();
                // now, selected is changed to subset space, except for Line/Step glyph
                if (this.glyph instanceof line_1.LineView || this.glyph instanceof step_1.StepView) {
                    for (const i of all_indices) {
                        if (selected_mask.has(i)) {
                            selected_subset_indices.push(i);
                        }
                        else {
                            nonselected_subset_indices.push(i);
                        }
                    }
                }
                else {
                    for (const i of indices) {
                        if (selected_mask.has(all_indices[i])) {
                            selected_subset_indices.push(i);
                        }
                        else {
                            nonselected_subset_indices.push(i);
                        }
                    }
                }
                nonselection_glyph.paint(ctx, nonselected_subset_indices);
                selection_glyph.paint(ctx, selected_subset_indices);
                if (this.hover_glyph != null) {
                    if (this.glyph instanceof line_1.LineView || this.glyph instanceof step_1.StepView) {
                        this.hover_glyph.paint(ctx, this.model.view.convert_indices_from_subset(inspected_subset_indices));
                    }
                    else {
                        this.hover_glyph.paint(ctx, inspected_subset_indices);
                    }
                }
            }
            ctx.restore();
        }
        get_reference_point(field, value) {
            return this._get_reference_point(field, value) ?? 0; // fall back to first index
        }
        _get_reference_point(field, value) {
            if (field != null) {
                const array = this.model.data_source.get_column(field);
                if (array != null) {
                    return this.model.view.get_reference_point(array, value);
                }
            }
            return null;
        }
        draw_legend(ctx, x0, x1, y0, y1, field, label, index) {
            if (this.glyph.data_size == 0) {
                return;
            }
            const subset_index = (() => {
                if (index == null) {
                    return this.get_reference_point(field, label);
                }
                else {
                    return this.model.view.get_subset_index(index);
                }
            })();
            this.glyph.draw_legend_for_index(ctx, { x0, x1, y0, y1 }, subset_index);
        }
        hit_test(geometry) {
            if (!this.model.visible) {
                return null;
            }
            const hit_test_result = this.glyph.hit_test(geometry);
            // glyphs that don't have hit-testing implemented will return null
            if (hit_test_result == null) {
                return null;
            }
            return this.model.view.convert_selection_from_subset(hit_test_result);
        }
    }
    exports.GlyphRendererView = GlyphRendererView;
    class GlyphRenderer extends data_renderer_1.DataRenderer {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = GlyphRendererView;
            this.define(({ Bool, Auto, Or, Ref, Null, Nullable }) => ({
                data_source: [Ref(columnar_data_source_1.ColumnarDataSource)],
                view: [Ref(cds_view_1.CDSView), () => new cds_view_1.CDSView()],
                glyph: [Ref(glyph_1.Glyph)],
                hover_glyph: [Nullable(Ref(glyph_1.Glyph)), null],
                nonselection_glyph: [Or(Ref(glyph_1.Glyph), Auto, Null), "auto"],
                selection_glyph: [Or(Ref(glyph_1.Glyph), Auto, Null), "auto"],
                muted_glyph: [Or(Ref(glyph_1.Glyph), Auto, Null), "auto"],
                muted: [Bool, false],
            }));
        }
        get_selection_manager() {
            return this.data_source.selection_manager;
        }
        add_decoration(marking, node) {
            const decoration = new decoration_1.Decoration({ marking, node });
            const glyphs = [
                this.glyph,
                this.selection_glyph,
                this.nonselection_glyph,
                this.hover_glyph,
                this.muted_glyph,
            ];
            for (const glyph of glyphs) {
                if (glyph instanceof glyph_1.Glyph) {
                    glyph.decorations = [...glyph.decorations, decoration];
                }
            }
            return decoration;
        }
    }
    exports.GlyphRenderer = GlyphRenderer;
},
/* models/renderers/data_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const renderer_1 = require(98) /* ./renderer */;
    const data_range1d_1 = require(118) /* ../ranges/data_range1d */;
    class DataRendererView extends renderer_1.RendererView {
        get xscale() {
            return this.coordinates.x_scale;
        }
        get yscale() {
            return this.coordinates.y_scale;
        }
        [data_range1d_1.auto_ranged] = true;
        bounds(window_axis = "none") {
            return this.glyph_view.bounds(window_axis);
        }
        log_bounds() {
            return this.glyph_view.log_bounds();
        }
    }
    exports.DataRendererView = DataRendererView;
    class DataRenderer extends renderer_1.Renderer {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.override({
                level: "glyph",
            });
        }
        get selection_manager() {
            return this.get_selection_manager();
        }
    }
    exports.DataRenderer = DataRenderer;
},
/* models/glyphs/line.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(305) /* ./xy_glyph */;
    const utils_1 = require(310) /* ./utils */;
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    const hittest = tslib_1.__importStar(require(311) /* ../../core/hittest */);
    const selection_1 = require(144) /* ../selections/selection */;
    class LineView extends xy_glyph_1.XYGlyphView {
        async load_glglyph() {
            const { LineGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(668) /* ./webgl/line_gl */));
            return LineGL;
        }
        _paint(ctx, indices, data) {
            const { sx, sy } = { ...this, ...data };
            const nonselection = this.parent.nonselection_glyph == this;
            let iprev = null;
            const gap = (i) => iprev != null && i - iprev != 1;
            let move = true;
            ctx.beginPath();
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                if (nonselection && !move && iprev != null && i - iprev > 1 && isFinite(sx[iprev + 1] + sy[iprev + 1])) {
                    ctx.lineTo(sx[iprev + 1], sy[iprev + 1]); // End of previous line
                }
                if (!isFinite(sx_i + sy_i)) {
                    move = true;
                }
                else {
                    if (move || gap(i)) {
                        if (nonselection && i > 0 && isFinite(sx[i - 1] + sy[i - 1])) {
                            ctx.moveTo(sx[i - 1], sy[i - 1]); // Start of new line
                            ctx.lineTo(sx_i, sy_i);
                        }
                        else {
                            ctx.moveTo(sx_i, sy_i);
                        }
                        move = false;
                    }
                    else {
                        ctx.lineTo(sx_i, sy_i);
                    }
                    iprev = i;
                }
            }
            if (nonselection && !move && iprev != null) {
                const n = sx.length;
                if (iprev < n - 1 && isFinite(sx[iprev + 1] + sy[iprev + 1])) {
                    ctx.lineTo(sx[iprev + 1], sy[iprev + 1]); // End of final line
                }
            }
            this.visuals.line.set_value(ctx);
            ctx.stroke();
        }
        _hit_point(geometry) {
            /* Check if the point geometry hits this line glyph and return an object
            that describes the hit result:
              Args:
                * geometry (object): object with the following keys
                  * sx (float): screen x coordinate of the point
                  * sy (float): screen y coordinate of the point
                  * type (str): type of geometry (in this case it's a point)
            */
            const result = new selection_1.Selection();
            const point = { x: geometry.sx, y: geometry.sy };
            let shortest = 9999;
            const threshold = Math.max(2, this.line_width.value / 2);
            for (let i = 0, end = this.sx.length - 1; i < end; i++) {
                const p0 = { x: this.sx[i], y: this.sy[i] };
                const p1 = { x: this.sx[i + 1], y: this.sy[i + 1] };
                const dist = hittest.dist_to_segment(point, p0, p1);
                if (dist < threshold && dist < shortest) {
                    shortest = dist;
                    result.add_to_selected_glyphs(this.model);
                    result.view = this;
                    result.line_indices = [i];
                }
            }
            return result;
        }
        _hit_span(geometry) {
            const { sx, sy } = geometry;
            let val;
            let values;
            if (geometry.direction == "v") {
                val = this.renderer.yscale.invert(sy);
                values = this.y;
            }
            else {
                val = this.renderer.xscale.invert(sx);
                values = this.x;
            }
            const indices = [];
            for (let i = 0, end = values.length - 1; i < end; i++) {
                const curr = values[i];
                const next = values[i + 1];
                if ((curr <= val && val <= next) || (next <= val && val <= curr)) {
                    indices.push(i);
                }
            }
            const result = new selection_1.Selection();
            if (indices.length != 0) {
                result.add_to_selected_glyphs(this.model);
                result.view = this;
                result.line_indices = indices;
            }
            return result;
        }
        get_interpolation_hit(i, geometry) {
            const [x2, y2, x3, y3] = [this.x[i], this.y[i], this.x[i + 1], this.y[i + 1]];
            return (0, utils_1.line_interpolation)(this.renderer, geometry, x2, y2, x3, y3);
        }
        draw_legend_for_index(ctx, bbox, _index) {
            (0, utils_1.generic_line_scalar_legend)(this.visuals, ctx, bbox);
        }
    }
    exports.LineView = LineView;
    class Line extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = LineView;
            this.mixins(mixins.LineScalar);
        }
    }
    exports.Line = Line;
},
/* models/glyphs/xy_glyph.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const glyph_1 = require(306) /* ./glyph */;
    class XYGlyphView extends glyph_1.GlyphView {
        _project_data() {
            this._project_xy("x", this.x, "y", this.y);
        }
        _index_data(index) {
            const { x, y, data_size } = this;
            for (let i = 0; i < data_size; i++) {
                index.add_point(x[i], y[i]);
            }
        }
        scenterxy(i) {
            return [this.sx[i], this.sy[i]];
        }
    }
    exports.XYGlyphView = XYGlyphView;
    class XYGlyph extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(() => ({
                x: [p.XCoordinateSpec, { field: "x" }],
                y: [p.YCoordinateSpec, { field: "y" }],
            }));
        }
    }
    exports.XYGlyph = XYGlyph;
},
/* models/glyphs/glyph.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const bbox = tslib_1.__importStar(require(62) /* ../../core/util/bbox */);
    const visuals = tslib_1.__importStar(require(99) /* ../../core/visuals */);
    const uniforms = tslib_1.__importStar(require(40) /* ../../core/uniforms */);
    const settings_1 = require(30) /* ../../core/settings */;
    const dom_view_1 = require(64) /* ../../core/dom_view */;
    const model_1 = require(52) /* ../../model */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const logging_1 = require(11) /* ../../core/logging */;
    const types_1 = require(25) /* ../../core/types */;
    const types_2 = require(8) /* ../../core/util/types */;
    const ragged_array_1 = require(307) /* ../../core/util/ragged_array */;
    const array_1 = require(10) /* ../../core/util/array */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const projections_1 = require(148) /* ../../core/util/projections */;
    const eq_1 = require(27) /* ../../core/util/eq */;
    const spatial_1 = require(308) /* ../../core/util/spatial */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    const bbox_1 = require(62) /* ../../core/util/bbox */;
    const factor_range_1 = require(121) /* ../ranges/factor_range */;
    const selection_1 = require(144) /* ../selections/selection */;
    const decoration_1 = require(309) /* ../graphics/decoration */;
    const { abs, ceil } = Math;
    exports.inherit = Symbol("inherit");
    class GlyphView extends dom_view_1.DOMComponentView {
        visuals;
        get renderer() {
            return this.parent;
        }
        /** @internal */
        glglyph;
        has_webgl() {
            return this.glglyph != null && this._can_use_webgl;
        }
        _can_use_webgl = false;
        _compute_can_use_webgl() {
            return true;
        }
        _index = null;
        _data_size = null;
        _nohit_warned = new Set();
        get index() {
            const { _index } = this;
            if (_index != null) {
                return _index;
            }
            else {
                throw new Error(`${this}.index_data() wasn't called`);
            }
        }
        get data_size() {
            const { base } = this;
            if (base != null) {
                return base.data_size;
            }
            else {
                const { _data_size } = this;
                if (_data_size != null) {
                    return _data_size;
                }
                else {
                    throw new Error(`${this}.set_data() wasn't called`);
                }
            }
        }
        initialize() {
            super.initialize();
            this.visuals = new visuals.Visuals(this);
        }
        decorations = new Map();
        children_views() {
            return [...super.children_views(), ...this.decorations.values()];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await (0, build_views_1.build_views)(this.decorations, this.model.decorations, { parent: this.parent });
            const { webgl } = this.canvas;
            if (webgl != null && this.load_glglyph != null) {
                const cls = await this.load_glglyph();
                this.glglyph = new cls(webgl.regl_wrapper, this);
            }
        }
        request_paint() {
            this.parent.request_paint();
        }
        get canvas() {
            return this.renderer.parent.canvas_view;
        }
        paint(ctx, indices, data) {
            if (this.has_webgl()) {
                this.glglyph.render(ctx, indices, this.base ?? this);
            }
            else if (this.canvas.webgl != null && settings_1.settings.force_webgl) {
                throw new Error(`${this} doesn't support webgl rendering`);
            }
            else {
                this._paint(ctx, indices, data);
            }
        }
        has_finished() {
            return true;
        }
        notify_finished() {
            this.renderer.notify_finished();
        }
        _bounds(bounds) {
            return bounds;
        }
        bounds(window_axis = "none") {
            switch (window_axis) {
                case "none": {
                    return this._bounds(this.index.bbox);
                }
                case "x": {
                    const x_range = this.renderer.coordinates.x_source;
                    if (isNaN(x_range.start) || isNaN(x_range.end)) {
                        return this._bounds(this.index.bbox);
                    }
                    const hit_box = bbox.x_range(x_range.start, x_range.end);
                    const { x0, y0, x1, y1 } = this.index.bounds(hit_box);
                    if (!isFinite(y0 + y1)) {
                        return this._bounds(this.index.bbox);
                    }
                    return this._bounds({ x0, y0, x1, y1 });
                }
                case "y": {
                    const y_range = this.renderer.coordinates.y_source;
                    if (isNaN(y_range.start) || isNaN(y_range.end)) {
                        return this._bounds(this.index.bbox);
                    }
                    const hit_box = bbox.y_range(y_range.start, y_range.end);
                    const { x0, y0, x1, y1 } = this.index.bounds(hit_box);
                    if (!isFinite(x0 + x1)) {
                        return this._bounds(this.index.bbox);
                    }
                    return this._bounds({ x0, y0, x1, y1 });
                }
            }
        }
        log_bounds() {
            const { x0, x1 } = this.index.bounds(bbox.positive_x());
            const { y0, y1 } = this.index.bounds(bbox.positive_y());
            return this._bounds({ x0, y0, x1, y1 });
        }
        get_anchor_point(anchor, i, [sx, sy]) {
            switch (anchor) {
                case "center":
                case "center_center": {
                    const [x, y] = this.scenterxy(i, sx, sy);
                    return { x, y };
                }
                default:
                    return null;
            }
        }
        sdist(scale, pts, spans, pts_location = "edge", dilate = false) {
            const n = pts.length;
            const sdist = new types_1.ScreenArray(n);
            const compute = scale.s_compute;
            if (pts_location == "center") {
                for (let i = 0; i < n; i++) {
                    const pts_i = pts[i];
                    const halfspan_i = spans.get(i) / 2;
                    const spt0 = compute(pts_i - halfspan_i);
                    const spt1 = compute(pts_i + halfspan_i);
                    sdist[i] = abs(spt1 - spt0);
                }
            }
            else {
                for (let i = 0; i < n; i++) {
                    const pts_i = pts[i];
                    const spt0 = compute(pts_i);
                    const spt1 = compute(pts_i + spans.get(i));
                    sdist[i] = abs(spt1 - spt0);
                }
            }
            if (dilate) {
                (0, arrayable_1.inplace_map)(sdist, (sd) => ceil(sd));
            }
            return sdist;
        }
        draw_legend_for_index(_ctx, _bbox, _index) { }
        hit_test(geometry) {
            const hit = (() => {
                switch (geometry.type) {
                    case "point": return this._hit_point?.(geometry);
                    case "span": return this._hit_span?.(geometry);
                    case "rect": return this._hit_rect?.(geometry);
                    case "poly": return this._hit_poly?.(geometry);
                }
            })();
            if (hit != null) {
                return hit;
            }
            if (!this._nohit_warned.has(geometry.type)) {
                logging_1.logger.debug(`'${geometry.type}' selection not available for ${this.model.type}`);
                this._nohit_warned.add(geometry.type);
            }
            return null;
        }
        _hit_rect_against_index(geometry) {
            const { sx0, sx1, sy0, sy1 } = geometry;
            const [x0, x1] = this.renderer.coordinates.x_scale.r_invert(sx0, sx1);
            const [y0, y1] = this.renderer.coordinates.y_scale.r_invert(sy0, sy1);
            const indices = [...this.index.indices({ x0, x1, y0, y1 })];
            return new selection_1.Selection({ indices });
        }
        _project_xy(x, xs, y, ys) {
            const inherited_x = this._is_inherited(x);
            const inherited_y = this._is_inherited(y);
            if (!inherited_x && !inherited_y) {
                projections_1.inplace.project_xy(xs, ys);
            }
            else if (!inherited_x || !inherited_y) {
                const [proj_x, proj_y] = (0, projections_1.project_xy)(xs, ys);
                this._define_attr(x, proj_x);
                this._define_attr(y, proj_y);
            }
        }
        _project_data() { }
        *_iter_visuals() {
            for (const visual of this.visuals) {
                for (const prop of visual) {
                    if (prop instanceof p.VectorSpec || prop instanceof p.ScalarSpec) {
                        yield prop;
                    }
                }
            }
        }
        _base = null;
        get base() {
            return this._base;
        }
        set_base(base) {
            if (base != this && base instanceof this.constructor) {
                this._base = base;
            }
            else {
                this._base = null;
            }
        }
        _define_or_inherit_attr(attr, fn) {
            const value = fn();
            if (value === exports.inherit) {
                this._inherit_attr(attr);
            }
            else {
                this._define_attr(attr, value);
            }
        }
        _define_attr(attr, value) {
            Object.defineProperty(this, attr, {
                configurable: true,
                enumerable: true,
                value,
            });
            this._define_inherited(attr, false);
        }
        _inherit_attr(attr) {
            const { base } = this;
            (0, assert_1.assert)(base != null);
            this._inherit_from(attr, base);
        }
        _inherit_from(attr, base) {
            Object.defineProperty(this, attr, {
                configurable: true,
                enumerable: true,
                get() {
                    return base[attr];
                },
            });
            this._define_inherited(attr, true);
        }
        _define_inherited(attr, value) {
            Object.defineProperty(this, `inherited_${attr}`, {
                configurable: true,
                enumerable: true,
                value,
            });
        }
        /**
         * Determine if this view can inherit a property value from the base glyph.
         *
         * This enables selection/hover/muted glyphs to inherit properties from the base
         * glyph when not explicitly overridden, which is critical when a derived glyph
         * only overrides some properties (e.g., radius) but should inherit others
         * (e.g., start_angle, end_angle).
         *
         * Inheritance occurs when either:
         * 1. The derived property value equals the base value (original behavior), OR
         * 2. The derived property value equals its default (new behavior)
         *
         * Example (case 2):
         *   Base glyph: start_angle: {value: 0}
         *   Selection glyph: (unspecified) → gets default {field: "start_angle"}
         *   Without inheritance: would try to read missing field → rendering fails
         *   With inheritance: inherits {value: 0} from base → renders correctly ✓
         *
         * @param prop - The property to check for inheritance
         * @param base - The base glyph view to potentially inherit from
         * @returns true if the property should be inherited from base
         */
        _can_inherit_from(prop, base) {
            if (base == null) {
                return false;
            }
            const base_prop = base.model.property(prop.attr);
            const value = prop.get_value();
            const base_value = base_prop.get_value();
            try {
                if ((0, eq_1.is_equal)(value, base_value)) {
                    return true;
                }
                // If the selection glyph's property has its default value, inherit from base
                // This handles cases like: base glyph has start_angle={value:0}, selection glyph
                // doesn't specify start_angle (gets default {field:"start_angle"}), but should
                // inherit the base value instead of trying to read a non-existent field
                const default_value = prop.default_value(this.model);
                return (0, eq_1.is_equal)(value, default_value);
            }
            catch (error) {
                if (error instanceof eq_1.EqNotImplemented) {
                    return false;
                }
                else {
                    throw error;
                }
            }
        }
        _is_inherited(prop) {
            const name = (0, types_2.isString)(prop) ? prop : prop.attr;
            return this[`inherited_${name}`];
        }
        set_visuals(source, indices) {
            for (const prop of this._iter_visuals()) {
                const { base } = this;
                if (base != null && this._can_inherit_from(prop, base)) {
                    this._inherit_from(prop.attr, base);
                }
                else {
                    const uniform = prop.uniform(source).select(indices);
                    this._define_attr(prop.attr, uniform);
                }
            }
            for (const visual of this.visuals) {
                visual.update();
            }
            if (this.has_webgl()) {
                this.glglyph.set_visuals_changed();
            }
        }
        _transform_array(prop, array) {
            // examine just the top level of a 2-d array to validate
            // that every subitem is an array of some kind, as expected
            if (prop instanceof p.CoordinateSeqSpec) {
                // work around issues with empty data sources (see #14424)
                const indeterminate_length = this.renderer.data_source.get_value().get_length() == null;
                if (!indeterminate_length && !(0, array_1.every)(array, types_2.isArrayable)) {
                    const msg = `expected a 2-d array for ${this.model.type}.${prop.attr}`;
                    logging_1.logger.error(msg);
                    throw new Error(msg);
                }
            }
            const { x_source, y_source } = this.renderer.coordinates;
            const range = prop.dimension == "x" ? x_source : y_source;
            if (range instanceof factor_range_1.FactorRange) {
                if (prop instanceof p.CoordinateSpec) {
                    array = range.v_synthetic(array);
                }
                else if (prop instanceof p.CoordinateSeqSpec) {
                    for (let i = 0; i < array.length; i++) {
                        array[i] = range.v_synthetic(array[i]);
                    }
                }
                else if (prop instanceof p.CoordinateSeqSeqSeqSpec) {
                    // TODO
                }
            }
            let final_array;
            if (prop instanceof p.CoordinateSeqSpec) {
                // TODO: infer precision
                final_array = ragged_array_1.RaggedArray.from(array, Float64Array);
            }
            else if (prop instanceof p.CoordinateSeqSeqSeqSpec) {
                // TODO RaggedArrayN
                final_array = array;
            }
            else {
                final_array = array;
            }
            return final_array;
        }
        async set_data(source, indices, indices_to_update) {
            const visuals = new Set(this._iter_visuals());
            const { base } = this;
            this._data_size = indices.count;
            for (const prop of this.model) {
                if (!(prop instanceof p.VectorSpec || prop instanceof p.ScalarSpec)) {
                    continue;
                }
                if (visuals.has(prop)) { // let set_visuals() do the work, at least for now
                    continue;
                }
                if (base != null && this._can_inherit_from(prop, base)) {
                    this._inherit_from(prop.attr, base);
                    if (prop instanceof p.DistanceSpec || prop instanceof p.ScreenSizeSpec) {
                        this._inherit_from(`max_${prop.attr}`, base);
                    }
                }
                else {
                    if (prop instanceof p.BaseCoordinateSpec) {
                        const array = this._transform_array(prop, indices.select(prop.array(source)));
                        this._define_attr(prop.attr, array);
                    }
                    else {
                        const uniform = prop.uniform(source).select(indices);
                        this._define_attr(prop.attr, uniform);
                        if (prop instanceof p.DistanceSpec || prop instanceof p.ScreenSizeSpec) {
                            const max_value = uniforms.max(uniform);
                            this._define_attr(`max_${prop.attr}`, max_value);
                        }
                    }
                }
            }
            if (this.renderer.plot_view.model.use_map) {
                this._project_data();
            }
            this._set_data(indices_to_update ?? null); // TODO doesn't take subset indices into account
            await this._set_lazy_data(indices_to_update ?? null); // TODO doesn't take subset indices into account
            for (const decoration of this.decorations.values()) {
                decoration.marking.set_data(source, indices);
            }
            if (this.glglyph != null) {
                this._can_use_webgl = this._compute_can_use_webgl();
            }
            if (this.has_webgl()) {
                this.glglyph.set_data_changed();
            }
            if (base == null) {
                this.index_data();
            }
        }
        _set_data(_indices) { }
        async _set_lazy_data(_indices) { }
        /**
         * Any data transformations that require visuals.
         */
        after_visuals() { }
        async after_lazy_visuals() { }
        get _index_size() {
            return this.data_size;
        }
        index_data() {
            const index = new spatial_1.SpatialIndex(this._index_size);
            this._index_data(index);
            index.finish();
            this._index = index;
        }
        mask_data() {
            /** Returns subset indices in the viewport. */
            if (this._mask_data == null) {
                return types_1.Indices.all_set(this.data_size);
            }
            else {
                return this._mask_data();
            }
        }
        map_data() {
            const { x_scale, y_scale } = this.renderer.coordinates;
            const { base } = this;
            const v_compute = (prop) => {
                const scale = prop.dimension == "x" ? x_scale : y_scale;
                const array = this[prop.attr];
                if (array instanceof ragged_array_1.RaggedArray) {
                    return new ragged_array_1.RaggedArray(array.offsets, scale.v_compute(array.data));
                }
                else {
                    return scale.v_compute(array);
                }
            };
            for (const prop of this.model) {
                if (prop instanceof p.BaseCoordinateSpec) {
                    if (base != null && this._is_inherited(prop)) {
                        this._inherit_from(`s${prop.attr}`, base);
                    }
                    else {
                        const array = v_compute(prop);
                        this._define_attr(`s${prop.attr}`, array);
                    }
                }
            }
            this._map_data();
            if (this.has_webgl()) {
                this.glglyph.set_data_mapped();
            }
        }
        // This is where specs not included in coords are computed, e.g. radius.
        _map_data() { }
        get bbox() {
            if (this.base == null) {
                const { x0, y0, x1, y1 } = this.index.bbox;
                const { x_scale, y_scale } = this.renderer.coordinates;
                const [sx0, sx1] = x_scale.r_compute(x0, x1);
                const [sy0, sy1] = y_scale.r_compute(y0, y1);
                return bbox_1.BBox.from_rect({ x0: sx0, y0: sy0, x1: sx1, y1: sy1 });
            }
            else {
                return undefined;
            }
        }
    }
    exports.GlyphView = GlyphView;
    class Glyph extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ List, Ref }) => ({
                decorations: [List(Ref(decoration_1.Decoration)), []],
            }));
        }
    }
    exports.Glyph = Glyph;
},
/* core/util/ragged_array.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const eq_1 = require(27) /* ./eq */;
    const assert_1 = require(13) /* ./assert */;
    class RaggedArray {
        offsets;
        data;
        static [Symbol.toStringTag] = "RaggedArray";
        constructor(offsets, data) {
            this.offsets = offsets;
            this.data = data;
        }
        [eq_1.equals](that, cmp) {
            return cmp.arrays(this.offsets, that.offsets) && cmp.arrays(this.data, that.data);
        }
        get length() {
            return this.offsets.length;
        }
        clone() {
            return new RaggedArray(this.offsets.slice(), this.data.slice());
        }
        static from(items, ctor) {
            const n = items.length;
            let offset = 0;
            const offsets = (() => {
                const offsets = new Uint32Array(n);
                for (let i = 0; i < n; i++) {
                    const length = items[i].length;
                    offsets[i] = offset;
                    offset += length;
                }
                if (offset < 256) {
                    return new Uint8Array(offsets);
                }
                else if (offset < 65536) {
                    return new Uint16Array(offsets);
                }
                else {
                    return offsets;
                }
            })();
            const array = new ctor(offset);
            for (let i = 0; i < n; i++) {
                array.set(items[i], offsets[i]);
            }
            return new RaggedArray(offsets, array);
        }
        *[Symbol.iterator]() {
            const { offsets, length } = this;
            for (let i = 0; i < length; i++) {
                yield this.data.subarray(offsets[i], offsets[i + 1]);
            }
        }
        _check_bounds(i) {
            (0, assert_1.assert)(0 <= i && i < this.length, `Out of bounds: 0 <= ${i} < ${this.length}`);
        }
        get(i) {
            this._check_bounds(i);
            const { offsets } = this;
            return this.data.subarray(offsets[i], offsets[i + 1]);
        }
        set(i, array) {
            this._check_bounds(i);
            this.data.set(array, this.offsets[i]);
        }
    }
    exports.RaggedArray = RaggedArray;
},
/* core/util/spatial.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(25) /* ../types */;
    const bbox_1 = require(62) /* ./bbox */;
    /*
     Algorithm (ported from https://github.com/rawrunprotected/hilbert_curves & https://github.com/becheran/fast-hilbert)
    
     Copyright (c) 2021 Armin Becher
    
     Permission is hereby granted, free of charge, to any person obtaining a copy
     of this software and associated documentation files (the "Software"), to deal
     in the Software without restriction, including without limitation the rights
     to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     copies of the Software, and to permit persons to whom the Software is
     furnished to do so, subject to the following conditions:
    
     The above copyright notice and this permission notice shall be included in all
     copies or substantial portions of the Software.
    
     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
     AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
     SOFTWARE.
    
     LUT-based Hilbert curve: xy → 32-bit Hilbert index on a 2^16 × 2^16 grid.
    
     The 2D Hilbert curve is a state machine with 4 orientations.
     At each step we consume 4 bits of x and 4 bits of y (8 bits total = 1 Morton byte),
     emit 8 bits of Hilbert output, and transition to the next state.
     16 input bits ÷ 4 bits/step = 4 steps total (fully unrolled).
    */
    // 1-bit state machine: index = state(2b) << 2 | xb(1b) << 1 | yb(1b) → next_state(2b) << 2 | h(2b)
    // Derived by probing the reference function for all 4 orientation states.
    const _LUT1 = new Uint8Array([
        //  (s=0)         (s=1)         (s=2)          (s=3)
        4, 1, 15, 2, 0, 11, 5, 6, 10, 7, 9, 12, 14, 13, 3, 8,
    ]);
    // 4-bit state machine: compose 4 consecutive 1-bit steps.
    // index  = state(2b) << 8 | x4(4b) << 4 | y4(4b)   → 1024 Uint16 entries
    // value  = next_state(2b) << 8 | h8(8b)
    // Size: 1024 × 2 bytes = 2 KB — fits into L1 cache.
    const HILBERT_LUT = (() => {
        const lut = new Uint16Array(1024);
        for (let state = 0; state < 4; state++) {
            for (let x4 = 0; x4 < 16; x4++) {
                for (let y4 = 0; y4 < 16; y4++) {
                    let s = state;
                    let hOut = 0;
                    // Process 4 bit-pairs MSB first
                    for (let bit = 3; bit >= 0; bit--) {
                        const e = _LUT1[(s << 2) | (((x4 >>> bit) & 1) << 1) | ((y4 >>> bit) & 1)];
                        hOut = (hOut << 2) | (e & 3);
                        s = e >>> 2;
                    }
                    lut[(state << 8) | (x4 << 4) | y4] = (s << 8) | hOut;
                }
            }
        }
        return lut;
    })();
    function compute_hilbert(x, y) {
        let e;
        let s = 0;
        let h = 0;
        e = HILBERT_LUT[(s << 8) | (((x >>> 12) & 15) << 4) | ((y >>> 12) & 15)];
        h = (h << 8) | (e & 255);
        s = e >>> 8;
        e = HILBERT_LUT[(s << 8) | (((x >>> 8) & 15) << 4) | ((y >>> 8) & 15)];
        h = (h << 8) | (e & 255);
        s = e >>> 8;
        e = HILBERT_LUT[(s << 8) | (((x >>> 4) & 15) << 4) | ((y >>> 4) & 15)];
        h = (h << 8) | (e & 255);
        s = e >>> 8;
        e = HILBERT_LUT[(s << 8) | (((x) & 15) << 4) | ((y) & 15)];
        h = (h << 8) | (e & 255);
        return h >>> 0;
    }
    class SpatialIndex {
        /* Core algorithm is heavily inspired by the flatbush libary (https://github.com/mourner/flatbush)
        Copyright (c) 2022, Vladimir Agafonkin
      
        Permission to use, copy, modify, and/or distribute this software for any purpose
        with or without fee is hereby granted, provided that the above copyright notice
        and this permission notice appear in all copies.
      
        THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
        REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
        FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
        INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
        OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
        TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
        THIS SOFTWARE.
        */
        // 4 coordinates values per rect -> bitshift by 2 (or multiply by 4) to transform index
        factor_bbox = 4;
        shift_factor_bbox = 2;
        n_items;
        node_size;
        array_type_coordinates;
        array_type_indices;
        _tree_level_bounds;
        _n_total_nodes;
        _coordinate_index_position;
        minX;
        minY;
        maxX;
        maxY;
        // buffer layout: [coordinate rects - coordinate indices]
        _data_byte_buffer;
        _bboxes;
        _indices;
        constructor(n_items, node_size = 16, array_type_coordinates = Float64Array) {
            if (!Number.isInteger(n_items) || n_items < 0) {
                throw new Error(`Invalid coordinates count: ${n_items}. Value must be a non-negative integer.`);
            }
            if (!Number.isInteger(node_size) || node_size < 0) {
                throw new Error(`Invalid node_size: ${node_size}. Value must be a non-negative integer.`);
            }
            this.n_items = n_items;
            this.node_size = Math.min(Math.max(node_size, 2), 65535);
            this.array_type_coordinates = array_type_coordinates;
            this._coordinate_index_position = 0;
            this.minX = Infinity;
            this.minY = Infinity;
            this.maxX = -Infinity;
            this.maxY = -Infinity;
            if (n_items === 0) {
                // init empty spatial index
                this._tree_level_bounds = [0];
                this._n_total_nodes = 0;
                this.array_type_indices = Uint16Array;
                this._data_byte_buffer = new ArrayBuffer(0);
                this._bboxes = new this.array_type_coordinates(this._data_byte_buffer, 0, 0);
                this._indices = new this.array_type_indices(this._data_byte_buffer, 0, 0);
                return;
            }
            this._init_tree_structure();
            this.array_type_indices = this._n_total_nodes < 16384 ? Uint16Array : Uint32Array;
            this._configure_data_buffer();
        }
        _init_tree_structure() {
            let node_count = this.n_items;
            let nodes_last_level = node_count;
            const cumulative_nodes_per_level = [nodes_last_level];
            do {
                const nodes_this_level = Math.ceil(nodes_last_level / this.node_size);
                node_count += nodes_this_level;
                cumulative_nodes_per_level.push(node_count);
                nodes_last_level = nodes_this_level;
            } while (nodes_last_level !== 1);
            this._tree_level_bounds = cumulative_nodes_per_level.map(x => x * this.factor_bbox);
            this._n_total_nodes = node_count;
        }
        _configure_data_buffer() {
            const bytes_per_coordinate_value = this.array_type_coordinates.BYTES_PER_ELEMENT;
            const n_total_coordinate_values = this._n_total_nodes * this.factor_bbox;
            const n_bytes_nodes = n_total_coordinate_values * bytes_per_coordinate_value;
            const bytes_per_index_value = this.array_type_indices.BYTES_PER_ELEMENT;
            const n_bytes_indices = this._n_total_nodes * bytes_per_index_value;
            const n_total_bytes = n_bytes_nodes + n_bytes_indices;
            this._data_byte_buffer = new ArrayBuffer(n_total_bytes);
            this._bboxes = new this.array_type_coordinates(this._data_byte_buffer, 0, n_total_coordinate_values);
            this._indices = new this.array_type_indices(this._data_byte_buffer, n_bytes_nodes, this._n_total_nodes);
        }
        add_rect(x0, y0, x1, y1) {
            if (!isFinite(x0 + y0 + x1 + y1)) {
                x0 = Infinity;
                y0 = Infinity;
                x1 = -Infinity;
                y1 = -Infinity;
            }
            const { _indices, _bboxes } = this;
            const index = this._coordinate_index_position >> this.shift_factor_bbox;
            _indices[index] = index;
            _bboxes[this._coordinate_index_position++] = x0;
            _bboxes[this._coordinate_index_position++] = y0;
            _bboxes[this._coordinate_index_position++] = x1;
            _bboxes[this._coordinate_index_position++] = y1;
            if (x0 < this.minX) {
                this.minX = x0;
            }
            if (y0 < this.minY) {
                this.minY = y0;
            }
            if (x1 > this.maxX) {
                this.maxX = x1;
            }
            if (y1 > this.maxY) {
                this.maxY = y1;
            }
        }
        add_point(x, y) {
            this.add_rect(x, y, x, y);
        }
        add_empty() {
            this.add_rect(Infinity, Infinity, -Infinity, -Infinity);
        }
        build_index() {
            const { n_items, _bboxes, minX, minY, maxX, maxY } = this;
            const index = this._coordinate_index_position >> this.shift_factor_bbox;
            if (index !== n_items) {
                throw new Error(`Index is at wrong position, added ${index} items when expected ${n_items}.`);
            }
            if (n_items <= this.node_size) {
                // single and therefore the root node
                _bboxes[this._coordinate_index_position++] = minX;
                _bboxes[this._coordinate_index_position++] = minY;
                _bboxes[this._coordinate_index_position++] = maxX;
                _bboxes[this._coordinate_index_position++] = maxY;
                return;
            }
            this._optimize_item_order();
            this._generate_internal_tree_nodes();
        }
        finish() {
            if (this.n_items === 0) {
                return;
            }
            this.build_index();
        }
        get bbox() {
            const { minX, minY, maxX, maxY } = this;
            return { x0: minX, y0: minY, x1: maxX, y1: maxY };
        }
        indices(rect) {
            const { x0, y0, x1, y1 } = this._normalize(rect);
            const result = new types_1.Indices(this.n_items);
            this._search(x0, y0, x1, y1, (index) => {
                result.set_unchecked(index);
                return false;
            });
            return result;
        }
        bounds(rect) {
            const { x0, y0, x1, y1 } = this._normalize(rect);
            const result = (0, bbox_1.empty)();
            this._search(x0, y0, x1, y1, (_, node_x0, node_y0, node_x1, node_y1) => {
                if (node_x0 >= x0 && node_x0 < result.x0) {
                    result.x0 = node_x0;
                }
                if (node_x1 <= x1 && node_x1 > result.x1) {
                    result.x1 = node_x1;
                }
                if (node_y0 >= y0 && node_y0 < result.y0) {
                    result.y0 = node_y0;
                }
                if (node_y1 <= y1 && node_y1 > result.y1) {
                    result.y1 = node_y1;
                }
                return false;
            });
            return result;
        }
        _search(minX, minY, maxX, maxY, leaf_fn) {
            const { _coordinate_index_position, _bboxes, n_items } = this;
            if (n_items === 0) {
                return;
            }
            if (_coordinate_index_position !== _bboxes.length) {
                throw new Error("Data is not yet indexed - call finish().");
            }
            const node_index = _bboxes.length - this.factor_bbox;
            this._search_recursive(minX, minY, maxX, maxY, node_index, leaf_fn);
        }
        _search_recursive(minX, minY, maxX, maxY, node_index, leaf_fn) {
            const { n_items, node_size, _bboxes, _indices, _tree_level_bounds } = this;
            const end = Math.min(node_index + node_size * this.factor_bbox, SpatialIndex._upperBound(node_index, _tree_level_bounds));
            // search through child nodes
            for (let pos = node_index; pos < end; pos += this.factor_bbox) {
                // skip if no intersection with bbox
                const x0 = _bboxes[pos];
                if (maxX < x0) {
                    continue;
                }
                const y0 = _bboxes[pos + 1];
                if (maxY < y0) {
                    continue;
                }
                const x1 = _bboxes[pos + 2];
                if (minX > x1) {
                    continue;
                }
                const y1 = _bboxes[pos + 3];
                if (minY > y1) {
                    continue;
                }
                const index = _indices[pos >> this.shift_factor_bbox] | 0;
                if (node_index >= n_items * this.factor_bbox) {
                    // check if node bbox is completely inside query bbox
                    if (minX <= x0 && minY <= y0 && maxX >= x1 && maxY >= y1) {
                        this._addAllLeavesOfNode(pos, leaf_fn);
                    }
                    else {
                        this._search_recursive(minX, minY, maxX, maxY, index, leaf_fn);
                    }
                }
                else {
                    leaf_fn(index, x0, y0, x1, y1); // leaf item
                }
            }
        }
        _normalize(rect) {
            let { x0, y0, x1, y1 } = rect;
            if ((x0 > x1) && isFinite(x0 + x1)) {
                [x0, x1] = [x1, x0];
            }
            if ((y0 > y1) && isFinite(y0 + y1)) {
                [y0, y1] = [y1, y0];
            }
            return { x0, y0, x1, y1 };
        }
        _addAllLeavesOfNode(pos, leaf_fn) {
            let posStart = pos;
            let posEnd = pos;
            const { n_items, node_size, _bboxes, _indices, _tree_level_bounds, factor_bbox, shift_factor_bbox } = this;
            // depth search while not leaf
            while (posStart >= n_items * factor_bbox) {
                posStart = _indices[posStart >> shift_factor_bbox] | 0;
                const posEndStart = _indices[posEnd >> shift_factor_bbox] | 0;
                posEnd = Math.min(posEndStart + node_size * factor_bbox, SpatialIndex._upperBound(posEndStart, _tree_level_bounds)) - factor_bbox;
            }
            for (let leafPos = posStart; leafPos <= posEnd; leafPos += this.factor_bbox) {
                const leafIndex = this._indices[leafPos >> this.shift_factor_bbox];
                leaf_fn(leafIndex, _bboxes[leafPos], _bboxes[leafPos + 1], _bboxes[leafPos + 2], _bboxes[leafPos + 3]);
            }
        }
        static _upperBound(value, arr) {
            let lo = 0;
            let hi = arr.length - 1;
            while (lo < hi) {
                const mid = (lo + hi) >> 1;
                if (arr[mid] > value) {
                    hi = mid;
                }
                else {
                    lo = mid + 1;
                }
            }
            return arr[lo];
        }
        _optimize_item_order() {
            const { n_items } = this;
            const hilbert_values = new Uint32Array(n_items);
            this._compute_hilbert_values(hilbert_values);
            // sort items by their Hilbert value
            this._sort_by_hilbert_values(hilbert_values);
        }
        _compute_hilbert_values(hilbert_values) {
            const { n_items, _bboxes, minX, minY, maxX, maxY } = this;
            const width = (maxX - minX);
            const height = (maxY - minY);
            const hilbertMax = (1 << 16) - 1;
            const scaleX = hilbertMax / width;
            const scaleY = hilbertMax / height;
            // calculate Hilbert values from rect center
            for (let i = 0, pos = 0; i < n_items; i++) {
                const _minX = _bboxes[pos++];
                const _minY = _bboxes[pos++];
                const _maxX = _bboxes[pos++];
                const _maxY = _bboxes[pos++];
                const x_center = (_minX + _maxX) * 0.5;
                const y_center = (_minY + _maxY) * 0.5;
                const x = Math.floor((x_center - minX) * scaleX);
                const y = Math.floor((y_center - minY) * scaleY);
                hilbert_values[i] = compute_hilbert(x, y);
            }
        }
        _sort_by_hilbert_values(hilbert_values) {
            const { n_items, node_size, _bboxes, _indices, shift_factor_bbox } = this;
            const is_power_of_2 = (node_size & (node_size - 1)) === 0;
            const node_mask = node_size - 1;
            // log(N) allocation possible due to pushing smallest partition always last
            const stack = new Int32Array(2 * 2 * Math.ceil(Math.log2(n_items + 1)));
            let sp = 0;
            stack[sp++] = 0;
            stack[sp++] = n_items - 1;
            while (sp > 0) {
                const r = stack[--sp];
                const l = stack[--sp];
                const r_mod = is_power_of_2 ? (r & node_mask) : (r % node_size);
                if (r - l <= node_size && r - r_mod <= l) {
                    continue;
                }
                const a = hilbert_values[l];
                const b = hilbert_values[(l + r) >> 1];
                const c = hilbert_values[r];
                const pivot = ((a > b) !== (a > c)) ? a :
                    ((b < a) !== (b < c)) ? b : c;
                let i = l - 1;
                let j = r + 1;
                while (true) {
                    do {
                        i++;
                    } while (hilbert_values[i] < pivot);
                    do {
                        j--;
                    } while (hilbert_values[j] > pivot);
                    if (i >= j) {
                        break;
                    }
                    const temp_h = hilbert_values[i];
                    hilbert_values[i] = hilbert_values[j];
                    hilbert_values[j] = temp_h;
                    const k = i << shift_factor_bbox;
                    const m = j << shift_factor_bbox;
                    const b0 = _bboxes[k];
                    const b1 = _bboxes[k + 1];
                    const b2 = _bboxes[k + 2];
                    const b3 = _bboxes[k + 3];
                    _bboxes[k] = _bboxes[m];
                    _bboxes[k + 1] = _bboxes[m + 1];
                    _bboxes[k + 2] = _bboxes[m + 2];
                    _bboxes[k + 3] = _bboxes[m + 3];
                    _bboxes[m] = b0;
                    _bboxes[m + 1] = b1;
                    _bboxes[m + 2] = b2;
                    _bboxes[m + 3] = b3;
                    const temp_i = _indices[i];
                    _indices[i] = _indices[j];
                    _indices[j] = temp_i;
                }
                const left_size = j - l;
                const right_size = r - (j + 1);
                // always push smallest partition last to process it first
                if (left_size < right_size) {
                    stack[sp++] = j + 1;
                    stack[sp++] = r;
                    stack[sp++] = l;
                    stack[sp++] = j;
                }
                else {
                    stack[sp++] = l;
                    stack[sp++] = j;
                    stack[sp++] = j + 1;
                    stack[sp++] = r;
                }
            }
        }
        _generate_internal_tree_nodes() {
            // build tree bottom up
            const { node_size, _tree_level_bounds, _bboxes, _indices, shift_factor_bbox } = this;
            let pos = 0;
            for (let i = 0; i < _tree_level_bounds.length - 1; i++) {
                const level_end = _tree_level_bounds[i];
                while (pos < level_end) {
                    const index_node = pos;
                    // calculate new node
                    let node_x0 = Infinity;
                    let node_y0 = Infinity;
                    let node_x1 = -Infinity;
                    let node_y1 = -Infinity;
                    for (let j = 0; j < node_size && pos < level_end; j++) {
                        node_x0 = Math.min(node_x0, _bboxes[pos++]);
                        node_y0 = Math.min(node_y0, _bboxes[pos++]);
                        node_x1 = Math.max(node_x1, _bboxes[pos++]);
                        node_y1 = Math.max(node_y1, _bboxes[pos++]);
                    }
                    // set new node in tree structure
                    _indices[this._coordinate_index_position >> shift_factor_bbox] = index_node;
                    _bboxes[this._coordinate_index_position++] = node_x0;
                    _bboxes[this._coordinate_index_position++] = node_y0;
                    _bboxes[this._coordinate_index_position++] = node_x1;
                    _bboxes[this._coordinate_index_position++] = node_y1;
                }
            }
        }
    }
    exports.SpatialIndex = SpatialIndex;
},
/* models/graphics/decoration.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const marking_1 = require(253) /* ./marking */;
    const model_1 = require(52) /* ../../model */;
    const view_1 = require(65) /* ../../core/view */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    class DecorationView extends view_1.View {
        visuals;
        marking;
        children_views() {
            return [...super.children_views(), this.marking];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            this.marking = await (0, build_views_1.build_view)(this.model.marking, { parent: this.parent });
        }
    }
    exports.DecorationView = DecorationView;
    class Decoration extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = DecorationView;
            this.define(({ Enum, Ref }) => ({
                marking: [Ref(marking_1.Marking)],
                node: [Enum("start", "middle", "end")],
            }));
        }
    }
    exports.Decoration = Decoration;
},
/* models/glyphs/utils.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.generic_line_scalar_legend = generic_line_scalar_legend;
    exports.generic_line_vector_legend = generic_line_vector_legend;
    exports.generic_line_legend = generic_line_vector_legend;
    exports.generic_area_scalar_legend = generic_area_scalar_legend;
    exports.generic_area_vector_legend = generic_area_vector_legend;
    exports.generic_area_legend = generic_area_vector_legend;
    exports.line_interpolation = line_interpolation;
    const tslib_1 = require(1) /* tslib */;
    const hittest = tslib_1.__importStar(require(311) /* ../../core/hittest */);
    function generic_line_scalar_legend(visuals, ctx, { x0, x1, y0, y1 }) {
        ctx.save();
        ctx.beginPath();
        ctx.moveTo(x0, (y0 + y1) / 2);
        ctx.lineTo(x1, (y0 + y1) / 2);
        visuals.line.apply(ctx);
        ctx.restore();
    }
    function generic_line_vector_legend(visuals, ctx, { x0, x1, y0, y1 }, i) {
        ctx.save();
        ctx.beginPath();
        ctx.moveTo(x0, (y0 + y1) / 2);
        ctx.lineTo(x1, (y0 + y1) / 2);
        visuals.line.apply(ctx, i);
        ctx.restore();
    }
    function generic_area_scalar_legend(visuals, ctx, { x0, x1, y0, y1 }) {
        const w = Math.abs(x1 - x0);
        const dw = w * 0.1;
        const h = Math.abs(y1 - y0);
        const dh = h * 0.1;
        const sx0 = x0 + dw;
        const sx1 = x1 - dw;
        const sy0 = y0 + dh;
        const sy1 = y1 - dh;
        ctx.beginPath();
        ctx.rect(sx0, sy0, sx1 - sx0, sy1 - sy0);
        visuals.fill.apply(ctx);
        visuals.hatch?.apply(ctx);
        visuals.line?.apply(ctx);
    }
    function generic_area_vector_legend(visuals, ctx, { x0, x1, y0, y1 }, i) {
        const w = Math.abs(x1 - x0);
        const dw = w * 0.1;
        const h = Math.abs(y1 - y0);
        const dh = h * 0.1;
        const sx0 = x0 + dw;
        const sx1 = x1 - dw;
        const sy0 = y0 + dh;
        const sy1 = y1 - dh;
        ctx.beginPath();
        ctx.rect(sx0, sy0, sx1 - sx0, sy1 - sy0);
        visuals.fill.apply(ctx, i);
        visuals.hatch?.apply(ctx, i);
        visuals.line?.apply(ctx, i);
    }
    function line_interpolation(renderer, geometry, x2, y2, x3, y3) {
        const { sx, sy } = geometry;
        let x0, x1;
        let y0, y1;
        if (geometry.type == "point") {
            // The +/- adjustments here are to dilate the hit point into a virtual "segment" to use below
            [y0, y1] = renderer.yscale.r_invert(sy - 1, sy + 1);
            [x0, x1] = renderer.xscale.r_invert(sx - 1, sx + 1);
        }
        else {
            // The +/- adjustments here are to handle cases such as purely horizontal or vertical lines
            if (geometry.direction == "v") {
                [y0, y1] = renderer.yscale.r_invert(sy, sy);
                [x0, x1] = [Math.min(x2 - 1, x3 - 1), Math.max(x2 + 1, x3 + 1)];
            }
            else {
                [x0, x1] = renderer.xscale.r_invert(sx, sx);
                [y0, y1] = [Math.min(y2 - 1, y3 - 1), Math.max(y2 + 1, y3 + 1)];
            }
        }
        const { x, y } = hittest.check_2_segments_intersect(x0, y0, x1, y1, x2, y2, x3, y3);
        return [x, y]; // XXX: null is not handled at use sites
    }
},
/* core/hittest.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.point_in_poly = point_in_poly;
    exports.point_in_ellipse = point_in_ellipse;
    exports.dist_2_pts = dist_2_pts;
    exports.dist_to_segment_squared = dist_to_segment_squared;
    exports.dist_to_segment = dist_to_segment;
    exports.check_2_segments_intersect = check_2_segments_intersect;
    exports.vertex_overlap = vertex_overlap;
    exports.edge_intersection = edge_intersection;
    function point_in_poly(x, y, px, py) {
        let inside = false;
        let x1 = px[px.length - 1];
        let y1 = py[py.length - 1];
        for (let i = 0; i < px.length; i++) {
            const x2 = px[i];
            const y2 = py[i];
            if ((y1 < y) != (y2 < y)) {
                if ((x1 + (y - y1) / (y2 - y1) * (x2 - x1)) < x) {
                    inside = !inside;
                }
            }
            x1 = x2;
            y1 = y2;
        }
        return inside;
    }
    function point_in_ellipse(x, y, angle, b, a, x0, y0) {
        const A = ((Math.cos(angle) / a) ** 2 + (Math.sin(angle) / b) ** 2);
        const B = 2 * Math.cos(angle) * Math.sin(angle) * ((1 / a) ** 2 - (1 / b) ** 2);
        const C = ((Math.cos(angle) / b) ** 2 + (Math.sin(angle) / a) ** 2);
        const eqn = A * (x - x0) ** 2 + B * (x - x0) * (y - y0) + C * (y - y0) ** 2;
        const inside = eqn <= 1;
        return inside;
    }
    function dist_2_pts(p0, p1) {
        return (p0.x - p1.x) ** 2 + (p0.y - p1.y) ** 2;
    }
    function dist_to_segment_squared(p, v, w) {
        const l2 = dist_2_pts(v, w);
        if (l2 == 0) {
            return dist_2_pts(p, v);
        }
        const t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2;
        if (t < 0) {
            return dist_2_pts(p, v);
        }
        if (t > 1) {
            return dist_2_pts(p, w);
        }
        const q = { x: v.x + t * (w.x - v.x), y: v.y + t * (w.y - v.y) };
        return dist_2_pts(p, q);
    }
    function dist_to_segment(p, v, w) {
        return Math.sqrt(dist_to_segment_squared(p, v, w));
    }
    function check_2_segments_intersect(l0_x0, l0_y0, l0_x1, l0_y1, l1_x0, l1_y0, l1_x1, l1_y1) {
        /*
         *  Check if 2 segments (l0 and l1) intersect. Returns a structure with
         *  the following attributes:
         *   * hit (boolean): whether the 2 segments intersect
         *   * x (float): x coordinate of the intersection point
         *   * y (float): y coordinate of the intersection point
         */
        const den = ((l1_y1 - l1_y0) * (l0_x1 - l0_x0)) - ((l1_x1 - l1_x0) * (l0_y1 - l0_y0));
        if (den == 0) {
            return { hit: false, x: null, y: null };
        }
        else {
            let a = l0_y0 - l1_y0;
            let b = l0_x0 - l1_x0;
            const num1 = ((l1_x1 - l1_x0) * a) - ((l1_y1 - l1_y0) * b);
            const num2 = ((l0_x1 - l0_x0) * a) - ((l0_y1 - l0_y0) * b);
            a = num1 / den;
            b = num2 / den;
            const x = l0_x0 + (a * (l0_x1 - l0_x0));
            const y = l0_y0 + (a * (l0_y1 - l0_y0));
            return { hit: (a > 0 && a < 1) && (b > 0 && b < 1), x, y };
        }
    }
    // Given two polygons, is any vertex of one inside the other
    function vertex_overlap(x0, y0, x1, y1) {
        // need to check "both directions" to handle total inclusion cases
        for (let i = 0; i < x0.length; i++) {
            if (point_in_poly(x0[i], y0[i], x1, y1)) {
                return true;
            }
        }
        for (let i = 0; i < x1.length; i++) {
            if (point_in_poly(x1[i], y1[i], x0, y0)) {
                return true;
            }
        }
        return false;
    }
    // Given two polygons, do any pair of edges intersect
    function edge_intersection(x0, y0, x1, y1) {
        for (let i = 0; i < x0.length - 1; i++) {
            for (let j = 0; j < x1.length - 1; j++) {
                if (check_2_segments_intersect(x0[i], y0[i], x0[i + 1], y0[i + 1], x1[j], y1[j], x1[j + 1], y1[j + 1]).hit) {
                    return true;
                }
            }
            // consider x1, y1 "closing" segment
            if (check_2_segments_intersect(x0[i], y0[i], x0[i + 1], y0[i + 1], x1[x1.length - 1], y1[x1.length - 1], x1[0], y1[0]).hit) {
                return true;
            }
        }
        // consider x0, y0, "closing" segment
        if (check_2_segments_intersect(x0[x0.length - 1], y0[x0.length - 1], x0[0], y0[0], x1[x1.length - 1], y1[x1.length - 1], x1[0], y1[0]).hit) {
            return true;
        }
        return false;
    }
},
/* models/glyphs/step.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(305) /* ./xy_glyph */;
    const utils_1 = require(310) /* ./utils */;
    const selection_1 = require(144) /* ../selections/selection */;
    const hittest = tslib_1.__importStar(require(311) /* ../../core/hittest */);
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    const enums_1 = require(21) /* ../../core/enums */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    class StepView extends xy_glyph_1.XYGlyphView {
        async load_glglyph() {
            const { StepGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(679) /* ./webgl/step */));
            return StepGL;
        }
        _bounds(bounds) {
            // Override to account for padding
            const { pad_before, pad_after } = this.model;
            return {
                x0: bounds.x0 - pad_before,
                x1: bounds.x1 + pad_after,
                y0: bounds.y0,
                y1: bounds.y1,
            };
        }
        _paint(ctx, indices, data) {
            const npoints = indices.length;
            if (npoints < 2) {
                return;
            }
            let indices_consecutive = [];
            for (let i = 0; i < indices.length; i++) {
                if (i == 0) {
                    indices_consecutive.push(indices[i]);
                }
                else if ((indices[i] - 1) != indices[i - 1]) {
                    this._paint_consecutive(ctx, indices_consecutive, data);
                    indices_consecutive = [indices[i]];
                }
                else {
                    indices_consecutive.push(indices[i]);
                    if (i + 1 == indices.length) {
                        this._paint_consecutive(ctx, indices_consecutive, data);
                    }
                }
            }
        }
        _build_step_path(indices, data) {
            // Builds the step path points for the given indices, including padding
            const { sx, sy } = { ...this, ...data };
            const { mode, pad_before, pad_after } = this.model;
            const xs = [];
            const ys = [];
            if (indices.length == 0) {
                return { xs, ys };
            }
            const first_i = indices[0];
            const last_i = indices[indices.length - 1];
            if (pad_before != 0) {
                const pad_sx = this.renderer.xscale.s_compute(this.x[first_i] - pad_before); // screen units
                xs.push(pad_sx);
                ys.push(sy[first_i]);
            }
            // Step from data points
            for (let k = 0; k < indices.length; k++) {
                const i = indices[k];
                if (!isFinite(sx[i] + sy[i])) {
                    xs.push(NaN);
                    ys.push(NaN);
                    continue;
                }
                const has_next = k < indices.length - 1;
                const next_i = has_next ? indices[k + 1] : -1;
                const valid_next = has_next && isFinite(sx[next_i] + sy[next_i]);
                switch (mode) {
                    case "before":
                        /* First adds vertical line
                           For each point: horizontal+vertical (┐ or ┘)
                           Finally horizontal */
                        xs.push(sx[i]);
                        ys.push(sy[i]);
                        if (valid_next) {
                            xs.push(sx[i]);
                            ys.push(sy[next_i]);
                        }
                        break;
                    case "after":
                        /* First: horizontal line
                           Middle: vertical+horizontal (┌ or L)
                           Last: vertical */
                        xs.push(sx[i]);
                        ys.push(sy[i]);
                        if (valid_next) {
                            xs.push(sx[next_i]);
                            ys.push(sy[i]);
                        }
                        break;
                    case "center":
                        /* Each point contributes a horizontal segment from left_edge to right_edge at y=sy[i].
                           First: Left edge is the first x point itself.
                           Middle points: Left edge is halfway to previous point, right edge is halfway to next point.
                           Last: Right edge is the last x point itself.
                           This works with gaps as well by breaking the path */
                        const prev_i = k > 0 ? indices[k - 1] : -1;
                        const valid_prev = k > 0 && isFinite(sx[prev_i] + sy[prev_i]);
                        const left = valid_prev ? (sx[prev_i] + sx[i]) / 2 : sx[i];
                        const right = valid_next ? (sx[i] + sx[next_i]) / 2 : sx[i];
                        xs.push(left);
                        ys.push(sy[i]);
                        xs.push(right);
                        ys.push(sy[i]);
                        break;
                    default:
                        (0, assert_1.unreachable)();
                }
            }
            if (pad_after != 0) {
                const pad_sx = this.renderer.xscale.s_compute(this.x[last_i] + pad_after); // screen units
                xs.push(pad_sx);
                ys.push(sy[last_i]);
            }
            return { xs, ys };
        }
        _paint_consecutive(ctx, indices, data) {
            this.visuals.line.set_value(ctx);
            const { xs, ys } = this._build_step_path(indices, data);
            let drawing = false;
            for (let i = 0; i < xs.length; i++) {
                drawing = this._render_xy(ctx, drawing, xs[i], ys[i]);
            }
            if (drawing) {
                ctx.stroke();
            }
        }
        _render_xy(ctx, drawing, x, y) {
            if (isFinite(x + y)) {
                if (drawing) {
                    ctx.lineTo(x, y);
                }
                else {
                    ctx.beginPath();
                    ctx.moveTo(x, y);
                    drawing = true;
                }
            }
            else if (drawing) {
                ctx.stroke();
                drawing = false;
            }
            return drawing;
        }
        draw_legend_for_index(ctx, bbox, _index) {
            (0, utils_1.generic_line_scalar_legend)(this.visuals, ctx, bbox);
        }
        get_interpolation_hit(i, _geometry) {
            // For step glyphs, return the data point at index i (snapped)
            return [this.x[i], this.y[i]];
        }
        _hit_point(geometry) {
            const result = new selection_1.Selection();
            const point = { x: geometry.sx, y: geometry.sy };
            const threshold = Math.max(2, this.line_width.value / 2);
            const mode = this.model.mode;
            const n = Math.min(this.sx.length, this.sy.length);
            let shortest = Infinity;
            let hit_index = null;
            for (let j = 0; j < n - 1; j++) {
                const segments = this._get_step_segments(j, mode);
                for (const [p0, p1] of segments) {
                    const dist = hittest.dist_to_segment(point, p0, p1);
                    if (dist < threshold && dist < shortest) {
                        shortest = dist;
                        hit_index = j;
                    }
                }
            }
            if (hit_index != null) {
                result.add_to_selected_glyphs(this.model);
                result.view = this;
                result.line_indices = [hit_index];
            }
            return result;
        }
        _hit_span(geometry) {
            const { sx, sy } = geometry;
            let val;
            let values;
            if (geometry.direction == "v") {
                val = this.renderer.yscale.invert(sy);
                values = this.y;
            }
            else {
                val = this.renderer.xscale.invert(sx);
                values = this.x;
            }
            const indices = [];
            for (let i = 0, end = values.length - 1; i < end; i++) {
                const curr = values[i];
                const next = values[i + 1];
                if ((curr <= val && val <= next) || (next <= val && val <= curr)) {
                    indices.push(i);
                }
            }
            const result = new selection_1.Selection();
            if (indices.length != 0) {
                result.add_to_selected_glyphs(this.model);
                result.view = this;
                result.line_indices = indices;
            }
            return result;
        }
        /**
         * Convert a step between two data points into line segments.
         * For "before" mode: vertical then horizontal.
         * For "after" mode: horizontal then vertical.
         * For "center" mode: horizontal to midpoint, vertical, then horizontal.
         */
        _get_step_segments(j, mode) {
            const segments = [];
            const x0 = this.sx[j];
            const y0 = this.sy[j];
            const x1 = this.sx[j + 1];
            const y1 = this.sy[j + 1];
            if (!isFinite(x0 + y0 + x1 + y1)) {
                return segments;
            }
            switch (mode) {
                case "before":
                    segments.push([{ x: x0, y: y0 }, { x: x0, y: y1 }]);
                    segments.push([{ x: x0, y: y1 }, { x: x1, y: y1 }]);
                    break;
                case "after":
                    segments.push([{ x: x0, y: y0 }, { x: x1, y: y0 }]);
                    segments.push([{ x: x1, y: y0 }, { x: x1, y: y1 }]);
                    break;
                case "center": {
                    const midx = (x0 + x1) / 2;
                    segments.push([{ x: x0, y: y0 }, { x: midx, y: y0 }]);
                    segments.push([{ x: midx, y: y0 }, { x: midx, y: y1 }]);
                    segments.push([{ x: midx, y: y1 }, { x: x1, y: y1 }]);
                    break;
                }
            }
            return segments;
        }
    }
    exports.StepView = StepView;
    class Step extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = StepView;
            this.mixins(mixins.LineScalar);
            this.define(({ Float, NonNegative }) => ({
                mode: [enums_1.StepMode, "before"],
                pad_before: [NonNegative(Float), 0],
                pad_after: [NonNegative(Float), 0],
            }));
        }
    }
    exports.Step = Step;
},
/* models/glyphs/patch.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(305) /* ./xy_glyph */;
    const utils_1 = require(310) /* ./utils */;
    const hittest = tslib_1.__importStar(require(311) /* ../../core/hittest */);
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    const selection_1 = require(144) /* ../selections/selection */;
    class PatchView extends xy_glyph_1.XYGlyphView {
        async load_glglyph() {
            const { PatchGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(672) /* ./webgl/patch */));
            return PatchGL;
        }
        _paint(ctx, indices, data) {
            const { sx, sy } = { ...this, ...data };
            let move = true;
            ctx.beginPath();
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                if (!isFinite(sx_i + sy_i)) {
                    ctx.closePath();
                    move = true;
                }
                else {
                    if (move) {
                        ctx.moveTo(sx_i, sy_i);
                        move = false;
                    }
                    else {
                        ctx.lineTo(sx_i, sy_i);
                    }
                }
            }
            ctx.closePath();
            this.visuals.fill.apply(ctx, "evenodd");
            this.visuals.hatch.apply(ctx, "evenodd");
            this.visuals.line.apply(ctx);
        }
        draw_legend_for_index(ctx, bbox, _index) {
            (0, utils_1.generic_area_scalar_legend)(this.visuals, ctx, bbox);
        }
        _hit_point(geometry) {
            const result = new selection_1.Selection();
            const { sx, sy } = geometry;
            // Collect NaN-separated sub-paths
            const sub_paths_sx = [];
            const sub_paths_sy = [];
            const n = this.sx.length;
            let k = 0;
            for (let j = 0; j <= n; j++) {
                if (j == n || isNaN(this.sx[j])) {
                    if (j > k) {
                        // Use subarray to create views (like patches.ts does)
                        sub_paths_sx.push(this.sx.subarray(k, j));
                        sub_paths_sy.push(this.sy.subarray(k, j));
                    }
                    k = j + 1;
                }
            }
            if (sub_paths_sx.length == 0) {
                return result;
            }
            // Use "evenodd" fill rule (matches Canvas2D rendering):
            // A point is inside the filled region if it's contained by an odd number of sub-paths.
            // This handles both holes (even count = outside) and disjoint polygons (each adds to count).
            let inside_count = 0;
            for (let i = 0; i < sub_paths_sx.length; i++) {
                if (hittest.point_in_poly(sx, sy, sub_paths_sx[i], sub_paths_sy[i])) {
                    inside_count++;
                }
            }
            // Odd count = inside filled region, Even count = inside hole or outside
            if (inside_count % 2 === 1) {
                result.add_to_selected_glyphs(this.model);
                result.view = this;
            }
            return result;
        }
    }
    exports.PatchView = PatchView;
    class Patch extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = PatchView;
            this.mixins([mixins.LineScalar, mixins.FillScalar, mixins.HatchScalar]);
        }
    }
    exports.Patch = Patch;
},
/* models/glyphs/harea_step.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const area_1 = require(315) /* ./area */;
    const hittest = tslib_1.__importStar(require(311) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const enums_1 = require(21) /* ../../core/enums */;
    const flip_step_mode_1 = require(316) /* ../../core/util/flip_step_mode */;
    const selection_1 = require(144) /* ../selections/selection */;
    class HAreaStepView extends area_1.AreaView {
        _index_data(index) {
            const { min, max } = Math;
            const { x1, x2, y } = this;
            for (let i = 0; i < this.data_size; i++) {
                const x1_i = x1[i];
                const x2_i = x2[i];
                const y_i = y[i];
                index.add_rect(min(x1_i, x2_i), y_i, max(x1_i, x2_i), y_i);
            }
        }
        _step_path(ctx, mode, sx, sy, from_i, to_i) {
            // Assume the path was already moved to the first point
            let prev_x = sx[from_i];
            let prev_y = sy[from_i];
            const idx_dir = from_i < to_i ? 1 : -1;
            for (let i = from_i + idx_dir; i != to_i; i += idx_dir) {
                switch (mode) {
                    case "before": {
                        ctx.lineTo(sx[i], prev_y);
                        ctx.lineTo(sx[i], sy[i]);
                        break;
                    }
                    case "after": {
                        ctx.lineTo(prev_x, sy[i]);
                        ctx.lineTo(sx[i], sy[i]);
                        break;
                    }
                    case "center": {
                        const mid_y = (prev_y + sy[i]) / 2;
                        ctx.lineTo(prev_x, mid_y);
                        ctx.lineTo(sx[i], mid_y);
                        ctx.lineTo(sx[i], sy[i]);
                        break;
                    }
                }
                prev_x = sx[i];
                prev_y = sy[i];
            }
        }
        _paint(ctx, _indices, data) {
            const { sx1, sx2, sy } = { ...this, ...data };
            const forward_mode = this.model.step_mode;
            const backward_mode = (0, flip_step_mode_1.flip_step_mode)(this.model.step_mode);
            ctx.beginPath();
            ctx.moveTo(sx1[0], sy[0]);
            this._step_path(ctx, forward_mode, sx1, sy, 0, sy.length);
            this._step_path(ctx, backward_mode, sx2, sy, sy.length, -1);
            ctx.closePath();
            this.visuals.fill.apply(ctx);
            this.visuals.hatch.apply(ctx);
        }
        scenterxy(i) {
            const scx = (this.sx1[i] + this.sx2[i]) / 2;
            const scy = this.sy[i];
            return [scx, scy];
        }
        _line_selection_for(i) {
            return new selection_1.Selection({ line_indices: [i], selected_glyphs: [this.model], view: this });
        }
        _hit_point_before(geometry) {
            const { sy, sx1, sx2 } = this;
            for (let i = 1; i < this.data_size; i++) {
                const px = [sx1[i], sx1[i], sx2[i], sx2[i]];
                const py = [sy[i - 1], sy[i], sy[i], sy[i - 1]];
                if (hittest.point_in_poly(geometry.sx, geometry.sy, px, py)) {
                    return this._line_selection_for(i);
                }
            }
            return new selection_1.Selection();
        }
        _hit_point_after(geometry) {
            const { sy, sx1, sx2 } = this;
            for (let i = 0; i < this.data_size - 1; i++) {
                const px = [sx1[i], sx1[i], sx2[i], sx2[i]];
                const py = [sy[i], sy[i + 1], sy[i + 1], sy[i]];
                if (hittest.point_in_poly(geometry.sx, geometry.sy, px, py)) {
                    return this._line_selection_for(i);
                }
            }
            return new selection_1.Selection();
        }
        _hit_point_center(geometry) {
            const { sy, sx1, sx2 } = this;
            for (let i = 0; i < this.data_size; i++) {
                const mid_prev_y = (sy[i - 1] + sy[i]) / 2; /* undefined for first */
                const mid_next_y = (sy[i] + sy[i + 1]) / 2; /* undefined for last  */
                const px = [sx1[i], sx1[i], sx2[i], sx2[i]];
                const py = (() => {
                    if (i == 0) {
                        return [sy[i], mid_next_y, mid_next_y, sy[i]];
                    }
                    else if (i == this.data_size - 1) {
                        return [mid_prev_y, sy[i], sy[i], mid_prev_y];
                    }
                    else {
                        return [mid_prev_y, mid_next_y, mid_next_y, mid_prev_y];
                    }
                })();
                if (hittest.point_in_poly(geometry.sx, geometry.sy, px, py)) {
                    return this._line_selection_for(i);
                }
            }
            return new selection_1.Selection();
        }
        _hit_point(geometry) {
            switch (this.model.step_mode) {
                case "before": return this._hit_point_before(geometry);
                case "after": return this._hit_point_after(geometry);
                case "center": return this._hit_point_center(geometry);
            }
        }
    }
    exports.HAreaStepView = HAreaStepView;
    class HAreaStep extends area_1.Area {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = HAreaStepView;
            this.define(({}) => ({
                x1: [p.XCoordinateSpec, { field: "x1" }],
                x2: [p.XCoordinateSpec, { field: "x2" }],
                y: [p.YCoordinateSpec, { field: "y" }],
                step_mode: [enums_1.StepMode, "before"],
            }));
        }
    }
    exports.HAreaStep = HAreaStep;
},
/* models/glyphs/area.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(306) /* ./glyph */;
    const utils_1 = require(310) /* ./utils */;
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    class AreaView extends glyph_1.GlyphView {
        draw_legend_for_index(ctx, bbox, _index) {
            (0, utils_1.generic_area_scalar_legend)(this.visuals, ctx, bbox);
        }
    }
    exports.AreaView = AreaView;
    class Area extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.mixins([mixins.FillScalar, mixins.HatchScalar]);
        }
    }
    exports.Area = Area;
},
/* core/util/flip_step_mode.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.flip_step_mode = flip_step_mode;
    function flip_step_mode(mode) {
        switch (mode) {
            case "before":
                return "after";
            case "after":
                return "before";
            case "center":
                return "center";
        }
    }
},
/* models/glyphs/harea.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const area_1 = require(315) /* ./area */;
    const hittest = tslib_1.__importStar(require(311) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const selection_1 = require(144) /* ../selections/selection */;
    class HAreaView extends area_1.AreaView {
        _index_data(index) {
            const { min, max } = Math;
            const { data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const x1_i = this.x1[i];
                const x2_i = this.x2[i];
                const y_i = this.y[i];
                index.add_rect(min(x1_i, x2_i), y_i, max(x1_i, x2_i), y_i);
            }
        }
        _paint(ctx, _indices, data) {
            const { sx1, sx2, sy } = { ...this, ...data };
            ctx.beginPath();
            for (let i = 0, end = sx1.length; i < end; i++) {
                ctx.lineTo(sx1[i], sy[i]);
            }
            // iterate backwards so that the upper end is below the lower start
            for (let i = sx2.length - 1; i >= 0; i--) {
                ctx.lineTo(sx2[i], sy[i]);
            }
            ctx.closePath();
            this.visuals.fill.apply(ctx);
            this.visuals.hatch.apply(ctx);
        }
        _hit_point(geometry) {
            const L = this.sy.length;
            const result = new selection_1.Selection();
            for (let i = 0, end = L - 1; i < end; i++) {
                const sx = [this.sx1[i], this.sx1[i + 1], this.sx2[i + 1], this.sx2[i]];
                const sy = [this.sy[i], this.sy[i + 1], this.sy[i + 1], this.sy[i]];
                if (hittest.point_in_poly(geometry.sx, geometry.sy, sx, sy)) {
                    result.add_to_selected_glyphs(this.model);
                    result.view = this;
                    result.line_indices = [i];
                    break;
                }
            }
            return result;
        }
        scenterxy(i) {
            const scx = (this.sx1[i] + this.sx2[i]) / 2;
            const scy = this.sy[i];
            return [scx, scy];
        }
    }
    exports.HAreaView = HAreaView;
    class HArea extends area_1.Area {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = HAreaView;
            this.define(({}) => ({
                x1: [p.XCoordinateSpec, { field: "x1" }],
                x2: [p.XCoordinateSpec, { field: "x2" }],
                y: [p.YCoordinateSpec, { field: "y" }],
            }));
        }
    }
    exports.HArea = HArea;
},
/* models/glyphs/varea_step.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const area_1 = require(315) /* ./area */;
    const hittest = tslib_1.__importStar(require(311) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const enums_1 = require(21) /* ../../core/enums */;
    const flip_step_mode_1 = require(316) /* ../../core/util/flip_step_mode */;
    const selection_1 = require(144) /* ../selections/selection */;
    class VAreaStepView extends area_1.AreaView {
        _index_data(index) {
            const { min, max } = Math;
            const { x, y1, y2 } = this;
            for (let i = 0; i < this.data_size; i++) {
                const x_i = x[i];
                const y1_i = y1[i];
                const y2_i = y2[i];
                index.add_rect(x_i, min(y1_i, y2_i), x_i, max(y1_i, y2_i));
            }
        }
        _step_path(ctx, mode, sx, sy, from_i, to_i) {
            // Assume the path was already moved to the first point
            let prev_x = sx[from_i];
            let prev_y = sy[from_i];
            const idx_dir = from_i < to_i ? 1 : -1;
            for (let i = from_i + idx_dir; i != to_i; i += idx_dir) {
                switch (mode) {
                    case "before": {
                        ctx.lineTo(prev_x, sy[i]);
                        ctx.lineTo(sx[i], sy[i]);
                        break;
                    }
                    case "after": {
                        ctx.lineTo(sx[i], prev_y);
                        ctx.lineTo(sx[i], sy[i]);
                        break;
                    }
                    case "center": {
                        const mid_x = (prev_x + sx[i]) / 2;
                        ctx.lineTo(mid_x, prev_y);
                        ctx.lineTo(mid_x, sy[i]);
                        ctx.lineTo(sx[i], sy[i]);
                        break;
                    }
                }
                prev_x = sx[i];
                prev_y = sy[i];
            }
        }
        _paint(ctx, _indices, data) {
            const { sx, sy1, sy2 } = { ...this, ...data };
            const forward_mode = this.model.step_mode;
            const backward_mode = (0, flip_step_mode_1.flip_step_mode)(this.model.step_mode);
            ctx.beginPath();
            ctx.moveTo(sx[0], sy1[0]);
            this._step_path(ctx, forward_mode, sx, sy1, 0, sx.length);
            this._step_path(ctx, backward_mode, sx, sy2, sx.length, -1);
            ctx.closePath();
            this.visuals.fill.apply(ctx);
            this.visuals.hatch.apply(ctx);
        }
        scenterxy(i) {
            const scx = this.sx[i];
            const scy = (this.sy1[i] + this.sy2[i]) / 2;
            return [scx, scy];
        }
        _line_selection_for(i) {
            return new selection_1.Selection({ line_indices: [i], selected_glyphs: [this.model], view: this });
        }
        _hit_point_before(geometry) {
            const { sx, sy1, sy2 } = this;
            for (let i = 1; i < this.data_size; i++) {
                const px = [sx[i - 1], sx[i], sx[i], sx[i - 1]];
                const py = [sy1[i], sy1[i], sy2[i], sy2[i]];
                if (hittest.point_in_poly(geometry.sx, geometry.sy, px, py)) {
                    return this._line_selection_for(i);
                }
            }
            return new selection_1.Selection();
        }
        _hit_point_after(geometry) {
            const { sx, sy1, sy2 } = this;
            for (let i = 0; i < this.data_size - 1; i++) {
                const px = [sx[i], sx[i + 1], sx[i + 1], sx[i]];
                const py = [sy1[i], sy1[i], sy2[i], sy2[i]];
                if (hittest.point_in_poly(geometry.sx, geometry.sy, px, py)) {
                    return this._line_selection_for(i);
                }
            }
            return new selection_1.Selection();
        }
        _hit_point_center(geometry) {
            const { sx, sy1, sy2 } = this;
            for (let i = 0; i < this.data_size; i++) {
                const mid_prev_x = (sx[i - 1] + sx[i]) / 2; /* undefined for first */
                const mid_next_x = (sx[i] + sx[i + 1]) / 2; /* undefined for last  */
                const px = (() => {
                    if (i == 0) {
                        return [sx[i], mid_next_x, mid_next_x, sx[i]];
                    }
                    else if (i == this.data_size - 1) {
                        return [mid_prev_x, sx[i], sx[i], mid_prev_x];
                    }
                    else {
                        return [mid_prev_x, mid_next_x, mid_next_x, mid_prev_x];
                    }
                })();
                const py = [sy1[i], sy1[i], sy2[i], sy2[i]];
                if (hittest.point_in_poly(geometry.sx, geometry.sy, px, py)) {
                    return this._line_selection_for(i);
                }
            }
            return new selection_1.Selection();
        }
        _hit_point(geometry) {
            switch (this.model.step_mode) {
                case "before": return this._hit_point_before(geometry);
                case "after": return this._hit_point_after(geometry);
                case "center": return this._hit_point_center(geometry);
            }
        }
    }
    exports.VAreaStepView = VAreaStepView;
    class VAreaStep extends area_1.Area {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = VAreaStepView;
            this.define(({}) => ({
                x: [p.XCoordinateSpec, { field: "x" }],
                y1: [p.YCoordinateSpec, { field: "y1" }],
                y2: [p.YCoordinateSpec, { field: "y2" }],
                step_mode: [enums_1.StepMode, "before"],
            }));
        }
    }
    exports.VAreaStep = VAreaStep;
},
/* models/glyphs/varea.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const area_1 = require(315) /* ./area */;
    const hittest = tslib_1.__importStar(require(311) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const selection_1 = require(144) /* ../selections/selection */;
    class VAreaView extends area_1.AreaView {
        _index_data(index) {
            const { min, max } = Math;
            const { data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const x = this.x[i];
                const y1 = this.y1[i];
                const y2 = this.y2[i];
                index.add_rect(x, min(y1, y2), x, max(y1, y2));
            }
        }
        _paint(ctx, _indices, data) {
            const { sx, sy1, sy2 } = { ...this, ...data };
            ctx.beginPath();
            for (let i = 0, end = sy1.length; i < end; i++) {
                ctx.lineTo(sx[i], sy1[i]);
            }
            // iterate backwards so that the upper end is below the lower start
            for (let i = sy2.length - 1; i >= 0; i--) {
                ctx.lineTo(sx[i], sy2[i]);
            }
            ctx.closePath();
            this.visuals.fill.apply(ctx);
            this.visuals.hatch.apply(ctx);
        }
        scenterxy(i) {
            const scx = this.sx[i];
            const scy = (this.sy1[i] + this.sy2[i]) / 2;
            return [scx, scy];
        }
        _hit_point(geometry) {
            const L = this.sx.length;
            const result = new selection_1.Selection();
            for (let i = 0, end = L - 1; i < end; i++) {
                const sx = [this.sx[i], this.sx[i + 1], this.sx[i + 1], this.sx[i]];
                const sy = [this.sy1[i], this.sy1[i + 1], this.sy2[i + 1], this.sy2[i]];
                if (hittest.point_in_poly(geometry.sx, geometry.sy, sx, sy)) {
                    result.add_to_selected_glyphs(this.model);
                    result.view = this;
                    result.line_indices = [i];
                    break;
                }
            }
            return result;
        }
    }
    exports.VAreaView = VAreaView;
    class VArea extends area_1.Area {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = VAreaView;
            this.define(({}) => ({
                x: [p.XCoordinateSpec, { field: "x" }],
                y1: [p.YCoordinateSpec, { field: "y1" }],
                y2: [p.YCoordinateSpec, { field: "y2" }],
            }));
        }
    }
    exports.VArea = VArea;
},
/* models/sources/cds_view.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    const indices_1 = require(321) /* ../../core/util/indices */;
    const view_1 = require(65) /* ../../core/view */;
    const types_1 = require(25) /* ../../core/types */;
    const filter_1 = require(322) /* ../filters/filter */;
    const all_indices_1 = require(323) /* ../filters/all_indices */;
    const intersection_filter_1 = require(324) /* ../filters/intersection_filter */;
    class CDSViewView extends view_1.View {
        initialize() {
            super.initialize();
            this.compute_indices();
        }
        connect_signals() {
            super.connect_signals();
            const compute_indices = () => {
                this.compute_indices();
            };
            const connect_filter = (filter) => {
                this.connect(filter.change, compute_indices);
            };
            const disconnect_filter = (filter) => {
                this.disconnect(filter.change, compute_indices);
            };
            let { filter } = this.model;
            connect_filter(filter);
            this.on_change(this.model.properties.filter, () => {
                disconnect_filter(filter);
                filter = this.model.filter;
                connect_filter(filter);
                compute_indices();
            });
            const connect_data_source = (data_source) => {
                this.connect(data_source.change, compute_indices);
                this.connect(data_source.streaming, compute_indices);
                this.connect(data_source.patching, compute_indices);
                this.connect(data_source.properties.data.change, compute_indices);
            };
            const disconnect_data_source = (data_source) => {
                this.disconnect(data_source.change, compute_indices);
                this.disconnect(data_source.streaming, compute_indices);
                this.disconnect(data_source.patching, compute_indices);
                this.disconnect(data_source.properties.data.change, compute_indices);
            };
            let data_source = this.parent.data_source.get_value();
            connect_data_source(data_source);
            this.on_change(this.parent.data_source, () => {
                disconnect_data_source(data_source);
                data_source = this.parent.data_source.get_value();
                connect_data_source(data_source);
                compute_indices();
            });
        }
        compute_indices() {
            // XXX: if the data source is empty, there still may be one
            // index originating from glyph's scalar values.
            const source = this.parent.data_source.get_value();
            this.model.compute_indices(source);
        }
    }
    exports.CDSViewView = CDSViewView;
    class CDSView extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = CDSViewView;
            this.define(({ Ref }) => ({
                filter: [Ref(filter_1.Filter), () => new all_indices_1.AllIndices()],
            }));
            this.internal(({ Ref, Nullable }) => ({
                indices: [Ref(types_1.Indices)],
                indices_map: [Ref(indices_1.SubsetIndexMapper), () => new indices_1.SubsetIndexMapper(0)],
                masked: [Nullable(Ref(types_1.Indices)), null],
            }));
        }
        get_subset_index(index) {
            return this.indices_map.get_subset_index(index);
        }
        has_subset_index(index) {
            return this.indices_map.has_subset_index(index);
        }
        convert_selection_from_subset(selection_subset) {
            return selection_subset.map((i) => this.indices_map.get_superset_index(i));
        }
        convert_selection_to_subset(selection_full) {
            return selection_full.map((i) => this.indices_map.get_subset_index(i)); // XXX ?? NaN
        }
        convert_indices_from_subset(indices) {
            return this.indices_map.convert_indices_from_subset(indices);
        }
        get_reference_point(array, value) {
            return this.indices_map.subset_index_of(array, value);
        }
        compute_indices(source) {
            const size = source.get_length() ?? 1;
            const indices = types_1.Indices.all_set(size);
            const filtered = this.filter.compute_indices(source);
            indices.intersect(filtered);
            this.indices = indices;
            // reuse mapper if possible
            if (size !== this.indices_map.size) {
                this.indices_map = new indices_1.SubsetIndexMapper(size);
            }
            this.indices_map.set_subset(indices.ones());
        }
        /** @deprecated */
        get filters() {
            const { filter } = this;
            if (filter instanceof intersection_filter_1.IntersectionFilter) {
                return filter.operands;
            }
            else if (filter instanceof all_indices_1.AllIndices) {
                return [];
            }
            else {
                return [filter];
            }
        }
        /** @deprecated */
        set filters(filters) {
            if (filters.length == 0) {
                this.filter = new all_indices_1.AllIndices();
            }
            else if (filters.length == 1) {
                this.filter = filters[0];
            }
            else {
                this.filter = new intersection_filter_1.IntersectionFilter({ operands: filters });
            }
        }
    }
    exports.CDSView = CDSView;
},
/* core/util/indices.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    /**
     * Allows to efficiently map back and forth between superset and subset indices.
     * E.g. with superset indices = [0, 1, 2, 3] the subset [1, 3] has subset indices [0, 1].
    */
    class SubsetIndexMapper {
        superset_to_subset;
        subset_to_superset;
        size;
        size_subset;
        constructor(size) {
            this.superset_to_subset = new Int32Array(size);
            this.subset_to_superset = new Int32Array(size);
            this.superset_to_subset.fill(-1);
            this.size = size;
            this.size_subset = 0;
        }
        set_subset(superset_indices) {
            // reset existing entries
            for (let i = 0; i < this.size_subset; i++) {
                const old_superset_idx = this.subset_to_superset[i];
                this.superset_to_subset[old_superset_idx] = -1;
            }
            this.size_subset = superset_indices.length;
            for (let i = 0; i < this.size_subset; i++) {
                const superset_idx = superset_indices[i];
                this.subset_to_superset[i] = superset_idx;
                this.superset_to_subset[superset_idx] = i;
            }
        }
        get_subset_index(superset_index) {
            if (!this.is_superset_index_in_bounds(superset_index)) {
                throw new Error(`Global index ${superset_index} is out of bounds`);
            }
            const subset_index = this.superset_to_subset[superset_index];
            if (subset_index === -1) {
                throw new Error(`No subset index found: Global_index ${superset_index} is not part of the subset.`);
            }
            return subset_index;
        }
        has_subset_index(superset_index) {
            return this.is_superset_index_in_bounds(superset_index) && this.superset_to_subset[superset_index] !== -1;
        }
        get_superset_index(subset_index) {
            if (!this.is_subset_index_in_bounds(subset_index)) {
                throw new Error(`Subset index ${subset_index} is out of bounds`);
            }
            const superset_index = this.subset_to_superset[subset_index];
            return superset_index;
        }
        convert_indices_from_subset(subset_indices) {
            return subset_indices.map((i) => this.get_superset_index(i));
        }
        convert_indices_to_subset(superset_indices) {
            return superset_indices.map((i) => this.get_subset_index(i));
        }
        subset_index_of(array, value) {
            for (let i = 0; i < this.size_subset; i++) {
                const superset_idx = this.subset_to_superset[i];
                if (array[superset_idx] === value) {
                    return i;
                }
            }
            return null;
        }
        is_superset_index_in_bounds(superset_index) {
            return superset_index >= 0 && superset_index < this.size;
        }
        is_subset_index_in_bounds(subset_index) {
            return subset_index >= 0 && subset_index < this.size_subset;
        }
    }
    exports.SubsetIndexMapper = SubsetIndexMapper;
},
/* models/filters/filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    class Filter extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Filter = Filter;
},
/* models/filters/all_indices.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const filter_1 = require(322) /* ./filter */;
    const types_1 = require(25) /* ../../core/types */;
    class AllIndices extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        compute_indices(source) {
            const size = source.get_length() ?? 1;
            return types_1.Indices.all_set(size);
        }
    }
    exports.AllIndices = AllIndices;
},
/* models/filters/intersection_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const composite_filter_1 = require(325) /* ./composite_filter */;
    class IntersectionFilter extends composite_filter_1.CompositeFilter {
        constructor(attrs) {
            super(attrs);
        }
        _inplace_op(index, op) {
            index.intersect(op);
        }
    }
    exports.IntersectionFilter = IntersectionFilter;
},
/* models/filters/composite_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const filter_1 = require(322) /* ./filter */;
    const types_1 = require(25) /* ../../core/types */;
    class CompositeFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ List, Ref }) => ({
                operands: [List(Ref(filter_1.Filter))],
            }));
        }
        connect_signals() {
            super.connect_signals();
            const emit_changed = () => {
                this.change.emit();
            };
            const connect_operands = (operands) => {
                for (const operand of operands) {
                    this.connect(operand.change, emit_changed);
                }
            };
            const disconnect_operands = (operands) => {
                for (const operand of operands) {
                    this.disconnect(operand.change, emit_changed);
                }
            };
            let operands = (() => {
                const { operands } = this.properties;
                return operands.is_unset ? [] : operands.get_value();
            })();
            connect_operands(operands);
            this.on_change(this.properties.operands, () => {
                disconnect_operands(operands);
                operands = this.operands;
                connect_operands(operands);
            });
        }
        compute_indices(source) {
            const { operands } = this;
            if (operands.length == 0) {
                const size = source.get_length() ?? 1;
                return types_1.Indices.all_set(size);
            }
            else {
                const [index, ...rest] = operands.map((op) => op.compute_indices(source));
                for (const op of rest) {
                    this._inplace_op(index, op);
                }
                return index;
            }
        }
    }
    exports.CompositeFilter = CompositeFilter;
},
/* models/formatters/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var basic_tick_formatter_1 = require(279) /* ./basic_tick_formatter */;
    __esExport("BasicTickFormatter", basic_tick_formatter_1.BasicTickFormatter);
    var categorical_tick_formatter_1 = require(327) /* ./categorical_tick_formatter */;
    __esExport("CategoricalTickFormatter", categorical_tick_formatter_1.CategoricalTickFormatter);
    var datetime_tick_formatter_1 = require(328) /* ./datetime_tick_formatter */;
    __esExport("DatetimeTickFormatter", datetime_tick_formatter_1.DatetimeTickFormatter);
    var customjs_tick_formatter_1 = require(333) /* ./customjs_tick_formatter */;
    __esExport("CustomJSTickFormatter", customjs_tick_formatter_1.CustomJSTickFormatter);
    var log_tick_formatter_1 = require(334) /* ./log_tick_formatter */;
    __esExport("LogTickFormatter", log_tick_formatter_1.LogTickFormatter);
    var mercator_tick_formatter_1 = require(335) /* ./mercator_tick_formatter */;
    __esExport("MercatorTickFormatter", mercator_tick_formatter_1.MercatorTickFormatter);
    var numeral_tick_formatter_1 = require(336) /* ./numeral_tick_formatter */;
    __esExport("NumeralTickFormatter", numeral_tick_formatter_1.NumeralTickFormatter);
    var printf_tick_formatter_1 = require(337) /* ./printf_tick_formatter */;
    __esExport("PrintfTickFormatter", printf_tick_formatter_1.PrintfTickFormatter);
    var tick_formatter_1 = require(275) /* ./tick_formatter */;
    __esExport("TickFormatter", tick_formatter_1.TickFormatter);
    var timedelta_tick_formatter_1 = require(338) /* ./timedelta_tick_formatter */;
    __esExport("TimedeltaTickFormatter", timedelta_tick_formatter_1.TimedeltaTickFormatter);
},
/* models/formatters/categorical_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tick_formatter_1 = require(275) /* ./tick_formatter */;
    const array_1 = require(10) /* ../../core/util/array */;
    class CategoricalTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        doFormat(ticks, _opts) {
            return (0, array_1.copy)(ticks);
        }
    }
    exports.CategoricalTickFormatter = CategoricalTickFormatter;
},
/* models/formatters/datetime_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports._get_resolution = _get_resolution;
    exports._mktime = _mktime;
    exports._strftime = _strftime;
    exports._us = _us;
    exports._ns = _ns;
    const enums_1 = require(21) /* ../../core/enums */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    const templating_1 = require(329) /* ../../core/util/templating */;
    const types_1 = require(8) /* ../../core/util/types */;
    const tick_formatter_1 = require(275) /* ./tick_formatter */;
    const util_1 = require(290) /* ../tickers/util */;
    // Labels of time units, from finest to coarsest.
    exports.resolution_order = [
        "microseconds", "milliseconds", "seconds", "minsec", "minutes", "hourmin", "hours", "days", "months", "years",
    ];
    // This dictionary maps the name of a time resolution (in @resolution_order)
    // to its index in a time.localtime() time tuple. The default is to map
    // everything to index 0, which is year. This is not ideal; it might cause
    // a problem with the tick at midnight, january 1st, 0 a.d. being incorrectly
    // promoted at certain tick resolutions.
    exports.tm_index_for_resolution = {
        microseconds: 0,
        milliseconds: 0,
        seconds: 5,
        minsec: 4,
        minutes: 4,
        hourmin: 3,
        hours: 3,
        days: 0,
        months: 0,
        years: 0,
    };
    function _get_resolution(resolution_secs, span_secs) {
        // Our resolution boundaries should not be round numbers, because we want
        // them to fall between the possible tick intervals (which *are* round
        // numbers, as we've worked hard to ensure). Consequently, we adjust the
        // resolution upwards a small amount (less than any possible step in
        // scales) to make the effective boundaries slightly lower.
        const adjusted_ms = resolution_secs * 1.1 * 1000;
        const span_ms = span_secs * 1000;
        if (adjusted_ms < util_1.ONE_MILLI) {
            return "microseconds";
        }
        if (adjusted_ms < util_1.ONE_SECOND) {
            return "milliseconds";
        }
        if (adjusted_ms < util_1.ONE_MINUTE) {
            return span_ms >= util_1.ONE_MINUTE ? "minsec" : "seconds";
        }
        if (adjusted_ms < util_1.ONE_HOUR) {
            return span_ms >= util_1.ONE_HOUR ? "hourmin" : "minutes";
        }
        if (adjusted_ms < util_1.ONE_DAY) {
            return "hours";
        }
        if (adjusted_ms < util_1.ONE_MONTH) {
            return "days";
        }
        if (adjusted_ms < util_1.ONE_YEAR) {
            return "months";
        }
        return "years";
    }
    function _mktime(t) {
        return (0, templating_1.datetime)(t, "%Y %m %d %H %M %S").split(/\s+/).map(e => parseInt(e, 10));
    }
    function _strftime(t, format) {
        // Python's datetime library augments the microsecond directive %f, which is not
        // supported by the javascript library timezone: http://bigeasy.github.io/timezone/.
        // Use a regular expression to replace %f directive with microseconds.
        const microsecond_replacement_string = (0, templating_1.sprintf)("$1%06d", _us(t));
        format = format.replace(/((^|[^%])(%%)*)%f/, microsecond_replacement_string);
        format = format.replace(/((^|[^%])(%%)*)%[0-9]*N/, match => {
            // By default use 9 digits for nanoseconds, this is applied not only in case of no padding
            // (%N) but also for padding out of range (i.e. %0N, %15N)
            let padding = 9;
            const str_padding_matched = match.match(/%([1-9])N/);
            if (str_padding_matched != null) {
                const padding_parsed = parseInt(str_padding_matched[1], 10);
                if (!Number.isNaN(padding_parsed)) {
                    padding = padding_parsed;
                }
            }
            const ns = _ns(t);
            const nanosecond_replacement_string = (0, templating_1.sprintf)("%09d", ns).substring(0, padding);
            return match.replace(/%[0-9]*N/, nanosecond_replacement_string);
        });
        // timezone seems to ignore any strings without any formatting directives,
        // and just return the time argument back instead of the string argument.
        // But we want the string argument, in case a user supplies a format string
        // which doesn't contain a formatting directive or is only using %f.
        if (format.indexOf("%") == -1) {
            return format;
        }
        return (0, templating_1.datetime)(t, format);
    }
    function _us(t) {
        // From double-precision unix (millisecond) timestamp, get microseconds since
        // last second. Precision seems to run out around the hundreds of nanoseconds
        // scale, so rounding to the nearest microsecond should round to a nice
        // microsecond / millisecond tick.
        // Note: for negative timestamps (pre epoch) the microsecond scale needs to be
        // inverted as we are counting backwards.
        let us = Math.round(((t / 1000) % 1) * 1000000);
        if (t < 0.0) {
            us = (1000000 + us) % 1000000;
        }
        return us;
    }
    function _ns(t) {
        // Use rounded microsecond result as a baseline as the precision is not sufficient
        // for the sub microsecond range anyway.
        return _us(t) * 1000;
    }
    class DatetimeTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Bool, Nullable, Or, Ref, Str, Arrayable }) => ({
                microseconds: [Str, "%fus"],
                milliseconds: [Str, "%3Nms"],
                seconds: [Str, "%Ss"],
                minsec: [Str, ":%M:%S"],
                minutes: [Str, ":%M"],
                hourmin: [Str, "%H:%M"],
                hours: [Str, "%Hh"],
                days: [Str, "%m/%d"],
                months: [Str, "%m/%Y"],
                years: [Str, "%Y"],
                strip_leading_zeros: [Or(Bool, Arrayable(enums_1.ResolutionType)), false],
                boundary_scaling: [Bool, true],
                hide_repeats: [Bool, false],
                context: [Nullable(Or(Str, Ref(DatetimeTickFormatter))), null],
                context_which: [enums_1.ContextWhich, "start"],
                context_location: [enums_1.Location, "below"],
            }));
        }
        doFormat(ticks, _opts, _resolution) {
            if (ticks.length == 0) {
                return [];
            }
            const span = Math.abs(ticks[ticks.length - 1] - ticks[0]) / 1000.0;
            const r = span / (ticks.length - 1);
            const resolution = (0, types_1.is_undefined)(_resolution) ? _get_resolution(r, span) : _resolution;
            let base_labels = [];
            for (const tick of ticks) {
                const base_label = this._compute_label(tick, resolution);
                base_labels.push(base_label);
            }
            if (this.hide_repeats) {
                base_labels = this._hide_repeating_labels(base_labels);
            }
            if (this.context == null) {
                return base_labels;
            }
            const context_labels = this._compute_context_labels(ticks, resolution);
            return this._build_full_labels(base_labels, context_labels);
        }
        _compute_label(t, resolution) {
            const s0 = _strftime(t, this[resolution]);
            const tm = _mktime(t);
            const resolution_index = exports.resolution_order.indexOf(resolution);
            let final_resolution = resolution;
            let s = s0;
            if (this.boundary_scaling) {
                let hybrid_handled = false;
                let next_index = resolution_index;
                let next_resolution = resolution;
                // As we format each tick, check to see if we are at a boundary of the
                // next higher unit of time. If so, replace the current format with one
                // from that resolution. This is not the best heuristic but it works.
                while (tm[exports.tm_index_for_resolution[exports.resolution_order[next_index]]] == 0) {
                    next_index += 1;
                    if (next_index == exports.resolution_order.length) {
                        break;
                    }
                    // The way to check that we are at the boundary of the next unit of
                    // time is by checking that we have 0 units of the resolution, i.e.
                    // we are at zero minutes, so display hours, or we are at zero seconds,
                    // so display minutes (and if that is zero as well, then display hours).
                    if ((resolution == "minsec" || resolution == "hourmin") && !hybrid_handled) {
                        if ((resolution == "minsec" && tm[4] == 0 && tm[5] != 0) || (resolution == "hourmin" && tm[3] == 0 && tm[4] != 0)) {
                            next_resolution = exports.resolution_order[resolution_index - 1];
                            s = _strftime(t, this[next_resolution]);
                            break;
                        }
                        else {
                            hybrid_handled = true;
                        }
                    }
                    next_resolution = exports.resolution_order[next_index];
                    s = _strftime(t, this[next_resolution]);
                }
                final_resolution = next_resolution;
            }
            const { strip_leading_zeros } = this;
            if (((0, types_1.isBoolean)(strip_leading_zeros) && strip_leading_zeros) ||
                ((0, types_1.isArray)(strip_leading_zeros) && strip_leading_zeros.includes(final_resolution))) {
                const ss = s.replace(/^0+/g, "");
                if (ss != s && !Number.isInteger(Number(ss[0]))) {
                    // If the string can now be parsed as starting with an integer, then
                    // leave all zeros stripped, otherwise start with a zero.
                    return `0${ss}`;
                }
                return ss;
            }
            return s;
        }
        _compute_context_labels(ticks, resolution) {
            const { context } = this;
            (0, assert_1.assert)(context != null);
            const context_labels = [];
            if ((0, types_1.isString)(context)) {
                for (const tick of ticks) {
                    context_labels.push(_strftime(tick, context));
                }
            }
            else {
                context_labels.push(...context.doFormat(ticks, { loc: 0 }, resolution));
            }
            const which = this.context_which;
            const N = context_labels.length;
            for (let i = 0; i < context_labels.length; i++) {
                if ((which == "start" && i != 0) ||
                    (which == "end" && i != N - 1) ||
                    (which == "center" && i != Math.floor(N / 2))) {
                    context_labels[i] = "";
                }
            }
            return context_labels;
        }
        _build_full_labels(base_labels, context_labels) {
            const loc = this.context_location;
            const full_labels = [];
            if (context_labels.every(v => v === "")) {
                return base_labels;
            }
            for (let i = 0; i < base_labels.length; i++) {
                const label = base_labels[i];
                const context = context_labels[i];
                // In case of above and below blank strings are not trimmed in order to
                // keep the same visual format across all ticks.
                const full_label = (() => {
                    switch (loc) {
                        case "above": return `${context}\n${label}`;
                        case "below": return `${label}\n${context}`;
                        case "left": return context == "" ? label : `${context} ${label}`;
                        case "right": return context == "" ? label : `${label} ${context}`;
                    }
                })();
                full_labels.push(full_label);
            }
            return full_labels;
        }
        _hide_repeating_labels(labels) {
            // For repeating labels only utilize the first entry
            if (labels.length <= 1) {
                return labels;
            }
            const labels_h = [labels[0]];
            let index_first_entry = 0;
            for (let i = 1; i < labels.length; i++) {
                if (labels[index_first_entry] == labels[i]) {
                    labels_h.push("");
                }
                else {
                    labels_h.push(labels[i]);
                    index_first_entry = i;
                }
            }
            return labels_h;
        }
    }
    exports.DatetimeTickFormatter = DatetimeTickFormatter;
},
/* core/util/templating.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.datetime = datetime;
    exports.sprintf = sprintf;
    exports.basic_formatter = basic_formatter;
    exports.get_formatter = get_formatter;
    exports._get_column_value = _get_column_value;
    exports.get_value = get_value;
    exports.replace_placeholders_html = replace_placeholders_html;
    exports.replace_placeholders = replace_placeholders;
    exports.process_placeholders = process_placeholders;
    const tslib_1 = require(1) /* tslib */;
    const Numbro = tslib_1.__importStar(require(330) /* @bokeh/numbro */);
    const sprintf_js_1 = require(331) /* sprintf-js */;
    const timezone_1 = tslib_1.__importDefault(require(332) /* timezone */);
    const logging_1 = require(11) /* ../logging */;
    const object_1 = require(9) /* ./object */;
    const ndarray_1 = require(31) /* ./ndarray */;
    const types_1 = require(8) /* ./types */;
    const pretty_1 = require(43) /* ./pretty */;
    const string_1 = require(41) /* ./string */;
    const assert_1 = require(13) /* ./assert */;
    //import {Parser, Grammar} from "nearley"
    //import grammar from "./pipes"
    const { abs } = Math;
    exports.DEFAULT_FORMATTERS = {
        raw: (value, _format, _special_vars) => (0, pretty_1.to_string)(value),
        basic: (value, format, special_vars) => basic_formatter(value, format, special_vars),
        numeral: (value, format, _special_vars) => Numbro.format(value, format),
        datetime: (value, format, _special_vars) => datetime(value, format),
        printf: (value, format, _special_vars) => sprintf(format, value),
    };
    class Skip {
    }
    exports.Skip = Skip;
    /**
     * Format finite numbers as dates or return NaN.
     */
    function datetime(value, format) {
        if ((0, types_1.isNumber)(value) && isFinite(value)) {
            return (0, timezone_1.default)(value, format);
        }
        else {
            return "NaN";
        }
    }
    function sprintf(format, ...args) {
        return (0, sprintf_js_1.sprintf)(format, ...args);
    }
    function basic_formatter(value, _format, _special_vars) {
        if ((0, types_1.isNumber)(value)) {
            const format = (() => {
                if (Number.isInteger(value)) {
                    return "%d";
                }
                else if (0.1 < abs(value) && abs(value) < 1000) {
                    return "%0.3f";
                }
                else {
                    return "%0.3e";
                }
            })();
            return sprintf(format, value);
        }
        else if ((0, types_1.isString)(value)) {
            return value; // get strings for categorical types
        }
        else {
            // TODO to_string(value); currently ImageStack relies on the primitive representation of typed arrays
            return `${value}`;
        }
    }
    function get_formatter(spec, format, formatters) {
        // no format, use default built in formatter
        if (format == null) {
            return exports.DEFAULT_FORMATTERS.basic;
        }
        // format spec in the formatters dict, use that
        if (formatters != null) {
            const formatter = (0, object_1.dict)(formatters).get(spec);
            if (formatter != null) {
                if ((0, types_1.isString)(formatter)) {
                    if (formatter in exports.DEFAULT_FORMATTERS) {
                        return exports.DEFAULT_FORMATTERS[formatter];
                    }
                    else {
                        throw new Error(`Unknown tooltip field formatter type '${formatter}'`);
                    }
                }
                return function (value, format, special_vars) {
                    return formatter.format(value, format, special_vars);
                };
            }
        }
        // otherwise use "numeral" as default
        return exports.DEFAULT_FORMATTERS.numeral;
    }
    exports.MISSING = "???";
    function _get_special_value(name, special_vars) {
        if (name in special_vars) {
            return special_vars[name];
        }
        else {
            logging_1.logger.warn(`unknown special variable '\$${name}'`);
            return exports.MISSING;
        }
    }
    function _get_column_value(name, data_source, ind) {
        const column = data_source.get_column(name);
        // missing column
        if (column == null) {
            return null;
        }
        // null index (e.g for patch)
        if (ind == null) {
            return null;
        }
        // typical (non-image) index
        if ((0, types_1.isNumber)(ind)) {
            return column[ind];
        }
        // image index
        const data = column[ind.index];
        if ((0, types_1.isTypedArray)(data) || (0, types_1.isArray)(data)) {
            // inspect array of arrays
            if ((0, types_1.isArray)(data[0])) {
                const row = data[ind.j];
                return row[ind.i];
            }
            else if ((0, ndarray_1.is_NDArray)(data) && data.dimension == 3) {
                // For 3d array return whole of 3rd axis
                return data.slice(ind.flat_index * data.shape[2], (ind.flat_index + 1) * data.shape[2]);
            }
            else {
                // inspect flat array
                return data[ind.flat_index];
            }
        }
        else {
            // inspect per-image scalar data
            return data;
        }
    }
    function get_value(type, name, data_source, index, vars) {
        switch (type) {
            case "$": return _get_special_value(name, vars);
            case "@": return _get_column_value(name, data_source, index);
            case "@$": return name == "name" && (0, types_1.isString)(vars.name) ? _get_column_value(vars.name, data_source, index) : null;
        }
    }
    class HTML {
        html;
        constructor(html) {
            this.html = html;
        }
    }
    const functions = {
        safe: (value, ...args) => {
            (0, assert_1.assert)(args.length == 0);
            if (value == null) {
                return exports.MISSING;
            }
            else if ((0, types_1.isNumber)(value) && isNaN(value)) {
                return "NaN";
            }
            else {
                return new HTML(`${value}`);
            }
        },
        /*
        fixed: (value: unknown, ...args: unknown[]) => {
          assert(args.length == 1)
          const [digits] = args
          if (isNumber(value) && isInteger(digits)) {
            return value.toFixed(digits)
          } else {
            return value
          }
        },
        round: (value: unknown, ...args: unknown[]) => {
          assert(args.length == 0)
          if (isNumber(value)) {
            return Math.round(value)
          } else {
            return value
          }
        },
        upper: (value: unknown, ...args: unknown[]) => {
          assert(args.length == 0)
          if (isString(value)) {
            return value.toUpperCase()
          } else {
            return value
          }
        },
        lower: (value: unknown, ...args: unknown[]) => {
          assert(args.length == 0)
          if (isString(value)) {
            return value.toLowerCase()
          } else {
            return value
          }
        },
        filter: (value: unknown, ...args: unknown[]) => {
          assert(args.length == 1)
          const [expr] = args
          if (isPlainObject(expr) && "lit" in expr) {
            if (expr.lit == "finite") {
              if (!isNumber(value) || !isFinite(value)) {
                throw new Skip()
              }
            }
          }
          return value
        },
        */
    };
    function replace_placeholders_html(input, data_source, index, formatters, special_vars = {}) {
        const html = process_placeholders(input, (type, name, format, _, spec) => {
            const value = get_value(type, name, data_source, index, special_vars);
            /*
            type Lit = {lit: string}
            type Fn = {name: Lit, args: unknown[]}
        
            const parse = (input: string): Fn[] | null => {
              let parser: Parser
              try {
                parser = new Parser(Grammar.fromCompiled(grammar))
                parser.feed(input)
                const [pipeline] = parser.results
                return pipeline as Fn[]
              } catch (error) {
                return null
              }
            }
        
            const pipeline = parse(format ?? "")
            if (pipeline != null) {
              let result: unknown = value
              for (const fn of pipeline) {
                const name = fn.name.lit
                if (name in functions) {
                  result = functions[name as keyof typeof functions](result, ...fn.args)
                } else {
                  console.error(`unknown function '${fn.name}'`)
                  break
                }
              }
              if (result instanceof HTML) {
                return result.html
              } else {
                return escape(`${result}`)
              }
            */
            if (format == "safe") {
                const result = functions.safe(value);
                if (result instanceof HTML) {
                    return result.html;
                }
                else {
                    return (0, string_1.escape)(`${result}`);
                }
            }
            else {
                const result = (() => {
                    if (value == null) {
                        return exports.MISSING;
                    }
                    else if ((0, types_1.isNumber)(value) && isNaN(value)) {
                        return "NaN";
                    }
                    else {
                        const formatter = get_formatter(spec, format, formatters);
                        return `${formatter(value, format ?? "", special_vars)}`;
                    }
                })();
                return (0, string_1.escape)(result);
            }
        });
        const html_parser = new DOMParser();
        const document = html_parser.parseFromString(html, "text/html");
        return [...document.body.childNodes];
    }
    function replace_placeholders(content, data_source, i, formatters, special_vars = {}, encode) {
        let str;
        let has_html;
        if ((0, types_1.isString)(content)) {
            str = content;
            has_html = false;
        }
        else {
            str = content.html;
            has_html = true;
        }
        str = process_placeholders(str, (type, name, format, _, spec) => {
            const value = get_value(type, name, data_source, i, special_vars);
            // 'safe' format, return the value as-is
            if (format == "safe") {
                has_html = true;
                if (value == null) {
                    return exports.MISSING;
                }
                else if ((0, types_1.isNumber)(value) && isNaN(value)) {
                    return "NaN";
                }
                else {
                    return `${value}`;
                }
            }
            else {
                const result = (() => {
                    if (value == null) {
                        return exports.MISSING;
                    }
                    else if ((0, types_1.isNumber)(value) && isNaN(value)) {
                        return "NaN";
                    }
                    else {
                        const formatter = get_formatter(spec, format, formatters);
                        return `${formatter(value, format ?? "", special_vars)}`;
                    }
                })();
                return encode != null ? encode(result) : result;
            }
        });
        if (!has_html) {
            return str;
        }
        else {
            const parser = new DOMParser();
            const document = parser.parseFromString(str, "text/html");
            return [...document.body.childNodes];
        }
    }
    /**
     * This supports the following:
     *
     * - simple vars: $x
     * - simple names: @x, @słowa_0, @Wörter (@ symbol followed by unicode letters, numbers or underscore)
     * - full vars: ${one two}
     * - full names: @{one two} (@{anything except curly brackets}
     * - optional formatting: $x{format}, ${x}{format}, @x{format}, @{one two}{format}
     */
    const regex = /(@\$|@|\$)((?:[\p{Letter}\p{Number}_]+)|(?:\{(?:[^{}]+)\}))(?:\{([^{}]+)\})?/gu;
    function process_placeholders(text, fn) {
        let i = 0; // this var is used for testing purposes
        return text.replace(regex, (_match, type, content, format) => {
            const name = content.replace(/^{/, "").replace(/}$/, "").trim();
            const spec = `${type}${content}`;
            return fn(type, name, format, i++, spec) ?? exports.MISSING;
        });
    }
},
/* @bokeh/numbro/numbro.js */ function _(require, module, exports, __esModule, __esExport) {
    /*!
     * numbro.js
     * version : 1.6.2
     * author : Företagsplatsen AB
     * license : MIT
     * http://www.foretagsplatsen.se
     */
    /************************************
        Constants
    ************************************/
    var numbro, VERSION = '1.6.2', 
    // internal storage for culture config files
    cultures = {}, 
    // Todo: Remove in 2.0.0
    languages = cultures, currentCulture = 'en-US', zeroFormat = null, defaultFormat = '0,0', defaultCurrencyFormat = '0$', 
    // check for nodeJS
    hasModule = (typeof module !== 'undefined' && module.exports), 
    // default culture
    enUS = {
        delimiters: {
            thousands: ',',
            decimal: '.'
        },
        abbreviations: {
            thousand: 'k',
            million: 'm',
            billion: 'b',
            trillion: 't'
        },
        ordinal: function (number) {
            var b = number % 10;
            return (~~(number % 100 / 10) === 1) ? 'th' :
                (b === 1) ? 'st' :
                    (b === 2) ? 'nd' :
                        (b === 3) ? 'rd' : 'th';
        },
        currency: {
            symbol: '$',
            position: 'prefix'
        },
        defaults: {
            currencyFormat: ',0000 a'
        },
        formats: {
            fourDigits: '0000 a',
            fullWithTwoDecimals: '$ ,0.00',
            fullWithTwoDecimalsNoCurrency: ',0.00'
        }
    };
    /************************************
        Constructors
    ************************************/
    // Numbro prototype object
    function Numbro(number) {
        this._value = number;
    }
    function zeroes(count) {
        var i, ret = '';
        for (i = 0; i < count; i++) {
            ret += '0';
        }
        return ret;
    }
    /**
     * Implementation of toFixed() for numbers with exponent > 21
     *
     *
     */
    function toFixedLarge(value, precision) {
        var mantissa, beforeDec, afterDec, exponent, str;
        str = value.toString();
        mantissa = str.split('e')[0];
        exponent = str.split('e')[1];
        beforeDec = mantissa.split('.')[0];
        afterDec = mantissa.split('.')[1] || '';
        str = beforeDec + afterDec + zeroes(exponent - afterDec.length);
        if (precision > 0) {
            str += '.' + zeroes(precision);
        }
        return str;
    }
    /**
     * Implementation of toFixed() that treats floats more like decimals
     *
     * Fixes binary rounding issues (eg. (0.615).toFixed(2) === '0.61') that present
     * problems for accounting- and finance-related software.
     */
    function toFixed(value, precision, roundingFunction, optionals) {
        var power = Math.pow(10, precision), optionalsRegExp, output;
        if (value.toFixed(0).search('e') > -1) {
            // Above 1e21, toFixed returns scientific notation, which
            // is useless and unexpected
            output = toFixedLarge(value, precision);
        }
        else {
            //roundingFunction = (roundingFunction !== undefined ? roundingFunction : Math.round);
            // Multiply up by precision, round accurately, then divide and use native toFixed():
            output = (roundingFunction(value * power) / power).toFixed(precision);
        }
        if (optionals) {
            optionalsRegExp = new RegExp('0{1,' + optionals + '}$');
            output = output.replace(optionalsRegExp, '');
        }
        return output;
    }
    /************************************
        Formatting
    ************************************/
    // determine what type of formatting we need to do
    function formatNumbro(value, format, roundingFunction) {
        var output;
        // TODO: do something with `language`
        // figure out what kind of format we are dealing with
        if (format.indexOf('$') > -1) { // currency!!!!!
            output = formatCurrency(value, format, roundingFunction);
        }
        else if (format.indexOf('%') > -1) { // percentage
            output = formatPercentage(value, format, roundingFunction);
        }
        else if (format.indexOf(':') > -1) { // time
            output = formatTime(value);
        }
        else { // plain ol' numbers or bytes
            output = formatNumber(value, format, roundingFunction);
        }
        // return string
        return output;
    }
    function formatCurrency(value, originalFormat, roundingFunction) {
        var format = originalFormat, symbolIndex = format.indexOf('$'), openParenIndex = format.indexOf('('), plusSignIndex = format.indexOf('+'), minusSignIndex = format.indexOf('-'), space = '', decimalSeparator = '', spliceIndex, output;
        if (format.indexOf('$') === -1) {
            // Use defaults instead of the format provided
            if (cultures[currentCulture].currency.position === 'infix') {
                decimalSeparator = cultures[currentCulture].currency.symbol;
                if (cultures[currentCulture].currency.spaceSeparated) {
                    decimalSeparator = ' ' + decimalSeparator + ' ';
                }
            }
            else if (cultures[currentCulture].currency.spaceSeparated) {
                space = ' ';
            }
        }
        else {
            // check for space before or after currency
            if (format.indexOf(' $') > -1) {
                space = ' ';
                format = format.replace(' $', '');
            }
            else if (format.indexOf('$ ') > -1) {
                space = ' ';
                format = format.replace('$ ', '');
            }
            else {
                format = format.replace('$', '');
            }
        }
        // Format The Number
        output = formatNumber(value, format, roundingFunction, decimalSeparator);
        if (originalFormat.indexOf('$') === -1) {
            // Use defaults instead of the format provided
            switch (cultures[currentCulture].currency.position) {
                case 'postfix':
                    if (output.indexOf(')') > -1) {
                        output = output.split('');
                        output.splice(-1, 0, space + cultures[currentCulture].currency.symbol);
                        output = output.join('');
                    }
                    else {
                        output = output + space + cultures[currentCulture].currency.symbol;
                    }
                    break;
                case 'infix':
                    break;
                case 'prefix':
                    if (output.indexOf('(') > -1 || output.indexOf('-') > -1) {
                        output = output.split('');
                        spliceIndex = Math.max(openParenIndex, minusSignIndex) + 1;
                        output.splice(spliceIndex, 0, cultures[currentCulture].currency.symbol + space);
                        output = output.join('');
                    }
                    else {
                        output = cultures[currentCulture].currency.symbol + space + output;
                    }
                    break;
                default:
                    throw Error('Currency position should be among ["prefix", "infix", "postfix"]');
            }
        }
        else {
            // position the symbol
            if (symbolIndex <= 1) {
                if (output.indexOf('(') > -1 || output.indexOf('+') > -1 || output.indexOf('-') > -1) {
                    output = output.split('');
                    spliceIndex = 1;
                    if (symbolIndex < openParenIndex || symbolIndex < plusSignIndex || symbolIndex < minusSignIndex) {
                        // the symbol appears before the "(", "+" or "-"
                        spliceIndex = 0;
                    }
                    output.splice(spliceIndex, 0, cultures[currentCulture].currency.symbol + space);
                    output = output.join('');
                }
                else {
                    output = cultures[currentCulture].currency.symbol + space + output;
                }
            }
            else {
                if (output.indexOf(')') > -1) {
                    output = output.split('');
                    output.splice(-1, 0, space + cultures[currentCulture].currency.symbol);
                    output = output.join('');
                }
                else {
                    output = output + space + cultures[currentCulture].currency.symbol;
                }
            }
        }
        return output;
    }
    function formatPercentage(value, format, roundingFunction) {
        var space = '', output;
        value = value * 100;
        // check for space before %
        if (format.indexOf(' %') > -1) {
            space = ' ';
            format = format.replace(' %', '');
        }
        else {
            format = format.replace('%', '');
        }
        output = formatNumber(value, format, roundingFunction);
        if (output.indexOf(')') > -1) {
            output = output.split('');
            output.splice(-1, 0, space + '%');
            output = output.join('');
        }
        else {
            output = output + space + '%';
        }
        return output;
    }
    function formatTime(value) {
        var hours = Math.floor(value / 60 / 60), minutes = Math.floor((value - (hours * 60 * 60)) / 60), seconds = Math.round(value - (hours * 60 * 60) - (minutes * 60));
        return hours + ':' +
            ((minutes < 10) ? '0' + minutes : minutes) + ':' +
            ((seconds < 10) ? '0' + seconds : seconds);
    }
    function formatNumber(value, format, roundingFunction, sep) {
        var negP = false, signed = false, optDec = false, abbr = '', i, abbrK = false, // force abbreviation to thousands
        abbrM = false, // force abbreviation to millions
        abbrB = false, // force abbreviation to billions
        abbrT = false, // force abbreviation to trillions
        abbrForce = false, // force abbreviation
        bytes = '', ord = '', abs = Math.abs(value), binarySuffixes = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'], decimalSuffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], min, max, power, totalLength, length, minimumPrecision, pow, w, intPrecision, precision, prefix, postfix, thousands, d = '', forcedNeg = false, neg = false, indexOpenP, size, indexMinus, paren = '', minlen;
        // check if number is zero and a custom zero format has been set
        if (value === 0 && zeroFormat !== null) {
            return zeroFormat;
        }
        if (!isFinite(value)) {
            return '' + value;
        }
        if (format.indexOf('{') === 0) {
            var end = format.indexOf('}');
            if (end === -1) {
                throw Error('Format should also contain a "}"');
            }
            prefix = format.slice(1, end);
            format = format.slice(end + 1);
        }
        else {
            prefix = '';
        }
        if (format.indexOf('}') === format.length - 1) {
            var start = format.indexOf('{');
            if (start === -1) {
                throw Error('Format should also contain a "{"');
            }
            postfix = format.slice(start + 1, -1);
            format = format.slice(0, start + 1);
        }
        else {
            postfix = '';
        }
        // check for min length
        var info;
        if (format.indexOf('.') === -1) {
            info = format.match(/([0-9]+).*/);
        }
        else {
            info = format.match(/([0-9]+)\..*/);
        }
        minlen = info === null ? -1 : info[1].length;
        // see if we should use parentheses for negative number or if we should prefix with a sign
        // if both are present we default to parentheses
        if (format.indexOf('-') !== -1) {
            forcedNeg = true;
        }
        if (format.indexOf('(') > -1) {
            negP = true;
            format = format.slice(1, -1);
        }
        else if (format.indexOf('+') > -1) {
            signed = true;
            format = format.replace(/\+/g, '');
        }
        // see if abbreviation is wanted
        if (format.indexOf('a') > -1) {
            intPrecision = format.split('.')[0].match(/[0-9]+/g) || ['0'];
            intPrecision = parseInt(intPrecision[0], 10);
            // check if abbreviation is specified
            abbrK = format.indexOf('aK') >= 0;
            abbrM = format.indexOf('aM') >= 0;
            abbrB = format.indexOf('aB') >= 0;
            abbrT = format.indexOf('aT') >= 0;
            abbrForce = abbrK || abbrM || abbrB || abbrT;
            // check for space before abbreviation
            if (format.indexOf(' a') > -1) {
                abbr = ' ';
                format = format.replace(' a', '');
            }
            else {
                format = format.replace('a', '');
            }
            totalLength = Math.floor(Math.log(abs) / Math.LN10) + 1;
            minimumPrecision = totalLength % 3;
            minimumPrecision = minimumPrecision === 0 ? 3 : minimumPrecision;
            if (intPrecision && abs !== 0) {
                length = Math.floor(Math.log(abs) / Math.LN10) + 1 - intPrecision;
                pow = 3 * ~~((Math.min(intPrecision, totalLength) - minimumPrecision) / 3);
                abs = abs / Math.pow(10, pow);
                if (format.indexOf('.') === -1 && intPrecision > 3) {
                    format += '[.]';
                    size = length === 0 ? 0 : 3 * ~~(length / 3) - length;
                    size = size < 0 ? size + 3 : size;
                    for (i = 0; i < size; i++) {
                        format += '0';
                    }
                }
            }
            if (Math.floor(Math.log(Math.abs(value)) / Math.LN10) + 1 !== intPrecision) {
                if (abs >= Math.pow(10, 12) && !abbrForce || abbrT) {
                    // trillion
                    abbr = abbr + cultures[currentCulture].abbreviations.trillion;
                    value = value / Math.pow(10, 12);
                }
                else if (abs < Math.pow(10, 12) && abs >= Math.pow(10, 9) && !abbrForce || abbrB) {
                    // billion
                    abbr = abbr + cultures[currentCulture].abbreviations.billion;
                    value = value / Math.pow(10, 9);
                }
                else if (abs < Math.pow(10, 9) && abs >= Math.pow(10, 6) && !abbrForce || abbrM) {
                    // million
                    abbr = abbr + cultures[currentCulture].abbreviations.million;
                    value = value / Math.pow(10, 6);
                }
                else if (abs < Math.pow(10, 6) && abs >= Math.pow(10, 3) && !abbrForce || abbrK) {
                    // thousand
                    abbr = abbr + cultures[currentCulture].abbreviations.thousand;
                    value = value / Math.pow(10, 3);
                }
            }
        }
        // see if we are formatting binary bytes
        if (format.indexOf('b') > -1) {
            // check for space before
            if (format.indexOf(' b') > -1) {
                bytes = ' ';
                format = format.replace(' b', '');
            }
            else {
                format = format.replace('b', '');
            }
            for (power = 0; power <= binarySuffixes.length; power++) {
                min = Math.pow(1024, power);
                max = Math.pow(1024, power + 1);
                if (value >= min && value < max) {
                    bytes = bytes + binarySuffixes[power];
                    if (min > 0) {
                        value = value / min;
                    }
                    break;
                }
            }
        }
        // see if we are formatting decimal bytes
        if (format.indexOf('d') > -1) {
            // check for space before
            if (format.indexOf(' d') > -1) {
                bytes = ' ';
                format = format.replace(' d', '');
            }
            else {
                format = format.replace('d', '');
            }
            for (power = 0; power <= decimalSuffixes.length; power++) {
                min = Math.pow(1000, power);
                max = Math.pow(1000, power + 1);
                if (value >= min && value < max) {
                    bytes = bytes + decimalSuffixes[power];
                    if (min > 0) {
                        value = value / min;
                    }
                    break;
                }
            }
        }
        // see if ordinal is wanted
        if (format.indexOf('o') > -1) {
            // check for space before
            if (format.indexOf(' o') > -1) {
                ord = ' ';
                format = format.replace(' o', '');
            }
            else {
                format = format.replace('o', '');
            }
            if (cultures[currentCulture].ordinal) {
                ord = ord + cultures[currentCulture].ordinal(value);
            }
        }
        if (format.indexOf('[.]') > -1) {
            optDec = true;
            format = format.replace('[.]', '.');
        }
        w = value.toString().split('.')[0];
        precision = format.split('.')[1];
        thousands = format.indexOf(',');
        if (precision) {
            if (precision.indexOf('*') !== -1) {
                d = toFixed(value, value.toString().split('.')[1].length, roundingFunction);
            }
            else {
                if (precision.indexOf('[') > -1) {
                    precision = precision.replace(']', '');
                    precision = precision.split('[');
                    d = toFixed(value, (precision[0].length + precision[1].length), roundingFunction, precision[1].length);
                }
                else {
                    d = toFixed(value, precision.length, roundingFunction);
                }
            }
            w = d.split('.')[0];
            if (d.split('.')[1].length) {
                var p = sep ? abbr + sep : cultures[currentCulture].delimiters.decimal;
                d = p + d.split('.')[1];
            }
            else {
                d = '';
            }
            if (optDec && Number(d.slice(1)) === 0) {
                d = '';
            }
        }
        else {
            w = toFixed(value, null, roundingFunction);
        }
        // format number
        if (w.indexOf('-') > -1) {
            w = w.slice(1);
            neg = true;
        }
        if (w.length < minlen) {
            w = new Array(minlen - w.length + 1).join('0') + w;
        }
        if (thousands > -1) {
            w = w.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' +
                cultures[currentCulture].delimiters.thousands);
        }
        if (format.indexOf('.') === 0) {
            w = '';
        }
        indexOpenP = format.indexOf('(');
        indexMinus = format.indexOf('-');
        if (indexOpenP < indexMinus) {
            paren = ((negP && neg) ? '(' : '') + (((forcedNeg && neg) || (!negP && neg)) ? '-' : '');
        }
        else {
            paren = (((forcedNeg && neg) || (!negP && neg)) ? '-' : '') + ((negP && neg) ? '(' : '');
        }
        return prefix +
            paren + ((!neg && signed && value !== 0) ? '+' : '') +
            w + d +
            ((ord) ? ord : '') +
            ((abbr && !sep) ? abbr : '') +
            ((bytes) ? bytes : '') +
            ((negP && neg) ? ')' : '') +
            postfix;
    }
    /************************************
        Top Level Functions
    ************************************/
    numbro = function (input) {
        if (numbro.isNumbro(input)) {
            input = input.value();
        }
        else if (input === 0 || typeof input === 'undefined') {
            input = 0;
        }
        else if (!Number(input)) {
            input = numbro.fn.unformat(input);
        }
        return new Numbro(Number(input));
    };
    // version number
    numbro.version = VERSION;
    // compare numbro object
    numbro.isNumbro = function (obj) {
        return obj instanceof Numbro;
    };
    /**
     * This function allow the user to set a new language with a fallback if
     * the language does not exist. If no fallback language is provided,
     * it fallbacks to english.
     *
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `setCulture` should be used instead.
     */
    numbro.setLanguage = function (newLanguage, fallbackLanguage) {
        console.warn('`setLanguage` is deprecated since version 1.6.0. Use `setCulture` instead');
        var key = newLanguage, prefix = newLanguage.split('-')[0], matchingLanguage = null;
        if (!languages[key]) {
            Object.keys(languages).forEach(function (language) {
                if (!matchingLanguage && language.split('-')[0] === prefix) {
                    matchingLanguage = language;
                }
            });
            key = matchingLanguage || fallbackLanguage || 'en-US';
        }
        chooseCulture(key);
    };
    /**
     * This function allow the user to set a new culture with a fallback if
     * the culture does not exist. If no fallback culture is provided,
     * it fallbacks to "en-US".
     */
    numbro.setCulture = function (newCulture, fallbackCulture) {
        var key = newCulture, suffix = newCulture.split('-')[1], matchingCulture = null;
        if (!cultures[key]) {
            if (suffix) {
                Object.keys(cultures).forEach(function (language) {
                    if (!matchingCulture && language.split('-')[1] === suffix) {
                        matchingCulture = language;
                    }
                });
            }
            key = matchingCulture || fallbackCulture || 'en-US';
        }
        chooseCulture(key);
    };
    /**
     * This function will load languages and then set the global language.  If
     * no arguments are passed in, it will simply return the current global
     * language key.
     *
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `culture` should be used instead.
     */
    numbro.language = function (key, values) {
        console.warn('`language` is deprecated since version 1.6.0. Use `culture` instead');
        if (!key) {
            return currentCulture;
        }
        if (key && !values) {
            if (!languages[key]) {
                throw new Error('Unknown language : ' + key);
            }
            chooseCulture(key);
        }
        if (values || !languages[key]) {
            setCulture(key, values);
        }
        return numbro;
    };
    /**
     * This function will load cultures and then set the global culture.  If
     * no arguments are passed in, it will simply return the current global
     * culture code.
     */
    numbro.culture = function (code, values) {
        if (!code) {
            return currentCulture;
        }
        if (code && !values) {
            if (!cultures[code]) {
                throw new Error('Unknown culture : ' + code);
            }
            chooseCulture(code);
        }
        if (values || !cultures[code]) {
            setCulture(code, values);
        }
        return numbro;
    };
    /**
     * This function provides access to the loaded language data.  If
     * no arguments are passed in, it will simply return the current
     * global language object.
     *
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `culture` should be used instead.
     */
    numbro.languageData = function (key) {
        console.warn('`languageData` is deprecated since version 1.6.0. Use `cultureData` instead');
        if (!key) {
            return languages[currentCulture];
        }
        if (!languages[key]) {
            throw new Error('Unknown language : ' + key);
        }
        return languages[key];
    };
    /**
     * This function provides access to the loaded culture data.  If
     * no arguments are passed in, it will simply return the current
     * global culture object.
     */
    numbro.cultureData = function (code) {
        if (!code) {
            return cultures[currentCulture];
        }
        if (!cultures[code]) {
            throw new Error('Unknown culture : ' + code);
        }
        return cultures[code];
    };
    numbro.culture('en-US', enUS);
    /**
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `cultures` should be used instead.
     */
    numbro.languages = function () {
        console.warn('`languages` is deprecated since version 1.6.0. Use `cultures` instead');
        return languages;
    };
    numbro.cultures = function () {
        return cultures;
    };
    numbro.zeroFormat = function (format) {
        zeroFormat = typeof (format) === 'string' ? format : null;
    };
    numbro.defaultFormat = function (format) {
        defaultFormat = typeof (format) === 'string' ? format : '0.0';
    };
    numbro.defaultCurrencyFormat = function (format) {
        defaultCurrencyFormat = typeof (format) === 'string' ? format : '0$';
    };
    numbro.validate = function (val, culture) {
        var _decimalSep, _thousandSep, _currSymbol, _valArray, _abbrObj, _thousandRegEx, cultureData, temp;
        //coerce val to string
        if (typeof val !== 'string') {
            val += '';
            if (console.warn) {
                console.warn('Numbro.js: Value is not string. It has been co-erced to: ', val);
            }
        }
        //trim whitespaces from either sides
        val = val.trim();
        //if val is just digits return true
        if (!!val.match(/^\d+$/)) {
            return true;
        }
        //if val is empty return false
        if (val === '') {
            return false;
        }
        //get the decimal and thousands separator from numbro.cultureData
        try {
            //check if the culture is understood by numbro. if not, default it to current culture
            cultureData = numbro.cultureData(culture);
        }
        catch (e) {
            cultureData = numbro.cultureData(numbro.culture());
        }
        //setup the delimiters and currency symbol based on culture
        _currSymbol = cultureData.currency.symbol;
        _abbrObj = cultureData.abbreviations;
        _decimalSep = cultureData.delimiters.decimal;
        if (cultureData.delimiters.thousands === '.') {
            _thousandSep = '\\.';
        }
        else {
            _thousandSep = cultureData.delimiters.thousands;
        }
        // validating currency symbol
        temp = val.match(/^[^\d]+/);
        if (temp !== null) {
            val = val.substr(1);
            if (temp[0] !== _currSymbol) {
                return false;
            }
        }
        //validating abbreviation symbol
        temp = val.match(/[^\d]+$/);
        if (temp !== null) {
            val = val.slice(0, -1);
            if (temp[0] !== _abbrObj.thousand && temp[0] !== _abbrObj.million &&
                temp[0] !== _abbrObj.billion && temp[0] !== _abbrObj.trillion) {
                return false;
            }
        }
        _thousandRegEx = new RegExp(_thousandSep + '{2}');
        if (!val.match(/[^\d.,]/g)) {
            _valArray = val.split(_decimalSep);
            if (_valArray.length > 2) {
                return false;
            }
            else {
                if (_valArray.length < 2) {
                    return (!!_valArray[0].match(/^\d+.*\d$/) && !_valArray[0].match(_thousandRegEx));
                }
                else {
                    if (_valArray[0].length === 1) {
                        return (!!_valArray[0].match(/^\d+$/) &&
                            !_valArray[0].match(_thousandRegEx) &&
                            !!_valArray[1].match(/^\d+$/));
                    }
                    else {
                        return (!!_valArray[0].match(/^\d+.*\d$/) &&
                            !_valArray[0].match(_thousandRegEx) &&
                            !!_valArray[1].match(/^\d+$/));
                    }
                }
            }
        }
        return false;
    };
    /************************************
        Helpers
    ************************************/
    function setCulture(code, values) {
        cultures[code] = values;
    }
    function chooseCulture(code) {
        currentCulture = code;
        var defaults = cultures[code].defaults;
        if (defaults && defaults.format) {
            numbro.defaultFormat(defaults.format);
        }
        if (defaults && defaults.currencyFormat) {
            numbro.defaultCurrencyFormat(defaults.currencyFormat);
        }
    }
    function format(input, formatString, language, roundingFunction) {
        if (language != null && language !== numbro.culture()) {
            numbro.setCulture(language);
        }
        return formatNumbro(Number(input), formatString != null ? formatString : defaultFormat, roundingFunction == null ? Math.round : roundingFunction);
    }
    module.exports = { "format": format };
},
/* sprintf-js/src/sprintf.js */ function _(require, module, exports, __esModule, __esExport) {
    /* global window, exports, define */
    !function () {
        'use strict';
        var re = {
            not_string: /[^s]/,
            not_bool: /[^t]/,
            not_type: /[^T]/,
            not_primitive: /[^v]/,
            number: /[diefg]/,
            numeric_arg: /[bcdiefguxX]/,
            json: /[j]/,
            not_json: /[^j]/,
            text: /^[^\x25]+/,
            modulo: /^\x25{2}/,
            placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
            key: /^([a-z_][a-z_\d]*)/i,
            key_access: /^\.([a-z_][a-z_\d]*)/i,
            index_access: /^\[(\d+)\]/,
            sign: /^[+-]/
        };
        function sprintf(key) {
            // `arguments` is not an array, but should be fine for this call
            return sprintf_format(sprintf_parse(key), arguments);
        }
        function vsprintf(fmt, argv) {
            return sprintf.apply(null, [fmt].concat(argv || []));
        }
        function sprintf_format(parse_tree, argv) {
            var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign;
            for (i = 0; i < tree_length; i++) {
                if (typeof parse_tree[i] === 'string') {
                    output += parse_tree[i];
                }
                else if (typeof parse_tree[i] === 'object') {
                    ph = parse_tree[i]; // convenience purposes only
                    if (ph.keys) { // keyword argument
                        arg = argv[cursor];
                        for (k = 0; k < ph.keys.length; k++) {
                            if (arg == undefined) {
                                throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k - 1]));
                            }
                            arg = arg[ph.keys[k]];
                        }
                    }
                    else if (ph.param_no) { // positional argument (explicit)
                        arg = argv[ph.param_no];
                    }
                    else { // positional argument (implicit)
                        arg = argv[cursor++];
                    }
                    if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
                        arg = arg();
                    }
                    if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {
                        throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg));
                    }
                    if (re.number.test(ph.type)) {
                        is_positive = arg >= 0;
                    }
                    switch (ph.type) {
                        case 'b':
                            arg = parseInt(arg, 10).toString(2);
                            break;
                        case 'c':
                            arg = String.fromCharCode(parseInt(arg, 10));
                            break;
                        case 'd':
                        case 'i':
                            arg = parseInt(arg, 10);
                            break;
                        case 'j':
                            arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0);
                            break;
                        case 'e':
                            arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential();
                            break;
                        case 'f':
                            arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg);
                            break;
                        case 'g':
                            arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg);
                            break;
                        case 'o':
                            arg = (parseInt(arg, 10) >>> 0).toString(8);
                            break;
                        case 's':
                            arg = String(arg);
                            arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
                            break;
                        case 't':
                            arg = String(!!arg);
                            arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
                            break;
                        case 'T':
                            arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase();
                            arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
                            break;
                        case 'u':
                            arg = parseInt(arg, 10) >>> 0;
                            break;
                        case 'v':
                            arg = arg.valueOf();
                            arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
                            break;
                        case 'x':
                            arg = (parseInt(arg, 10) >>> 0).toString(16);
                            break;
                        case 'X':
                            arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase();
                            break;
                    }
                    if (re.json.test(ph.type)) {
                        output += arg;
                    }
                    else {
                        if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
                            sign = is_positive ? '+' : '-';
                            arg = arg.toString().replace(re.sign, '');
                        }
                        else {
                            sign = '';
                        }
                        pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' ';
                        pad_length = ph.width - (sign + arg).length;
                        pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : '';
                        output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg);
                    }
                }
            }
            return output;
        }
        var sprintf_cache = Object.create(null);
        function sprintf_parse(fmt) {
            if (sprintf_cache[fmt]) {
                return sprintf_cache[fmt];
            }
            var _fmt = fmt, match, parse_tree = [], arg_names = 0;
            while (_fmt) {
                if ((match = re.text.exec(_fmt)) !== null) {
                    parse_tree.push(match[0]);
                }
                else if ((match = re.modulo.exec(_fmt)) !== null) {
                    parse_tree.push('%');
                }
                else if ((match = re.placeholder.exec(_fmt)) !== null) {
                    if (match[2]) {
                        arg_names |= 1;
                        var field_list = [], replacement_field = match[2], field_match = [];
                        if ((field_match = re.key.exec(replacement_field)) !== null) {
                            field_list.push(field_match[1]);
                            while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
                                if ((field_match = re.key_access.exec(replacement_field)) !== null) {
                                    field_list.push(field_match[1]);
                                }
                                else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
                                    field_list.push(field_match[1]);
                                }
                                else {
                                    throw new SyntaxError('[sprintf] failed to parse named argument key');
                                }
                            }
                        }
                        else {
                            throw new SyntaxError('[sprintf] failed to parse named argument key');
                        }
                        match[2] = field_list;
                    }
                    else {
                        arg_names |= 2;
                    }
                    if (arg_names === 3) {
                        throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported');
                    }
                    parse_tree.push({
                        placeholder: match[0],
                        param_no: match[1],
                        keys: match[2],
                        sign: match[3],
                        pad_char: match[4],
                        align: match[5],
                        width: match[6],
                        precision: match[7],
                        type: match[8]
                    });
                }
                else {
                    throw new SyntaxError('[sprintf] unexpected placeholder');
                }
                _fmt = _fmt.substring(match[0].length);
            }
            return sprintf_cache[fmt] = parse_tree;
        }
        /**
         * export to either browser or node.js
         */
        /* eslint-disable quote-props */
        if (typeof exports !== 'undefined') {
            exports['sprintf'] = sprintf;
            exports['vsprintf'] = vsprintf;
        }
        if (typeof window !== 'undefined') {
            window['sprintf'] = sprintf;
            window['vsprintf'] = vsprintf;
            if (typeof define === 'function' && define['amd']) {
                define(function () {
                    return {
                        'sprintf': sprintf,
                        'vsprintf': vsprintf
                    };
                });
            }
        }
        /* eslint-enable quote-props */
    }(); // eslint-disable-line
},
/* timezone/index.js */ function _(require, module, exports, __esModule, __esExport) {
    !function (definition) {
        if (typeof module == "object" && module.exports)
            module.exports = definition();
        else if (typeof define == "function")
            define(definition);
        else
            this.tz = definition();
    }(function () {
        /*
          function die () {
            console.log.apply(console, __slice.call(arguments, 0));
            return process.exit(1);
          }
        
          function say () { return console.log.apply(console, __slice.call(arguments, 0)) }
        */
        function actualize(entry, rule, year) {
            var actualized, date = rule.day[1];
            do {
                actualized = new Date(Date.UTC(year, rule.month, Math.abs(date++)));
            } while (rule.day[0] < 7 && actualized.getUTCDay() != rule.day[0]);
            actualized = {
                clock: rule.clock,
                sort: actualized.getTime(),
                rule: rule,
                save: rule.save * 6e4,
                offset: entry.offset
            };
            actualized[actualized.clock] = actualized.sort + rule.time * 6e4;
            if (actualized.posix) {
                actualized.wallclock = actualized[actualized.clock] + (entry.offset + rule.saved);
            }
            else {
                actualized.posix = actualized[actualized.clock] - (entry.offset + rule.saved);
            }
            return actualized;
        }
        function find(request, clock, time) {
            var i, I, entry, found, zone = request[request.zone], actualized = [], abbrev, rules, j, year = new Date(time).getUTCFullYear(), off = 1;
            for (i = 1, I = zone.length; i < I; i++)
                if (zone[i][clock] <= time)
                    break;
            entry = zone[i];
            if (entry.rules) {
                rules = request[entry.rules];
                for (j = year + 1; j >= year - off; --j)
                    for (i = 0, I = rules.length; i < I; i++)
                        if (rules[i].from <= j && j <= rules[i].to)
                            actualized.push(actualize(entry, rules[i], j));
                        else if (rules[i].to < j && off == 1)
                            off = j - rules[i].to;
                actualized.sort(function (a, b) { return a.sort - b.sort; });
                for (i = 0, I = actualized.length; i < I; i++) {
                    if (time >= actualized[i][clock] && actualized[i][actualized[i].clock] > entry[actualized[i].clock])
                        found = actualized[i];
                }
            }
            if (found) {
                if (abbrev = /^(.*)\/(.*)$/.exec(entry.format)) {
                    found.abbrev = abbrev[found.save ? 2 : 1];
                }
                else {
                    found.abbrev = entry.format.replace(/%s/, found.rule.letter);
                }
            }
            return found || entry;
        }
        function convertToWallclock(request, posix) {
            if (request.zone == "UTC")
                return posix;
            request.entry = find(request, "posix", posix);
            return posix + request.entry.offset + request.entry.save;
        }
        function convertToPOSIX(request, wallclock) {
            if (request.zone == "UTC")
                return wallclock;
            var entry, diff;
            request.entry = entry = find(request, "wallclock", wallclock);
            diff = wallclock - entry.wallclock;
            return 0 < diff && diff < entry.save ? null : wallclock - entry.offset - entry.save;
        }
        function adjust(request, posix, match) {
            var increment = +(match[1] + 1) // conversion necessary for week day addition
            , offset = match[2] * increment, index = UNITS.indexOf(match[3].toLowerCase()), date;
            if (index > 9) {
                posix += offset * TIME[index - 10];
            }
            else {
                date = new Date(convertToWallclock(request, posix));
                if (index < 7) {
                    while (offset) {
                        date.setUTCDate(date.getUTCDate() + increment);
                        if (date.getUTCDay() == index)
                            offset -= increment;
                    }
                }
                else if (index == 7) {
                    date.setUTCFullYear(date.getUTCFullYear() + offset);
                }
                else if (index == 8) {
                    date.setUTCMonth(date.getUTCMonth() + offset);
                }
                else {
                    date.setUTCDate(date.getUTCDate() + offset);
                }
                if ((posix = convertToPOSIX(request, date.getTime())) == null) {
                    posix = convertToPOSIX(request, date.getTime() + 864e5 * increment) - 864e5 * increment;
                }
            }
            return posix;
        }
        function convert(vargs) {
            if (!vargs.length)
                return "1.0.23";
            var request = Object.create(this), adjustments = [], i, I, $, argument, date;
            for (i = 0; i < vargs.length; i++) { // leave the for loop alone, it works.
                argument = vargs[i];
                // https://twitter.com/bigeasy/status/215112186572439552
                if (Array.isArray(argument)) {
                    if (!i && !isNaN(argument[1])) {
                        date = argument;
                    }
                    else {
                        argument.splice.apply(vargs, [i--, 1].concat(argument));
                    }
                }
                else if (isNaN(argument)) {
                    $ = typeof argument;
                    if ($ == "string") {
                        if (~argument.indexOf("%")) {
                            request.format = argument;
                        }
                        else if (!i && argument == "*") {
                            date = argument;
                        }
                        else if (!i && ($ = /^(\d{4})-(\d{2})-(\d{2})(?:[T\s](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(Z|(([+-])(\d{2}(:\d{2}){0,2})))?)?$/.exec(argument))) {
                            date = [];
                            date.push.apply(date, $.slice(1, 8));
                            if ($[9]) {
                                date.push($[10] + 1);
                                date.push.apply(date, $[11].split(/:/));
                            }
                            else if ($[8]) {
                                date.push(1);
                            }
                        }
                        else if (/^\w{2,3}_\w{2}$/.test(argument)) {
                            request.locale = argument;
                        }
                        else if ($ = UNIT_RE.exec(argument)) {
                            adjustments.push($);
                        }
                        else {
                            request.zone = argument;
                        }
                    }
                    else if ($ == "function") {
                        if ($ = argument.call(request))
                            return $;
                    }
                    else if (/^\w{2,3}_\w{2}$/.test(argument.name)) {
                        request[argument.name] = argument;
                    }
                    else if (argument.zones) {
                        for ($ in argument.zones)
                            request[$] = argument.zones[$];
                        for ($ in argument.rules)
                            request[$] = argument.rules[$];
                    }
                }
                else if (!i) {
                    date = argument;
                }
            }
            if (!request[request.locale])
                delete request.locale;
            if (!request[request.zone])
                delete request.zone;
            if (date != null) {
                if (date == "*") {
                    date = request.clock();
                }
                else if (Array.isArray(date)) {
                    $ = [];
                    I = !date[7];
                    for (i = 0; i < 11; i++)
                        $[i] = +(date[i] || 0); // conversion necessary for decrement
                    --$[1]; // Grr..
                    date = Date.UTC.apply(Date.UTC, $) + -$[7] * ($[8] * 36e5 + $[9] * 6e4 + $[10] * 1e3);
                }
                else {
                    date = Math.floor(date);
                }
                if (!isNaN(date)) {
                    if (I)
                        date = convertToPOSIX(request, date);
                    if (date == null)
                        return date;
                    for (i = 0, I = adjustments.length; i < I; i++) {
                        date = adjust(request, date, adjustments[i]);
                    }
                    if (!request.format)
                        return date;
                    $ = new Date(convertToWallclock(request, date));
                    return request.format.replace(/%([-0_^]?)(:{0,3})(\d*)(.)/g, function (value, flag, colons, padding, specifier) {
                        var f, fill = "0", pad;
                        if (f = request[specifier]) {
                            value = String(f.call(request, $, date, flag, colons.length));
                            if ((flag || f.style) == "_")
                                fill = " ";
                            pad = flag == "-" ? 0 : f.pad || 0;
                            while (value.length < pad)
                                value = fill + value;
                            pad = flag == "-" ? 0 : padding || f.pad;
                            while (value.length < pad)
                                value = fill + value;
                            if (specifier == "N" && pad < value.length)
                                value = value.slice(0, pad);
                            if (flag == "^")
                                value = value.toUpperCase();
                        }
                        return value;
                    });
                }
            }
            return function () { return request.convert(arguments); };
        }
        var context = { clock: function () { return +(new Date()); },
            zone: "UTC",
            entry: { abbrev: "UTC", offset: 0, save: 0 },
            UTC: 1,
            z: function (date, posix, flag, delimiters) {
                var offset = this.entry.offset + this.entry.save, seconds = Math.abs(offset / 1000), parts = [], part = 3600, i, z;
                for (i = 0; i < 3; i++) {
                    parts.push(("0" + Math.floor(seconds / part)).slice(-2));
                    seconds %= part;
                    part /= 60;
                }
                if (flag == "^" && !offset)
                    return "Z";
                if (flag == "^")
                    delimiters = 3;
                if (delimiters == 3) {
                    z = parts.join(":");
                    z = z.replace(/:00$/, "");
                    if (flag != "^")
                        z = z.replace(/:00$/, "");
                }
                else if (delimiters) {
                    z = parts.slice(0, delimiters + 1).join(":");
                    if (flag == "^")
                        z = z.replace(/:00$/, "");
                }
                else {
                    z = parts.slice(0, 2).join("");
                }
                z = (offset < 0 ? "-" : "+") + z;
                z = z.replace(/([-+])(0)/, { "_": " $1", "-": "$1" }[flag] || "$1$2");
                return z;
            },
            "%": function (date) { return "%"; },
            n: function (date) { return "\n"; },
            t: function (date) { return "\t"; },
            U: function (date) { return weekOfYear(date, 0); },
            W: function (date) { return weekOfYear(date, 1); },
            V: function (date) { return isoWeek(date)[0]; },
            G: function (date) { return isoWeek(date)[1]; },
            g: function (date) { return isoWeek(date)[1] % 100; },
            j: function (date) { return Math.floor((date.getTime() - Date.UTC(date.getUTCFullYear(), 0)) / 864e5) + 1; },
            s: function (date) { return Math.floor(date.getTime() / 1000); },
            C: function (date) { return Math.floor(date.getUTCFullYear() / 100); },
            N: function (date) { return date.getTime() % 1000 * 1000000; },
            m: function (date) { return date.getUTCMonth() + 1; },
            Y: function (date) { return date.getUTCFullYear(); },
            y: function (date) { return date.getUTCFullYear() % 100; },
            H: function (date) { return date.getUTCHours(); },
            M: function (date) { return date.getUTCMinutes(); },
            S: function (date) { return date.getUTCSeconds(); },
            e: function (date) { return date.getUTCDate(); },
            d: function (date) { return date.getUTCDate(); },
            u: function (date) { return date.getUTCDay() || 7; },
            w: function (date) { return date.getUTCDay(); },
            l: function (date) { return date.getUTCHours() % 12 || 12; },
            I: function (date) { return date.getUTCHours() % 12 || 12; },
            k: function (date) { return date.getUTCHours(); },
            Z: function (date) { return this.entry.abbrev; },
            a: function (date) { return this[this.locale].day.abbrev[date.getUTCDay()]; },
            A: function (date) { return this[this.locale].day.full[date.getUTCDay()]; },
            h: function (date) { return this[this.locale].month.abbrev[date.getUTCMonth()]; },
            b: function (date) { return this[this.locale].month.abbrev[date.getUTCMonth()]; },
            B: function (date) { return this[this.locale].month.full[date.getUTCMonth()]; },
            P: function (date) { return this[this.locale].meridiem[Math.floor(date.getUTCHours() / 12)].toLowerCase(); },
            p: function (date) { return this[this.locale].meridiem[Math.floor(date.getUTCHours() / 12)]; },
            R: function (date, posix) { return this.convert([posix, "%H:%M"]); },
            T: function (date, posix) { return this.convert([posix, "%H:%M:%S"]); },
            D: function (date, posix) { return this.convert([posix, "%m/%d/%y"]); },
            F: function (date, posix) { return this.convert([posix, "%Y-%m-%d"]); },
            x: function (date, posix) { return this.convert([posix, this[this.locale].date]); },
            r: function (date, posix) { return this.convert([posix, this[this.locale].time12 || '%I:%M:%S']); },
            X: function (date, posix) { return this.convert([posix, this[this.locale].time24]); },
            c: function (date, posix) { return this.convert([posix, this[this.locale].dateTime]); },
            convert: convert,
            locale: "en_US",
            en_US: {
                date: "%m/%d/%Y",
                time24: "%I:%M:%S %p",
                time12: "%I:%M:%S %p",
                dateTime: "%a %d %b %Y %I:%M:%S %p %Z",
                meridiem: ["AM", "PM"],
                month: {
                    abbrev: "Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec".split("|"),
                    full: "January|February|March|April|May|June|July|August|September|October|November|December".split("|")
                },
                day: {
                    abbrev: "Sun|Mon|Tue|Wed|Thu|Fri|Sat".split("|"),
                    full: "Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday".split("|")
                }
            }
        };
        var UNITS = "Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|year|month|day|hour|minute|second|millisecond", UNIT_RE = new RegExp("^\\s*([+-])(\\d+)\\s+(" + UNITS + ")s?\\s*$", "i"), TIME = [36e5, 6e4, 1e3, 1];
        UNITS = UNITS.toLowerCase().split("|");
        "delmHMSUWVgCIky".replace(/./g, function (e) { context[e].pad = 2; });
        context.N.pad = 9;
        context.j.pad = 3;
        context.k.style = "_";
        context.l.style = "_";
        context.e.style = "_";
        function weekOfYear(date, startOfWeek) {
            var diff, nyd, weekStart;
            nyd = new Date(Date.UTC(date.getUTCFullYear(), 0));
            diff = Math.floor((date.getTime() - nyd.getTime()) / 864e5);
            if (nyd.getUTCDay() == startOfWeek) {
                weekStart = 0;
            }
            else {
                weekStart = 7 - nyd.getUTCDay() + startOfWeek;
                if (weekStart == 8) {
                    weekStart = 1;
                }
            }
            return diff >= weekStart ? Math.floor((diff - weekStart) / 7) + 1 : 0;
        }
        function isoWeek(date) {
            var nyd, nyy, week;
            nyy = date.getUTCFullYear();
            nyd = new Date(Date.UTC(nyy, 0)).getUTCDay();
            week = weekOfYear(date, 1) + (nyd > 1 && nyd <= 4 ? 1 : 0);
            if (!week) {
                nyy = date.getUTCFullYear() - 1;
                nyd = new Date(Date.UTC(nyy, 0)).getUTCDay();
                week = nyd == 4 || (nyd == 3 && new Date(nyy, 1, 29).getDate() == 29) ? 53 : 52;
                return [week, date.getUTCFullYear() - 1];
            }
            else if (week == 53 && !(nyd == 4 || (nyd == 3 && new Date(nyy, 1, 29).getDate() == 29))) {
                return [1, date.getUTCFullYear() + 1];
            }
            else {
                return [week, date.getUTCFullYear()];
            }
        }
        return function () { return context.convert(arguments); };
    });
},
/* models/formatters/customjs_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tick_formatter_1 = require(275) /* ./tick_formatter */;
    const object_1 = require(9) /* ../../core/util/object */;
    const string_1 = require(41) /* ../../core/util/string */;
    class CustomJSTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Unknown, Str, Dict }) => ({
                args: [Dict(Unknown), {}],
                code: [Str, ""],
            }));
        }
        get names() {
            return (0, object_1.keys)(this.args);
        }
        get values() {
            return (0, object_1.values)(this.args);
        }
        /*protected*/ _make_func() {
            const code = (0, string_1.use_strict)(this.code);
            return new Function("tick", "index", "ticks", ...this.names, code);
        }
        doFormat(ticks, _opts) {
            const cache = {};
            const func = this._make_func().bind(cache);
            return ticks.map((tick, index, ticks) => `${func(tick, index, ticks, ...this.values)}`);
        }
    }
    exports.CustomJSTickFormatter = CustomJSTickFormatter;
},
/* models/formatters/log_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tick_formatter_1 = require(275) /* ./tick_formatter */;
    const basic_tick_formatter_1 = require(279) /* ./basic_tick_formatter */;
    const log_ticker_1 = require(294) /* ../tickers/log_ticker */;
    const graphics_1 = require(262) /* ../../core/graphics */;
    const { abs, log, round } = Math;
    class LogTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Int, Ref, Nullable }) => ({
                ticker: [Nullable(Ref(log_ticker_1.LogTicker)), null],
                min_exponent: [Int, 0],
            }));
        }
        basic_formatter = new basic_tick_formatter_1.BasicTickFormatter();
        format_graphics(ticks, opts) {
            if (ticks.length == 0) {
                return [];
            }
            const base = this.ticker?.base ?? 10;
            const expos = this._exponents(ticks, base);
            if (expos == null) {
                return this.basic_formatter.format_graphics(ticks, opts);
            }
            else {
                return expos.map((expo) => {
                    if (abs(expo) < this.min_exponent) {
                        const b = new graphics_1.TextBox({ text: (0, basic_tick_formatter_1.unicode_replace)(`${base ** expo}`) });
                        const e = new graphics_1.TextBox({ text: "" });
                        return new graphics_1.BaseExpo(b, e);
                    }
                    else {
                        const b = new graphics_1.TextBox({ text: (0, basic_tick_formatter_1.unicode_replace)(`${base}`) });
                        const e = new graphics_1.TextBox({ text: (0, basic_tick_formatter_1.unicode_replace)(`${expo}`) });
                        return new graphics_1.BaseExpo(b, e);
                    }
                });
            }
        }
        _exponents(ticks, base) {
            let last_exponent = null;
            const exponents = [];
            for (const tick of ticks) {
                const exponent = round(log(tick) / log(base));
                if (last_exponent != exponent) {
                    last_exponent = exponent;
                    exponents.push(exponent);
                }
                else {
                    return null;
                }
            }
            return exponents;
        }
        doFormat(ticks, opts) {
            if (ticks.length == 0) {
                return [];
            }
            const base = this.ticker?.base ?? 10;
            const expos = this._exponents(ticks, base);
            if (expos == null) {
                return this.basic_formatter.doFormat(ticks, opts);
            }
            else {
                return expos.map((expo) => {
                    if (abs(expo) < this.min_exponent) {
                        return (0, basic_tick_formatter_1.unicode_replace)(`${base ** expo}`);
                    }
                    else {
                        return (0, basic_tick_formatter_1.unicode_replace)(`${base}^${expo}`);
                    }
                });
            }
        }
    }
    exports.LogTickFormatter = LogTickFormatter;
},
/* models/formatters/mercator_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const basic_tick_formatter_1 = require(279) /* ./basic_tick_formatter */;
    const enums_1 = require(21) /* ../../core/enums */;
    const projections_1 = require(148) /* ../../core/util/projections */;
    const zero_threshold = 1e-12; // degrees; about 0.1 micrometers at the equator
    function normalize_zeroish(value) {
        return Math.abs(value) < zero_threshold ? 0 : value;
    }
    class MercatorTickFormatter extends basic_tick_formatter_1.BasicTickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Nullable }) => ({
                dimension: [Nullable(enums_1.LatLon), null],
            }));
        }
        doFormat(ticks, opts) {
            if (this.dimension == null) {
                throw new Error("MercatorTickFormatter.dimension not configured");
            }
            if (ticks.length == 0) {
                return [];
            }
            const n = ticks.length;
            const proj_ticks = new Array(n);
            if (this.dimension == "lon") {
                for (let i = 0; i < n; i++) {
                    const [lon] = projections_1.wgs84_mercator.invert(ticks[i], opts.loc);
                    proj_ticks[i] = normalize_zeroish(lon);
                }
            }
            else {
                for (let i = 0; i < n; i++) {
                    const [, lat] = projections_1.wgs84_mercator.invert(opts.loc, ticks[i]);
                    proj_ticks[i] = normalize_zeroish(lat);
                }
            }
            return super.doFormat(proj_ticks, opts);
        }
    }
    exports.MercatorTickFormatter = MercatorTickFormatter;
},
/* models/formatters/numeral_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const Numbro = tslib_1.__importStar(require(330) /* @bokeh/numbro */);
    const tick_formatter_1 = require(275) /* ./tick_formatter */;
    const enums_1 = require(21) /* ../../core/enums */;
    class NumeralTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Str }) => ({
                // TODO (bev) all of these could be tightened up
                format: [Str, "0,0"],
                language: [Str, "en"],
                rounding: [enums_1.RoundingFunction, "round"],
            }));
        }
        get _rounding_fn() {
            switch (this.rounding) {
                case "round":
                case "nearest":
                    return Math.round;
                case "floor":
                case "rounddown":
                    return Math.floor;
                case "ceil":
                case "roundup":
                    return Math.ceil;
            }
        }
        doFormat(ticks, _opts) {
            const { format, language, _rounding_fn } = this;
            return ticks.map((tick) => Numbro.format(tick, format, language, _rounding_fn));
        }
    }
    exports.NumeralTickFormatter = NumeralTickFormatter;
},
/* models/formatters/printf_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tick_formatter_1 = require(275) /* ./tick_formatter */;
    const templating_1 = require(329) /* ../../core/util/templating */;
    class PrintfTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Str }) => ({
                format: [Str, "%s"],
            }));
        }
        doFormat(ticks, _opts) {
            return ticks.map((tick) => (0, templating_1.sprintf)(this.format, tick));
        }
    }
    exports.PrintfTickFormatter = PrintfTickFormatter;
},
/* models/formatters/timedelta_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports._get_resolution = _get_resolution;
    exports._str_timedelta = _str_timedelta;
    exports._days = _days;
    exports._hours = _hours;
    exports._minutes = _minutes;
    exports._seconds = _seconds;
    exports._ms = _ms;
    exports._us = _us;
    exports._ns = _ns;
    const enums_1 = require(21) /* ../../core/enums */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    const templating_1 = require(329) /* ../../core/util/templating */;
    const types_1 = require(8) /* ../../core/util/types */;
    const tick_formatter_1 = require(275) /* ./tick_formatter */;
    const util_1 = require(290) /* ../tickers/util */;
    // Labels of time units, from finest to coarsest.
    exports.resolution_order = [
        "nanoseconds", "microseconds", "milliseconds", "seconds", "minsec", "minutes", "hourmin", "hours", "days",
    ];
    exports.formatting_map = {
        "%NS": (t) => _ns(t, 1000),
        "%ns": (t) => _ns(t, null),
        "%US": (t) => _us(t, 1000),
        "%us": (t) => _us(t, null),
        "%MS": (t) => _ms(t, 1000),
        "%ms": (t) => _ms(t, null),
        "%S": (t) => _seconds(t, 60),
        "%s": (t) => _seconds(t, null),
        "%M": (t) => _minutes(t, 60),
        "%m": (t) => _minutes(t, null),
        "%H": (t) => _hours(t, 24),
        "%h": (t) => _hours(t, null),
        "%d": (t) => _days(t, null),
    };
    function _get_resolution(resolution_secs, span_secs) {
        // Our resolution boundaries should not be round numbers, because we want
        // them to fall between the possible tick intervals (which *are* round
        // numbers, as we've worked hard to ensure). Consequently, we adjust the
        // resolution upwards a small amount (less than any possible step in
        // scales) to make the effective boundaries slightly lower.
        const adjusted_ms = resolution_secs * 1.1 * 1000;
        const span_ms = span_secs * 1000;
        if (adjusted_ms < util_1.ONE_MICRO) {
            return "nanoseconds";
        }
        if (adjusted_ms < util_1.ONE_MILLI) {
            return "microseconds";
        }
        if (adjusted_ms < util_1.ONE_SECOND) {
            return "milliseconds";
        }
        if (adjusted_ms < util_1.ONE_MINUTE) {
            return span_ms >= util_1.ONE_MINUTE ? "minsec" : "seconds";
        }
        if (adjusted_ms < util_1.ONE_HOUR) {
            return span_ms >= util_1.ONE_HOUR ? "hourmin" : "minutes";
        }
        if (adjusted_ms < util_1.ONE_DAY) {
            return "hours";
        }
        return "days";
    }
    function _str_timedelta(t, format) {
        for (const [k, v] of Object.entries(exports.formatting_map)) {
            const format_template = new RegExp(`((^|[^%])(%%)*)${k}`);
            if (format_template.test(format)) {
                format = format.replace(format_template, `$1${v(t)}`);
            }
        }
        return format;
    }
    function _days(t, factor_next) {
        const days = _calc_tick_value(t, util_1.ONE_DAY, factor_next);
        return _str_tick_value(days, factor_next);
    }
    function _hours(t, factor_next) {
        const hours = _calc_tick_value(t, util_1.ONE_HOUR, factor_next);
        return _str_tick_value(hours, factor_next);
    }
    function _minutes(t, factor_next) {
        const minutes = _calc_tick_value(t, util_1.ONE_MINUTE, factor_next);
        return _str_tick_value(minutes, factor_next);
    }
    function _seconds(t, factor_next) {
        const seconds = _calc_tick_value(t, util_1.ONE_SECOND, factor_next);
        return _str_tick_value(seconds, factor_next);
    }
    function _ms(t, factor_next) {
        const millis = _calc_tick_value(t, util_1.ONE_MILLI, factor_next);
        return _str_tick_value(millis, factor_next);
    }
    function _us(t, factor_next) {
        const us = _calc_tick_value(t, util_1.ONE_MICRO, factor_next);
        return _str_tick_value(us, factor_next);
    }
    function _ns(t, factor_next) {
        const ns = _calc_tick_value(t, util_1.ONE_NANO, factor_next);
        return _str_tick_value(ns, factor_next);
    }
    function _str_tick_value(v, factor_next) {
        return factor_next !== null ? (0, templating_1.sprintf)(`%0${`${factor_next - 1}`.length}d`, v) : String(v);
    }
    function _calc_tick_value(t, factor_transform, factor_next) {
        if (factor_next !== null) {
            return _time_since_last_next(t, factor_transform, factor_next);
        }
        else {
            return _time_total(t, factor_transform);
        }
    }
    function _time_since_last_next(t, factor_transform, factor_next) {
        if (factor_transform < 1) {
            // sub milliseconds
            // handle floating point precision as best as possible
            const t_nano = Math.round(t * 1000000);
            const divisor_next = factor_transform * factor_next * 1000000;
            // switch to String to avoid precision issues,
            // e.g. 116011933670718300 - 116011933670718000 equals 304
            const digits = `${divisor_next}`.length;
            const str_t_nano = String(t_nano);
            const nanos_since_last_next = parseFloat(str_t_nano.substring(str_t_nano.length - digits)) % divisor_next;
            return (nanos_since_last_next / (factor_transform * 1000000)) % factor_next;
        }
        const millis_since_last_next = t % (factor_transform * factor_next);
        return millis_since_last_next / factor_transform;
    }
    function _time_total(t, factor_transform) {
        return Math.floor(t / factor_transform);
    }
    class TimedeltaTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Bool, Nullable, Or, Ref, Str, Arrayable }) => ({
                nanoseconds: [Str, "%NSns"],
                microseconds: [Str, "%USus"],
                milliseconds: [Str, "%MSms"],
                seconds: [Str, "%H:%M:%S"],
                minsec: [Str, "%H:%M:%S"],
                minutes: [Str, "%H:%M"],
                hourmin: [Str, "%H:%M"],
                hours: [Str, "%H:%M"],
                days: [Str, "%d days"],
                strip_leading_zeros: [Or(Bool, Arrayable(enums_1.TimedeltaResolutionType)), false],
                hide_repeats: [Bool, false],
                context: [Nullable(Or(Str, Ref(TimedeltaTickFormatter))), null],
                context_which: [enums_1.ContextWhich, "start"],
                context_location: [enums_1.Location, "below"],
            }));
        }
        doFormat(ticks, _opts, _resolution) {
            if (ticks.length == 0) {
                return [];
            }
            const span = Math.abs(ticks[ticks.length - 1] - ticks[0]) / 1000.0;
            const r = span / (ticks.length - 1);
            const resolution = (0, types_1.is_undefined)(_resolution) ? _get_resolution(r, span) : _resolution;
            let base_labels = [];
            for (const tick of ticks) {
                const base_label = this._compute_label(tick, resolution);
                base_labels.push(base_label);
            }
            if (this.hide_repeats) {
                base_labels = this._hide_repeating_labels(base_labels);
            }
            if (this.context == null) {
                return base_labels;
            }
            const context_labels = this._compute_context_labels(ticks, resolution);
            return this._build_full_labels(base_labels, context_labels);
        }
        _compute_label(t, resolution) {
            const s0 = _str_timedelta(t, this[resolution]);
            const { strip_leading_zeros } = this;
            if (((0, types_1.isBoolean)(strip_leading_zeros) && strip_leading_zeros) ||
                ((0, types_1.isArray)(strip_leading_zeros) && strip_leading_zeros.includes(resolution))) {
                const ss = s0.replace(/^0+/g, "");
                if (ss != s0 && !Number.isInteger(Number(ss[0]))) {
                    // If the string can now be parsed as starting with an integer, then
                    // leave all zeros stripped, otherwise start with a zero.
                    return `0${ss}`;
                }
                return ss;
            }
            return s0;
        }
        _compute_context_labels(ticks, resolution) {
            const { context } = this;
            (0, assert_1.assert)(context != null);
            const context_labels = [];
            if ((0, types_1.isString)(context)) {
                for (const tick of ticks) {
                    context_labels.push(_str_timedelta(tick, context));
                }
            }
            else {
                context_labels.push(...context.doFormat(ticks, { loc: 0 }, resolution));
            }
            const which = this.context_which;
            const N = context_labels.length;
            for (let i = 0; i < context_labels.length; i++) {
                if ((which == "start" && i != 0) ||
                    (which == "end" && i != N - 1) ||
                    (which == "center" && i != Math.floor(N / 2))) {
                    context_labels[i] = "";
                }
            }
            return context_labels;
        }
        _build_full_labels(base_labels, context_labels) {
            const loc = this.context_location;
            const full_labels = [];
            if (context_labels.every(v => v === "")) {
                return base_labels;
            }
            for (let i = 0; i < base_labels.length; i++) {
                const label = base_labels[i];
                const context = context_labels[i];
                // In case of above and below blank strings are not trimmed in order to
                // keep the same visual format across all ticks.
                const full_label = (() => {
                    switch (loc) {
                        case "above": return `${context}\n${label}`;
                        case "below": return `${label}\n${context}`;
                        case "left": return context == "" ? label : `${context} ${label}`;
                        case "right": return context == "" ? label : `${label} ${context}`;
                    }
                })();
                full_labels.push(full_label);
            }
            return full_labels;
        }
        _hide_repeating_labels(labels) {
            // For repeating labels only utilize the first entry
            if (labels.length <= 1) {
                return labels;
            }
            const labels_h = [labels[0]];
            let index_first_entry = 0;
            for (let i = 1; i < labels.length; i++) {
                if (labels[index_first_entry] == labels[i]) {
                    labels_h.push("");
                }
                else {
                    labels_h.push(labels[i]);
                    index_first_entry = i;
                }
            }
            return labels_h;
        }
    }
    exports.TimedeltaTickFormatter = TimedeltaTickFormatter;
},
/* models/scales/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var categorical_scale_1 = require(116) /* ./categorical_scale */;
    __esExport("CategoricalScale", categorical_scale_1.CategoricalScale);
    var composite_scale_1 = require(117) /* ./composite_scale */;
    __esExport("CompositeScale", composite_scale_1.CompositeScale);
    var continuous_scale_1 = require(114) /* ./continuous_scale */;
    __esExport("ContinuousScale", continuous_scale_1.ContinuousScale);
    var linear_interpolation_scale_1 = require(340) /* ./linear_interpolation_scale */;
    __esExport("LinearInterpolationScale", linear_interpolation_scale_1.LinearInterpolationScale);
    var linear_scale_1 = require(113) /* ./linear_scale */;
    __esExport("LinearScale", linear_scale_1.LinearScale);
    var log_scale_1 = require(115) /* ./log_scale */;
    __esExport("LogScale", log_scale_1.LogScale);
    var scale_1 = require(108) /* ./scale */;
    __esExport("Scale", scale_1.Scale);
},
/* models/scales/linear_interpolation_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const scale_1 = require(108) /* ./scale */;
    const linear_scale_1 = require(113) /* ./linear_scale */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    class LinearInterpolationScale extends scale_1.Scale {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.internal(({ Float, Arrayable, Ref }) => ({
                binning: [Arrayable(Float)],
                linear_scale: [Ref(linear_scale_1.LinearScale)], // TODO computed property of source_range and target_range
            }));
        }
        initialize() {
            super.initialize();
            const { source_range, target_range } = this.properties;
            if (!source_range.is_unset && !target_range.is_unset) {
                this.linear_scale = new linear_scale_1.LinearScale({
                    source_range: source_range.get_value(),
                    target_range: target_range.get_value(),
                });
            }
        }
        connect_signals() {
            super.connect_signals();
            const { source_range, target_range } = this.properties;
            this.on_change([source_range, target_range], () => {
                this.linear_scale = new linear_scale_1.LinearScale({
                    source_range: this.source_range,
                    target_range: this.target_range,
                });
            });
        }
        get s_compute() {
            throw new Error("not implemented");
        }
        get s_invert() {
            throw new Error("not implemented");
        }
        compute(x) {
            return x;
        }
        v_compute(vs) {
            const { binning } = this;
            const { start, end } = this.source_range;
            const min_val = start;
            const max_val = end;
            const n = binning.length;
            const step = (end - start) / (n - 1);
            const mapping = new Float64Array(n);
            for (let i = 0; i < n; i++) {
                mapping[i] = start + i * step;
            }
            const vvs = (0, arrayable_1.map)(vs, (v) => {
                if (v < min_val) {
                    return min_val;
                }
                if (v > max_val) {
                    return max_val;
                }
                const k = (0, arrayable_1.left_edge_index)(v, binning);
                if (k == -1) {
                    return min_val;
                }
                if (k >= n - 1) {
                    return max_val;
                }
                const b0 = binning[k];
                const b1 = binning[k + 1];
                const c = (v - b0) / (b1 - b0);
                const m0 = mapping[k];
                const m1 = mapping[k + 1];
                return m0 + c * (m1 - m0);
            });
            return this.linear_scale.v_compute(vvs);
        }
        invert(xprime) {
            return xprime;
        }
        v_invert(xprimes) {
            return new Float64Array(xprimes);
        }
    }
    exports.LinearInterpolationScale = LinearInterpolationScale;
},
/* models/ranges/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var data_range_1 = require(119) /* ./data_range */;
    __esExport("DataRange", data_range_1.DataRange);
    var data_range1d_1 = require(118) /* ./data_range1d */;
    __esExport("DataRange1d", data_range1d_1.DataRange1d);
    var factor_range_1 = require(121) /* ./factor_range */;
    __esExport("FactorRange", factor_range_1.FactorRange);
    var range_1 = require(110) /* ./range */;
    __esExport("Range", range_1.Range);
    var range1d_1 = require(111) /* ./range1d */;
    __esExport("Range1d", range1d_1.Range1d);
},
/* core/layout/border.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(136) /* ./types */;
    const layoutable_1 = require(137) /* ./layoutable */;
    const bbox_1 = require(62) /* ../util/bbox */;
    class BorderLayout extends layoutable_1.Layoutable {
        *[Symbol.iterator]() {
            yield this.top_panel;
            yield this.bottom_panel;
            yield this.left_panel;
            yield this.right_panel;
            yield this.center_panel;
        }
        top_panel;
        bottom_panel;
        left_panel;
        right_panel;
        center_panel;
        inner_top_panel;
        inner_bottom_panel;
        inner_left_panel;
        inner_right_panel;
        aligns = { left: true, right: true, top: true, bottom: true };
        min_border = { left: 0, top: 0, right: 0, bottom: 0 };
        padding = { left: 0, top: 0, right: 0, bottom: 0 };
        center_border_width = 0;
        _measure(viewport) {
            viewport = new types_1.Sizeable({
                width: this.sizing.width_policy == "fixed" || viewport.width == Infinity ? this.sizing.width : viewport.width,
                height: this.sizing.height_policy == "fixed" || viewport.height == Infinity ? this.sizing.height : viewport.height,
            });
            const left_hint = this.left_panel.measure({ width: 0, height: viewport.height });
            const left = Math.max(left_hint.width, this.min_border.left) + this.padding.left;
            const right_hint = this.right_panel.measure({ width: 0, height: viewport.height });
            const right = Math.max(right_hint.width, this.min_border.right) + this.padding.right;
            const top_hint = this.top_panel.measure({ width: viewport.width, height: 0 });
            const top = Math.max(top_hint.height, this.min_border.top) + this.padding.top;
            const bottom_hint = this.bottom_panel.measure({ width: viewport.width, height: 0 });
            const bottom = Math.max(bottom_hint.height, this.min_border.bottom) + this.padding.bottom;
            const center_viewport = new types_1.Sizeable(viewport).shrink_by({ left, right, top, bottom });
            const center = this.center_panel.measure(center_viewport);
            const width = left + center.width + right;
            const height = top + center.height + bottom;
            const align = (() => {
                const { width_policy, height_policy } = this.center_panel.sizing;
                return {
                    ...this.aligns,
                    fixed_width: width_policy == "fixed",
                    fixed_height: height_policy == "fixed",
                };
            })();
            return { width, height, inner: { left, right, top, bottom }, align };
        }
        _set_geometry(outer, inner) {
            super._set_geometry(outer, inner);
            if (this.sizing.visible) {
                this.center_panel.set_geometry(inner);
                const left_hint = this.left_panel.measure({ width: 0, height: outer.height });
                const right_hint = this.right_panel.measure({ width: 0, height: outer.height });
                const top_hint = this.top_panel.measure({ width: outer.width, height: 0 });
                const bottom_hint = this.bottom_panel.measure({ width: outer.width, height: 0 });
                const { left, top, right, bottom } = inner;
                this.top_panel.set_geometry(new bbox_1.BBox({ left, right, bottom: top, height: top_hint.height }));
                this.bottom_panel.set_geometry(new bbox_1.BBox({ left, right, top: bottom, height: bottom_hint.height }));
                this.left_panel.set_geometry(new bbox_1.BBox({ top, bottom, right: left, width: left_hint.width }));
                this.right_panel.set_geometry(new bbox_1.BBox({ top, bottom, left: right, width: right_hint.width }));
                const adjusted_inner = inner.shrink_by(this.center_border_width);
                if (this.inner_top_panel != null) {
                    const { left, right, top, width } = adjusted_inner;
                    const inner_top_hint = this.inner_top_panel.measure({ width, height: 0 });
                    this.inner_top_panel.set_geometry(new bbox_1.BBox({ left, right, top, height: inner_top_hint.height }));
                }
                if (this.inner_bottom_panel != null) {
                    const { left, right, bottom, width } = adjusted_inner;
                    const inner_bottom_hint = this.inner_bottom_panel.measure({ width, height: 0 });
                    this.inner_bottom_panel.set_geometry(new bbox_1.BBox({ left, right, bottom, height: inner_bottom_hint.height }));
                }
                if (this.inner_left_panel != null) {
                    const { top, bottom, left, height } = adjusted_inner;
                    const inner_left_hint = this.inner_left_panel.measure({ width: 0, height });
                    this.inner_left_panel.set_geometry(new bbox_1.BBox({ top, bottom, left, width: inner_left_hint.width }));
                }
                if (this.inner_right_panel != null) {
                    const { top, bottom, right, height } = adjusted_inner;
                    const inner_right_hint = this.inner_right_panel.measure({ width: 0, height });
                    this.inner_right_panel.set_geometry(new bbox_1.BBox({ top, bottom, right, width: inner_right_hint.width }));
                }
            }
            else {
                this.center_panel.set_geometry(new bbox_1.BBox());
                this.top_panel.set_geometry(new bbox_1.BBox());
                this.bottom_panel.set_geometry(new bbox_1.BBox());
                this.left_panel.set_geometry(new bbox_1.BBox());
                this.right_panel.set_geometry(new bbox_1.BBox());
                this.inner_top_panel?.set_geometry(new bbox_1.BBox());
                this.inner_bottom_panel?.set_geometry(new bbox_1.BBox());
                this.inner_left_panel?.set_geometry(new bbox_1.BBox());
                this.inner_right_panel?.set_geometry(new bbox_1.BBox());
            }
        }
    }
    exports.BorderLayout = BorderLayout;
},
/* models/annotations/band.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const upper_lower_1 = require(344) /* ./upper_lower */;
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    class BandView extends upper_lower_1.UpperLowerView {
        _paint_data(ctx) {
            // Draw the band body
            ctx.beginPath();
            ctx.moveTo(this._lower_sx[0], this._lower_sy[0]);
            for (let i = 0, end = this._lower_sx.length; i < end; i++) {
                ctx.lineTo(this._lower_sx[i], this._lower_sy[i]);
            }
            // iterate backwards so that the upper end is below the lower start
            for (let i = this._upper_sx.length - 1; i >= 0; i--) {
                ctx.lineTo(this._upper_sx[i], this._upper_sy[i]);
            }
            ctx.closePath();
            this.visuals.fill.apply(ctx);
            this.visuals.hatch.apply(ctx);
            // Draw the lower band edge
            ctx.beginPath();
            ctx.moveTo(this._lower_sx[0], this._lower_sy[0]);
            for (let i = 0, end = this._lower_sx.length; i < end; i++) {
                ctx.lineTo(this._lower_sx[i], this._lower_sy[i]);
            }
            this.visuals.line.apply(ctx);
            // Draw the upper band edge
            ctx.beginPath();
            ctx.moveTo(this._upper_sx[0], this._upper_sy[0]);
            for (let i = 0, end = this._upper_sx.length; i < end; i++) {
                ctx.lineTo(this._upper_sx[i], this._upper_sy[i]);
            }
            this.visuals.line.apply(ctx);
        }
    }
    exports.BandView = BandView;
    class Band extends upper_lower_1.UpperLower {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = BandView;
            this.mixins([mixins.Line, mixins.Fill, mixins.Hatch]);
            this.override({
                fill_color: "#fff9ba",
                fill_alpha: 0.4,
                line_color: "#cccccc",
                line_alpha: 0.3,
            });
        }
    }
    exports.Band = Band;
},
/* models/annotations/upper_lower.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const data_annotation_1 = require(141) /* ./data_annotation */;
    const types_1 = require(25) /* ../../core/types */;
    const enums_1 = require(21) /* ../../core/enums */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    class UpperLowerView extends data_annotation_1.DataAnnotationView {
        _lower;
        _upper;
        _base;
        _lower_sx;
        _lower_sy;
        _upper_sx;
        _upper_sy;
        map_data() {
            const { frame } = this.plot_view;
            const dim = this.model.dimension;
            const xscale = this.coordinates.x_scale;
            const yscale = this.coordinates.y_scale;
            const limit_scale = dim == "height" ? yscale : xscale;
            const base_scale = dim == "height" ? xscale : yscale;
            const limit_view = dim == "height" ? frame.bbox.yview : frame.bbox.xview;
            const base_view = dim == "height" ? frame.bbox.xview : frame.bbox.yview;
            const _lower_sx = (() => {
                switch (this.model.properties.lower.units) {
                    case "canvas":
                        return new types_1.ScreenArray(this._lower);
                    case "screen":
                        return limit_view.v_compute(this._lower);
                    case "data":
                        return limit_scale.v_compute(this._lower);
                }
            })();
            const _upper_sx = (() => {
                switch (this.model.properties.upper.units) {
                    case "canvas":
                        return new types_1.ScreenArray(this._upper);
                    case "screen":
                        return limit_view.v_compute(this._upper);
                    case "data":
                        return limit_scale.v_compute(this._upper);
                }
            })();
            const _base_sx = (() => {
                switch (this.model.properties.base.units) {
                    case "canvas":
                        return new types_1.ScreenArray(this._base);
                    case "screen":
                        return base_view.v_compute(this._base);
                    case "data":
                        return base_scale.v_compute(this._base);
                }
            })();
            const [i, j] = dim == "height" ? [1, 0] : [0, 1];
            const _lower = [_lower_sx, _base_sx];
            const _upper = [_upper_sx, _base_sx];
            this._lower_sx = _lower[i];
            this._lower_sy = _lower[j];
            this._upper_sx = _upper[i];
            this._upper_sy = _upper[j];
        }
    }
    exports.UpperLowerView = UpperLowerView;
    class XOrYCoordinateSpec extends p.CoordinateSpec {
        _value = p.unset;
        get dimension() {
            return this.obj.dimension == "width" ? "x" : "y";
        }
        // XXX: a hack to make a coordinate & unit spec
        get units() {
            return this._value === p.unset ? "data" : this._value.units ?? "data";
        }
    }
    exports.XOrYCoordinateSpec = XOrYCoordinateSpec;
    class UpperLower extends data_annotation_1.DataAnnotation {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(() => ({
                dimension: [enums_1.Dimension, "height"],
                lower: [XOrYCoordinateSpec, { field: "lower" }],
                upper: [XOrYCoordinateSpec, { field: "upper" }],
                base: [XOrYCoordinateSpec, { field: "base" }],
            }));
        }
    }
    exports.UpperLower = UpperLower;
},
/* models/annotations/box_annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(96) /* ./annotation */;
    const model_1 = require(52) /* ../../model */;
    const area_visuals_1 = require(94) /* ./area_visuals */;
    const data_range1d_1 = require(118) /* ../ranges/data_range1d */;
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    const enums_1 = require(21) /* ../../core/enums */;
    const array_1 = require(10) /* ../../core/util/array */;
    const bbox_1 = require(62) /* ../../core/util/bbox */;
    const signaling_1 = require(17) /* ../../core/signaling */;
    const types_1 = require(8) /* ../../core/util/types */;
    const math_1 = require(12) /* ../../core/util/math */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    const object_1 = require(9) /* ../../core/util/object */;
    const kinds_1 = require(124) /* ../common/kinds */;
    const Box = tslib_1.__importStar(require(346) /* ../common/box_kinds */);
    const painting_1 = require(267) /* ../common/painting */;
    const resolve = tslib_1.__importStar(require(127) /* ../common/resolve */);
    const node_1 = require(57) /* ../coordinates/node */;
    const coordinate_1 = require(58) /* ../coordinates/coordinate */;
    const factor_range_1 = require(121) /* ../ranges/factor_range */;
    const kinds_2 = require(22) /* ../../core/kinds */;
    const CoordinateLike = (0, kinds_2.Or)(kinds_2.Float, factor_range_1.FactorLike, (0, kinds_2.Ref)(coordinate_1.Coordinate));
    exports.EDGE_TOLERANCE = 2.5;
    const { abs } = Math;
    class BoxInteractionHandles extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Ref, Nullable }) => ({
                all: [Ref(area_visuals_1.AreaVisuals)],
                move: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
                resize: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
                sides: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
                corners: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
                left: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
                right: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
                top: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
                bottom: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
                top_left: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
                top_right: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
                bottom_left: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
                bottom_right: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
            }));
        }
    }
    exports.BoxInteractionHandles = BoxInteractionHandles;
    const DEFAULT_HANDLES = () => {
        return new BoxInteractionHandles({
            all: new area_visuals_1.AreaVisuals({
                fill_color: "white",
                fill_alpha: 1.0,
                line_color: "black",
                line_alpha: 1.0,
                hover_fill_color: "lightgray",
                hover_fill_alpha: 1.0,
            }),
        });
    };
    class BoxAnnotationView extends annotation_1.AnnotationView {
        _bbox = new bbox_1.BBox();
        get bbox() {
            return this._bbox;
        }
        _handles;
        _handles_views = {};
        initialize() {
            super.initialize();
            this._update_handles();
        }
        _update_handles() {
            const { editable, use_handles, handles } = this.model;
            if (editable && use_handles) {
                const { movable, resizable } = this;
                const common = {
                    visible: true,
                    resizable: "none",
                    left_units: "canvas",
                    right_units: "canvas",
                    top_units: "canvas",
                    bottom_units: "canvas",
                    level: this.model.level,
                    is_handle: true,
                };
                function attrs_of(source) {
                    return {
                        ...mixins.attrs_of(source, "", mixins.Line, true),
                        ...mixins.attrs_of(source, "", mixins.Fill, true),
                        ...mixins.attrs_of(source, "", mixins.Hatch, true),
                        ...mixins.attrs_of(source, "hover_", mixins.Line, true),
                        ...mixins.attrs_of(source, "hover_", mixins.Fill, true),
                        ...mixins.attrs_of(source, "hover_", mixins.Hatch, true),
                    };
                }
                const h = handles;
                const attrs = {
                    area: attrs_of(h.move ?? h.all),
                    left: attrs_of(h.left ?? h.sides ?? h.resize ?? h.all),
                    right: attrs_of(h.right ?? h.sides ?? h.resize ?? h.all),
                    top: attrs_of(h.top ?? h.sides ?? h.resize ?? h.all),
                    bottom: attrs_of(h.bottom ?? h.sides ?? h.resize ?? h.all),
                    top_left: attrs_of(h.top_left ?? h.corners ?? h.resize ?? h.all),
                    top_right: attrs_of(h.top_right ?? h.corners ?? h.resize ?? h.all),
                    bottom_left: attrs_of(h.bottom_left ?? h.corners ?? h.resize ?? h.all),
                    bottom_right: attrs_of(h.bottom_right ?? h.corners ?? h.resize ?? h.all),
                };
                const { tl_cursor, tr_cursor, bl_cursor, br_cursor, ew_cursor, ns_cursor, } = this.model;
                this._handles = {
                    area: movable ? new BoxAnnotation({ ...common, ...attrs.area, in_cursor: "move", movable: this.model.movable }) : null,
                    left: resizable.left ? new BoxAnnotation({ ...common, ...attrs.left, in_cursor: ew_cursor }) : null,
                    right: resizable.right ? new BoxAnnotation({ ...common, ...attrs.right, in_cursor: ew_cursor }) : null,
                    top: resizable.top ? new BoxAnnotation({ ...common, ...attrs.top, in_cursor: ns_cursor }) : null,
                    bottom: resizable.bottom ? new BoxAnnotation({ ...common, ...attrs.bottom, in_cursor: ns_cursor }) : null,
                    top_left: resizable.top_left ? new BoxAnnotation({ ...common, ...attrs.top_left, in_cursor: tl_cursor }) : null,
                    top_right: resizable.top_right ? new BoxAnnotation({ ...common, ...attrs.top_right, in_cursor: tr_cursor }) : null,
                    bottom_left: resizable.bottom_left ? new BoxAnnotation({ ...common, ...attrs.bottom_left, in_cursor: bl_cursor }) : null,
                    bottom_right: resizable.bottom_right ? new BoxAnnotation({ ...common, ...attrs.bottom_right, in_cursor: br_cursor }) : null,
                };
            }
            else {
                this._handles = {
                    area: null,
                    left: null,
                    right: null,
                    top: null,
                    bottom: null,
                    top_left: null,
                    top_right: null,
                    bottom_left: null,
                    bottom_right: null,
                };
            }
        }
        get computed_renderers() {
            return [...super.computed_renderers, ...(0, object_1.values)(this._handles).filter((handle) => handle != null)];
        }
        connect_signals() {
            super.connect_signals();
            const { editable, use_handles, handles, resizable, movable } = this.model.properties;
            this.on_change([editable, use_handles, handles, resizable, movable], async () => {
                this._update_handles();
                await this._update_renderers();
            });
            this.connect(this.model.change, () => this.request_paint());
        }
        async _build_renderers() {
            const build_result = await super._build_renderers();
            const get = (handle) => {
                return handle != null ? this._renderer_views.get(handle) : undefined;
            };
            this._handles_views = {
                area: get(this._handles.area),
                left: get(this._handles.left),
                right: get(this._handles.right),
                top: get(this._handles.top),
                bottom: get(this._handles.bottom),
                top_left: get(this._handles.top_left),
                top_right: get(this._handles.top_right),
                bottom_left: get(this._handles.bottom_left),
                bottom_right: get(this._handles.bottom_right),
            };
            return build_result;
        }
        _synthetic_lrtb() {
            const { left, left_units, right, right_units, top, top_units, bottom, bottom_units, } = this.model;
            const { x_source, y_source } = this.coordinates;
            const x_factor = x_source instanceof factor_range_1.FactorRange;
            const y_factor = y_source instanceof factor_range_1.FactorRange;
            return {
                left: (() => {
                    if (left_units == "data" && !(left instanceof coordinate_1.Coordinate)) {
                        if (x_factor) {
                            return x_source.synthetic(left);
                        }
                        else if ((0, types_1.isNumber)(left)) {
                            return left;
                        }
                    }
                    return NaN;
                })(),
                right: (() => {
                    if (right_units == "data" && !(right instanceof coordinate_1.Coordinate)) {
                        if (x_factor) {
                            return x_source.synthetic(right);
                        }
                        else if ((0, types_1.isNumber)(right)) {
                            return right;
                        }
                    }
                    return NaN;
                })(),
                top: (() => {
                    if (top_units == "data" && !(top instanceof coordinate_1.Coordinate)) {
                        if (y_factor) {
                            return y_source.synthetic(top);
                        }
                        else if ((0, types_1.isNumber)(top)) {
                            return top;
                        }
                    }
                    return NaN;
                })(),
                bottom: (() => {
                    if (bottom_units == "data" && !(bottom instanceof coordinate_1.Coordinate)) {
                        if (y_factor) {
                            return y_source.synthetic(bottom);
                        }
                        else if ((0, types_1.isNumber)(bottom)) {
                            return bottom;
                        }
                    }
                    return NaN;
                })(),
            };
        }
        [data_range1d_1.auto_ranged] = true;
        bounds() {
            const { left, right, top, bottom } = this._synthetic_lrtb();
            const left_ok = isFinite(left);
            const right_ok = isFinite(right);
            const top_ok = isFinite(top);
            const bottom_ok = isFinite(bottom);
            const [x0, x1] = (() => {
                if (left_ok && right_ok) {
                    return left <= right ? [left, right] : [right, left];
                }
                else if (left_ok) {
                    return [left, left];
                }
                else if (right_ok) {
                    return [right, right];
                }
                else {
                    return [NaN, NaN];
                }
            })();
            const [y0, y1] = (() => {
                if (top_ok && bottom_ok) {
                    return top <= bottom ? [top, bottom] : [bottom, top];
                }
                else if (top_ok) {
                    return [top, top];
                }
                else if (bottom_ok) {
                    return [bottom, bottom];
                }
                else {
                    return [NaN, NaN];
                }
            })();
            return { x0, x1, y0, y1 };
        }
        log_bounds() {
            return (0, bbox_1.empty)();
        }
        get mappers() {
            function mapper(units, scale, view, canvas) {
                switch (units) {
                    case "canvas": return canvas;
                    case "screen": return view;
                    case "data": return scale;
                }
            }
            const overlay = this.model;
            const { x_scale, y_scale } = this.coordinates;
            const { x_view, y_view } = this.plot_view.frame.bbox;
            const { x_screen, y_screen } = this.plot_view.canvas.bbox;
            const lrtb = {
                left: mapper(overlay.left_units, x_scale, x_view, x_screen),
                right: mapper(overlay.right_units, x_scale, x_view, x_screen),
                top: mapper(overlay.top_units, y_scale, y_view, y_screen),
                bottom: mapper(overlay.bottom_units, y_scale, y_view, y_screen),
            };
            return lrtb;
        }
        get border_radius() {
            return resolve.border_radius(this.model.border_radius);
        }
        compute_geometry() {
            super.compute_geometry();
            const bbox = (() => {
                const compute = (dim, value, mapper) => {
                    return value instanceof coordinate_1.Coordinate ? this.resolve_as_scalar(value, dim) : mapper.compute(value);
                };
                const { left, right, top, bottom } = this.model;
                const { mappers } = this;
                return bbox_1.BBox.from_lrtb({
                    left: compute("x", left, mappers.left),
                    right: compute("x", right, mappers.right),
                    top: compute("y", top, mappers.top),
                    bottom: compute("y", bottom, mappers.bottom),
                });
            })();
            this._bbox = bbox;
            const width = 10;
            const height = 10;
            function update(renderer, bbox) {
                const { left, right, top, bottom } = bbox;
                renderer?.setv({ left, right, top, bottom }, { silent: true });
            }
            update(this._handles.area, new bbox_1.BBox({ ...bbox.center, width, height, origin: "center" }));
            update(this._handles.left, new bbox_1.BBox({ ...bbox.center_left, width, height, origin: "center" }));
            update(this._handles.right, new bbox_1.BBox({ ...bbox.center_right, width, height, origin: "center" }));
            update(this._handles.top, new bbox_1.BBox({ ...bbox.top_center, width, height, origin: "center" }));
            update(this._handles.bottom, new bbox_1.BBox({ ...bbox.bottom_center, width, height, origin: "center" }));
            update(this._handles.top_left, new bbox_1.BBox({ ...bbox.top_left, width, height, origin: "center" }));
            update(this._handles.top_right, new bbox_1.BBox({ ...bbox.top_right, width, height, origin: "center" }));
            update(this._handles.bottom_left, new bbox_1.BBox({ ...bbox.bottom_left, width, height, origin: "center" }));
            update(this._handles.bottom_right, new bbox_1.BBox({ ...bbox.bottom_right, width, height, origin: "center" }));
        }
        _paint(ctx) {
            if (!this.bbox.is_valid) {
                return;
            }
            const { _is_hovered, visuals } = this;
            const fill = _is_hovered && visuals.hover_fill.doit ? visuals.hover_fill : visuals.fill;
            const hatch = _is_hovered && visuals.hover_hatch.doit ? visuals.hover_hatch : visuals.hatch;
            const line = _is_hovered && visuals.hover_line.doit ? visuals.hover_line : visuals.line;
            ctx.save();
            if (!this.model.inverted) {
                ctx.beginPath();
                (0, painting_1.round_rect)(ctx, this.bbox, this.border_radius);
                fill.apply(ctx);
                hatch.apply(ctx);
                line.apply(ctx);
            }
            else {
                ctx.beginPath();
                const parent = this.layout ?? this.plot_view.frame;
                const { x, y, width, height } = parent.bbox;
                ctx.rect(x, y, width, height);
                (0, painting_1.round_rect)(ctx, this.bbox, this.border_radius);
                fill.apply(ctx, "evenodd");
                hatch.apply(ctx, "evenodd");
                ctx.beginPath();
                (0, painting_1.round_rect)(ctx, this.bbox, this.border_radius);
                line.apply(ctx);
            }
            ctx.restore();
        }
        interactive_bbox() {
            const tolerance = this.model.line_width + exports.EDGE_TOLERANCE;
            return this.bbox.grow_by(tolerance);
        }
        interactive_hit(sx, sy) {
            if (!this.model.visible) {
                return false;
            }
            const bbox = this.interactive_bbox();
            return bbox.contains(sx, sy);
        }
        _hit_test(sx, sy) {
            const { left, right, bottom, top } = this.bbox;
            const tolerance = Math.max(exports.EDGE_TOLERANCE, this.model.line_width / 2);
            const dl = abs(left - sx);
            const dr = abs(right - sx);
            const dt = abs(top - sy);
            const db = abs(bottom - sy);
            const hits = {
                left: dl < tolerance && dl < dr,
                right: dr < tolerance && dr < dl,
                top: dt < tolerance && dt < db,
                bottom: db < tolerance && db < dt,
            };
            const hittable = this._hittable();
            const hits_handle = (hit_target, condition) => {
                if (!hittable[hit_target]) {
                    return false;
                }
                const handle = this._handles_views[hit_target];
                if (handle != null) {
                    return handle.bbox.contains(sx, sy);
                }
                else {
                    return condition;
                }
            };
            if (hits_handle("top_left", hits.top && hits.left)) {
                return "top_left";
            }
            if (hits_handle("top_right", hits.top && hits.right)) {
                return "top_right";
            }
            if (hits_handle("bottom_left", hits.bottom && hits.left)) {
                return "bottom_left";
            }
            if (hits_handle("bottom_right", hits.bottom && hits.right)) {
                return "bottom_right";
            }
            if (hits_handle("left", hits.left)) {
                return "left";
            }
            if (hits_handle("right", hits.right)) {
                return "right";
            }
            if (hits_handle("top", hits.top)) {
                return "top";
            }
            if (hits_handle("bottom", hits.bottom)) {
                return "bottom";
            }
            if (hits_handle("area", this.bbox.contains(sx, sy))) {
                return "area";
            }
            return null;
        }
        get resizable() {
            const { resizable } = this.model;
            const left = resizable == "left" || resizable == "x" || resizable == "all";
            const right = resizable == "right" || resizable == "x" || resizable == "all";
            const top = resizable == "top" || resizable == "y" || resizable == "all";
            const bottom = resizable == "bottom" || resizable == "y" || resizable == "all";
            return {
                left,
                right,
                top,
                bottom,
                top_left: top && left,
                top_right: top && right,
                bottom_left: bottom && left,
                bottom_right: bottom && right,
            };
        }
        get movable() {
            const movable = this.model.movable != "none";
            return this.model.is_handle ? movable : this.model.editable && movable;
        }
        _hittable() {
            const { left, right, top, bottom } = this.resizable;
            return {
                top_left: top && left,
                top_right: top && right,
                bottom_left: bottom && left,
                bottom_right: bottom && right,
                left,
                right,
                top,
                bottom,
                area: this.movable,
            };
        }
        _can_hit(target) {
            if (!this.model.editable && !this.model.is_handle) {
                return false;
            }
            const { left, right, top, bottom } = this.resizable;
            switch (target) {
                case "top_left": return top && left;
                case "top_right": return top && right;
                case "bottom_left": return bottom && left;
                case "bottom_right": return bottom && right;
                case "left": return left;
                case "right": return right;
                case "top": return top;
                case "bottom": return bottom;
                case "area": return this.movable;
            }
        }
        _pan_state = null;
        on_pan_start(ev) {
            if (this.model.visible && this.model.editable) {
                const { sx, sy } = ev;
                const target = this._hit_test(sx, sy);
                if (target != null && this._can_hit(target)) {
                    this._pan_state = {
                        bbox: this.bbox.clone(),
                        target,
                    };
                    this.model.pan.emit(["pan:start", ev.modifiers]);
                    return true;
                }
            }
            return false;
        }
        on_pan(ev) {
            (0, assert_1.assert)(this._pan_state != null);
            const { mappers } = this;
            const resolve = (dim, limit, mapper) => {
                if (limit instanceof coordinate_1.Coordinate) {
                    return this.resolve_as_scalar(limit, dim);
                }
                else if (limit == null) {
                    return NaN;
                }
                else {
                    return mapper.compute(limit);
                }
            };
            const slimits = bbox_1.BBox.from_lrtb({
                left: resolve("x", this.model.left_limit, mappers.left),
                right: resolve("x", this.model.right_limit, mappers.right),
                top: resolve("y", this.model.top_limit, mappers.top),
                bottom: resolve("y", this.model.bottom_limit, mappers.bottom),
            });
            const [dl, dr, dt, db] = (() => {
                const { dx, dy } = ev;
                const { target } = this._pan_state;
                const { symmetric } = this.model;
                const [Dx, Dy] = symmetric ? [-dx, -dy] : [0, 0];
                switch (target) {
                    // corners
                    case "top_left": return [dx, Dx, dy, Dy];
                    case "top_right": return [Dx, dx, dy, Dy];
                    case "bottom_left": return [dx, Dx, Dy, dy];
                    case "bottom_right": return [Dx, dx, Dy, dy];
                    // edges
                    case "left": return [dx, Dx, 0, 0];
                    case "right": return [Dx, dx, 0, 0];
                    case "top": return [0, 0, dy, Dy];
                    case "bottom": return [0, 0, Dy, dy];
                    // area
                    case "area": {
                        switch (this.model.movable) {
                            case "both": return [dx, dx, dy, dy];
                            case "x": return [dx, dx, 0, 0];
                            case "y": return [0, 0, dy, dy];
                            case "none": return [0, 0, 0, 0];
                        }
                    }
                }
            })();
            const slrtb = (() => {
                const min = (a, b) => (0, array_1.min)([a, b]);
                const sgn = (v) => v < 0 ? -1 : (v > 0 ? 1 : 0);
                const { bbox } = this._pan_state;
                let { left, right, left_sign, right_sign } = (() => {
                    const left = bbox.left + dl;
                    const right = bbox.right + dr;
                    const left_sign = sgn(dl);
                    const right_sign = sgn(dr);
                    if (left <= right) {
                        return { left, right, left_sign, right_sign };
                    }
                    else {
                        return { left: right, right: left, left_sign: right_sign, right_sign: left_sign };
                    }
                })();
                let { top, bottom, top_sign, bottom_sign } = (() => {
                    const top = bbox.top + dt;
                    const bottom = bbox.bottom + db;
                    const top_sign = sgn(dt);
                    const bottom_sign = sgn(db);
                    if (top <= bottom) {
                        return { top, bottom, top_sign, bottom_sign };
                    }
                    else {
                        return { top: bottom, bottom: top, top_sign: bottom_sign, bottom_sign: top_sign };
                    }
                })();
                const Dl = left - slimits.left;
                const Dr = slimits.right - right;
                const Dx = min(Dl < 0 ? Dl : NaN, Dr < 0 ? Dr : NaN);
                if (isFinite(Dx) && Dx < 0) {
                    left += -left_sign * (-Dx);
                    right += -right_sign * (-Dx);
                }
                const Dt = top - slimits.top;
                const Db = slimits.bottom - bottom;
                const Dy = min(Dt < 0 ? Dt : NaN, Db < 0 ? Db : NaN);
                if (isFinite(Dy) && Dy < 0) {
                    top += -top_sign * (-Dy);
                    bottom += -bottom_sign * (-Dy);
                }
                return bbox_1.BBox.from_lrtb({ left, right, top, bottom });
            })();
            const { min_width, min_height, max_width, max_height } = this.model;
            const { left, right, top, bottom } = this.model;
            const lrtb = {
                left: mappers.left.invert(slrtb.left),
                right: mappers.right.invert(slrtb.right),
                top: mappers.top.invert(slrtb.top),
                bottom: mappers.bottom.invert(slrtb.bottom),
            };
            if (0 < min_width || max_width < Infinity) {
                if (dl != 0 && dr == 0) {
                    const min_left = lrtb.right - max_width;
                    const max_left = lrtb.right - min_width;
                    lrtb.left = (0, math_1.clamp)(lrtb.left, min_left, max_left);
                }
                else if (dl == 0 && dr != 0) {
                    const min_right = lrtb.left + min_width;
                    const max_right = lrtb.left + max_width;
                    lrtb.right = (0, math_1.clamp)(lrtb.right, min_right, max_right);
                }
            }
            if (0 < min_height || max_height < Infinity) {
                if (dt != 0 && db == 0) {
                    const min_top = lrtb.bottom + max_height;
                    const max_top = lrtb.bottom + min_height;
                    lrtb.top = (0, math_1.clamp)(lrtb.top, min_top, max_top);
                }
                else if (dt == 0 && db != 0) {
                    const min_bottom = lrtb.top - min_height;
                    const max_bottom = lrtb.top - max_height;
                    lrtb.bottom = (0, math_1.clamp)(lrtb.bottom, min_bottom, max_bottom);
                }
            }
            const computed_lrtb = (() => {
                return {
                    left: left instanceof coordinate_1.Coordinate ? left : lrtb.left,
                    right: right instanceof coordinate_1.Coordinate ? right : lrtb.right,
                    top: top instanceof coordinate_1.Coordinate ? top : lrtb.top,
                    bottom: bottom instanceof coordinate_1.Coordinate ? bottom : lrtb.bottom,
                };
            })();
            this.model.update(computed_lrtb);
            this.model.pan.emit(["pan", ev.modifiers]);
        }
        on_pan_end(ev) {
            this._pan_state = null;
            this.model.pan.emit(["pan:end", ev.modifiers]);
        }
        _pinch_state = null;
        on_pinch_start(ev) {
            if (this.model.visible && this.model.editable && this.model.resizable != "none") {
                const { sx, sy } = ev;
                if (this.bbox.contains(sx, sy)) {
                    this._pinch_state = {
                        bbox: this.bbox.clone(),
                    };
                    this.model.pan.emit(["pan:start", ev.modifiers]); // TODO: pinch signal
                    return true;
                }
            }
            return false;
        }
        on_pinch(ev) {
            (0, assert_1.assert)(this._pinch_state != null);
            const slrtb = (() => {
                const { scale } = ev;
                const { bbox } = this._pinch_state;
                const { left, top, right, bottom, width, height } = bbox;
                const dw = width * (scale - 1);
                const dh = height * (scale - 1);
                const { resizable } = this;
                const dl = resizable.left ? -dw / 2 : 0;
                const dr = resizable.right ? dw / 2 : 0;
                const dt = resizable.top ? -dh / 2 : 0;
                const db = resizable.bottom ? dh / 2 : 0;
                return bbox_1.BBox.from_lrtb({
                    left: left + dl,
                    right: right + dr,
                    top: top + dt,
                    bottom: bottom + db,
                });
            })();
            const lrtb = (() => {
                const { left, right, top, bottom } = this.model;
                const { mappers } = this;
                return {
                    left: left instanceof coordinate_1.Coordinate ? left : mappers.left.invert(slrtb.left),
                    right: right instanceof coordinate_1.Coordinate ? right : mappers.right.invert(slrtb.right),
                    top: top instanceof coordinate_1.Coordinate ? top : mappers.top.invert(slrtb.top),
                    bottom: bottom instanceof coordinate_1.Coordinate ? bottom : mappers.bottom.invert(slrtb.bottom),
                };
            })();
            this.model.update(lrtb);
            this.model.pan.emit(["pan", ev.modifiers]);
        }
        on_pinch_end(ev) {
            this._pinch_state = null;
            this.model.pan.emit(["pan:end", ev.modifiers]);
        }
        get _has_hover() {
            const { hover_line, hover_fill, hover_hatch } = this.visuals;
            return hover_line.doit || hover_fill.doit || hover_hatch.doit;
        }
        _is_hovered = false;
        on_enter(_ev) {
            const { _has_hover } = this;
            if (_has_hover) {
                this._is_hovered = true;
                this.request_paint();
            }
            return _has_hover;
        }
        on_move(_ev) { }
        on_leave(_ev) {
            if (this._has_hover) {
                this._is_hovered = false;
                this.request_paint();
            }
        }
        cursor(sx, sy) {
            const target = this._pan_state?.target ?? this._hit_test(sx, sy);
            if (target == null || !this._can_hit(target)) {
                return null;
            }
            const { tl_cursor, tr_cursor, bl_cursor, br_cursor, ew_cursor, ns_cursor, in_cursor, } = this.model;
            switch (target) {
                case "top_left": return this._handles.top_left == null ? tl_cursor : this._handles.top_left.tl_cursor;
                case "top_right": return this._handles.top_right == null ? tr_cursor : this._handles.top_right.tr_cursor;
                case "bottom_left": return this._handles.bottom_left == null ? bl_cursor : this._handles.bottom_left.bl_cursor;
                case "bottom_right": return this._handles.bottom_right == null ? br_cursor : this._handles.bottom_right.br_cursor;
                case "left": return this._handles.left == null ? ew_cursor : this._handles.left.ew_cursor;
                case "right": return this._handles.right == null ? ew_cursor : this._handles.right.ew_cursor;
                case "top": return this._handles.top == null ? ns_cursor : this._handles.top.ns_cursor;
                case "bottom": return this._handles.bottom == null ? ns_cursor : this._handles.bottom.ns_cursor;
                case "area": {
                    if (!this.movable) {
                        return null;
                    }
                    else if (this._handles.area == null) {
                        if (this._pan_state != null && in_cursor === "grab") {
                            return "grabbing";
                        }
                        else {
                            return in_cursor;
                        }
                    }
                    else {
                        return this._handles.area.in_cursor;
                    }
                }
            }
        }
    }
    exports.BoxAnnotationView = BoxAnnotationView;
    class BoxAnnotation extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
        clone(attrs) {
            return super.clone(attrs);
        }
        static {
            this.prototype.default_view = BoxAnnotationView;
            this.mixins([
                mixins.Line,
                mixins.Fill,
                mixins.Hatch,
                ["hover_", mixins.Line],
                ["hover_", mixins.Fill],
                ["hover_", mixins.Hatch],
            ]);
            this.define(({ Bool, Float, Ref, NonNegative, Positive }) => ({
                top: [CoordinateLike, () => new node_1.Node({ target: "frame", symbol: "top" })],
                bottom: [CoordinateLike, () => new node_1.Node({ target: "frame", symbol: "bottom" })],
                left: [CoordinateLike, () => new node_1.Node({ target: "frame", symbol: "left" })],
                right: [CoordinateLike, () => new node_1.Node({ target: "frame", symbol: "right" })],
                top_units: [enums_1.CoordinateUnits, "data"],
                bottom_units: [enums_1.CoordinateUnits, "data"],
                left_units: [enums_1.CoordinateUnits, "data"],
                right_units: [enums_1.CoordinateUnits, "data"],
                top_limit: [Box.Limit, null],
                bottom_limit: [Box.Limit, null],
                left_limit: [Box.Limit, null],
                right_limit: [Box.Limit, null],
                min_width: [NonNegative(Float), 0],
                min_height: [NonNegative(Float), 0],
                max_width: [Positive(Float), Infinity],
                max_height: [Positive(Float), Infinity],
                border_radius: [kinds_1.BorderRadius, 0],
                editable: [Bool, false],
                resizable: [Box.Resizable, "all"],
                movable: [Box.Movable, "both"],
                symmetric: [Bool, false],
                use_handles: [Bool, false],
                handles: [Ref(BoxInteractionHandles), DEFAULT_HANDLES],
                inverted: [Bool, false],
            }));
            this.internal(({ Str, Bool }) => ({
                tl_cursor: [Str, "nwse-resize"],
                tr_cursor: [Str, "nesw-resize"],
                bl_cursor: [Str, "nesw-resize"],
                br_cursor: [Str, "nwse-resize"],
                ew_cursor: [Str, "ew-resize"],
                ns_cursor: [Str, "ns-resize"],
                in_cursor: [Str, "grab"],
                // Is this BoxAnnotation functioning as a handle for another BoxAnnotation?
                is_handle: [Bool, false],
            }));
            this.override({
                fill_color: "#fff9ba",
                fill_alpha: 0.4,
                line_color: "#cccccc",
                line_alpha: 0.3,
                hover_fill_color: null,
                hover_fill_alpha: 0.4,
                hover_line_color: null,
                hover_line_alpha: 0.3,
            });
        }
        pan = new signaling_1.Signal(this, "pan");
        update({ left, right, top, bottom }) {
            this.setv({ left, right, top, bottom, visible: true });
        }
        clear() {
            this.visible = false;
        }
        nodes = (() => {
            const known = new Map();
            const node = (symbol) => {
                let node = known.get(symbol);
                if (node === undefined) {
                    known.set(symbol, node = new node_1.Node({ target: this, symbol }));
                }
                return node;
            };
            return {
                get left() { return node("left"); },
                get right() { return node("right"); },
                get top() { return node("top"); },
                get bottom() { return node("bottom"); },
                get top_left() { return node("top_left"); },
                get top_center() { return node("top_center"); },
                get top_right() { return node("top_right"); },
                get center_left() { return node("center_left"); },
                get center() { return node("center"); },
                get center_right() { return node("center_right"); },
                get bottom_left() { return node("bottom_left"); },
                get bottom_center() { return node("bottom_center"); },
                get bottom_right() { return node("bottom_right"); },
                get width() { return node("width"); },
                get height() { return node("height"); },
            };
        })();
    }
    exports.BoxAnnotation = BoxAnnotation;
},
/* models/common/box_kinds.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const kinds_1 = require(22) /* ../../core/kinds */;
    const node_1 = require(57) /* ../coordinates/node */;
    exports.Corner = (0, kinds_1.Enum)("top_left", "top_right", "bottom_left", "bottom_right");
    exports.Edge = (0, kinds_1.Enum)("left", "right", "top", "bottom");
    exports.HitTarget = (0, kinds_1.Enum)(...exports.Corner, ...exports.Edge, "area");
    exports.Resizable = (0, kinds_1.Enum)("none", "left", "right", "top", "bottom", "x", "y", "all");
    exports.Movable = (0, kinds_1.Enum)("none", "x", "y", "both");
    exports.Limit = (0, kinds_1.Nullable)((0, kinds_1.Or)(kinds_1.Float, (0, kinds_1.Ref)(node_1.Node)));
},
/* models/annotations/color_bar.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const base_color_bar_1 = require(254) /* ./base_color_bar */;
    const axes_1 = require(348) /* ../axes */;
    const formatters_1 = require(326) /* ../formatters */;
    const color_mapper_1 = require(300) /* ../mappers/color_mapper */;
    const mappers_1 = require(354) /* ../mappers */;
    const ranges_1 = require(341) /* ../ranges */;
    const scales_1 = require(339) /* ../scales */;
    const tickers_1 = require(283) /* ../tickers */;
    const array_1 = require(10) /* ../../core/util/array */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    class ColorBarView extends base_color_bar_1.BaseColorBarView {
        _image;
        // Indices of displayed colors corresponding to low and high display cutoffs.
        _index_low;
        _index_high;
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.properties.color_mapper.change, async () => {
                this._title_view.remove();
                this._axis_view.remove();
                this.initialize();
                await this.lazy_initialize();
                this.plot_view.invalidate_layout();
            });
            this.connect(this.model.color_mapper.metrics_change, () => this._metrics_changed());
            this.connect(this.model.properties.display_low.change, () => this._metrics_changed());
            this.connect(this.model.properties.display_high.change, () => this._metrics_changed());
        }
        get color_mapper() {
            // Color mapper that is used to render this colorbar.
            let mapper = this.model.color_mapper;
            if (mapper instanceof mappers_1.WeightedStackColorMapper) {
                mapper = mapper.alpha_mapper;
            }
            return mapper;
        }
        update_layout() {
            super.update_layout();
            this._set_canvas_image();
        }
        _create_axis() {
            const { color_mapper } = this;
            if (color_mapper instanceof mappers_1.CategoricalColorMapper) {
                return new axes_1.CategoricalAxis();
            }
            else if (color_mapper instanceof mappers_1.LogColorMapper) {
                return new axes_1.LogAxis();
            }
            else {
                return new axes_1.LinearAxis();
            }
        }
        _create_formatter() {
            const { color_mapper } = this;
            if (this._ticker instanceof tickers_1.LogTicker) {
                return new formatters_1.LogTickFormatter();
            }
            else if (color_mapper instanceof mappers_1.CategoricalColorMapper) {
                return new formatters_1.CategoricalTickFormatter();
            }
            else {
                return new formatters_1.BasicTickFormatter();
            }
        }
        _create_major_range() {
            /*
            Creates and returns a scale instance that maps the `color_mapper` range
            (low to high) to a screen space range equal to the length of the ColorBar's
            scale image. The scale is used to calculate the tick coordinates in screen
            coordinates for plotting purposes.
        
            Note: the type of color_mapper has to match the type of scale (i.e.
            a LinearColorMapper will require a corresponding LinearScale instance).
            */
            const { color_mapper } = this;
            if (color_mapper instanceof mappers_1.CategoricalColorMapper) {
                return new ranges_1.FactorRange({ factors: color_mapper.factors });
            }
            else if (color_mapper instanceof mappers_1.ContinuousColorMapper) {
                const { min, max } = this._continuous_metrics(color_mapper);
                return new ranges_1.Range1d({ start: min, end: max });
            }
            else {
                (0, assert_1.unreachable)();
            }
        }
        _create_major_scale() {
            const { color_mapper } = this;
            if (color_mapper instanceof mappers_1.LinearColorMapper) {
                return new scales_1.LinearScale();
            }
            else if (color_mapper instanceof mappers_1.LogColorMapper) {
                return new scales_1.LogScale();
            }
            else if (color_mapper instanceof mappers_1.ScanningColorMapper) {
                return new scales_1.LinearInterpolationScale({ binning: this._scanning_binning(color_mapper) });
            }
            else if (color_mapper instanceof mappers_1.CategoricalColorMapper) {
                return new scales_1.CategoricalScale();
            }
            else {
                (0, assert_1.unreachable)();
            }
        }
        _create_ticker() {
            const { color_mapper } = this;
            if (color_mapper instanceof mappers_1.LogColorMapper) {
                return new tickers_1.LogTicker();
            }
            else if (color_mapper instanceof mappers_1.ScanningColorMapper) {
                return new tickers_1.BinnedTicker({ mapper: color_mapper });
            }
            else if (color_mapper instanceof mappers_1.CategoricalColorMapper) {
                return new tickers_1.CategoricalTicker();
            }
            else {
                return new tickers_1.BasicTicker();
            }
        }
        // Return min and max metrics of ContinuousColorMapper, modified to account
        // for low and high display cutoffs.
        _continuous_metrics(color_mapper) {
            const { display_low, display_high } = this.model;
            let { min, max } = color_mapper.metrics;
            if (display_high != null && display_low != null && display_high < display_low) {
                // Empty color bar.
                this._index_low = 0;
                this._index_high = -1;
                return { min: NaN, max: NaN };
            }
            this._index_high = null;
            if (display_high != null) {
                const palette_length = color_mapper.palette.length;
                const index_high = color_mapper.value_to_index(display_high, palette_length);
                if (index_high < palette_length - 1) {
                    this._index_high = index_high;
                    max = color_mapper.index_to_value(index_high + 1);
                }
            }
            this._index_low = null;
            if (display_low != null) {
                const index_low = color_mapper.value_to_index(display_low, color_mapper.palette.length);
                if (index_low > 0) {
                    this._index_low = index_low;
                    min = color_mapper.index_to_value(index_low);
                }
            }
            return { min, max };
        }
        _get_major_size_factor() {
            return this.color_mapper.palette.length;
        }
        _metrics_changed() {
            const range = this._major_range;
            const scale = this._major_scale;
            const { color_mapper } = this;
            if (color_mapper instanceof mappers_1.ScanningColorMapper && scale instanceof scales_1.LinearInterpolationScale) {
                const binning = this._scanning_binning(color_mapper);
                scale.binning = binning;
                // Update the frame's LinearInterpolationScale and Range1d as they are
                // different objects to this._major_scale and this._major_range.
                const vertical = this.orientation == "vertical";
                const frame_scale = vertical ? this._frame_view.y_scale : this._frame_view.x_scale;
                if (frame_scale instanceof scales_1.LinearInterpolationScale) {
                    frame_scale.binning = binning;
                    const frame_range = vertical ? this._frame_view.y_range : this._frame_view.x_range;
                    if (frame_range instanceof ranges_1.Range1d) {
                        frame_range.start = binning[0];
                        frame_range.end = binning[binning.length - 1];
                    }
                }
            }
            else if (color_mapper instanceof mappers_1.ContinuousColorMapper && range instanceof ranges_1.Range1d) {
                const { min, max } = this._continuous_metrics(color_mapper);
                range.setv({ start: min, end: max });
            }
            this._set_canvas_image();
            this.plot_view.request_layout(); // this.request_paint()
        }
        _paint_colors(ctx, bbox) {
            const { x, y, width, height } = bbox;
            ctx.save();
            ctx.globalAlpha = this.model.scale_alpha;
            if (this._image != null) {
                ctx.imageSmoothingEnabled = false;
                ctx.drawImage(this._image, x, y, width, height);
            }
            if (this.visuals.bar_line.doit) {
                this.visuals.bar_line.set_value(ctx);
                ctx.strokeRect(x, y, width, height);
            }
            ctx.restore();
        }
        // Return binning array of ScanningColorMapper, modified to account for low
        // and high display cutoffs.
        _scanning_binning(color_mapper) {
            let { binning, force_low_cutoff } = color_mapper.metrics;
            const { display_high } = this.model;
            let { display_low } = this.model;
            if (force_low_cutoff && (display_low == null || color_mapper.metrics.min > display_low)) {
                // ScanningColorMapper overrides display_low, for example when EqHistColorMapper
                // uses rescale_discrete_levels=True.
                display_low = color_mapper.metrics.min;
            }
            if (display_high != null && display_low != null && display_high < display_low) {
                // Empty color bar.
                this._index_low = 0;
                this._index_high = -1;
                return [NaN];
            }
            this._index_high = null;
            if (display_high != null) {
                const index_high = color_mapper.value_to_index(display_high, binning.length);
                if (index_high < binning.length - 1) {
                    this._index_high = index_high;
                }
            }
            this._index_low = null;
            if (display_low != null) {
                const index_low = color_mapper.value_to_index(display_low, binning.length);
                if (index_low > 0) {
                    this._index_low = index_low;
                }
            }
            if (this._index_low != null || this._index_high != null) {
                // Slice binning array.
                const start = this._index_low != null ? this._index_low : 0;
                const end = this._index_high != null ? this._index_high + 1 : binning.length - 1;
                const n = end - start + 1;
                if (n > 0) {
                    const new_binning = new Array(n);
                    for (let i = 0; i < n; i++) {
                        new_binning[i] = binning[i + start];
                    }
                    binning = new_binning;
                }
                else {
                    binning = [NaN];
                }
            }
            return binning;
        }
        _set_canvas_image() {
            const { orientation } = this;
            let { palette } = this.color_mapper;
            if (this._index_high != null || this._index_low != null) {
                palette = palette.slice(this._index_low != null ? this._index_low : 0, this._index_high != null ? this._index_high + 1 : palette.length);
            }
            if (palette.length < 1) {
                // Early exit for empty color bar.
                this._image = null;
                return;
            }
            if (orientation == "vertical") {
                palette = (0, array_1.reversed)(palette);
            }
            const [w, h] = (() => {
                if (orientation == "vertical") {
                    return [1, palette.length];
                }
                else {
                    return [palette.length, 1];
                }
            })();
            const canvas = this._image = document.createElement("canvas");
            canvas.width = w;
            canvas.height = h;
            const image_ctx = canvas.getContext("2d");
            const image_data = image_ctx.getImageData(0, 0, w, h);
            // We always want to draw the entire palette linearly, so we create a new
            // LinearColorMapper instance and map a monotonic range of values with
            // length = palette.length to get each palette color in order.
            const cmap = new mappers_1.LinearColorMapper({ palette }).rgba_mapper;
            const buf8 = cmap.v_compute((0, array_1.range)(0, palette.length));
            image_data.data.set(buf8);
            image_ctx.putImageData(image_data, 0, 0);
        }
    }
    exports.ColorBarView = ColorBarView;
    class ColorBar extends base_color_bar_1.BaseColorBar {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ColorBarView;
            this.define(({ Alpha, Nullable, Float, Ref }) => ({
                color_mapper: [Ref(color_mapper_1.ColorMapper)],
                display_low: [Nullable(Float), null],
                display_high: [Nullable(Float), null],
                scale_alpha: [Alpha, 1.0],
            }));
        }
    }
    exports.ColorBar = ColorBar;
},
/* models/axes/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var axis_1 = require(272) /* ./axis */;
    __esExport("Axis", axis_1.Axis);
    var categorical_axis_1 = require(349) /* ./categorical_axis */;
    __esExport("CategoricalAxis", categorical_axis_1.CategoricalAxis);
    var continuous_axis_1 = require(278) /* ./continuous_axis */;
    __esExport("ContinuousAxis", continuous_axis_1.ContinuousAxis);
    var datetime_axis_1 = require(350) /* ./datetime_axis */;
    __esExport("DatetimeAxis", datetime_axis_1.DatetimeAxis);
    var linear_axis_1 = require(277) /* ./linear_axis */;
    __esExport("LinearAxis", linear_axis_1.LinearAxis);
    var log_axis_1 = require(351) /* ./log_axis */;
    __esExport("LogAxis", log_axis_1.LogAxis);
    var mercator_axis_1 = require(352) /* ./mercator_axis */;
    __esExport("MercatorAxis", mercator_axis_1.MercatorAxis);
    var timedelta_axis_1 = require(353) /* ./timedelta_axis */;
    __esExport("TimedeltaAxis", timedelta_axis_1.TimedeltaAxis);
},
/* models/axes/categorical_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const axis_1 = require(272) /* ./axis */;
    const categorical_ticker_1 = require(284) /* ../tickers/categorical_ticker */;
    const categorical_tick_formatter_1 = require(327) /* ../formatters/categorical_tick_formatter */;
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    const enums_1 = require(21) /* ../../core/enums */;
    const graphics_1 = require(262) /* ../../core/graphics */;
    const types_1 = require(8) /* ../../core/util/types */;
    class CategoricalAxisView extends axis_1.AxisView {
        _hit_value(sx, sy) {
            const [range] = this.ranges;
            const { start, end, span } = range;
            switch (this.dimension) {
                case 0: {
                    const { x0, width } = this.bbox;
                    return range.factor(span * (sx - x0) / width + start);
                }
                case 1: {
                    const { y0, height } = this.bbox;
                    return range.factor(end - span * (sy - y0) / height);
                }
            }
        }
        _paint(ctx) {
            const { tick_coords, extents } = this;
            super._paint(ctx);
            this._draw_group_separators(ctx, extents, tick_coords);
        }
        _draw_group_separators(ctx, _extents, _tick_coords) {
            const [range] = this.ranges;
            const [start, end] = this.computed_bounds;
            const { factors } = range;
            const { tops } = range.mapper;
            if (tops == null || tops.length < 2 || !this.visuals.separator_line.doit) {
                return;
            }
            const dim = this.dimension;
            const alt = 1 - dim;
            const coords = [[], []];
            let ind = 0;
            for (let i = 0; i < tops.length - 1; i++) {
                let first, last;
                for (let j = ind; j < factors.length; j++) {
                    if (factors[j][0] == tops[i + 1]) {
                        [first, last] = [factors[j - 1], factors[j]];
                        ind = j;
                        break;
                    }
                }
                const pt = (range.synthetic(first) + range.synthetic(last)) / 2;
                if (pt > start && pt < end) {
                    coords[dim].push(pt);
                    coords[alt].push(this.loc);
                }
            }
            const tex = this.extents.tick_label;
            this._draw_ticks(ctx, coords, -3, tex - 6, this.visuals.separator_line);
        }
        _draw_major_labels(ctx, extents, _tick_coords) {
            const info = this._get_factor_info();
            let standoff = extents.tick + this.model.major_label_standoff;
            for (let i = 0; i < info.length; i++) {
                const [labels, coords, orient, visuals] = info[i];
                this._draw_oriented_labels(ctx, labels, coords, orient, standoff, visuals);
                standoff += extents.tick_labels[i];
            }
        }
        _tick_label_extents() {
            const info = this._get_factor_info();
            const extents = [];
            for (const [labels, , orient, visuals] of info) {
                const extent = this._oriented_labels_extent(labels, orient, this.model.major_label_standoff, visuals);
                extents.push(extent);
            }
            return extents;
        }
        _get_factor_info() {
            const [range] = this.ranges;
            const [start, end] = this.computed_bounds;
            const loc = this.loc;
            const ticks = this.model.ticker.get_ticks(start, end, range, loc);
            const coords = this.tick_coords;
            const info = [];
            const map = (labels) => {
                return new graphics_1.GraphicsBoxes(labels.map((label) => (0, types_1.isString)(label) ? new graphics_1.TextBox({ text: label }) : label));
            };
            const format = (ticks) => {
                return map(this.model.formatter.doFormat(ticks, this));
            };
            switch (range.mapper.levels) {
                case 1: {
                    const major = ticks.major;
                    const labels = format(major);
                    info.push([labels, coords.major, this.model.major_label_orientation, this.visuals.major_label_text]);
                    break;
                }
                case 2: {
                    const major = ticks.major.map((x) => x[1]);
                    const labels = format(major);
                    info.push([labels, coords.major, this.model.major_label_orientation, this.visuals.major_label_text]);
                    info.push([map(ticks.tops), coords.tops, this.model.group_label_orientation, this.visuals.group_text]);
                    break;
                }
                case 3: {
                    const major = ticks.major.map((x) => x[2]);
                    const labels = format(major);
                    const mid_labels = ticks.mids.map((x) => x[1]);
                    info.push([labels, coords.major, this.model.major_label_orientation, this.visuals.major_label_text]);
                    info.push([map(mid_labels), coords.mids, this.model.subgroup_label_orientation, this.visuals.subgroup_text]);
                    info.push([map(ticks.tops), coords.tops, this.model.group_label_orientation, this.visuals.group_text]);
                    break;
                }
            }
            return info;
        }
        get tick_coords() {
            const i = this.dimension;
            const j = 1 - i;
            const [range] = this.ranges;
            const [start, end] = this.computed_bounds;
            const ticks = this.model.ticker.get_ticks(start, end, range, this.loc);
            const coords = {
                major: [[], []],
                mids: [[], []],
                tops: [[], []],
                minor: [[], []],
            };
            coords.major[i] = ticks.major;
            coords.major[j] = ticks.major.map(() => this.loc);
            const { levels } = range.mapper;
            if (levels == 3) {
                coords.mids[i] = ticks.mids;
                coords.mids[j] = ticks.mids.map(() => this.loc);
            }
            if (levels > 1) {
                coords.tops[i] = ticks.tops;
                coords.tops[j] = ticks.tops.map(() => this.loc);
            }
            return coords;
        }
    }
    exports.CategoricalAxisView = CategoricalAxisView;
    class CategoricalAxis extends axis_1.Axis {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = CategoricalAxisView;
            this.mixins([
                ["separator_", mixins.Line],
                ["group_", mixins.Text],
                ["subgroup_", mixins.Text],
            ]);
            this.define(({ Float, Or }) => ({
                group_label_orientation: [Or(enums_1.LabelOrientation, Float), "parallel"],
                subgroup_label_orientation: [Or(enums_1.LabelOrientation, Float), "parallel"],
            }));
            this.override({
                ticker: () => new categorical_ticker_1.CategoricalTicker(),
                formatter: () => new categorical_tick_formatter_1.CategoricalTickFormatter(),
                separator_line_color: "lightgrey",
                separator_line_width: 2,
                group_text_font_style: "bold",
                group_text_font_size: "11px",
                group_text_color: "grey",
                subgroup_text_font_style: "bold",
                subgroup_text_font_size: "11px",
            });
        }
    }
    exports.CategoricalAxis = CategoricalAxis;
},
/* models/axes/datetime_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_axis_1 = require(278) /* ./continuous_axis */;
    const datetime_tick_formatter_1 = require(328) /* ../formatters/datetime_tick_formatter */;
    const datetime_ticker_1 = require(287) /* ../tickers/datetime_ticker */;
    class DatetimeAxisView extends continuous_axis_1.ContinuousAxisView {
    }
    exports.DatetimeAxisView = DatetimeAxisView;
    class DatetimeAxis extends continuous_axis_1.ContinuousAxis {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = DatetimeAxisView;
            this.override({
                ticker: () => new datetime_ticker_1.DatetimeTicker(),
                formatter: () => new datetime_tick_formatter_1.DatetimeTickFormatter(),
            });
        }
    }
    exports.DatetimeAxis = DatetimeAxis;
},
/* models/axes/log_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_axis_1 = require(278) /* ./continuous_axis */;
    const log_tick_formatter_1 = require(334) /* ../formatters/log_tick_formatter */;
    const log_ticker_1 = require(294) /* ../tickers/log_ticker */;
    class LogAxisView extends continuous_axis_1.ContinuousAxisView {
        _hit_value(sx, sy) {
            const [range] = this.ranges;
            const { start, end } = range;
            const { log10 } = Math;
            switch (this.dimension) {
                case 0: {
                    const { x0, width } = this.bbox;
                    return log10(end / start) * (sx - x0) / width + log10(start);
                }
                case 1: {
                    const { y0, height } = this.bbox;
                    return log10(end) - log10(end / start) * (sy - y0) / height;
                }
            }
        }
    }
    exports.LogAxisView = LogAxisView;
    class LogAxis extends continuous_axis_1.ContinuousAxis {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = LogAxisView;
            this.override({
                ticker: () => new log_ticker_1.LogTicker(),
                formatter: () => new log_tick_formatter_1.LogTickFormatter(),
            });
        }
    }
    exports.LogAxis = LogAxis;
},
/* models/axes/mercator_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const linear_axis_1 = require(277) /* ./linear_axis */;
    const mercator_tick_formatter_1 = require(335) /* ../formatters/mercator_tick_formatter */;
    const mercator_ticker_1 = require(295) /* ../tickers/mercator_ticker */;
    class MercatorAxisView extends linear_axis_1.LinearAxisView {
    }
    exports.MercatorAxisView = MercatorAxisView;
    class MercatorAxis extends linear_axis_1.LinearAxis {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = MercatorAxisView;
            this.override({
                ticker: () => new mercator_ticker_1.MercatorTicker({ dimension: "lat" }),
                formatter: () => new mercator_tick_formatter_1.MercatorTickFormatter({ dimension: "lat" }),
            });
        }
    }
    exports.MercatorAxis = MercatorAxis;
},
/* models/axes/timedelta_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_axis_1 = require(278) /* ./continuous_axis */;
    const timedelta_tick_formatter_1 = require(338) /* ../formatters/timedelta_tick_formatter */;
    const timedelta_ticker_1 = require(296) /* ../tickers/timedelta_ticker */;
    class TimedeltaAxisView extends continuous_axis_1.ContinuousAxisView {
    }
    exports.TimedeltaAxisView = TimedeltaAxisView;
    class TimedeltaAxis extends continuous_axis_1.ContinuousAxis {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = TimedeltaAxisView;
            this.override({
                ticker: () => new timedelta_ticker_1.TimedeltaTicker(),
                formatter: () => new timedelta_tick_formatter_1.TimedeltaTickFormatter(),
            });
        }
    }
    exports.TimedeltaAxis = TimedeltaAxis;
},
/* models/mappers/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var categorical_color_mapper_1 = require(355) /* ./categorical_color_mapper */;
    __esExport("CategoricalColorMapper", categorical_color_mapper_1.CategoricalColorMapper);
    var categorical_marker_mapper_1 = require(357) /* ./categorical_marker_mapper */;
    __esExport("CategoricalMarkerMapper", categorical_marker_mapper_1.CategoricalMarkerMapper);
    var categorical_pattern_mapper_1 = require(358) /* ./categorical_pattern_mapper */;
    __esExport("CategoricalPatternMapper", categorical_pattern_mapper_1.CategoricalPatternMapper);
    var continuous_color_mapper_1 = require(299) /* ./continuous_color_mapper */;
    __esExport("ContinuousColorMapper", continuous_color_mapper_1.ContinuousColorMapper);
    var color_mapper_1 = require(300) /* ./color_mapper */;
    __esExport("ColorMapper", color_mapper_1.ColorMapper);
    var linear_color_mapper_1 = require(359) /* ./linear_color_mapper */;
    __esExport("LinearColorMapper", linear_color_mapper_1.LinearColorMapper);
    var log_color_mapper_1 = require(360) /* ./log_color_mapper */;
    __esExport("LogColorMapper", log_color_mapper_1.LogColorMapper);
    var scanning_color_mapper_1 = require(298) /* ./scanning_color_mapper */;
    __esExport("ScanningColorMapper", scanning_color_mapper_1.ScanningColorMapper);
    var eqhist_color_mapper_1 = require(361) /* ./eqhist_color_mapper */;
    __esExport("EqHistColorMapper", eqhist_color_mapper_1.EqHistColorMapper);
    var stack_color_mapper_1 = require(362) /* ./stack_color_mapper */;
    __esExport("StackColorMapper", stack_color_mapper_1.StackColorMapper);
    var weighted_stack_color_mapper_1 = require(363) /* ./weighted_stack_color_mapper */;
    __esExport("WeightedStackColorMapper", weighted_stack_color_mapper_1.WeightedStackColorMapper);
},
/* models/mappers/categorical_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const categorical_mapper_1 = require(356) /* ./categorical_mapper */;
    const color_mapper_1 = require(300) /* ./color_mapper */;
    const factor_range_1 = require(121) /* ../ranges/factor_range */;
    class CategoricalColorMapper extends color_mapper_1.ColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Float, Nullable }) => ({
                factors: [factor_range_1.FactorSeq],
                start: [Float, 0],
                end: [Nullable(Float), null],
            }));
        }
        _v_compute(data, values, palette, { nan_color }) {
            (0, categorical_mapper_1.cat_v_compute)(data, this.factors, palette, values, this.start, this.end, nan_color);
        }
    }
    exports.CategoricalColorMapper = CategoricalColorMapper;
},
/* models/mappers/categorical_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports._cat_equals = _cat_equals;
    exports.cat_v_compute = cat_v_compute;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const types_1 = require(8) /* ../../core/util/types */;
    function _cat_equals(a, b) {
        if (a.length != b.length) {
            return false;
        }
        const n = a.length;
        for (let i = 0; i < n; i++) {
            if (a[i] !== b[i]) {
                return false;
            }
        }
        return true;
    }
    function cat_v_compute(data, factors, targets, values, start, end, extra_value) {
        let i = 0;
        for (const item of data) {
            let key;
            if (!(0, types_1.isArray)(item)) {
                key = (0, arrayable_1.index_of)(factors, item);
            }
            else {
                const d = item.slice(start, end ?? undefined);
                if (d.length == 1) {
                    key = (0, arrayable_1.index_of)(factors, d[0]);
                }
                else {
                    key = (0, arrayable_1.find_index)(factors, (x) => _cat_equals(x, d));
                }
            }
            const value = key in targets ? targets[key] : extra_value;
            values[i++] = value;
        }
    }
},
/* models/mappers/categorical_marker_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const categorical_mapper_1 = require(356) /* ./categorical_mapper */;
    const factor_range_1 = require(121) /* ../ranges/factor_range */;
    const mapper_1 = require(301) /* ./mapper */;
    const enums_1 = require(21) /* ../../core/enums */;
    class CategoricalMarkerMapper extends mapper_1.Mapper {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Float, List, Nullable }) => ({
                factors: [factor_range_1.FactorSeq],
                markers: [List(enums_1.MarkerType)],
                start: [Float, 0],
                end: [Nullable(Float), null],
                default_value: [enums_1.MarkerType, "circle"],
            }));
        }
        v_compute(xs) {
            const values = new Array(xs.length);
            (0, categorical_mapper_1.cat_v_compute)(xs, this.factors, this.markers, values, this.start, this.end, this.default_value);
            return values;
        }
    }
    exports.CategoricalMarkerMapper = CategoricalMarkerMapper;
},
/* models/mappers/categorical_pattern_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const categorical_mapper_1 = require(356) /* ./categorical_mapper */;
    const factor_range_1 = require(121) /* ../ranges/factor_range */;
    const mapper_1 = require(301) /* ./mapper */;
    const enums_1 = require(21) /* ../../core/enums */;
    class CategoricalPatternMapper extends mapper_1.Mapper {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Float, List, Nullable }) => ({
                factors: [factor_range_1.FactorSeq],
                patterns: [List(enums_1.HatchPatternType)],
                start: [Float, 0],
                end: [Nullable(Float), null],
                default_value: [enums_1.HatchPatternType, " "],
            }));
        }
        v_compute(xs) {
            const values = new Array(xs.length);
            (0, categorical_mapper_1.cat_v_compute)(xs, this.factors, this.patterns, values, this.start, this.end, this.default_value);
            return values;
        }
    }
    exports.CategoricalPatternMapper = CategoricalPatternMapper;
},
/* models/mappers/linear_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_color_mapper_1 = require(299) /* ./continuous_color_mapper */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const math_1 = require(12) /* ../../core/util/math */;
    class LinearColorMapper extends continuous_color_mapper_1.ContinuousColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        scan(data, n) {
            const [low, high] = (() => {
                if (this.low == null && this.high == null) {
                    return (0, arrayable_1.minmax)(data);
                }
                else {
                    return [this.low ?? (0, arrayable_1.min)(data), this.high ?? (0, arrayable_1.max)(data)];
                }
            })();
            const norm_factor = 1 / (high - low);
            const normed_interval = 1 / n;
            return { max: high, min: low, norm_factor, normed_interval };
        }
        index_to_value(index) {
            const scan_data = this._scan_data;
            return scan_data.min + scan_data.normed_interval * index / scan_data.norm_factor;
        }
        value_to_index(value, palette_length) {
            const scan_data = this._scan_data;
            // This handles the edge case where value == high, since the code below maps
            // values exactly equal to high to palette.length when it should be one less.
            if (value == scan_data.max) {
                return palette_length - 1;
            }
            const normed_value = (value - scan_data.min) * scan_data.norm_factor;
            const index = Math.floor(normed_value / scan_data.normed_interval);
            return (0, math_1.clamp)(index, -1, palette_length);
        }
    }
    exports.LinearColorMapper = LinearColorMapper;
},
/* models/mappers/log_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_color_mapper_1 = require(299) /* ./continuous_color_mapper */;
    const logging_1 = require(11) /* ../../core/logging */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const math_1 = require(12) /* ../../core/util/math */;
    class LogColorMapper extends continuous_color_mapper_1.ContinuousColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        scan(data, n) {
            const low = this.low != null ? this.low : (0, arrayable_1.min)(data);
            if (low <= 0) {
                logging_1.logger.warn(`LogColorMapper detects invalid value "${low}" for parameter "low".`);
            }
            const high = this.high != null ? this.high : (0, arrayable_1.max)(data);
            if (high <= 0) {
                logging_1.logger.warn(`LogColorMapper detects invalid value "${high}" for parameter "high".`);
            }
            const scale = n / Math.log(high / low); // subtract the low offset
            const is_reversed = high < low;
            return { max: high, min: low, scale, is_reversed };
        }
        index_to_value(index) {
            const scan_data = this._scan_data;
            return scan_data.min * Math.exp(index / Math.abs(scan_data.scale));
        }
        value_to_index(value, palette_length) {
            const scan_data = this._scan_data;
            // This handles the edge case where value == high, since the code below maps
            // values exactly equal to high to palette.length when it should be one less.
            if (value == scan_data.max) {
                return palette_length - 1;
            }
            if (scan_data.is_reversed) {
                if (value > scan_data.min) {
                    return -1;
                }
                else if (value < scan_data.max) {
                    return palette_length;
                }
            }
            else {
                if (value > scan_data.max) {
                    return palette_length;
                }
                else if (value < scan_data.min) {
                    return -1;
                }
            }
            const log = Math.log(value / scan_data.min);
            const index = Math.abs(Math.floor(log * scan_data.scale));
            return (0, math_1.clamp)(index, -1, palette_length);
        }
    }
    exports.LogColorMapper = LogColorMapper;
},
/* models/mappers/eqhist_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const scanning_color_mapper_1 = require(298) /* ./scanning_color_mapper */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const array_1 = require(10) /* ../../core/util/array */;
    class EqHistColorMapper extends scanning_color_mapper_1.ScanningColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Bool, Int }) => ({
                bins: [Int, 256 * 256],
                rescale_discrete_levels: [Bool, false],
            }));
        }
        // Public for unit tests
        /*protected*/ scan(data, n) {
            const low = this.low != null ? this.low : (0, arrayable_1.min)(data);
            const high = this.high != null ? this.high : (0, arrayable_1.max)(data);
            const nbins = this.bins;
            const eq_bin_edges = (0, array_1.linspace)(low, high, nbins + 1);
            const full_hist = (0, arrayable_1.bin_counts)(data, eq_bin_edges);
            // Remove empty bins from histogram to make interpolation more accurate and faster
            // 1) Count non-zeros
            let nhist = 0;
            for (let i = 0; i < nbins; i++) {
                if (full_hist[i] != 0) {
                    nhist++;
                }
            }
            // 2) Remove zeros, leaving extra element at beginning for rescale_discrete_levels
            const hist = new Array(nhist + 1);
            const eq_bin_centers = new Array(nhist + 1);
            for (let i = 0, j = 1; i < nbins; i++) {
                if (full_hist[i] != 0) {
                    hist[j] = full_hist[i];
                    eq_bin_centers[j] = (eq_bin_edges[i] + eq_bin_edges[i + 1]) / 2;
                    j++;
                }
            }
            hist[0] = 0;
            eq_bin_centers[0] = 2 * eq_bin_centers[1] - eq_bin_centers[nhist];
            // CDF scaled from 0 to 1 except for first value
            const cdf = (0, array_1.cumsum)(hist);
            const lo = cdf[1];
            const diff = cdf[nhist] - lo;
            for (let i = 1; i <= nhist; i++) {
                cdf[i] = (cdf[i] - lo) / diff;
            }
            cdf[0] = -1.0;
            let { rescale_discrete_levels } = this;
            let lower_span = 0;
            if (rescale_discrete_levels) {
                const discrete_levels = nhist;
                // Straight line y = mx + c through (2, 1.5) and (100, 1) where
                // x is number of discrete_levels and y is lower span limit.
                const m = -0.5 / 98.0; // (y[1] - y[0]) / (x[1] - x[0])
                const c = 1.5 - 2 * m; // y[0] - m*x[0]
                const multiple = m * discrete_levels + c;
                if (multiple > 1) {
                    lower_span = 1 - multiple;
                }
                else {
                    rescale_discrete_levels = false;
                }
            }
            // Color bin boundaries are equally spaced in CDF
            const cdf_bins = (0, array_1.linspace)(lower_span, 1, n + 1);
            const binning = (0, arrayable_1.interpolate)(cdf_bins, cdf, eq_bin_centers);
            // Ensure binning limits are correct
            let force_low_cutoff = false;
            if (rescale_discrete_levels) {
                const low_cutoff_index = (0, arrayable_1.sorted_index)(binning, low);
                // This index satisfies: binning[low_cutoff_index-1] < low <= binning[low_cutoff_index]
                // If low < binning[low_cutoff_index] then set previous bin to low so that the
                // lowest colorbar label equals low rather than than the arbitrary value set by
                // rescale_discrete_levels. This ensures the bottom colorbar label is correct.
                // If low == binning[low_cutoff_index] then do nothing as label is already correct.
                if (low < binning[low_cutoff_index] && low_cutoff_index > 0) {
                    binning[low_cutoff_index - 1] = low;
                }
                force_low_cutoff = true;
            }
            else {
                binning[0] = low;
            }
            binning[binning.length - 1] = high;
            return { min: low, max: high, binning, force_low_cutoff };
        }
    }
    exports.EqHistColorMapper = EqHistColorMapper;
},
/* models/mappers/stack_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const color_mapper_1 = require(300) /* ./color_mapper */;
    class StackColorMapper extends color_mapper_1.ColorMapper {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.StackColorMapper = StackColorMapper;
},
/* models/mappers/weighted_stack_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const color_mapper_1 = require(300) /* ./color_mapper */;
    const continuous_color_mapper_1 = require(299) /* ./continuous_color_mapper */;
    const stack_color_mapper_1 = require(362) /* ./stack_color_mapper */;
    const types_1 = require(25) /* ../../core/types */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    const color_1 = require(23) /* ../../core/util/color */;
    class WeightedStackColorMapper extends stack_color_mapper_1.StackColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ List, Nullable, Float, Ref, Str }) => ({
                alpha_mapper: [Ref(continuous_color_mapper_1.ContinuousColorMapper)],
                color_baseline: [Nullable(Float), null],
                stack_labels: [Nullable(List(Str)), null],
            }));
        }
        // Weighted mix of colors.
        _mix_colors(colors_rgba, nan_color, weights, total_weight) {
            if (isNaN(total_weight)) {
                return nan_color;
            }
            let r = 0.0, g = 0.0, b = 0.0, a = 0.0;
            const n = weights.length;
            if (total_weight != 0) {
                for (let i = 0; i < n; i++) {
                    if (isNaN(weights[i])) {
                        continue;
                    }
                    const weight = weights[i] / total_weight;
                    r += colors_rgba[i * 4] * weight;
                    g += colors_rgba[i * 4 + 1] * weight;
                    b += colors_rgba[i * 4 + 2] * weight;
                    a += colors_rgba[i * 4 + 3] * weight;
                }
            }
            else {
                // Special case if total is zero then take mean color of all non-nan categories.
                let count = 0;
                for (let i = 0; i < n; i++) {
                    if (weights[i] == 0) {
                        r += colors_rgba[i * 4];
                        g += colors_rgba[i * 4 + 1];
                        b += colors_rgba[i * 4 + 2];
                        a += colors_rgba[i * 4 + 3];
                        count++;
                    }
                }
                r /= count;
                g /= count;
                b /= count;
                a /= count;
            }
            return (0, color_1.encode_rgba)([(0, color_1.byte)(r), (0, color_1.byte)(g), (0, color_1.byte)(b), (0, color_1.byte)(a)]);
        }
        _v_compute(data, values, palette, colors) {
            const n = values.length;
            const ncolor = palette.length;
            const nstack = data.length / n;
            (0, assert_1.assert)(nstack == ncolor, `Expected ${nstack} not ${ncolor} colors in palette`);
            // Color mixing is performed separately on each RGBA component, decode them just once
            const palette_as_rgba = new types_1.RGBAArray(ncolor * 4);
            for (let i = 0; i < ncolor; i++) {
                const [r, g, b, a] = (0, color_1.decode_rgba)(palette[i]);
                palette_as_rgba[i * 4] = r;
                palette_as_rgba[i * 4 + 1] = g;
                palette_as_rgba[i * 4 + 2] = b;
                palette_as_rgba[i * 4 + 3] = a;
            }
            // If color_baseline not specified, use nan-aware minimum of data.
            const color_baseline = this.color_baseline;
            const baseline = color_baseline == null ? (0, arrayable_1.min)(data) : color_baseline;
            // Mix colors based on weights.
            const { nan_color } = colors;
            const totals = new Array(n); // Array of totals per pixel
            const weights = new Array(ncolor); // For single pixel
            for (let i = 0; i < n; i++) {
                let total = NaN;
                for (let icol = 0; icol < ncolor; icol++) {
                    const index = i * ncolor + icol;
                    // If baseline non-zero, subtract it and clip to zero. Datashader only clips non-integers.
                    const val = baseline == 0 ? data[index] : Math.max(data[index] - baseline, 0);
                    weights[icol] = val;
                    if (!isNaN(val)) {
                        if (isNaN(total)) {
                            total = val;
                        }
                        else {
                            total += val;
                        }
                    }
                }
                values[i] = this._mix_colors(palette_as_rgba, nan_color, weights, total);
                totals[i] = total + baseline * ncolor;
            }
            // Calculate alphas using alpha_mapper.
            const alpha_palette = (0, color_mapper_1.convert_to_uint32_palette)(this.alpha_mapper.palette);
            const alphas = new Uint32Array(n);
            this.alpha_mapper._v_compute(totals, alphas, alpha_palette, colors);
            // Combine RGBA and alphas.
            for (let i = 0; i < n; i++) {
                const alpha = (0, color_1.byte)((values[i] & 0xff) * (alphas[i] & 0xff) / 255.0);
                values[i] = (values[i] & 0xffffff00) | alpha;
            }
        }
    }
    exports.WeightedStackColorMapper = WeightedStackColorMapper;
},
/* models/annotations/contour_color_bar.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const base_color_bar_1 = require(254) /* ./base_color_bar */;
    const ranges_1 = require(341) /* ../ranges */;
    const glyph_renderer_1 = require(302) /* ../renderers/glyph_renderer */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    class ContourColorBarView extends base_color_bar_1.BaseColorBarView {
        _fill_view;
        _line_view;
        children_views() {
            return [...super.children_views(), this._fill_view, this._line_view];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const { fill_renderer, line_renderer } = this.model;
            this._fill_view = await (0, build_views_1.build_view)(fill_renderer, { parent: this.parent });
            this._line_view = await (0, build_views_1.build_view)(line_renderer, { parent: this.parent });
        }
        _create_major_range() {
            const levels = this.model.levels;
            if (levels.length > 0) {
                return new ranges_1.Range1d({ start: levels[0], end: levels[levels.length - 1] });
            }
            else {
                return new ranges_1.Range1d({ start: 0, end: 1 });
            }
        }
        _paint_colors(ctx, bbox) {
            const vertical = this.orientation == "vertical";
            const levels = this.model.levels;
            const scale = this._major_scale;
            scale.source_range = this._major_range;
            if (vertical) {
                scale.target_range = new ranges_1.Range1d({ start: bbox.bottom, end: bbox.top });
            }
            else {
                scale.target_range = new ranges_1.Range1d({ start: bbox.left, end: bbox.right });
            }
            const scaled_levels = scale.v_compute(levels);
            const multi_polygons = this._fill_view.glyph;
            const nfill = multi_polygons.data_size;
            if (nfill > 0) {
                (0, assert_1.assert)(levels.length == nfill + 1, "Inconsistent number of filled contour levels");
                ctx.save();
                for (let i = 0; i < nfill; i++) {
                    ctx.beginPath();
                    if (vertical) {
                        ctx.rect(bbox.left, scaled_levels[i], bbox.width, scaled_levels[i + 1] - scaled_levels[i]);
                    }
                    else {
                        ctx.rect(scaled_levels[i], bbox.top, scaled_levels[i + 1] - scaled_levels[i], bbox.height);
                    }
                    multi_polygons.visuals.fill.apply(ctx, i);
                    multi_polygons.visuals.hatch.apply(ctx, i);
                }
                ctx.restore();
            }
            const multi_line = this._line_view.glyph;
            const nline = multi_line.data_size;
            if (nline > 0) {
                (0, assert_1.assert)(levels.length == nline, "Inconsistent number of line contour levels");
                ctx.save();
                for (let i = 0; i < nline; i++) {
                    ctx.beginPath();
                    if (vertical) {
                        ctx.moveTo(bbox.left, scaled_levels[i]);
                        ctx.lineTo(bbox.right, scaled_levels[i]);
                    }
                    else {
                        ctx.moveTo(scaled_levels[i], bbox.bottom);
                        ctx.lineTo(scaled_levels[i], bbox.top);
                    }
                    multi_line.visuals.line.set_vectorize(ctx, i);
                    ctx.stroke();
                }
                ctx.restore();
            }
        }
    }
    exports.ContourColorBarView = ContourColorBarView;
    class ContourColorBar extends base_color_bar_1.BaseColorBar {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ContourColorBarView;
            this.define(({ List, Float, Ref }) => ({
                fill_renderer: [Ref(glyph_renderer_1.GlyphRenderer)],
                line_renderer: [Ref(glyph_renderer_1.GlyphRenderer)],
                levels: [List(Float), []],
            }));
        }
    }
    exports.ContourColorBar = ContourColorBar;
},
/* models/annotations/label.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const text_annotation_1 = require(256) /* ./text_annotation */;
    const math_1 = require(12) /* ../../core/util/math */;
    const enums_1 = require(21) /* ../../core/enums */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    const signaling_1 = require(17) /* ../../core/signaling */;
    const affine_1 = require(73) /* ../../core/util/affine */;
    const kinds_1 = require(124) /* ../common/kinds */;
    const resolve = tslib_1.__importStar(require(127) /* ../common/resolve */);
    const coordinate_1 = require(58) /* ../coordinates/coordinate */;
    function xy(x, y) {
        return { x, y };
    }
    class LabelView extends text_annotation_1.TextAnnotationView {
        get mappers() {
            function mapper(units, scale, view, canvas) {
                switch (units) {
                    case "canvas": return canvas;
                    case "screen": return view;
                    case "data": return scale;
                }
            }
            const overlay = this.model;
            const parent = this.layout ?? this.plot_view.frame;
            const { x_scale, y_scale } = this.coordinates;
            const { x_view, y_view } = parent.bbox;
            const { x_screen, y_screen } = this.plot_view.canvas.bbox;
            const xy = {
                x: mapper(overlay.x_units, x_scale, x_view, x_screen),
                y: mapper(overlay.y_units, y_scale, y_view, y_screen),
            };
            return xy;
        }
        get anchor() {
            const { align, baseline } = this.visuals.text.values();
            return resolve.text_anchor(this.model.anchor, align, baseline);
        }
        get angle() {
            const { angle, angle_units, direction } = this.model;
            return (0, math_1.compute_angle)(angle, angle_units, direction);
        }
        get origin() {
            const { mappers } = this;
            const { x, y, x_offset, y_offset } = this.model;
            const compute = (dim, value, mapper) => {
                return value instanceof coordinate_1.Coordinate ? this.resolve_as_scalar(value, dim) : mapper.compute(value);
            };
            const sx = compute("x", x, mappers.x) + x_offset;
            const sy = compute("y", y, mappers.y) - y_offset; // TODO this needs to be unified with the rest of bokehjs
            return { sx, sy };
        }
        interactive_hit(sx, sy) {
            if (!this.model.visible || !this.model.editable) {
                return false;
            }
            return this._hit_test(sx, sy) == "area";
        }
        _hit_test(cx, cy) {
            const { sx, sy, anchor, angle, width, height } = this._rect;
            const { x, y } = (0, affine_1.rotate_around)(xy(cx, cy), xy(sx, sy), -angle);
            const left = sx - anchor.x * width;
            const top = sy - anchor.y * height;
            const right = left + width;
            const bottom = top + height;
            if (left <= x && x <= right && top <= y && y <= bottom) {
                return "area";
            }
            else {
                return null;
            }
        }
        _can_hit(_target) {
            return true;
        }
        _pan_state = null;
        on_pan_start(ev) {
            if (this.model.visible && this.model.editable) {
                const { sx, sy } = ev;
                const target = this._hit_test(sx, sy);
                if (target != null && this._can_hit(target)) {
                    this._pan_state = {
                        angle: this.angle,
                        base: { sx, sy },
                        target,
                        action: "rotate",
                    };
                    this.model.pan.emit(["pan:start", ev.modifiers]);
                    return true;
                }
            }
            return false;
        }
        on_pan(ev) {
            (0, assert_1.assert)(this._pan_state != null);
            const { dx, dy } = ev;
            const { angle, base } = this._pan_state;
            const { origin } = this;
            const angle0 = (0, math_1.atan2)([origin.sx, origin.sy], [base.sx, base.sy]);
            const angle1 = (0, math_1.atan2)([origin.sx, origin.sy], [base.sx + dx, base.sy + dy]);
            const da = angle1 - angle0;
            const na = angle + da;
            const nna = na % (2 * Math.PI);
            const { angle_units, direction } = this.model;
            this.model.angle = (0, math_1.invert_angle)(nna, angle_units, direction);
            this.model.pan.emit(["pan", ev.modifiers]);
        }
        on_pan_end(ev) {
            this._pan_state = null;
            this.model.pan.emit(["pan:end", ev.modifiers]);
        }
        cursor(sx, sy) {
            const target = this._pan_state?.target ?? this._hit_test(sx, sy);
            if (target == null || !this._can_hit(target)) {
                return null;
            }
            return "var(--bokeh-cursor-rotate)";
        }
    }
    exports.LabelView = LabelView;
    class Label extends text_annotation_1.TextAnnotation {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = LabelView;
            this.define(({ Bool, Float, Angle, Or, Ref }) => ({
                anchor: [kinds_1.TextAnchor, "auto"],
                x: [Or(Float, Ref(coordinate_1.Coordinate))],
                y: [Or(Float, Ref(coordinate_1.Coordinate))],
                x_units: [enums_1.CoordinateUnits, "data"],
                y_units: [enums_1.CoordinateUnits, "data"],
                x_offset: [Float, 0],
                y_offset: [Float, 0],
                angle: [Angle, 0],
                angle_units: [enums_1.AngleUnits, "rad"],
                direction: [enums_1.Direction, "anticlock"],
                editable: [Bool, false],
            }));
        }
        pan = new signaling_1.Signal(this, "pan");
    }
    exports.Label = Label;
},
/* models/annotations/label_set.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const data_annotation_1 = require(141) /* ./data_annotation */;
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    const enums_1 = require(21) /* ../../core/enums */;
    const graphics_1 = require(262) /* ../../core/graphics */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const types_1 = require(25) /* ../../core/types */;
    class LabelSetView extends data_annotation_1.DataAnnotationView {
        _x;
        _y;
        sx;
        sy;
        text;
        angle;
        x_offset;
        y_offset;
        map_data() {
            const { x_scale, y_scale } = this.coordinates;
            const panel = this.layout != null ? this.layout : this.plot_view.frame;
            this.sx = (() => {
                switch (this.model.x_units) {
                    case "canvas":
                        return new types_1.ScreenArray(this._x);
                    case "screen":
                        return panel.bbox.xview.v_compute(this._x);
                    case "data":
                        return x_scale.v_compute(this._x);
                }
            })();
            this.sy = (() => {
                switch (this.model.y_units) {
                    case "canvas":
                        return new types_1.ScreenArray(this._y);
                    case "screen":
                        return panel.bbox.yview.v_compute(this._y);
                    case "data":
                        return y_scale.v_compute(this._y);
                }
            })();
        }
        _paint_data(ctx) {
            for (let i = 0, end = this.text.length; i < end; i++) {
                const x_offset_i = this.x_offset.get(i);
                const y_offset_i = this.y_offset.get(i);
                const sx_i = this.sx[i] + x_offset_i;
                const sy_i = this.sy[i] - y_offset_i;
                const angle_i = this.angle.get(i);
                const text_i = this.text.get(i);
                if (!isFinite(sx_i + sy_i + angle_i) || text_i == null) {
                    continue;
                }
                this._paint_text(ctx, i, `${text_i}`, sx_i, sy_i, angle_i);
            }
        }
        _paint_text(ctx, i, text, sx, sy, angle) {
            const graphics = new graphics_1.TextBox({ text });
            graphics.angle = angle;
            graphics.position = { sx, sy };
            graphics.visuals = this.visuals.text.values(i);
            const { background_fill, background_hatch, border_line } = this.visuals;
            if (background_fill.doit || background_hatch.doit || border_line.doit) {
                const { p0, p1, p2, p3 } = graphics.rect();
                ctx.beginPath();
                ctx.moveTo(p0.x, p0.y);
                ctx.lineTo(p1.x, p1.y);
                ctx.lineTo(p2.x, p2.y);
                ctx.lineTo(p3.x, p3.y);
                ctx.closePath();
                this.visuals.background_fill.apply(ctx, i);
                this.visuals.background_hatch.apply(ctx, i);
                this.visuals.border_line.apply(ctx, i);
            }
            if (this.visuals.text.doit) {
                graphics.paint(ctx);
            }
        }
    }
    exports.LabelSetView = LabelSetView;
    class LabelSet extends data_annotation_1.DataAnnotation {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = LabelSetView;
            this.mixins([
                mixins.TextVector,
                ["border_", mixins.LineVector],
                ["background_", mixins.FillVector],
                ["background_", mixins.HatchVector],
            ]);
            this.define(() => ({
                x: [p.XCoordinateSpec, { field: "x" }],
                y: [p.YCoordinateSpec, { field: "y" }],
                x_units: [enums_1.CoordinateUnits, "data"],
                y_units: [enums_1.CoordinateUnits, "data"],
                text: [p.NullStringSpec, { field: "text" }],
                angle: [p.AngleSpec, 0],
                x_offset: [p.NumberSpec, { value: 0 }],
                y_offset: [p.NumberSpec, { value: 0 }],
            }));
            this.override({
                background_fill_color: null,
                border_line_color: null,
            });
        }
    }
    exports.LabelSet = LabelSet;
},
/* models/annotations/legend.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(96) /* ./annotation */;
    const legend_item_1 = require(368) /* ./legend_item */;
    const enums_1 = require(21) /* ../../core/enums */;
    const line_1 = require(100) /* ../../core/visuals/line */;
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    const side_panel_1 = require(257) /* ../../core/layout/side_panel */;
    const bbox_1 = require(62) /* ../../core/util/bbox */;
    const array_1 = require(10) /* ../../core/util/array */;
    const object_1 = require(9) /* ../../core/util/object */;
    const types_1 = require(8) /* ../../core/util/types */;
    const iterator_1 = require(15) /* ../../core/util/iterator */;
    const bokeh_events_1 = require(80) /* ../../core/bokeh_events */;
    const dom_1 = require(61) /* ../../core/dom */;
    const graphics_1 = require(262) /* ../../core/graphics */;
    const legend_css = tslib_1.__importStar(require(369) /* ../../styles/legend.css */);
    const kinds_1 = require(124) /* ../common/kinds */;
    const painting_1 = require(267) /* ../common/painting */;
    const resolve = tslib_1.__importStar(require(127) /* ../common/resolve */);
    const { ceil } = Math;
    class LegendView extends annotation_1.AnnotationView {
        get is_dual_renderer() {
            return true;
        }
        _get_size() {
            const { width, height } = this.bbox;
            const { margin } = this.model;
            return {
                width: width + 2 * margin,
                height: height + 2 * margin,
            };
        }
        update_layout() {
            this.update_geometry();
            const { panel } = this;
            if (panel != null) {
                this.layout = new side_panel_1.SideLayout(panel, () => this.get_size());
            }
            else {
                this.layout = undefined;
            }
        }
        _resize_observer;
        initialize() {
            super.initialize();
            this._resize_observer = new ResizeObserver((_entries) => this.request_layout());
            this._resize_observer.observe(this.el, { box: "border-box" });
        }
        remove() {
            this._resize_observer.disconnect();
            super.remove();
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.rerender());
            const { items } = this.model.properties;
            this.on_transitive_change(items, () => this._render_items(), { recursive: true });
        }
        _bbox = new bbox_1.BBox();
        get bbox() {
            return this._bbox;
        }
        grid_el = (0, dom_1.div)({ class: legend_css.grid });
        title_el = (0, dom_1.div)();
        entries = [];
        get padding() {
            const padding = this.model.border_line_color != null ? this.model.padding : 0;
            return resolve.padding(padding);
        }
        get border_radius() {
            return resolve.border_radius(this.model.border_radius);
        }
        stylesheets() {
            return [...super.stylesheets(), legend_css.default];
        }
        _paint_glyphs() {
            const { glyph_width, glyph_height } = this.model;
            const x0 = 0;
            const y0 = 0;
            const x1 = glyph_width;
            const y1 = glyph_height;
            for (const { glyph, item, label } of this.entries) {
                const field = item.get_field_from_label_prop();
                glyph.resize(glyph_width, glyph_height);
                const ctx = glyph.prepare();
                for (const renderer of item.renderers) {
                    const view = this.plot_view.views.find_one(renderer);
                    view?.draw_legend(ctx, x0, x1, y0, y1, field, label, item.index);
                }
                glyph.finish();
            }
        }
        get labels() {
            const collected = [];
            for (const item of this.model.items) {
                const labels = item.get_labels_list_from_label_prop();
                for (const label of labels) {
                    collected.push({ item, label });
                }
            }
            return collected;
        }
        get _should_rerender_items() {
            const { entries, labels } = this;
            if (entries.length != labels.length) {
                return true;
            }
            for (const [entry, { item, label }] of (0, iterator_1.zip)(entries, labels)) {
                if (entry.item != item || entry.label != label) {
                    return true;
                }
            }
            return false;
        }
        _toggle_inactive({ el, item }) {
            el.classList.toggle(legend_css.inactive, !this.is_active(item));
        }
        _render_items() {
            this.entries = [];
            const { click_policy } = this;
            let i = 0;
            for (const item of this.model.items) {
                const labels = item.get_labels_list_from_label_prop();
                for (const label of labels) {
                    const glyph = this.plot_view.canvas.create_layer();
                    glyph.el.classList.add(legend_css.glyph);
                    const glyph_el = glyph.canvas;
                    const label_el = (0, dom_1.div)({ class: legend_css.label }, `${label}`);
                    const overlay_el = (0, dom_1.div)({ class: legend_css.overlay });
                    const item_el = (0, dom_1.div)({ class: legend_css.item }, glyph_el, label_el, overlay_el);
                    item_el.classList.toggle(legend_css.hidden, !item.visible);
                    const entry = { el: item_el, glyph, label_el, item, label, i: i++, row: 0, col: 0 };
                    this.entries.push(entry);
                    item_el.addEventListener("pointerdown", () => {
                        this.model.trigger_event(new bokeh_events_1.LegendItemClick(this.model, item));
                        for (const renderer of item.renderers) {
                            click_policy(renderer);
                        }
                        this._toggle_inactive(entry);
                    });
                }
            }
            const vertical = this.model.orientation == "vertical";
            const { nc: ncols, nr: nrows } = (() => {
                const { ncols, nrows } = this.model;
                const n = this.entries.length;
                let nc;
                let nr;
                if (ncols != "auto" && nrows != "auto") {
                    nc = ncols;
                    nr = nrows;
                }
                else if (ncols != "auto") {
                    nc = ncols;
                    nr = ceil(n / ncols);
                }
                else if (nrows != "auto") {
                    nc = ceil(n / nrows);
                    nr = nrows;
                }
                else {
                    if (vertical) {
                        nc = 1;
                        nr = n;
                    }
                    else {
                        nc = n;
                        nr = 1;
                    }
                }
                return { nc, nr };
            })();
            let row = 0;
            let col = 0;
            for (const entry of this.entries) {
                entry.el.id = `item_${row}_${col}`;
                entry.row = row;
                entry.col = col;
                if (vertical) {
                    row += 1;
                    if (row >= nrows) {
                        row = 0;
                        col += 1;
                    }
                }
                else {
                    col += 1;
                    if (col >= ncols) {
                        col = 0;
                        row += 1;
                    }
                }
            }
            for (const entry of this.entries) {
                this._toggle_inactive(entry);
            }
            for (const { el, i, row, col } of this.entries) {
                if (this.has_item_background(i, row, col)) {
                    el.classList.add(legend_css.styled);
                }
            }
            (0, dom_1.empty)(this.grid_el);
            this.grid_el.style.setProperty("--ncols", `${ncols}`);
            this.grid_el.style.setProperty("--nrows", `${nrows}`);
            this.grid_el.append(...this.entries.map(({ el }) => el));
        }
        render() {
            super.render();
            const { orientation } = this.model;
            const vertical = orientation == "vertical";
            this.el.classList.toggle(legend_css.interactive, this.is_interactive);
            this.el.classList.toggle(legend_css.vertical, vertical);
            const title_el = (0, dom_1.div)({ class: legend_css.title }, this.model.title);
            this.title_el.remove();
            this.title_el = title_el;
            // can't simply use `rotate`, because rotation doesn't affect layout
            const { writing_mode, rotate } = (() => {
                const label_panel = new side_panel_1.SidePanel(this.model.title_location);
                switch (label_panel.face_adjusted_side) {
                    case "above": return { writing_mode: "horizontal-tb", rotate: 0 };
                    case "below": return { writing_mode: "horizontal-tb", rotate: 0 };
                    case "left": return { writing_mode: "vertical-rl", rotate: 180 };
                    case "right": return { writing_mode: "vertical-rl", rotate: 0 };
                }
            })();
            const title_styles = this.visuals.title_text.computed_values();
            this.style.append(`
    .${legend_css.title} {
      font: ${title_styles.font};
      color: ${title_styles.color};
      -webkit-text-stroke: ${title_styles.outline_width}px ${title_styles.outline_color};
      writing-mode: ${writing_mode};
      rotate: ${rotate}deg;
    }
    `);
            const label_styles = this.visuals.label_text.computed_values();
            this.style.append(`
    .${legend_css.item} .${legend_css.label} {
      font: ${label_styles.font};
      color: ${label_styles.color};
      -webkit-text-stroke: ${label_styles.outline_width}px ${label_styles.outline_color};
    }
    `);
            const { anchor } = this;
            this.style.append(`
    :host {
      transform: translate(-${anchor.x * 100}%, -${anchor.y * 100}%);
    }
    `);
            this.style.append(`
    :host {
      gap: ${(0, dom_1.px)(this.model.title_standoff)};
    }
    .${legend_css.grid} {
      gap: ${(0, dom_1.px)(this.model.spacing)};
    }
    .${legend_css.item} {
      gap: ${(0, dom_1.px)(this.model.label_standoff)};
    }
    .${legend_css.item} .${legend_css.glyph} {
      width: ${(0, dom_1.px)(this.model.glyph_width)};
      height: ${(0, dom_1.px)(this.model.glyph_height)};
    }
    .${legend_css.item} .${legend_css.label} {
      min-width: ${(0, dom_1.px)(this.model.label_width)};
      min-height: ${(0, dom_1.px)(this.model.label_height)};
    }
    `);
            if (this.visuals.item_background_fill.doit) {
                const { color } = this.visuals.item_background_fill.computed_values();
                this.style.append(`
      .${legend_css.item} {
        --item-background-color: ${color};
      }
      `);
            }
            if (this.visuals.item_background_hatch.doit) {
                const { scale, pattern } = this.visuals.item_background_hatch.computed_values();
                this.style.append(`
      .${legend_css.item} {
        --item-background-hatch: url(${pattern});
        --item-background-hatch-scale: ${scale}px;
      }
      `);
            }
            if (this.visuals.inactive_fill.doit) {
                const { color } = this.visuals.inactive_fill.computed_values();
                this.style.append(`
      .${legend_css.item} {
        --item-background-inactive-color: ${color};
      }
      `);
            }
            if (this.visuals.inactive_hatch.doit) {
                const { scale, pattern } = this.visuals.inactive_hatch.computed_values();
                this.style.append(`
      .${legend_css.item} {
        --item-background-inactive-hatch: url(${pattern});
        --item-background-inactive-hatch-scale: ${scale}px;
      }
      `);
            }
            const grid_auto_flow = (() => {
                switch (this.model.title_location) {
                    case "above":
                    case "below": return "row";
                    case "left":
                    case "right": return "column";
                }
            })();
            this.style.append(`
      :host {
        grid-auto-flow: ${grid_auto_flow};
      }
    `);
            this.shadow_el.append(...(() => {
                switch (this.model.title_location) {
                    case "above": return [title_el, this.grid_el];
                    case "below": return [this.grid_el, title_el];
                    case "left": return [title_el, this.grid_el];
                    case "right": return [this.grid_el, title_el];
                }
            })());
            const { padding, border_radius } = this;
            this.style.append(`
    :host {
      padding-left: ${padding.left}px;
      padding-right: ${padding.right}px;
      padding-top: ${padding.top}px;
      padding-bottom: ${padding.bottom}px;

      border-top-left-radius: ${border_radius.top_left}px;
      border-top-right-radius: ${border_radius.top_right}px;
      border-bottom-right-radius: ${border_radius.bottom_right}px;
      border-bottom-left-radius: ${border_radius.bottom_left}px;
    }
    `);
            if (this.visuals.background_fill.doit) {
                const { color } = this.visuals.background_fill.computed_values();
                this.style.append(`
      :host {
        --background-color: ${color};
        background-color: ${color};
      }
      `);
            }
            if (this.visuals.background_hatch.doit) {
                const { scale, pattern } = this.visuals.background_hatch.computed_values();
                this.style.append(`
      :host {
        --background-hatch: url(${pattern});
        --background-hatch-scale: ${scale}px;
        background-image: var(--background-hatch);
        background-size: var(--background-hatch-scale);
      }
      `);
            }
            if (this.visuals.border_line.doit) {
                const { color, width, dash: raw_dash } = this.visuals.border_line.computed_values();
                const invalid_css_border_style = ["dotdash", "dashdot"];
                let dash = raw_dash;
                // Invalid string dash to use CSS/border-style approach
                if ((0, types_1.isString)(dash) && invalid_css_border_style.includes(dash)) {
                    // Convert to array representation
                    dash = (0, line_1.resolve_line_dash)(dash);
                }
                // Non-empty dash array case
                if (!(0, types_1.isString)(dash) && dash.length > 0) {
                    // Make dash array even
                    if (dash.length % 2 !== 0) {
                        dash = dash.concat(dash);
                    }
                    // Compute extra patterns rules
                    let extra_patterns = "";
                    for (let index = 0; index < dash.length; index++) {
                        if (index !== 0 && index % 2 === 0) {
                            extra_patterns += `,
            linear-gradient(to right, ${color} ${dash[index]}px, transparent ${dash[index]}px) ${(0, array_1.sum)(dash.slice(0, index))}px top/var(--border-line-full-length) ${width}px repeat-x,
            linear-gradient(to right, ${color} ${dash[index]}px, transparent ${dash[index]}px) ${(0, array_1.sum)(dash.slice(0, index))}px bottom/var(--border-line-full-length) ${width}px repeat-x,
            linear-gradient(to bottom, ${color} ${dash[index]}px, transparent ${dash[index]}px) right ${(0, array_1.sum)(dash.slice(0, index))}px/${width}px var(--border-line-full-length) repeat-y,
            linear-gradient(to bottom, ${color} ${dash[index]}px, transparent ${dash[index]}px) left ${(0, array_1.sum)(dash.slice(0, index))}px/${width}px var(--border-line-full-length) repeat-y`;
                        }
                    }
                    this.style.append(`
        :host {
          --border-color: ${color};
          --border-line-full-length: ${(0, array_1.sum)(dash)}px;

          background:
             linear-gradient(to right, ${color} ${dash[0]}px, transparent ${dash[0]}px) left top/var(--border-line-full-length) ${width}px repeat-x,
             linear-gradient(to right, ${color} ${dash[0]}px, transparent ${dash[0]}px) left bottom/var(--border-line-full-length) ${width}px repeat-x,
             linear-gradient(to bottom, ${color} ${dash[0]}px, transparent ${dash[0]}px) right top/${width}px var(--border-line-full-length) repeat-y,
             linear-gradient(to bottom, ${color} ${dash[0]}px, transparent ${dash[0]}px) left top/${width}px var(--border-line-full-length) repeat-y ${extra_patterns.length > 0 ? `${extra_patterns}` : ""},
             ${this.visuals.background_hatch.doit ? "var(--background-hatch) left top/var(--background-hatch-scale) repeat," : ""} var(--background-color, --inverted-color);
        }
        `);
                    // Empty dash array (solid border) or border-style supported string case
                }
                else {
                    this.style.append(`
        :host {
          border-color: ${color};
          border-width: ${width}px;
          border-style: ${(0, types_1.isString)(dash) ? `${dash}` : "solid"};
        }
        `);
                }
            }
            this._render_items();
        }
        after_render() {
            super.after_render();
            this.update_position();
            this.request_paint(); // paint glyphs
        }
        get location() {
            const { location } = this.model;
            if ((0, types_1.isString)(location)) {
                const normal_location = (() => {
                    switch (location) {
                        case "top": return "top_center";
                        case "bottom": return "bottom_center";
                        case "left": return "center_left";
                        case "center": return "center_center";
                        case "right": return "center_right";
                        default: return location;
                    }
                })();
                const [v_loc, h_loc] = normal_location.split("_");
                return { x: h_loc, y: v_loc };
            }
            else {
                const [x_loc, y_loc] = location;
                return { x: x_loc, y: y_loc };
            }
        }
        get anchor() {
            const { location } = this;
            const x_anchor = (() => {
                switch (location.x) {
                    case "left": return 0.0;
                    case "center": return 0.5;
                    case "right": return 1.0;
                    default: return 0.0;
                }
            })();
            const y_anchor = (() => {
                switch (location.y) {
                    case "top": return 0.0;
                    case "center": return 0.5;
                    case "bottom": return 1.0;
                    default: return 1.0;
                }
            })();
            return { x: x_anchor, y: y_anchor };
        }
        get css_position() {
            const { location } = this;
            const { margin } = this.model;
            const panel = this.layout ?? this.plot_view.frame;
            const x_pos = (() => {
                const { x } = location;
                switch (x) {
                    case "left": return `calc(0% + ${(0, dom_1.px)(margin)})`;
                    case "center": return "50%";
                    case "right": return `calc(100% - ${(0, dom_1.px)(margin)})`;
                    default: return (0, dom_1.px)(panel.bbox.relative().x_view.compute(x));
                }
            })();
            const y_pos = (() => {
                const { y } = location;
                switch (y) {
                    case "top": return `calc(0% + ${(0, dom_1.px)(margin)})`;
                    case "center": return "50%";
                    case "bottom": return `calc(100% - ${(0, dom_1.px)(margin)})`;
                    default: return (0, dom_1.px)(panel.bbox.relative().y_view.compute(y));
                }
            })();
            return { x: x_pos, y: y_pos };
        }
        get is_visible() {
            const { visible, items } = this.model;
            return visible && items.length != 0 && (0, array_1.some)(items, (item) => item.visible);
        }
        update_position() {
            if (this.is_visible) {
                const { x, y } = this.css_position;
                this.position.replace(`
      :host {
        position: ${this.layout != null ? "relative" : "absolute"};
        left: ${x};
        top:  ${y};
      }
      `);
            }
            else {
                this.position.replace(`
      :host {
        display: none;
      }
      `);
            }
            const legend_bbox = (0, dom_1.bounding_box)(this.el);
            const canvas_bbox = (0, dom_1.bounding_box)(this.plot_view.canvas.el);
            this._bbox = legend_bbox.relative_to(canvas_bbox);
        }
        get is_interactive() {
            // this doesn't cover server callbacks
            return this.model.click_policy != "none" || (0, object_1.dict)(this.model.js_event_callbacks).has("legend_item_click");
        }
        get click_policy() {
            switch (this.model.click_policy) {
                case "hide": return (r) => r.visible = !r.visible;
                case "mute": return (r) => r.muted = !r.muted;
                case "none": return (_) => { };
            }
        }
        get is_active() {
            switch (this.model.click_policy) {
                case "none": return (_item) => true;
                case "hide": return (item) => (0, array_1.every)(item.renderers, (r) => r.visible);
                case "mute": return (item) => (0, array_1.every)(item.renderers, (r) => !r.muted);
            }
        }
        has_item_background(_i, row, col) {
            if (!this.visuals.item_background_fill.doit && !this.visuals.item_background_hatch.doit) {
                return false;
            }
            switch (this.model.item_background_policy) {
                case "every": return true;
                case "even": return (row % 2 == 0) == (col % 2 == 0);
                case "odd": return (row % 2 == 0) != (col % 2 == 0);
                case "none": return false;
            }
        }
        _paint(ctx) {
            if (!this.is_visible) {
                return;
            }
            if (this.is_dual_renderer && !this.parent.is_forcing_paint) {
                if (this._should_rerender_items) {
                    this._render_items();
                }
                this._paint_glyphs();
            }
            else {
                ctx.save();
                const canvas_bbox = (0, dom_1.bounding_box)(this.plot_view.canvas.el);
                this._draw_legend_box(ctx, canvas_bbox);
                this._draw_title(ctx, canvas_bbox);
                this._draw_legend_items(ctx, canvas_bbox);
                ctx.restore();
            }
        }
        _draw_legend_box(ctx, canvas_bbox) {
            ctx.beginPath();
            const bbox = (0, dom_1.bounding_box)(this.el).relative_to(canvas_bbox);
            (0, painting_1.round_rect)(ctx, bbox, this.border_radius);
            this.visuals.background_fill.apply(ctx);
            this.visuals.background_hatch.apply(ctx);
            this.visuals.border_line.apply(ctx);
        }
        _draw_title(ctx, canvas_bbox) {
            const { title } = this.model;
            if (title == null || title.length == 0 || !this.visuals.title_text.doit) {
                return;
            }
            const text = this.title_el.textContent;
            const text_box = new graphics_1.TextBox({ text });
            const title_bbox = (0, dom_1.bounding_box)(this.title_el).relative_to(canvas_bbox);
            let { x: sx, y: sy } = title_bbox;
            switch (this.model.title_location) {
                case "left": {
                    sy += title_bbox.height;
                    break;
                }
                case "right": {
                    sx += title_bbox.width;
                    break;
                }
                default:
            }
            text_box.position = { sx, sy, x_anchor: "left", y_anchor: "top" };
            text_box.visuals = this.visuals.title_text.values();
            const panel = new side_panel_1.SidePanel(this.model.title_location);
            text_box.angle = panel.get_label_angle_heuristic("parallel");
            text_box.paint(ctx);
        }
        _draw_legend_items(ctx, canvas_bbox) {
            const { is_active } = this;
            for (const { el: item_el, glyph, label_el, item, i, row, col } of this.entries) {
                const item_bbox = (0, dom_1.bounding_box)(item_el).relative_to(canvas_bbox);
                if (this.has_item_background(i, row, col)) {
                    ctx.beginPath();
                    ctx.rect_bbox(item_bbox);
                    this.visuals.item_background_fill.apply(ctx);
                    this.visuals.item_background_hatch.apply(ctx);
                }
                ctx.layer.undo_transform(() => {
                    const glyph_el = glyph.canvas;
                    const glyph_bbox = (0, dom_1.bounding_box)(glyph_el).relative_to(canvas_bbox).scale(ctx.layer.pixel_ratio);
                    ctx.drawImage(glyph_el, glyph_bbox.x, glyph_bbox.y);
                });
                const text = label_el.textContent;
                const text_box = new graphics_1.TextBox({ text });
                const { x: sx, vcenter: sy } = (0, dom_1.bounding_box)(label_el).relative_to(canvas_bbox);
                text_box.position = { sx, sy, x_anchor: "left", y_anchor: "center" };
                text_box.visuals = this.visuals.label_text.values();
                text_box.paint(ctx);
                if (!is_active(item)) {
                    ctx.beginPath();
                    ctx.rect_bbox(item_bbox);
                    this.visuals.inactive_fill.apply(ctx);
                    this.visuals.inactive_hatch.apply(ctx);
                }
            }
        }
    }
    exports.LegendView = LegendView;
    class Legend extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = LegendView;
            this.mixins([
                ["label_", mixins.Text],
                ["title_", mixins.Text],
                ["inactive_", mixins.Fill],
                ["inactive_", mixins.Hatch],
                ["border_", mixins.Line],
                ["background_", mixins.Fill],
                ["background_", mixins.Hatch],
                ["item_background_", mixins.Fill],
                ["item_background_", mixins.Hatch],
            ]);
            this.define(({ Float, Int, Str, List, Tuple, Or, Ref, Nullable, Positive, Auto }) => ({
                orientation: [enums_1.Orientation, "vertical"],
                ncols: [Or(Positive(Int), Auto), "auto"],
                nrows: [Or(Positive(Int), Auto), "auto"],
                location: [Or(enums_1.LegendLocation, Tuple(Float, Float)), "top_right"],
                title: [Nullable(Str), null],
                title_location: [enums_1.Location, "above"],
                title_standoff: [Float, 5],
                label_standoff: [Float, 5],
                glyph_width: [Float, 20],
                glyph_height: [Float, 20],
                label_width: [Float, 20],
                label_height: [Or(Float, Auto), "auto"],
                margin: [Float, 10],
                padding: [kinds_1.Padding, 10],
                border_radius: [kinds_1.BorderRadius, 0],
                spacing: [Float, 3],
                items: [List(Ref(legend_item_1.LegendItem)), []],
                click_policy: [enums_1.LegendClickPolicy, "none"],
                item_background_policy: [enums_1.AlternationPolicy, "none"],
            }));
            this.override({
                border_line_color: "#e5e5e5",
                border_line_alpha: 0.5,
                border_line_width: 1,
                background_fill_color: "#ffffff",
                background_fill_alpha: 0.95,
                item_background_fill_color: "#f1f1f1",
                item_background_fill_alpha: 0.8,
                inactive_fill_color: "white",
                inactive_fill_alpha: 0.7,
                label_text_font_size: "13px",
                label_text_baseline: "middle",
                title_text_font_size: "13px",
                title_text_font_style: "italic",
            });
        }
    }
    exports.Legend = Legend;
},
/* models/annotations/legend_item.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const model_1 = require(52) /* ../../model */;
    const glyph_renderer_1 = require(302) /* ../renderers/glyph_renderer */;
    const columnar_data_source_1 = require(142) /* ../sources/columnar_data_source */;
    const vectorization_1 = require(29) /* ../../core/vectorization */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const logging_1 = require(11) /* ../../core/logging */;
    const array_1 = require(10) /* ../../core/util/array */;
    class LegendItem extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Bool, Int, List, Ref, Nullable }) => ({
                label: [p.NullStringSpec, null],
                renderers: [List(Ref(glyph_renderer_1.GlyphRenderer)), []],
                index: [Nullable(Int), null],
                visible: [Bool, true],
            }));
        }
        /*protected*/ _check_data_sources_on_renderers() {
            const field = this.get_field_from_label_prop();
            if (field != null) {
                if (this.renderers.length < 1) {
                    return false;
                }
                const source = this.renderers[0].data_source;
                for (const r of this.renderers) {
                    if (r.data_source != source) {
                        return false;
                    }
                }
            }
            return true;
        }
        /*protected*/ _check_field_label_on_data_source() {
            const field = this.get_field_from_label_prop();
            if (field != null) {
                if (this.renderers.length < 1) {
                    return false;
                }
                const source = this.renderers[0].data_source;
                if (!(0, array_1.includes)(source.columns(), field)) {
                    return false;
                }
            }
            return true;
        }
        _validate_integrity() {
            // Validate data_sources match
            if (!this._check_data_sources_on_renderers()) {
                logging_1.logger.error("Non matching data sources on legend item renderers");
            }
            // Validate label in data_source
            if (!this._check_field_label_on_data_source()) {
                logging_1.logger.error(`Bad column name on label: ${this.label}`);
            }
        }
        initialize() {
            super.initialize();
            this._validate_integrity(); // TODO should validate after update
        }
        get_field_from_label_prop() {
            const { label } = this;
            return (0, vectorization_1.isField)(label) ? label.field : null;
        }
        get_labels_list_from_label_prop() {
            if (!this.visible) {
                return [];
            }
            const { index } = this;
            if (index != null && this.renderers.every((r) => !r.view.has_subset_index(index))) {
                // this index points to nowhere, so skip this item altogether from its legend
                return [];
            }
            if ((0, vectorization_1.isValue)(this.label)) {
                const { value } = this.label;
                return value != null ? [value] : [];
            }
            const field = this.get_field_from_label_prop();
            if (field != null) {
                if (this.renderers.length === 0) {
                    return ["No source found"];
                }
                const renderer = this.renderers[0];
                const source = renderer.data_source;
                const view_indices = renderer.view.indices;
                if (source instanceof columnar_data_source_1.ColumnarDataSource) {
                    const data = source.get_column(field);
                    if (data != null) {
                        const filtered_data = [];
                        for (const i of view_indices) {
                            filtered_data.push(data[i]);
                        }
                        return (0, array_1.uniq)(filtered_data);
                    }
                    else {
                        return ["Invalid field"];
                    }
                }
            }
            return [];
        }
    }
    exports.LegendItem = LegendItem;
},
/* styles/legend.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.hidden = "bk-hidden";
    exports.title = "bk-title";
    exports.label = "bk-label";
    exports.grid = "bk-grid";
    exports.vertical = "bk-vertical";
    exports.item = "bk-item";
    exports.styled = "bk-styled";
    exports.interactive = "bk-interactive";
    exports.glyph = "bk-glyph";
    exports.overlay = "bk-overlay";
    exports.inactive = "bk-inactive";
    exports.default = `:host{position:relative;display:grid;grid-template-rows:auto;grid-template-columns:auto;pointer-events:all;}.bk-hidden{display:none;}.bk-title{position:relative;white-space:pre;cursor:auto;}.bk-title:empty{display:none;}.bk-label{position:relative;white-space:pre;cursor:auto;width:fit-content;height:fit-content;display:flex;align-items:center;}.bk-grid{position:relative;display:grid;grid-auto-flow:row;grid-template-rows:repeat(var(--nrows), max-content);grid-template-columns:repeat(var(--ncols), max-content);width:max-content;height:max-content;}:host(.bk-vertical) .bk-grid{grid-auto-flow:column;}.bk-item{position:relative;display:flex;flex-direction:row;flex-wrap:nowrap;align-items:center;}.bk-item.bk-styled{background-color:var(--item-background-color);background-image:var(--item-background-hatch);background-size:var(--item-background-hatch-scale);}:host(.bk-interactive) .bk-item{cursor:pointer;}.bk-glyph{position:relative;}.bk-overlay{position:absolute;left:0;top:0;width:100%;height:100%;pointer-events:none;}.bk-item.bk-inactive .bk-overlay{background-color:var(--item-background-inactive-color);background-image:var(--item-background-inactive-hatch);background-size:var(--item-background-inactive-hatch-scale);}`;
},
/* models/annotations/poly_annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(96) /* ./annotation */;
    const data_range1d_1 = require(118) /* ../ranges/data_range1d */;
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    const enums_1 = require(21) /* ../../core/enums */;
    const hittest_1 = require(311) /* ../../core/hittest */;
    const signaling_1 = require(17) /* ../../core/signaling */;
    const bbox_1 = require(62) /* ../../core/util/bbox */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    class Polygon {
        xs;
        ys;
        constructor(xs = [], ys = []) {
            this.xs = xs;
            this.ys = ys;
            (0, assert_1.assert)(xs.length == ys.length);
        }
        clone() {
            return new Polygon(this.xs.slice(), this.ys.slice());
        }
        [Symbol.iterator]() {
            return this.nodes();
        }
        *nodes() {
            const { xs, ys, n } = this;
            for (let i = 0; i < n; i++) {
                yield [xs[i], ys[i], i];
            }
        }
        *edges() {
            const { xs, ys, n } = this;
            for (let i = 1; i < n; i++) {
                const p0 = { x: xs[i - 1], y: ys[i - 1] };
                const p1 = { x: xs[i], y: ys[i] };
                yield [p0, p1, i - 1];
            }
            if (n >= 3) {
                const p0 = { x: xs[n - 1], y: ys[n - 1] };
                const p1 = { x: xs[0], y: ys[0] };
                yield [p0, p1, n - 1];
            }
        }
        contains(x, y) {
            return (0, hittest_1.point_in_poly)(x, y, this.xs, this.ys);
        }
        get bbox() {
            const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(this.xs, this.ys);
            return new bbox_1.BBox({ x0, x1, y0, y1 });
        }
        get n() {
            return this.xs.length;
        }
        translate(dx, dy, ...i) {
            const poly = this.clone();
            const { xs, ys, n } = poly;
            if (i.length != 0) {
                for (const j of i) {
                    const k = j % n;
                    xs[k] += dx;
                    ys[k] += dy;
                }
            }
            else {
                for (let i = 0; i < n; i++) {
                    xs[i] += dx;
                    ys[i] += dy;
                }
            }
            return poly;
        }
    }
    class PolyAnnotationView extends annotation_1.AnnotationView {
        poly = new Polygon();
        get bbox() {
            return this.poly.bbox;
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.request_paint());
        }
        [data_range1d_1.auto_ranged] = true;
        bounds() {
            const { xs_units, ys_units } = this.model;
            if (xs_units == "data" && ys_units == "data") {
                const { xs, ys } = this.model;
                const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(xs, ys);
                return { x0, x1, y0, y1 };
            }
            else {
                return (0, bbox_1.empty)();
            }
        }
        log_bounds() {
            return (0, bbox_1.empty)();
        }
        _mappers() {
            const mapper = (units, scale, view, canvas) => {
                switch (units) {
                    case "canvas": return canvas;
                    case "screen": return view;
                    case "data": return scale;
                }
            };
            const overlay = this.model;
            const { frame, canvas } = this.plot_view;
            const { x_scale, y_scale } = frame;
            const { x_view, y_view } = frame.bbox;
            const { x_screen, y_screen } = canvas.bbox;
            return {
                x: mapper(overlay.xs_units, x_scale, x_view, x_screen),
                y: mapper(overlay.ys_units, y_scale, y_view, y_screen),
            };
        }
        _paint(ctx) {
            const { xs, ys } = this.model;
            (0, assert_1.assert)(xs.length == ys.length);
            this.poly = (() => {
                const { x, y } = this._mappers();
                return new Polygon(x.v_compute(xs), y.v_compute(ys));
            })();
            ctx.beginPath();
            for (const [sx, sy] of this.poly) {
                ctx.lineTo(sx, sy);
            }
            const { _is_hovered, visuals } = this;
            const fill = _is_hovered && visuals.hover_fill.doit ? visuals.hover_fill : visuals.fill;
            const hatch = _is_hovered && visuals.hover_hatch.doit ? visuals.hover_hatch : visuals.hatch;
            const line = _is_hovered && visuals.hover_line.doit ? visuals.hover_line : visuals.line;
            if (this.poly.n >= 3) {
                ctx.closePath();
                fill.apply(ctx);
                hatch.apply(ctx);
            }
            line.apply(ctx);
        }
        interactive_hit(sx, sy) {
            if (!this.model.visible || !this.model.editable) {
                return false;
            }
            return this.poly.contains(sx, sy);
        }
        _hit_test(sx, sy) {
            const { abs } = Math;
            const EDGE_TOLERANCE = 2.5;
            const tolerance = Math.max(EDGE_TOLERANCE, this.model.line_width / 2);
            for (const [px, py, i] of this.poly) {
                if (abs(px - sx) < tolerance && abs(py - sy) < tolerance) {
                    return { type: "node", i };
                }
            }
            const spt = { x: sx, y: sy };
            let j = null;
            let dist = Infinity;
            for (const [p0, p1, i] of this.poly.edges()) {
                const d = (0, hittest_1.dist_to_segment)(spt, p0, p1);
                if (d < tolerance && d < dist) {
                    dist = d;
                    j = i;
                }
            }
            if (j != null) {
                return { type: "edge", i: j };
            }
            if (this.poly.contains(sx, sy)) {
                return { type: "area" };
            }
            return null;
        }
        _can_hit(_target) {
            return true;
        }
        _pan_state = null;
        on_pan_start(ev) {
            if (this.model.visible && this.model.editable) {
                const { sx, sy } = ev;
                const target = this._hit_test(sx, sy);
                if (target != null && this._can_hit(target)) {
                    this._pan_state = {
                        poly: this.poly.clone(),
                        target,
                    };
                    this.model.pan.emit(["pan:start", ev.modifiers]);
                    return true;
                }
            }
            return false;
        }
        on_pan(ev) {
            (0, assert_1.assert)(this._pan_state != null);
            const spoly = (() => {
                const { poly, target } = this._pan_state;
                const { dx, dy } = ev;
                switch (target.type) {
                    case "node": {
                        const { i } = target;
                        return poly.translate(dx, dy, i);
                    }
                    case "edge": {
                        const { i } = target;
                        return poly.translate(dx, dy, i, i + 1);
                    }
                    case "area": {
                        return poly.translate(dx, dy);
                    }
                }
            })();
            const { x, y } = this._mappers();
            const xs = x.v_invert(spoly.xs);
            const ys = y.v_invert(spoly.ys);
            this.model.update({ xs, ys });
            this.model.pan.emit(["pan", ev.modifiers]);
        }
        on_pan_end(ev) {
            this._pan_state = null;
            this.model.pan.emit(["pan:end", ev.modifiers]);
        }
        get _has_hover() {
            const { hover_line, hover_fill, hover_hatch } = this.visuals;
            return hover_line.doit || hover_fill.doit || hover_hatch.doit;
        }
        _is_hovered = false;
        on_enter(_ev) {
            const { _has_hover } = this;
            if (_has_hover) {
                this._is_hovered = true;
                this.request_paint();
            }
            return _has_hover;
        }
        on_move(_ev) { }
        on_leave(_ev) {
            if (this._has_hover) {
                this._is_hovered = false;
                this.request_paint();
            }
        }
        cursor(sx, sy) {
            const target = this._pan_state?.target ?? this._hit_test(sx, sy);
            if (target == null || !this._can_hit(target)) {
                return null;
            }
            switch (target.type) {
                case "node": return "move";
                case "edge": return "move";
                case "area": return "move";
            }
        }
    }
    exports.PolyAnnotationView = PolyAnnotationView;
    class PolyAnnotation extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = PolyAnnotationView;
            this.mixins([
                mixins.Line,
                mixins.Fill,
                mixins.Hatch,
                ["hover_", mixins.Line],
                ["hover_", mixins.Fill],
                ["hover_", mixins.Hatch],
            ]);
            this.define(({ Bool, Float, Arrayable }) => ({
                xs: [Arrayable(Float), []],
                ys: [Arrayable(Float), []],
                xs_units: [enums_1.CoordinateUnits, "data"],
                ys_units: [enums_1.CoordinateUnits, "data"],
                editable: [Bool, false],
            }));
            this.override({
                fill_color: "#fff9ba",
                fill_alpha: 0.4,
                line_color: "#cccccc",
                line_alpha: 0.3,
                hover_fill_color: null,
                hover_fill_alpha: 0.4,
                hover_line_color: null,
                hover_line_alpha: 0.3,
            });
        }
        pan = new signaling_1.Signal(this, "pan");
        update({ xs, ys }) {
            this.setv({ xs: xs.slice(), ys: ys.slice(), visible: true });
        }
        clear() {
            this.setv({ xs: [], ys: [], visible: false });
        }
    }
    exports.PolyAnnotation = PolyAnnotation;
},
/* models/annotations/scale_bar.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(96) /* ./annotation */;
    const dimensional_1 = require(372) /* ./dimensional */;
    const range_1 = require(110) /* ../ranges/range */;
    const range1d_1 = require(111) /* ../ranges/range1d */;
    const enums_1 = require(21) /* ../../core/enums */;
    const enums = tslib_1.__importStar(require(21) /* ../../core/enums */);
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    const graphics_1 = require(262) /* ../../core/graphics */;
    const side_panel_1 = require(257) /* ../../core/layout/side_panel */;
    const bbox_1 = require(62) /* ../../core/util/bbox */;
    const layout_1 = require(135) /* ../../core/layout */;
    const grid_1 = require(139) /* ../../core/layout/grid */;
    const linear_axis_1 = require(277) /* ../axes/linear_axis */;
    const ticker_1 = require(274) /* ../tickers/ticker */;
    const fixed_ticker_1 = require(293) /* ../tickers/fixed_ticker */;
    const linear_scale_1 = require(113) /* ../scales/linear_scale */;
    const categorical_scale_1 = require(116) /* ../scales/categorical_scale */;
    const coordinate_mapping_1 = require(107) /* ../coordinates/coordinate_mapping */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const math_1 = require(12) /* ../../core/util/math */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    const iterator_1 = require(15) /* ../../core/util/iterator */;
    const types_1 = require(8) /* ../../core/util/types */;
    const templating_1 = require(329) /* ../../core/util/templating */;
    const kinds_1 = require(22) /* ../../core/kinds */;
    const kinds_2 = require(124) /* ../common/kinds */;
    const resolve = tslib_1.__importStar(require(127) /* ../common/resolve */);
    const factor_range_1 = require(121) /* ../ranges/factor_range */;
    const { round } = Math;
    const Position = (0, kinds_1.Or)(enums.Anchor, (0, kinds_1.Tuple)((0, kinds_1.Or)(kinds_1.Float, factor_range_1.Factor, enums_1.HAlign), (0, kinds_1.Or)(kinds_1.Float, factor_range_1.Factor, enums_1.VAlign)));
    const PositionUnits = (0, kinds_1.Enum)("data", "screen", "view", "percent");
    const LengthUnits = (0, kinds_1.Enum)("screen", "data", "percent");
    const LengthSizing = (0, kinds_1.Enum)("adaptive", "exact");
    class ScaleBarView extends annotation_1.AnnotationView {
        _bbox = new bbox_1.BBox();
        get bbox() {
            return this._bbox;
        }
        label_layout;
        title_layout;
        axis_layout;
        box_layout;
        axis;
        axis_view;
        children_views() {
            return [...super.children_views(), this.axis_view];
        }
        axis_scale;
        cross_scale;
        range;
        _get_size() {
            const { width, height } = this.bbox;
            const { margin } = this.model;
            return {
                width: width + 2 * margin,
                height: height + 2 * margin,
            };
        }
        initialize() {
            super.initialize();
            const { ticker } = this.model;
            this.axis = new linear_axis_1.LinearAxis({
                ticker,
                ...mixins.attrs_of(this.model, "bar_", mixins.Line, "axis_"),
            });
            this.range = (() => {
                const { range, orientation } = this.model;
                if (range == "auto") {
                    const { frame } = this.parent;
                    switch (orientation) {
                        case "horizontal": return frame.x_range;
                        case "vertical": return frame.y_range;
                    }
                }
                else {
                    return range;
                }
            })();
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const coordinates = (() => {
                const axis_source = new range1d_1.Range1d();
                const axis_target = new range1d_1.Range1d();
                const cross_source = new range1d_1.Range1d();
                const cross_target = new range1d_1.Range1d();
                this.axis_scale = new linear_scale_1.LinearScale({ source_range: axis_source, target_range: axis_target });
                this.cross_scale = new linear_scale_1.LinearScale({ source_range: cross_source, target_range: cross_target });
                if (this.model.orientation == "horizontal") {
                    return new coordinate_mapping_1.CoordinateTransform(this.axis_scale, this.cross_scale);
                }
                else {
                    return new coordinate_mapping_1.CoordinateTransform(this.cross_scale, this.axis_scale);
                }
            })();
            this.axis_view = await (0, build_views_1.build_view)(this.axis, { parent: this.plot_view });
            this.axis_view.coordinates = coordinates;
            this.axis_view.panel = new side_panel_1.SidePanel(this.model.orientation == "horizontal" ? "below" : "right");
            this.axis_view.update_layout();
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => {
                this.request_paint();
            });
            this.connect(this.range.change, () => {
                this.request_paint();
            });
        }
        update_layout() {
            this.update_geometry();
            const { panel } = this;
            if (panel != null) {
                this.layout = new side_panel_1.SideLayout(panel, () => this.get_size());
            }
            else {
                this.layout = undefined;
            }
        }
        update_geometry() {
            super.update_geometry();
        }
        get horizontal() {
            return this.model.orientation == "horizontal";
        }
        text_layout(args) {
            const { text, location, align, visuals } = args;
            const { orientation } = this.model;
            const text_box = new graphics_1.TextBox({ text });
            const text_panel = new side_panel_1.SidePanel(location);
            text_box.visuals = visuals.values();
            const text_orientation = (() => {
                switch (location) {
                    case "above":
                    case "below": return "horizontal";
                    default: return orientation;
                }
            })();
            text_box.angle = text_panel.get_label_angle_heuristic(text_orientation);
            text_box.base_font_size = this.plot_view.base_font_size;
            text_box.position = {
                sx: 0,
                sy: 0,
                x_anchor: "left",
                y_anchor: "top",
            };
            text_box.align = "auto";
            const text_layout = new layout_1.TextLayout(text_box);
            text_layout.absolute = true;
            const horizontal = orientation == "horizontal";
            const halign = horizontal ? align : undefined;
            const valign = !horizontal ? align : undefined;
            text_layout.set_sizing({
                width_policy: "min",
                height_policy: "min",
                visible: text != "" && visuals.doit,
                halign, valign,
            });
            return text_layout;
        }
        compute_geometry() {
            super.compute_geometry();
            const { orientation, length_sizing, padding, margin } = this.model;
            const { border_line, bar_line } = this.visuals;
            const bar_width = bar_line.line_width.get_value();
            const border_width = border_line.line_width.get_value();
            const { frame } = this.parent;
            const frame_span = orientation == "horizontal" ? frame.bbox.width : frame.bbox.height;
            const bar_length_percent = (() => {
                const { bar_length, bar_length_units } = this.model;
                switch (bar_length_units) {
                    case "screen": {
                        if (0.0 <= bar_length && bar_length <= 1.0) {
                            return bar_length;
                        }
                        else {
                            return (0, math_1.clamp)(bar_length / frame_span, 0.0, 1.0);
                        }
                    }
                    case "data": {
                        const scale = orientation == "horizontal" ? this.coordinates.x_scale : this.coordinates.y_scale;
                        (0, assert_1.assert)(scale instanceof linear_scale_1.LinearScale || scale instanceof categorical_scale_1.CategoricalScale);
                        const [sv0, sv1] = scale.r_compute(0, bar_length);
                        const sdist = Math.abs(sv1 - sv0);
                        return sdist / frame_span;
                    }
                    case "percent": {
                        return (0, math_1.clamp)(bar_length, 0.0, 1.0);
                    }
                }
            })();
            const { new_value, new_unit, scale_factor, exact } = (() => {
                const { unit, dimensional } = this.model;
                const value = this.range.span * bar_length_percent;
                return dimensional.compute(value, unit, length_sizing == "exact");
            })();
            const init_bar_length_px = frame_span * bar_length_percent;
            const bar_length_px = round(init_bar_length_px * scale_factor);
            const label_text = (() => {
                const { label } = this.model;
                return (0, templating_1.process_placeholders)(label, (_, name, format) => {
                    switch (name) {
                        case "value": {
                            if (exact) {
                                if (format != null) {
                                    return (0, templating_1.sprintf)(format, new_value);
                                }
                                else {
                                    return new_value.toFixed(2);
                                }
                            }
                            else {
                                return `${new_value}`;
                            }
                        }
                        case "unit": {
                            switch (format ?? "short") {
                                case "short": return new_unit;
                            }
                        }
                        default: {
                            return null;
                        }
                    }
                });
            })();
            this.label_layout = this.text_layout({
                text: label_text,
                location: this.model.label_location,
                align: this.model.label_align,
                visuals: this.visuals.label_text,
            });
            this.title_layout = this.text_layout({
                text: this.model.title,
                location: this.model.title_location,
                align: this.model.title_align,
                visuals: this.visuals.title_text,
            });
            const bar_size = (() => {
                if (orientation == "horizontal") {
                    return { width: bar_length_px, height: bar_width };
                }
                else {
                    return { width: bar_width, height: bar_length_px };
                }
            })();
            const axis_layout = this.axis_view.layout;
            (0, assert_1.assert)(axis_layout != null);
            this.axis_layout = axis_layout;
            axis_layout.absolute = true;
            if (orientation == "horizontal") {
                axis_layout.set_sizing({
                    width_policy: "fixed", width: bar_size.width,
                    height_policy: "min",
                    valign: "center",
                });
            }
            else {
                axis_layout.set_sizing({
                    width_policy: "min",
                    height_policy: "fixed", height: bar_size.height,
                    halign: "center",
                });
            }
            this.box_layout = (() => {
                const panels = {
                    above: [],
                    below: [],
                    left: [],
                    right: [],
                };
                function spacer(location, spacing) {
                    const layout = new layout_1.FixedLayout();
                    layout.absolute = true;
                    layout.set_sizing((() => {
                        if (location == "left" || location == "right") {
                            return { width_policy: "fixed", width: spacing };
                        }
                        else {
                            return { height_policy: "fixed", height: spacing };
                        }
                    })());
                    return layout;
                }
                function insert(layout, location, spacing) {
                    if (layout.visible) {
                        panels[location].push(spacer(location, spacing), layout);
                    }
                }
                insert(this.label_layout, this.model.label_location, this.model.label_standoff);
                insert(this.title_layout, this.model.title_location, this.model.title_standoff);
                const row = panels.above.length;
                const col = panels.left.length;
                const items = [
                    { layout: axis_layout, row, col },
                ];
                for (const [layout, i] of (0, iterator_1.enumerate)(panels.above)) {
                    items.push({ layout, row: row - i - 1, col });
                }
                for (const [layout, i] of (0, iterator_1.enumerate)(panels.below)) {
                    items.push({ layout, row: row + i + 1, col });
                }
                for (const [layout, i] of (0, iterator_1.enumerate)(panels.left)) {
                    items.push({ layout, row, col: col - i - 1 });
                }
                for (const [layout, i] of (0, iterator_1.enumerate)(panels.right)) {
                    items.push({ layout, row, col: col + i + 1 });
                }
                return new grid_1.Grid(items);
            })();
            const { box_layout } = this;
            box_layout.absolute = true;
            box_layout.position = { left: padding, top: padding };
            box_layout.set_sizing();
            box_layout.compute();
            const [axis_range, cross_range] = (() => {
                const { x_range, y_range } = this.axis_view.bbox;
                if (orientation == "horizontal") {
                    return [x_range, y_range];
                }
                else {
                    return [y_range, x_range];
                }
            })();
            this.axis_scale.source_range.end = new_value;
            this.axis_scale.target_range.setv(axis_range);
            this.cross_scale.source_range.end = 1.0;
            this.cross_scale.target_range.setv(cross_range);
            const position = (() => {
                const { location: position } = this.model;
                if ((0, types_1.isString)(position)) {
                    const normalized = (() => {
                        switch (position) {
                            case "top": return "top_center";
                            case "bottom": return "bottom_center";
                            case "left": return "center_left";
                            case "center": return "center_center";
                            case "right": return "center_right";
                            default: return position;
                        }
                    })();
                    const [v_loc, h_loc] = normalized.split("_");
                    return { x: h_loc, y: v_loc };
                }
                else {
                    const [x_loc, y_loc] = position;
                    return { x: x_loc, y: y_loc };
                }
            })();
            const { x, y } = (() => {
                const { bbox } = this.layout ?? this.plot_view.frame;
                const inset = bbox.shrink_by(margin);
                const x_pos = (() => {
                    const { x } = position;
                    switch (x) {
                        case "left": return inset.left;
                        case "center": return inset.x_center;
                        case "right": return inset.right;
                    }
                    const x_mapper = (() => {
                        switch (this.model.x_units) {
                            case "data": return this.coordinates.x_scale;
                            case "screen": return bbox.x_screen;
                            case "view": return bbox.x_view;
                            case "percent": return bbox.x_percent;
                        }
                    })();
                    return x_mapper.compute(
                    // @ts-ignore(TS2345): Argument of type 'number | ...' is not assignable to parameter of type 'number'.
                    x);
                })();
                const y_pos = (() => {
                    const { y } = position;
                    switch (y) {
                        case "top": return inset.top;
                        case "center": return inset.y_center;
                        case "bottom": return inset.bottom;
                    }
                    const y_mapper = (() => {
                        switch (this.model.y_units) {
                            case "data": return this.coordinates.y_scale;
                            case "screen": return bbox.y_screen;
                            case "view": return bbox.y_view;
                            case "percent": return bbox.y_percent;
                        }
                    })();
                    return y_mapper.compute(
                    // @ts-ignore(TS2345): Argument of type 'number | ...' is not assignable to parameter of type 'number'.
                    y);
                })();
                return { x: x_pos, y: y_pos };
            })();
            const anchor = (() => {
                const anchor = resolve.anchor(this.model.anchor);
                const x_anchor = (() => {
                    if (anchor.x == "auto") {
                        switch (position.x) {
                            case "left": return 0.0;
                            case "center": return 0.5;
                            case "right": return 1.0;
                            default: return 0.5;
                        }
                    }
                    else {
                        return anchor.x;
                    }
                })();
                const y_anchor = (() => {
                    if (anchor.y == "auto") {
                        switch (position.y) {
                            case "top": return 0.0;
                            case "center": return 0.5;
                            case "bottom": return 1.0;
                            default: return 0.5;
                        }
                    }
                    else {
                        return anchor.y;
                    }
                })();
                return { x: x_anchor, y: y_anchor };
            })();
            const width = border_width + padding + box_layout.bbox.width + padding + border_width;
            const height = border_width + padding + box_layout.bbox.height + padding + border_width;
            const sx = x - anchor.x * width;
            const sy = y - anchor.y * height;
            this._bbox = new bbox_1.BBox({ left: sx, top: sy, width, height });
        }
        _draw_box(ctx) {
            const { width, height } = this.bbox;
            ctx.beginPath();
            ctx.rect(0, 0, width, height);
            this.visuals.background_fill.apply(ctx);
            this.visuals.background_hatch.apply(ctx);
            this.visuals.border_line.apply(ctx);
        }
        _draw_axis(ctx) {
            this.axis_view.paint(ctx);
        }
        _draw_text(ctx, layout, location) {
            const { bbox } = layout;
            const [x_offset, y_offset] = (() => {
                const { orientation } = this.model;
                const horizontal = orientation == "horizontal";
                switch (location) {
                    case "left": return horizontal ? [0, 0] : [0, bbox.height];
                    case "right": return horizontal ? [0, 0] : [bbox.width, 0];
                    case "above": return [0, 0];
                    case "below": return [0, 0];
                }
            })();
            const { left, top } = bbox.translate(x_offset, y_offset);
            ctx.translate(left, top);
            layout.text.paint(ctx);
            ctx.translate(-left, -top);
        }
        _draw_label(ctx) {
            this._draw_text(ctx, this.label_layout, this.model.label_location);
        }
        _draw_title(ctx) {
            this._draw_text(ctx, this.title_layout, this.model.title_location);
        }
        _paint(ctx) {
            const { left, top } = this.bbox;
            ctx.translate(left, top);
            if (this.box_layout.visible) {
                this._draw_box(ctx);
            }
            if (this.axis_layout.visible) {
                this._draw_axis(ctx);
            }
            if (this.label_layout.visible) {
                this._draw_label(ctx);
            }
            if (this.title_layout.visible) {
                this._draw_title(ctx);
            }
            ctx.translate(-left, -top);
        }
    }
    exports.ScaleBarView = ScaleBarView;
    class ScaleBar extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ScaleBarView;
            this.mixins([
                ["background_", mixins.Fill],
                ["background_", mixins.Hatch],
                ["bar_", mixins.Line],
                ["border_", mixins.Line],
                ["label_", mixins.Text],
                ["title_", mixins.Text],
            ]);
            this.define(({ NonNegative, Float, Str, Ref, Or, Auto }) => ({
                anchor: [kinds_2.AutoAnchor, "auto"],
                bar_length: [NonNegative(Float), 0.2],
                bar_length_units: [LengthUnits, "screen"],
                dimensional: [Ref(dimensional_1.Dimensional), () => new dimensional_1.MetricLength()],
                label: [Str, "@{value} @{unit}"],
                label_align: [enums_1.Align, "center"],
                label_location: [enums_1.Location, "below"],
                label_standoff: [Float, 5],
                length_sizing: [LengthSizing, "adaptive"],
                location: [Position, "top_right"],
                margin: [Float, 10],
                orientation: [enums_1.Orientation, "horizontal"],
                padding: [Float, 10],
                range: [Or(Ref(range_1.Range), Auto), "auto"],
                ticker: [Ref(ticker_1.Ticker), () => new fixed_ticker_1.FixedTicker({ ticks: [] })],
                title: [Str, ""],
                title_align: [enums_1.Align, "center"],
                title_location: [enums_1.Location, "above"],
                title_standoff: [Float, 5],
                unit: [Str, "m"],
                x_units: [PositionUnits, "data"],
                y_units: [PositionUnits, "data"],
            }));
            this.override({
                background_fill_alpha: 0.95,
                background_fill_color: "#ffffff",
                bar_line_width: 2,
                border_line_alpha: 0.5,
                border_line_color: "#e5e5e5",
                border_line_width: 1,
                label_text_baseline: "middle",
                label_text_font_size: "13px",
                title_text_font_size: "13px",
                title_text_font_style: "italic",
            });
        }
    }
    exports.ScaleBar = ScaleBar;
},
/* models/annotations/dimensional.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    const object_1 = require(9) /* ../../core/util/object */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const { min } = Math;
    class Dimensional extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Nullable, List, Str, Float }) => ({
                ticks: [List(Float)],
                include: [Nullable(List(Str)), null],
                exclude: [List(Str), []],
            }));
        }
        compute(value, unit, exact) {
            const basis = (() => {
                const { include, exclude } = this;
                const basis = (0, object_1.entries)(this.get_basis())
                    .map(([name, [factor, tex_name, long_name]]) => ({ name, factor, tex_name, long_name }))
                    .filter(({ name }) => (include == null || include.includes(name)) && !exclude.includes(name));
                return (0, arrayable_1.sort_by)(basis, ({ factor }) => factor);
            })();
            const { ticks } = this;
            const found_unit = basis.find(({ name }) => name == unit);
            (0, assert_1.assert)(found_unit != null);
            const value_in_unit = value * found_unit.factor;
            const [new_unit, new_value] = (() => {
                const index = (0, arrayable_1.bisect_right_by)(basis, value_in_unit, ({ factor }) => factor);
                if (index > 0) {
                    const { name: new_unit, factor } = basis[index - 1];
                    const new_value = value_in_unit / factor;
                    return [new_unit, new_value];
                }
                else {
                    return [unit, value_in_unit];
                }
            })();
            exact = exact ?? ticks.length == 0;
            const preferred_value = (() => {
                if (exact) {
                    return new_value;
                }
                else {
                    const index = (0, arrayable_1.bisect_right)(ticks, new_value);
                    return ticks[min(index, ticks.length - 1)];
                }
            })();
            const preferred_value_raw = preferred_value * (value_in_unit / new_value);
            const scale_factor = (preferred_value_raw / value) / found_unit.factor;
            return {
                new_value: preferred_value,
                new_unit,
                scale_factor,
                exact,
            };
        }
    }
    exports.Dimensional = Dimensional;
    class CustomDimensional extends Dimensional {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Dict, Tuple, Float, Str, Or }) => ({
                basis: [Dict(Or(Tuple(Float, Str), Tuple(Float, Str, Str)))],
            }));
        }
        get_basis() {
            return this.basis;
        }
    }
    exports.CustomDimensional = CustomDimensional;
    class Metric extends Dimensional {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Str, Nullable }) => ({
                base_unit: [Str],
                full_unit: [Nullable(Str), null],
            }));
            this.override({
                ticks: [1, 2, 5, 10, 15, 20, 25, 50, 75, 100, 125, 150, 200, 250, 500, 750],
            });
        }
        static _metric_basis = [
            ["Q", 1e30, "Q", "quetta"],
            ["R", 1e27, "R", "ronna"],
            ["Y", 1e24, "Y", "yotta"],
            ["Z", 1e21, "Z", "zetta"],
            ["E", 1e18, "E", "exa"],
            ["P", 1e15, "P", "peta"],
            ["T", 1e12, "T", "tera"],
            ["G", 1e9, "G", "giga"],
            ["M", 1e6, "M", "mega"],
            ["k", 1e3, "k", "kilo"],
            ["h", 1e2, "h", "hecto"],
            ["", 1e0, "", ""],
            ["d", 1e-1, "d", "deci"],
            ["c", 1e-2, "c", "centi"],
            ["m", 1e-3, "m", "milli"],
            ["µ", 1e-6, "\\mu", "micro"],
            ["n", 1e-9, "n", "nano"],
            ["p", 1e-12, "p", "pico"],
            ["f", 1e-15, "f", "femto"],
            ["a", 1e-18, "a", "atto"],
            ["z", 1e-21, "z", "zepto"],
            ["y", 1e-24, "y", "yocto"],
            ["r", 1e-27, "r", "ronto"],
            ["q", 1e-30, "q", "quecto"],
        ];
        get_basis() {
            const { base_unit, full_unit } = this;
            const basis = {};
            for (const [prefix, factor, tex_prefix, long_prefix] of Metric._metric_basis) {
                const name = `${prefix}${base_unit}`;
                const tex_name = `${tex_prefix}${base_unit}`;
                const long_name = full_unit != null ? `${long_prefix}${full_unit}` : undefined;
                basis[name] = [factor, tex_name, long_name];
            }
            return basis;
        }
    }
    exports.Metric = Metric;
    class ReciprocalMetric extends Metric {
        constructor(attrs) {
            super(attrs);
        }
        get_basis() {
            const basis = super.get_basis();
            const reciprocal_basis = {};
            for (const [name, [factor, tex_name]] of (0, object_1.entries)(basis)) {
                reciprocal_basis[`${name}⁻1`] = [factor ** -1, `${tex_name}^{-1}`];
            }
            return reciprocal_basis;
        }
    }
    exports.ReciprocalMetric = ReciprocalMetric;
    class MetricLength extends Metric {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.override({
                base_unit: "m",
                exclude: ["dm", "hm"],
            });
        }
    }
    exports.MetricLength = MetricLength;
    class ReciprocalMetricLength extends ReciprocalMetric {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.override({
                base_unit: "m",
                exclude: ["dm", "hm"],
            });
        }
    }
    exports.ReciprocalMetricLength = ReciprocalMetricLength;
    class ImperialLength extends CustomDimensional {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.override({
                basis: {
                    in: [1 / 12, "in", "inch"],
                    ft: [1, "ft", "foot"],
                    yd: [3, "yd", "yard"],
                    ch: [66, "ch", "chain"],
                    fur: [660, "fur", "furlong"],
                    mi: [5280, "mi", "mile"],
                    lea: [15840, "lea", "league"],
                },
                ticks: [1, 3, 6, 12, 60],
            });
        }
    }
    exports.ImperialLength = ImperialLength;
    class Angular extends CustomDimensional {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.override({
                basis: {
                    "°": [1, "^\\circ", "degree"],
                    "'": [1 / 60, "^\\prime", "minute"],
                    "''": [1 / 3600, "^{\\prime\\prime}", "second"],
                },
                ticks: [1, 3, 6, 12, 60, 120, 240, 360],
            });
        }
    }
    exports.Angular = Angular;
},
/* models/annotations/size_bar.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const base_bar_1 = require(374) /* ./base_bar */;
    const radial_glyph_1 = require(375) /* ../glyphs/radial_glyph */;
    const glyph_renderer_1 = require(302) /* ../renderers/glyph_renderer */;
    const canvas_1 = require(71) /* ../../core/util/canvas */;
    const scales_1 = require(339) /* ../scales */;
    const range1d_1 = require(111) /* ../ranges/range1d */;
    const linear_axis_1 = require(277) /* ../axes/linear_axis */;
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    const uniforms = tslib_1.__importStar(require(40) /* ../../core/uniforms */);
    const column_data_source_1 = require(147) /* ../sources/column_data_source */;
    const types_1 = require(8) /* ../../core/util/types */;
    const title_1 = require(255) /* ../annotations/title */;
    const plot_1 = require(376) /* ../plots/plot */;
    const basic_tick_formatter_1 = require(279) /* ../formatters/basic_tick_formatter */;
    const adaptive_ticker_1 = require(281) /* ../tickers/adaptive_ticker */;
    const fixed_ticker_1 = require(293) /* ../tickers/fixed_ticker */;
    const array_1 = require(10) /* ../../core/util/array */;
    const logging_1 = require(11) /* ../../core/logging */;
    const circle_1 = require(413) /* ../glyphs/circle */;
    const bbox_1 = require(62) /* ../../core/util/bbox */;
    const border_1 = require(342) /* ../../core/layout/border */;
    class InternalBorderLayout extends border_1.BorderLayout {
        offset_position = { x: 0, y: 0 };
        set_geometry(viewport) {
            const { outer, inner } = this._compute(viewport);
            this.offset_position = { x: viewport.x, y: viewport.y };
            super.set_geometry(outer, inner);
        }
    }
    class InternalPlotView extends plot_1.PlotView {
        initialize() {
            super.initialize();
            this._range_manager.warn_initial_ranges = false;
        }
        _make_layout() {
            return new InternalBorderLayout();
        }
        _after_resize() { }
    }
    class InternalPlot extends plot_1.Plot {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = InternalPlotView;
        }
    }
    class SizeBarView extends base_bar_1.BaseBarView {
        _major_range;
        _major_scale;
        _minor_range;
        _minor_scale;
        _size_bar;
        _size_bar_view;
        _data_source;
        _major_axis;
        _major_ticker;
        _major_formatter;
        get align() {
            const { location } = this.model;
            if ((0, types_1.isString)(location)) {
                switch (location) {
                    case "top_left": return { v: "start", h: "start" };
                    case "top":
                    case "top_center": return { v: "start", h: "center" };
                    case "top_right": return { v: "start", h: "end" };
                    case "bottom_left": return { v: "end", h: "start" };
                    case "bottom":
                    case "bottom_center": return { v: "end", h: "center" };
                    case "bottom_right": return { v: "end", h: "end" };
                    case "left":
                    case "center_left": return { v: "center", h: "start" };
                    case "center":
                    case "center_center": return { v: "center", h: "center" };
                    case "right":
                    case "center_right": return { v: "center", h: "end" };
                }
            }
            else {
                return { v: "end", h: "start" };
            }
        }
        get orientation() {
            const { orientation } = this.model;
            const { align } = this;
            if (orientation == "auto") {
                if (this.panel != null) {
                    return this.panel.is_horizontal ? "horizontal" : "vertical";
                }
                else {
                    if (align.h == "start" || align.h == "end" || ( /*align.h == "center" &&*/align.v == "center")) {
                        return "vertical";
                    }
                    else {
                        return "horizontal";
                    }
                }
            }
            else {
                return orientation;
            }
        }
        initialize() {
            super.initialize();
            const { orientation } = this;
            this._major_range = new range1d_1.Range1d();
            this._major_scale = new scales_1.LinearScale();
            this._minor_range = new range1d_1.Range1d();
            this._minor_scale = new scales_1.LinearScale();
            const renderer = this.renderer ?? new glyph_renderer_1.GlyphRenderer({ glyph: new circle_1.Circle() });
            const Cls = renderer.glyph.constructor; // expression not constructible
            const glyph = new Cls({
                x: { field: "x" },
                y: { field: "y" },
                radius: { field: "s", units: "screen" },
                ...mixins.attrs_of(this.model, "glyph_", mixins.LineVector),
                ...mixins.attrs_of(this.model, "glyph_", mixins.FillVector),
                ...mixins.attrs_of(this.model, "glyph_", mixins.HatchVector),
            });
            this._data_source = new column_data_source_1.ColumnDataSource({
                data: {
                    x: [],
                    y: [],
                    s: [],
                },
            });
            const circle_renderer = new glyph_renderer_1.GlyphRenderer({ data_source: this._data_source, glyph });
            const { ticker, formatter } = this.model;
            this._major_ticker = ticker != "auto" ? ticker : new fixed_ticker_1.FixedTicker({ ticks: [] });
            this._major_formatter = formatter != "auto" ? formatter : new basic_tick_formatter_1.BasicTickFormatter();
            this._major_axis = new linear_axis_1.LinearAxis({
                ticker: this._major_ticker,
                formatter: this._major_formatter,
                axis_line_color: null,
                major_label_standoff: this.model.label_standoff,
                major_tick_in: this.model.major_tick_in,
                major_tick_out: this.model.major_tick_out,
                minor_tick_in: this.model.minor_tick_in,
                minor_tick_out: this.model.minor_tick_out,
                major_label_overrides: this.model.major_label_overrides,
                major_label_policy: this.model.major_label_policy,
                ...mixins.attrs_of(this.model, "major_label_", mixins.Text, true),
                ...mixins.attrs_of(this.model, "major_tick_", mixins.Line, true),
                ...mixins.attrs_of(this.model, "minor_tick_", mixins.Line, true),
            });
            const { width, height } = this.model;
            const title = new title_1.Title({
                text: this.model.title ?? undefined,
                standoff: this.model.title_standoff,
                ...mixins.attrs_of(this.model, "title_", mixins.Text, false),
            });
            const plot_attrs = {
                renderers: [circle_renderer],
                toolbar_location: null,
                title,
                ...mixins.attrs_of(this.model, "background_", mixins.Fill, true),
                ...mixins.attrs_of(this.model, "background_", mixins.Hatch, true),
                ...mixins.attrs_of(this.model, "border_", mixins.Line, true),
                ...mixins.attrs_of(this.model, "bar_", mixins.Line, "outline_"),
            };
            switch (orientation) {
                case "horizontal": {
                    this._size_bar = new InternalPlot({
                        width_policy: width == "max" ? "max" : "fit",
                        height_policy: height == "max" ? "max" : "fit",
                        frame_width: width == "max" ? undefined : width,
                        frame_height: height == "max" ? undefined : height,
                        below: [this._major_axis],
                        x_range: this._major_range,
                        y_range: this._minor_range,
                        x_scale: this._major_scale,
                        y_scale: this._minor_scale,
                        ...plot_attrs,
                    });
                    break;
                }
                case "vertical": {
                    this._size_bar = new InternalPlot({
                        width_policy: height == "max" ? "max" : "fit",
                        height_policy: width == "max" ? "max" : "fit",
                        frame_width: height == "max" ? undefined : height,
                        frame_height: width == "max" ? undefined : width,
                        right: [this._major_axis],
                        x_range: this._minor_range,
                        y_range: this._major_range,
                        x_scale: this._minor_scale,
                        y_scale: this._major_scale,
                        ...plot_attrs,
                    });
                    break;
                }
            }
        }
        get computed_elements() {
            return [...super.computed_elements, this._size_bar];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            this._size_bar_view = this._element_views.get(this._size_bar);
        }
        _last_bbox = new bbox_1.BBox();
        update_layout() {
            this.layout = this._size_bar_view.layout;
            this.layout.on_resize((outer) => {
                if (!outer.equals(this._last_bbox)) {
                    this._last_bbox = outer;
                    this.parent.request_layout(true);
                }
            });
        }
        get renderer() {
            const { renderer } = this.model;
            if (renderer == "auto") {
                const renderers = this.plot_view.model.renderers.filter((r) => {
                    return r instanceof glyph_renderer_1.GlyphRenderer && r.glyph instanceof radial_glyph_1.RadialGlyph;
                });
                switch (renderers.length) {
                    case 0: {
                        logging_1.logger.warn("can't find any radial glyph renderers");
                        return null;
                    }
                    case 1: {
                        return renderers[0];
                    }
                    default: {
                        logging_1.logger.warn("found multiple radial glyph renderers; choosing the first one");
                        return renderers[0];
                    }
                }
            }
            else {
                return renderer;
            }
        }
        get glyph_view() {
            const { renderer } = this;
            if (renderer == null) {
                return null;
            }
            else {
                const rv = this.plot_view.views.get_one(renderer);
                return rv.glyph_view;
            }
        }
        _paint(_ctx) {
            const { glyph_view } = this;
            if (glyph_view == null) {
                return;
            }
            const bounds = (() => {
                const { bounds } = this.model;
                return bounds == "auto" ? [-Infinity, Infinity] : bounds;
            })();
            const r_min = Math.max(uniforms.min(glyph_view.radius), bounds[0]);
            const r_max = Math.min(uniforms.max(glyph_view.radius), bounds[1]);
            const equal = r_max == r_min;
            const eps = 0.000001;
            const start = equal ? Math.max(r_min - eps, 0) : r_min;
            const end = equal ? r_max + eps : r_max;
            const n_ticks = equal ? 1 : 5;
            const t = new adaptive_ticker_1.AdaptiveTicker({ desired_num_ticks: n_ticks });
            const ticks = t.get_ticks(start == 0 ? end * eps : start, end, new range1d_1.Range1d(), NaN);
            const radii = ticks.major;
            if (this.model.ticker == "auto" && this._major_ticker instanceof fixed_ticker_1.FixedTicker) {
                this._major_ticker.ticks = radii;
            }
            const x = radii;
            const y = (0, array_1.repeat)(0, x.length);
            const s = (() => {
                if (glyph_view.model.properties.radius.units == "data") {
                    const sradius_x = () => glyph_view.sdist(glyph_view.renderer.xscale, (0, array_1.repeat)(0, radii.length), new uniforms.UniformVector(radii));
                    const sradius_y = () => glyph_view.sdist(glyph_view.renderer.yscale, (0, array_1.repeat)(0, radii.length), new uniforms.UniformVector(radii));
                    const { radius_dimension } = glyph_view.model;
                    switch (radius_dimension) {
                        case "x": {
                            return sradius_x();
                        }
                        case "y": {
                            return sradius_y();
                        }
                        case "min":
                        case "max": {
                            return (0, array_1.elementwise)(sradius_x(), sradius_y(), Math[radius_dimension]);
                        }
                    }
                }
                else {
                    return radii;
                }
            })();
            this._major_range.setv({ start, end });
            this._minor_range.setv({ start: -end, end });
            this._data_source.data = (() => {
                switch (this.orientation) {
                    case "horizontal": return { x, y, s };
                    case "vertical": return { x: y, y: x, s };
                }
            })();
        }
        [canvas_1.exportable] = true;
        export(type = "auto", hidpi = true) {
            return this._size_bar_view.export(type, hidpi);
        }
        get bbox() {
            const { bbox, offset_position: { x, y } } = this.layout;
            return bbox.translate(x, y);
        }
    }
    exports.SizeBarView = SizeBarView;
    class SizeBar extends base_bar_1.BaseBar {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = SizeBarView;
            this.mixins([
                ["glyph_", mixins.LineVector],
                ["glyph_", mixins.FillVector],
                ["glyph_", mixins.HatchVector],
            ]);
            this.override({
                glyph_line_color: null,
            });
            this.define(({ Ref, Auto, Or, Float, Tuple }) => ({
                renderer: [Or(Ref(glyph_renderer_1.GlyphRenderer), Auto), "auto"],
                bounds: [Or(Tuple(Float, Float), Auto), "auto"],
            }));
        }
    }
    exports.SizeBar = SizeBar;
},
/* models/annotations/base_bar.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(96) /* ./annotation */;
    const axis_1 = require(272) /* ../axes/axis */;
    const fixed_ticker_1 = require(293) /* ../tickers/fixed_ticker */;
    const tick_formatter_1 = require(275) /* ../formatters/tick_formatter */;
    const labeling_1 = require(276) /* ../policies/labeling */;
    const base_text_1 = require(258) /* ../text/base_text */;
    const enums_1 = require(21) /* ../../core/enums */;
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    class BaseBarView extends annotation_1.AnnotationView {
    }
    exports.BaseBarView = BaseBarView;
    class BaseBar extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.mixins([
                ["title_", mixins.Text],
                ["major_label_", mixins.Text],
                ["major_tick_", mixins.Line],
                ["minor_tick_", mixins.Line],
                ["background_", mixins.Fill],
                ["background_", mixins.Hatch],
                ["border_", mixins.Line],
                ["bar_", mixins.Line],
            ]);
            this.define(({ Float, Str, Tuple, Or, Ref, Enum, Auto, Nullable }) => ({
                location: [Or(enums_1.Anchor, Tuple(Float, Float)), "top_right"],
                orientation: [Or(enums_1.Orientation, Auto), "auto"],
                width: [Or(Float, Enum("max")), 200],
                height: [Or(Float, Enum("max")), 50],
                margin: [Float, 30],
                padding: [Float, 10],
                title: [Nullable(Or(Str, Ref(base_text_1.BaseText))), null],
                title_standoff: [Float, 2],
                ticker: [Or(Ref(fixed_ticker_1.FixedTicker), Auto), "auto"],
                formatter: [Or(Ref(tick_formatter_1.TickFormatter), Auto), "auto"],
                major_label_overrides: [axis_1.LabelOverrides, new Map()],
                major_label_policy: [Ref(labeling_1.LabelingPolicy), () => new labeling_1.NoOverlap()],
                label_standoff: [Float, 5],
                major_tick_in: [Float, 5],
                major_tick_out: [Float, 0],
                minor_tick_in: [Float, 0],
                minor_tick_out: [Float, 0],
            }));
            this.override({
                background_fill_color: "#ffffff",
                background_fill_alpha: 0.95,
                border_line_color: null,
                bar_line_color: null,
                major_label_text_font_size: "11px",
                major_tick_line_color: "black",
                minor_tick_line_color: null,
                title_text_font_size: "13px",
                title_text_font_style: "italic",
            });
        }
    }
    exports.BaseBar = BaseBar;
},
/* models/glyphs/radial_glyph.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(305) /* ./xy_glyph */;
    const glyph_1 = require(306) /* ./glyph */;
    const property_mixins_1 = require(95) /* ../../core/property_mixins */;
    const types_1 = require(25) /* ../../core/types */;
    const enums_1 = require(21) /* ../../core/enums */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const array_1 = require(10) /* ../../core/util/array */;
    class RadialGlyphView extends xy_glyph_1.XYGlyphView {
        _index_data(index) {
            const { x, y, radius, data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const x_i = x[i];
                const y_i = y[i];
                const r_i = radius.get(i);
                index.add_rect(x_i - r_i, y_i - r_i, x_i + r_i, y_i + r_i);
            }
        }
        _map_data() {
            this._define_or_inherit_attr("sradius", () => {
                if (this.model.properties.radius.units == "data") {
                    const sradius_x = () => this.sdist(this.renderer.xscale, this.x, this.radius);
                    const sradius_y = () => this.sdist(this.renderer.yscale, this.y, this.radius);
                    const { radius_dimension } = this.model;
                    switch (radius_dimension) {
                        case "x": {
                            return this.inherited_x && this.inherited_radius ? glyph_1.inherit : sradius_x();
                        }
                        case "y": {
                            return this.inherited_y && this.inherited_radius ? glyph_1.inherit : sradius_y();
                        }
                        case "min":
                        case "max": {
                            if (this.inherited_x && this.inherited_y && this.inherited_radius) {
                                return glyph_1.inherit;
                            }
                            else {
                                return (0, array_1.elementwise)(sradius_x(), sradius_y(), Math[radius_dimension]);
                            }
                        }
                    }
                }
                else {
                    return this.inherited_sradius ? glyph_1.inherit : (0, types_1.to_screen)(this.radius);
                }
            });
        }
        _mask_data() {
            const { frame } = this.renderer.plot_view;
            const shr = frame.x_target;
            const svr = frame.y_target;
            let hr;
            let vr;
            if (this.model.properties.radius.units == "data") {
                hr = shr.map((x) => this.renderer.xscale.invert(x)).widen(this.max_radius);
                vr = svr.map((y) => this.renderer.yscale.invert(y)).widen(this.max_radius);
            }
            else {
                hr = shr.widen(this.max_radius).map((x) => this.renderer.xscale.invert(x));
                vr = svr.widen(this.max_radius).map((y) => this.renderer.yscale.invert(y));
            }
            return this.index.indices({
                x0: hr.start, x1: hr.end,
                y0: vr.start, y1: vr.end,
            });
        }
        draw_legend_for_index(ctx, { x0, y0, x1, y1 }, index) {
            // using objects like this is wonky, since the keys are coerced to strings, but it works
            const len = index + 1;
            const sx = new Array(len);
            sx[index] = (x0 + x1) / 2;
            const sy = new Array(len);
            sy[index] = (y0 + y1) / 2;
            const sradius = new Array(len);
            sradius[index] = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.2;
            this._paint(ctx, [index], { sx, sy, sradius });
        }
    }
    exports.RadialGlyphView = RadialGlyphView;
    class RadialGlyph extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
            this.define(() => ({
                radius: [p.DistanceSpec],
                radius_dimension: [enums_1.RadiusDimension, "x"],
            }));
        }
    }
    exports.RadialGlyph = RadialGlyph;
},
/* models/plots/plot.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const signaling_1 = require(17) /* ../../core/signaling */;
    const enums_1 = require(21) /* ../../core/enums */;
    const array_1 = require(10) /* ../../core/util/array */;
    const set_1 = require(45) /* ../../core/util/set */;
    const types_1 = require(8) /* ../../core/util/types */;
    const layout_dom_1 = require(131) /* ../layouts/layout_dom */;
    const axis_1 = require(272) /* ../axes/axis */;
    const grid_1 = require(377) /* ../grids/grid */;
    const annotation_1 = require(96) /* ../annotations/annotation */;
    const title_1 = require(255) /* ../annotations/title */;
    const linear_scale_1 = require(113) /* ../scales/linear_scale */;
    const toolbar_1 = require(378) /* ../tools/toolbar */;
    const html_1 = require(133) /* ../dom/html */;
    const range_1 = require(110) /* ../ranges/range */;
    const scale_1 = require(108) /* ../scales/scale */;
    const column_data_source_1 = require(147) /* ../sources/column_data_source */;
    const renderer_1 = require(98) /* ../renderers/renderer */;
    const data_renderer_1 = require(303) /* ../renderers/data_renderer */;
    const glyph_renderer_1 = require(302) /* ../renderers/glyph_renderer */;
    const tool_1 = require(379) /* ../tools/tool */;
    const data_range1d_1 = require(118) /* ../ranges/data_range1d */;
    const styled_element_1 = require(56) /* ../ui/styled_element */;
    const plot_canvas_1 = require(398) /* ./plot_canvas */;
    __esExport("PlotView", plot_canvas_1.PlotView);
    class Plot extends layout_dom_1.LayoutDOM {
        use_map = false;
        reset = new signaling_1.Signal0(this, "reset");
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = plot_canvas_1.PlotView;
            this.mixins([
                ["outline_", mixins.Line],
                ["background_", mixins.Fill],
                ["background_", mixins.Hatch],
                ["border_", mixins.Line],
                ["border_", mixins.Fill],
                ["border_", mixins.Hatch],
            ]);
            this.define(({ Bool, Float, Str, List, Dict, Or, Ref, Null, Nullable, Struct, Opt }) => ({
                toolbar: [Ref(toolbar_1.Toolbar), () => new toolbar_1.Toolbar()],
                toolbar_location: [Nullable(enums_1.Location), "right"],
                toolbar_sticky: [Bool, true],
                toolbar_inner: [Bool, false],
                frame_width: [Nullable(Float), null],
                frame_height: [Nullable(Float), null],
                frame_align: [Or(Bool, Struct({ left: Opt(Bool), right: Opt(Bool), top: Opt(Bool), bottom: Opt(Bool) })), true],
                // revise this when https://github.com/microsoft/TypeScript/pull/42425 is merged
                title: [Or(Ref(title_1.Title), Str, Null), "", {
                        convert: (title) => (0, types_1.isString)(title) ? new title_1.Title({ text: title }) : title,
                    }],
                title_location: [Nullable(enums_1.Location), "above"],
                above: [List(Or(Ref(annotation_1.Annotation), Ref(axis_1.Axis), Ref(styled_element_1.StyledElement))), []],
                below: [List(Or(Ref(annotation_1.Annotation), Ref(axis_1.Axis), Ref(styled_element_1.StyledElement))), []],
                left: [List(Or(Ref(annotation_1.Annotation), Ref(axis_1.Axis), Ref(styled_element_1.StyledElement))), []],
                right: [List(Or(Ref(annotation_1.Annotation), Ref(axis_1.Axis), Ref(styled_element_1.StyledElement))), []],
                center: [List(Or(Ref(annotation_1.Annotation), Ref(grid_1.Grid), Ref(styled_element_1.StyledElement))), []],
                renderers: [List(Ref(renderer_1.Renderer)), []],
                x_range: [Ref(range_1.Range), () => new data_range1d_1.DataRange1d()],
                y_range: [Ref(range_1.Range), () => new data_range1d_1.DataRange1d()],
                x_scale: [Ref(scale_1.Scale), () => new linear_scale_1.LinearScale()],
                y_scale: [Ref(scale_1.Scale), () => new linear_scale_1.LinearScale()],
                extra_x_ranges: [Dict(Ref(range_1.Range)), {}],
                extra_y_ranges: [Dict(Ref(range_1.Range)), {}],
                extra_x_scales: [Dict(Ref(scale_1.Scale)), {}],
                extra_y_scales: [Dict(Ref(scale_1.Scale)), {}],
                window_axis: [enums_1.WindowAxis, "none"],
                lod_factor: [Float, 10],
                lod_interval: [Float, 300],
                lod_threshold: [Nullable(Float), 2000],
                lod_timeout: [Float, 500],
                hidpi: [Bool, true],
                output_backend: [enums_1.OutputBackend, "canvas"],
                min_border: [Nullable(Float), 5],
                min_border_top: [Nullable(Float), null],
                min_border_left: [Nullable(Float), null],
                min_border_bottom: [Nullable(Float), null],
                min_border_right: [Nullable(Float), null],
                inner_width: [Float, p.unset, { readonly: true }],
                inner_height: [Float, p.unset, { readonly: true }],
                outer_width: [Float, p.unset, { readonly: true }],
                outer_height: [Float, p.unset, { readonly: true }],
                match_aspect: [Bool, false],
                aspect_scale: [Float, 1],
                reset_policy: [enums_1.ResetPolicy, "standard"],
                hold_render: [Bool, false],
                attribution: [List(Or(Str, Ref(html_1.HTML))), []],
            }));
            this.override({
                width: 600,
                height: 600,
                outline_line_color: "#e5e5e5",
                border_line_color: null,
                border_fill_color: "#ffffff",
                background_fill_color: "#ffffff",
                context_menu: "auto",
            });
        }
        add_layout(renderer, side = "center") {
            this.remove_layout(renderer);
            const renderers = this.properties[side].get_value();
            this.setv({ [side]: [...renderers, renderer] });
        }
        remove_layout(renderer) {
            (0, array_1.remove)(this.left, renderer);
            (0, array_1.remove)(this.right, renderer);
            (0, array_1.remove)(this.above, renderer);
            (0, array_1.remove)(this.below, renderer);
            (0, array_1.remove)(this.center, renderer);
        }
        get data_renderers() {
            return this.renderers.filter((r) => r instanceof data_renderer_1.DataRenderer);
        }
        add_renderers(...renderers) {
            this.renderers = [...this.renderers, ...renderers];
        }
        add_glyph(glyph, source = new column_data_source_1.ColumnDataSource(), attrs = {}) {
            const renderer = new glyph_renderer_1.GlyphRenderer({ ...attrs, data_source: source, glyph });
            this.add_renderers(renderer);
            return renderer;
        }
        add_tools(...tools) {
            const computed_tools = tools.map((tool) => tool instanceof tool_1.Tool ? tool : tool_1.Tool.from_string(tool));
            this.toolbar.tools = [...this.toolbar.tools, ...computed_tools];
        }
        remove_tools(...tools) {
            this.toolbar.tools = [...(0, set_1.difference)(new Set(this.toolbar.tools), new Set(tools))];
        }
        get panels() {
            return [...this.side_panels, ...this.center];
        }
        get side_panels() {
            const { above, below, left, right } = this;
            return (0, array_1.concat)([above, below, left, right]);
        }
    }
    exports.Plot = Plot;
},
/* models/grids/grid.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const axes_1 = require(348) /* ../axes */;
    const guide_renderer_1 = require(273) /* ../renderers/guide_renderer */;
    const ticker_1 = require(274) /* ../tickers/ticker */;
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    const types_1 = require(8) /* ../../core/util/types */;
    class GridView extends guide_renderer_1.GuideRendererView {
        _paint(ctx) {
            ctx.save();
            this._draw_regions(ctx);
            this._draw_minor_grids(ctx);
            this._draw_grids(ctx);
            ctx.restore();
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.request_paint());
        }
        _draw_regions(ctx) {
            if (!this.visuals.band_fill.doit && !this.visuals.band_hatch.doit) {
                return;
            }
            const [xs, ys] = this.grid_coords("major", false);
            for (let i = 0; i < xs.length - 1; i++) {
                if (i % 2 != 1) {
                    continue;
                }
                const [sx0, sy0] = this.coordinates.map_to_screen(xs[i], ys[i]);
                const [sx1, sy1] = this.coordinates.map_to_screen(xs[i + 1], ys[i + 1]);
                ctx.beginPath();
                ctx.rect(sx0[0], sy0[0], sx1[1] - sx0[0], sy1[1] - sy0[0]);
                this.visuals.band_fill.apply(ctx);
                this.visuals.band_hatch.apply(ctx);
            }
        }
        _draw_grids(ctx) {
            if (!this.visuals.grid_line.doit) {
                return;
            }
            const [xs, ys] = this.grid_coords("major");
            this._draw_grid_helper(ctx, this.visuals.grid_line, xs, ys);
        }
        _draw_minor_grids(ctx) {
            if (!this.visuals.minor_grid_line.doit) {
                return;
            }
            const [xs, ys] = this.grid_coords("minor");
            this._draw_grid_helper(ctx, this.visuals.minor_grid_line, xs, ys);
        }
        _draw_grid_helper(ctx, visuals, xs, ys) {
            visuals.set_value(ctx);
            ctx.beginPath();
            for (let i = 0; i < xs.length; i++) {
                const [sx, sy] = this.coordinates.map_to_screen(xs[i], ys[i]);
                ctx.moveTo(Math.round(sx[0]), Math.round(sy[0]));
                for (let i = 1; i < sx.length; i++) {
                    ctx.lineTo(Math.round(sx[i]), Math.round(sy[i]));
                }
            }
            ctx.stroke();
        }
        // {{{ TODO: state
        ranges() {
            const i = this.model.dimension;
            const j = 1 - i;
            const { ranges } = this.coordinates;
            return [ranges[i], ranges[j]];
        }
        computed_bounds() {
            const [range] = this.ranges();
            const user_bounds = this.model.bounds;
            const range_bounds = [range.min, range.max];
            let start;
            let end;
            if ((0, types_1.isArray)(user_bounds)) {
                start = Math.min(user_bounds[0], user_bounds[1]);
                end = Math.max(user_bounds[0], user_bounds[1]);
                if (start < range_bounds[0]) {
                    start = range_bounds[0];
                }
                // XXX:
                //else if (start > range_bounds[1])
                //  start = null
                if (end > range_bounds[1]) {
                    end = range_bounds[1];
                }
                // XXX:
                //else if (end < range_bounds[0])
                //  end = null
            }
            else {
                [start, end] = range_bounds;
                for (const axis_view of this.plot_view.axis_views) {
                    if (axis_view.dimension == this.model.dimension
                        && axis_view.model.x_range_name == this.model.x_range_name
                        && axis_view.model.y_range_name == this.model.y_range_name) {
                        [start, end] = axis_view.computed_bounds;
                    }
                }
            }
            return [start, end];
        }
        grid_coords(location, exclude_ends = true) {
            const i = this.model.dimension;
            const j = 1 - i;
            const [range, cross_range] = this.ranges();
            const [start, end] = (() => {
                const [start, end] = this.computed_bounds();
                return [Math.min(start, end), Math.max(start, end)];
            })();
            const coords = [[], []];
            // TODO: (bev) using cross_range.min for cross_loc is a bit of a cheat. Since we
            // currently only support "straight line" grids, this should be OK for now. If
            // we ever want to support "curved" grids, e.g. for some projections, we may
            // have to communicate more than just a single cross location.
            const ticker = this.model.get_ticker();
            if (ticker == null) {
                return coords;
            }
            const ticks = ticker.get_ticks(start, end, range, cross_range.min)[location];
            const min = range.min;
            const max = range.max;
            const [cmin, cmax] = (() => {
                const { cross_bounds } = this.model;
                if (cross_bounds == "auto") {
                    return [cross_range.min, cross_range.max];
                }
                else {
                    return cross_bounds;
                }
            })();
            if (!exclude_ends) {
                if (ticks[0] != min) {
                    ticks.splice(0, 0, min);
                }
                if (ticks[ticks.length - 1] != max) {
                    ticks.push(max);
                }
            }
            for (let ii = 0; ii < ticks.length; ii++) {
                if ((ticks[ii] == min || ticks[ii] == max) && exclude_ends) {
                    continue;
                }
                const dim_i = [];
                const dim_j = [];
                const N = 2;
                for (let n = 0; n < N; n++) {
                    const loc = cmin + (cmax - cmin) / (N - 1) * n;
                    dim_i.push(ticks[ii]);
                    dim_j.push(loc);
                }
                coords[i].push(dim_i);
                coords[j].push(dim_j);
            }
            return coords;
        }
    }
    exports.GridView = GridView;
    class Grid extends guide_renderer_1.GuideRenderer {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = GridView;
            this.mixins([
                ["grid_", mixins.Line],
                ["minor_grid_", mixins.Line],
                ["band_", mixins.Fill],
                ["band_", mixins.Hatch],
            ]);
            this.define(({ Float, Auto, Enum, Ref, Tuple, Or, Nullable }) => ({
                bounds: [Or(Tuple(Float, Float), Auto), "auto"],
                cross_bounds: [Or(Tuple(Float, Float), Auto), "auto"],
                dimension: [Enum(0, 1), 0],
                axis: [Nullable(Ref(axes_1.Axis)), null],
                ticker: [Nullable(Ref(ticker_1.Ticker)), null],
            }));
            this.override({
                level: "underlay",
                band_fill_color: null,
                band_fill_alpha: 0,
                grid_line_color: "#e5e5e5",
                minor_grid_line_color: null,
            });
        }
        get_ticker() {
            if (this.ticker != null) {
                return this.ticker;
            }
            if (this.axis != null) {
                return this.axis.ticker;
            }
            return null;
        }
    }
    exports.Grid = Grid;
},
/* models/tools/toolbar.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const logging_1 = require(11) /* ../../core/logging */;
    const dom_1 = require(61) /* ../../core/dom */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const ui_element_1 = require(55) /* ../ui/ui_element */;
    const enums_1 = require(21) /* ../../core/enums */;
    const array_1 = require(10) /* ../../core/util/array */;
    const iterator_1 = require(15) /* ../../core/util/iterator */;
    const object_1 = require(9) /* ../../core/util/object */;
    const types_1 = require(8) /* ../../core/util/types */;
    const tool_1 = require(379) /* ./tool */;
    const tool_proxy_1 = require(383) /* ./tool_proxy */;
    const tool_group_1 = require(384) /* ./tool_group */;
    const tool_button_1 = require(385) /* ./tool_button */;
    const gesture_tool_1 = require(390) /* ./gestures/gesture_tool */;
    const inspect_tool_1 = require(392) /* ./inspectors/inspect_tool */;
    const action_tool_1 = require(393) /* ./actions/action_tool */;
    const help_tool_1 = require(395) /* ./actions/help_tool */;
    const menus_1 = require(380) /* ../ui/menus */;
    const menus_2 = require(387) /* ../../core/util/menus */;
    const signaling_1 = require(17) /* ../../core/signaling */;
    const version_1 = require(3) /* ../../version */;
    const toolbar_css_1 = tslib_1.__importStar(require(396) /* ../../styles/toolbar.css */), toolbars = toolbar_css_1;
    const logo_css_1 = tslib_1.__importStar(require(397) /* ../../styles/logo.css */), logos = logo_css_1;
    const icons_css_1 = tslib_1.__importDefault(require(76) /* ../../styles/icons.css */);
    class ToolbarView extends ui_element_1.UIElementView {
        _tool_button_views = new Map();
        _tool_buttons;
        _items = [];
        get tool_buttons() {
            return this._tool_buttons.flat();
        }
        get tool_button_views() {
            return this.tool_buttons.map((tb) => this._tool_button_views.get(tb)).filter((view) => view != null);
        }
        _overflow_menu;
        _overflow_el;
        get overflow_el() {
            return this._overflow_el;
        }
        _visible = null;
        get visible() {
            return !this.model.visible ? false : (!this.model.autohide || (this._visible ?? false));
        }
        children_views() {
            return [...super.children_views(), ...this._tool_button_views.values()];
        }
        has_finished() {
            if (!super.has_finished()) {
                return false;
            }
            for (const child_view of this._tool_button_views.values()) {
                if (!child_view.has_finished()) {
                    return false;
                }
            }
            return true;
        }
        initialize() {
            super.initialize();
            const { location } = this.model;
            const reversed = location == "left" || location == "above";
            const orientation = this.model.horizontal ? "vertical" : "horizontal";
            this._overflow_menu = new menus_2.ContextMenu([], {
                target: this.el,
                orientation,
                reversed,
                prevent_hide: (event) => {
                    return event.composedPath().includes(this._overflow_el);
                },
            });
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._build_tool_button_views();
        }
        connect_signals() {
            super.connect_signals();
            const { buttons, tools, location, autohide, group, group_types } = this.model.properties;
            this.on_change([buttons, tools, group, group_types], async () => {
                await this._build_tool_button_views();
                this.rerender();
            });
            this.on_change(location, () => {
                this.rerender();
            });
            this.on_change(autohide, () => {
                this._on_visible_change();
            });
            this.on_transitive_change(tools, () => {
                this.rerender();
            }, {
                signal: (obj) => obj.properties.visible.change,
            });
        }
        stylesheets() {
            return [...super.stylesheets(), toolbar_css_1.default, logo_css_1.default, icons_css_1.default];
        }
        remove() {
            this._destroy_proxies();
            super.remove();
        }
        // Manually keep track of view constructed ToolProxy models, because models don't
        // have any sensible life cycle management (at least from views' perspective).
        _our_proxies = [];
        _destroy_proxies() {
            for (const proxy of this._our_proxies) {
                proxy.destroy();
            }
            (0, array_1.clear)(this._our_proxies);
        }
        /**
         * Group similar tools into tool proxies.
         */
        _group_tools(tools) {
            const { group_types } = this.model;
            const grouped = new Map();
            for (const [tool, i] of (0, iterator_1.enumerate)(tools)) {
                const group_type = group_types.find((type) => tool_1.Tool.is_alias_of(tool, type));
                if (group_type != null && tool.group !== false) {
                    const key = tool.group === true ? tool.type : `${tool.type}_${tool.group}`;
                    const group = grouped.get(key);
                    if (group != null) {
                        group.push(tool);
                    }
                    else {
                        grouped.set(key, [tool]);
                    }
                }
                else {
                    // The key doesn't matter, just use something unique.
                    grouped.set(`${i}`, [tool]);
                }
            }
            return Array.from(grouped.values(), (group) => {
                if (group.length > 1) {
                    const proxy = new tool_group_1.ToolGroup({ tools: group });
                    this._our_proxies.push(proxy);
                    return proxy;
                }
                else {
                    return group[0];
                }
            });
        }
        async _build_tool_button_views() {
            this._destroy_proxies();
            this._tool_buttons = (() => {
                const { buttons } = this.model;
                if (buttons == "auto") {
                    const tool_bars = [
                        ...(0, object_1.values)(this.model.gestures).map((gesture) => gesture.tools),
                        this.model.actions,
                        this.model.inspectors,
                        this.model.auxiliaries,
                    ];
                    const { group } = this.model;
                    const button_bars = tool_bars.map((bar) => {
                        const grouped = group ? this._group_tools(bar) : bar;
                        return grouped.map((tool) => tool.tool_button());
                    });
                    return button_bars;
                }
                else {
                    return (0, array_1.split)(buttons, null);
                }
            })();
            await (0, build_views_1.build_views)(this._tool_button_views, this._tool_buttons.flat(), { parent: this });
        }
        set_visibility(visible) {
            if (visible != this._visible) {
                this._visible = visible;
                this._on_visible_change();
            }
        }
        _on_visible_change() {
            this.el.classList.toggle(toolbars.hidden, !this.visible);
        }
        _after_resize() {
            super._after_resize();
            this._after_render();
        }
        _menu_at() {
            switch (this.model.location) {
                case "right": return { left_of: this._overflow_el };
                case "left": return { right_of: this._overflow_el };
                case "above": return { below: this._overflow_el };
                case "below": return { above: this._overflow_el };
            }
        }
        toggle_menu() {
            this._overflow_menu.toggle(this._menu_at());
        }
        render() {
            super.render();
            this.el.classList.add(toolbars[this.model.location]);
            this.el.classList.toggle(toolbars.inner, this.model.inner);
            this._on_visible_change();
            const { horizontal } = this.model;
            this._overflow_el = (0, dom_1.div)({ class: toolbars.tool_overflow, tabIndex: 0 }, horizontal ? "⋮" : "⋯");
            this._overflow_el.addEventListener("click", (_event) => {
                this.toggle_menu();
            });
            this._overflow_el.addEventListener("keydown", (event) => {
                if (event.key == "Enter") {
                    this.toggle_menu();
                }
            });
            this._items = [];
            if (this.model.logo != null) {
                const gray = this.model.logo === "grey" ? logos.grey : null;
                const logo_el = (0, dom_1.a)({ href: "https://bokeh.org/", target: "_blank", class: [logos.logo, logos.logo_small, gray], title: `Bokeh ${version_1.version}` });
                this._items.push(logo_el);
                this.shadow_el.appendChild(logo_el);
            }
            for (const [, button_view] of this._tool_button_views) {
                button_view.render();
            }
            const bars = this._tool_buttons.map((group) => {
                return group
                    .filter((button) => button.tool.visible)
                    .map((button) => this._tool_button_views.get(button))
                    .filter((view) => view != null)
                    .map((view) => view.el);
            }).filter((bar) => bar.length != 0);
            const divider = () => (0, dom_1.div)({ class: toolbars.divider });
            for (const el of (0, iterator_1.join)(bars, divider)) {
                this._items.push(el);
            }
            this.shadow_el.append(...this._items);
        }
        _after_render() {
            super._after_render();
            (0, array_1.clear)(this._overflow_menu.items);
            if (this.shadow_el.contains(this._overflow_el)) {
                this.shadow_el.removeChild(this._overflow_el);
            }
            for (const el of this._items) {
                if (!this.shadow_el.contains(el)) {
                    this.shadow_el.append(el);
                }
            }
            const { horizontal } = this.model;
            const overflow_size = 15;
            const { bbox } = this;
            const overflow_cls = horizontal ? toolbars.right : toolbars.above;
            let size = 0;
            let overflowed = false;
            for (const el of this._items) {
                if (overflowed) {
                    this.shadow_el.removeChild(el);
                    this._overflow_menu.items.push({ custom: el, class: overflow_cls });
                }
                else {
                    const { width, height } = el.getBoundingClientRect();
                    size += horizontal ? width : height;
                    overflowed = horizontal ? size > bbox.width - overflow_size : size > bbox.height - overflow_size;
                    if (overflowed) {
                        this.shadow_el.removeChild(el);
                        this.shadow_el.appendChild(this._overflow_el);
                        this._overflow_menu.items.push({ custom: el, class: overflow_cls });
                    }
                }
            }
            if (this._overflow_menu.is_open) {
                this._overflow_menu.show(this._menu_at());
            }
            for (const tb_view of this.tool_button_views) {
                tb_view.update_bbox();
            }
        }
        toggle_auto_scroll(force) {
            if (this.model.active_scroll != "auto") {
                return;
            }
            for (const tool of this.model.tools) {
                if (tool.event_types.includes("scroll")) {
                    tool.active = force ?? !tool.active;
                    break;
                }
            }
        }
    }
    exports.ToolbarView = ToolbarView;
    const kinds_1 = require(22) /* ../../core/kinds */;
    const GestureToolLike = (0, kinds_1.Or)((0, kinds_1.Ref)(gesture_tool_1.GestureTool), (0, kinds_1.Ref)(tool_proxy_1.ToolProxy));
    const GestureEntry = (0, kinds_1.Struct)({
        tools: (0, kinds_1.List)(GestureToolLike),
        active: (0, kinds_1.Nullable)(GestureToolLike),
    });
    const GesturesMap = (0, kinds_1.Struct)({
        pan: GestureEntry,
        scroll: GestureEntry,
        pinch: GestureEntry,
        rotate: GestureEntry,
        move: GestureEntry,
        tap: GestureEntry,
        doubletap: GestureEntry,
        press: GestureEntry,
        pressup: GestureEntry,
        multi: GestureEntry,
    });
    exports.Inspection = tool_1.Tool;
    function create_gesture_map() {
        return {
            pan: { tools: [], active: null },
            scroll: { tools: [], active: null },
            pinch: { tools: [], active: null },
            rotate: { tools: [], active: null },
            move: { tools: [], active: null },
            tap: { tools: [], active: null },
            doubletap: { tools: [], active: null },
            press: { tools: [], active: null },
            pressup: { tools: [], active: null },
            multi: { tools: [], active: null },
        };
    }
    class Toolbar extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ToolbarView;
            this.define(({ Bool, List, Or, Ref, Nullable, Auto }) => ({
                tools: [List(Or(Ref(tool_1.Tool), Ref(tool_proxy_1.ToolProxy))), []],
                logo: [Nullable(enums_1.Logo), "normal"],
                autohide: [Bool, false],
                group: [Bool, true],
                group_types: [List(enums_1.ToolName), ["hover"]],
                active_drag: [Nullable(Or(GestureToolLike, Auto)), "auto"],
                active_inspect: [Nullable(Or(Ref(exports.Inspection), List(Ref(exports.Inspection)), Ref(tool_proxy_1.ToolProxy), Auto)), "auto"],
                active_scroll: [Nullable(Or(GestureToolLike, Auto)), "auto"],
                active_tap: [Nullable(Or(GestureToolLike, Auto)), "auto"],
                active_multi: [Nullable(Or(GestureToolLike, Auto)), "auto"],
            }));
            this.internal(({ List, Bool, Ref, Or, Null, Auto }) => {
                return {
                    buttons: [Or(List(Or(Ref(tool_button_1.ToolButton), Null)), Auto), "auto"],
                    location: [enums_1.Location, "right"],
                    inner: [Bool, false],
                    gestures: [GesturesMap, create_gesture_map],
                    actions: [List(Or(Ref(action_tool_1.ActionTool), Ref(tool_proxy_1.ToolProxy))), []],
                    inspectors: [List(Or(Ref(inspect_tool_1.InspectTool), Ref(tool_proxy_1.ToolProxy))), []],
                    auxiliaries: [List(Or(Ref(tool_1.Tool), Ref(tool_proxy_1.ToolProxy))), []],
                    help: [List(Or(Ref(help_tool_1.HelpTool), Ref(tool_proxy_1.ToolProxy))), []],
                };
            });
        }
        active_changed = new signaling_1.Signal0(this, "active_changed");
        get horizontal() {
            return this.location == "above" || this.location == "below";
        }
        get vertical() {
            return this.location == "left" || this.location == "right";
        }
        connect_signals() {
            super.connect_signals();
            const { tools, active_drag, active_inspect, active_scroll, active_tap, active_multi } = this.properties;
            this.on_change([tools, active_drag, active_inspect, active_scroll, active_tap, active_multi], () => {
                this._init_tools();
                this._activate_tools(true);
            });
        }
        initialize() {
            super.initialize();
            this._init_tools();
            this._activate_tools(false);
        }
        _init_tools() {
            const visited = new Set();
            function isa(tool, type) {
                const is = tool.underlying instanceof type;
                if (is) {
                    visited.add(tool);
                }
                return is;
            }
            const new_inspectors = this.tools.filter(t => isa(t, inspect_tool_1.InspectTool));
            this.inspectors = new_inspectors;
            const new_help = this.tools.filter(t => isa(t, help_tool_1.HelpTool));
            this.help = new_help;
            const new_actions = this.tools.filter(t => isa(t, action_tool_1.ActionTool));
            this.actions = new_actions;
            const new_gestures = create_gesture_map();
            for (const tool of this.tools) {
                if (isa(tool, gesture_tool_1.GestureTool)) {
                    new_gestures[tool.event_role].tools.push(tool);
                }
            }
            for (const et of (0, object_1.typed_keys)(new_gestures)) {
                const gesture = this.gestures[et];
                gesture.tools = (0, array_1.sort_by)(new_gestures[et].tools, (tool) => tool.default_order);
                if (gesture.active != null && (0, array_1.every)(gesture.tools, (tool) => tool.id != gesture.active?.id)) {
                    gesture.active = null;
                }
            }
            const new_auxiliaries = this.tools.filter((tool) => !visited.has(tool));
            this.auxiliaries = new_auxiliaries;
        }
        _activate_tools(emit) {
            if (this.active_inspect == "auto") {
                // do nothing as all tools are active be default
            }
            else if (this.active_inspect == null) {
                for (const inspector of this.inspectors) {
                    inspector.active = false;
                }
            }
            else if ((0, types_1.isArray)(this.active_inspect)) {
                const active_inspect = (0, array_1.intersection)(this.active_inspect, this.inspectors);
                if (active_inspect.length != this.active_inspect.length) {
                    this.active_inspect = active_inspect;
                }
                for (const inspector of this.inspectors) {
                    if (!(0, array_1.includes)(this.active_inspect, inspector)) {
                        inspector.active = false;
                    }
                }
            }
            else {
                let found = false;
                for (const inspector of this.inspectors) {
                    if (inspector != this.active_inspect) {
                        inspector.active = false;
                    }
                    else {
                        found = true;
                    }
                }
                if (!found) {
                    this.active_inspect = null;
                }
            }
            const _activate_gesture = (tool) => {
                if (tool.active) {
                    // tool was activated by a proxy, but we need to finish configuration manually
                    this._active_change(tool);
                }
                else {
                    tool.active = true;
                }
            };
            // Connecting signals has to be done before changing the active state of the tools.
            for (const gesture of (0, object_1.values)(this.gestures)) {
                for (const tool of gesture.tools) {
                    // XXX: connect once
                    this.connect(tool.properties.active.change, () => {
                        this._active_change(tool);
                        if (emit) {
                            this.active_changed.emit();
                        }
                    });
                }
            }
            function _get_active_attr(et) {
                switch (et) {
                    case "tap": return "active_tap";
                    case "pan": return "active_drag";
                    case "pinch":
                    case "scroll": return "active_scroll";
                    case "multi": return "active_multi";
                    default: return null;
                }
            }
            function _supports_auto(et, tool) {
                return et == "tap" || et == "pan" || tool.supports_auto();
            }
            const is_active_gesture = (active_tool) => {
                return this.tools.includes(active_tool) || (active_tool instanceof tool_1.Tool && this.tools.some((tool) => tool instanceof tool_proxy_1.ToolProxy && tool.tools.includes(active_tool)));
            };
            const _resolve_gesture_activation = (gesture, active_attr) => {
                // some tools may already be initialized as active
                if (gesture.tools.every((tool) => !tool.active)) {
                    return;
                }
                // active attr takes precedence over any active initialization
                if (active_attr != null && this[active_attr] != null && this[active_attr] != "auto") {
                    gesture.tools.forEach((tool) => {
                        if (tool.tool_name != this[active_attr]) {
                            tool.active = false;
                        }
                    });
                    return;
                }
                for (const tool of gesture.tools) {
                    if (!tool.active) {
                        continue;
                    }
                    if (gesture.active == null) {
                        _activate_gesture(tool);
                    }
                    else if (gesture.active.id != tool.id && gesture.active.tool_name != tool.tool_name) {
                        tool.active = false;
                    }
                }
            };
            for (const [event_role, gesture] of (0, object_1.entries)(this.gestures)) {
                const et = event_role;
                const active_attr = _get_active_attr(et);
                _resolve_gesture_activation(gesture, active_attr);
                if (active_attr != null) {
                    const active_tool = this[active_attr];
                    if (active_tool == "auto") {
                        if (gesture.tools.length != 0 && gesture.active == null) {
                            const [tool] = gesture.tools;
                            if (_supports_auto(et, tool)) {
                                _activate_gesture(tool);
                            }
                        }
                    }
                    else if (active_tool != null) {
                        if (is_active_gesture(active_tool)) {
                            _activate_gesture(active_tool);
                        }
                        else {
                            this[active_attr] = null;
                        }
                    }
                    else {
                        this.gestures[et].active = null;
                        for (const tool of this.gestures[et].tools) {
                            tool.active = false;
                        }
                    }
                }
            }
            if (emit) {
                this.active_changed.emit();
            }
        }
        _active_change(tool) {
            const { event_types } = tool;
            for (const et of event_types) {
                if (tool.active) {
                    const currently_active_tool = this.gestures[et].active;
                    if (currently_active_tool != null && tool != currently_active_tool) {
                        logging_1.logger.debug(`Toolbar: deactivating tool: ${currently_active_tool} for event type '${et}'`);
                        currently_active_tool.active = false;
                    }
                    this.gestures[et].active = tool;
                    logging_1.logger.debug(`Toolbar: activating tool: ${tool} for event type '${et}'`);
                }
                else {
                    this.gestures[et].active = null;
                }
            }
        }
        to_menu() {
            const groups = [
                ...(0, object_1.values)(this.gestures).map((gesture) => gesture.tools),
                this.actions,
                this.inspectors,
                this.auxiliaries,
            ];
            const entries = groups
                .filter((group) => group.length != 0)
                .map((group) => group.map((tool) => tool.menu_item()));
            const items = [...(0, iterator_1.join)(entries, () => new menus_1.DividerItem())];
            return new menus_1.Menu({ items });
        }
    }
    exports.Toolbar = Toolbar;
},
/* models/tools/tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const view_1 = require(65) /* ../../core/view */;
    const array_1 = require(10) /* ../../core/util/array */;
    const object_1 = require(9) /* ../../core/util/object */;
    const types_1 = require(8) /* ../../core/util/types */;
    const eq_1 = require(27) /* ../../core/util/eq */;
    const model_1 = require(52) /* ../../model */;
    const menus_1 = require(380) /* ../ui/menus */;
    const kinds_1 = require(124) /* ../common/kinds */;
    class ToolView extends view_1.View {
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.properties.active.change, () => {
                if (this.model.active) {
                    this.activate();
                }
                else {
                    this.deactivate();
                }
            });
        }
        get overlays() {
            return [];
        }
        // activate is triggered by toolbar ui actions
        activate() { }
        // deactivate is triggered by toolbar ui actions
        deactivate() { }
    }
    exports.ToolView = ToolView;
    class Tool extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype._known_aliases = new Map();
            this.define(({ Bool, Or, Str, Nullable }) => ({
                icon: [Nullable(kinds_1.IconLike), null],
                description: [Nullable(Str), null],
                visible: [Bool, true],
                group: [Or(Str, Bool), true],
            }));
            this.internal(({ Bool }) => ({
                active: [Bool, false],
                disabled: [Bool, false],
            }));
        }
        tool_name;
        tool_icon; // CSS class (no dot)
        get event_role() {
            const { event_type } = this;
            return (0, types_1.isString)(event_type) ? event_type : "multi";
        }
        get event_types() {
            const { event_type } = this;
            return event_type == null ? [] : ((0, types_1.isString)(event_type) ? [event_type] : event_type);
        }
        // }}}
        button_view;
        menu_item() {
            const item = new menus_1.MenuItem({
                icon: this.computed_icon,
                label: this.tool_name,
                tooltip: this.tooltip != this.tool_name ? this.tooltip : undefined,
                checked: () => this.active,
                disabled: () => this.disabled,
                action: () => this.active = !this.active,
            });
            const submenu = this.menu;
            if (submenu != null) {
                item.menu = new menus_1.Menu({ items: submenu });
            }
            return item;
        }
        get tooltip() {
            return this.description ?? this.tool_name;
        }
        get computed_icon() {
            const { icon, tool_icon } = this;
            return icon ?? (tool_icon != null ? `.${tool_icon}` : undefined);
        }
        get menu() {
            return null;
        }
        supports_auto() {
            return false;
        }
        // utility function to get limits along both dimensions, given
        // optional dimensional constraints
        _get_dim_limits([sx0, sy0], [sx1, sy1], frame, dims) {
            const hr = frame.bbox.h_range;
            let sxlim;
            if (dims == "width" || dims == "both") {
                sxlim = [(0, array_1.min)([sx0, sx1]), (0, array_1.max)([sx0, sx1])];
                sxlim = [(0, array_1.max)([sxlim[0], hr.start]), (0, array_1.min)([sxlim[1], hr.end])];
            }
            else {
                sxlim = [hr.start, hr.end];
            }
            const vr = frame.bbox.v_range;
            let sylim;
            if (dims == "height" || dims == "both") {
                sylim = [(0, array_1.min)([sy0, sy1]), (0, array_1.max)([sy0, sy1])];
                sylim = [(0, array_1.max)([sylim[0], vr.start]), (0, array_1.min)([sylim[1], vr.end])];
            }
            else {
                sylim = [vr.start, vr.end];
            }
            return [sxlim, sylim];
        }
        _compute_overlay_limits(sxlim, sylim, dims, line_width) {
            if (dims == "width") {
                sylim[0] -= line_width; // top
                sylim[1] += line_width; // bottom
            }
            else if (dims == "height") {
                sxlim[0] -= line_width; // left
                sxlim[1] += line_width; // right
            }
            return [sxlim, sylim];
        }
        // utility function to return a tool name, modified
        // by the active dimensions. Used by tools that have dimensions
        _get_dim_tooltip(dims) {
            const { description, tool_name } = this;
            if (description != null) {
                return description;
            }
            else if (dims == "both") {
                return tool_name;
            }
            else if (dims == "auto") {
                return `${tool_name} (either x, y or both dimensions)`;
            }
            else {
                return `${tool_name} (${dims == "width" ? "x" : "y"}-axis)`;
            }
        }
        /** @prototype */
        _known_aliases;
        static register_alias(name, fn) {
            const tool = fn();
            const attrs = tool.dirty_attributes;
            const cmp = new eq_1.Comparator();
            const query = (obj) => {
                if (!(obj instanceof tool.constructor)) {
                    return false;
                }
                for (const [attr, value] of (0, object_1.entries)(attrs)) {
                    if (!cmp.eq(value, obj.property(attr).get_value())) {
                        return false;
                    }
                }
                return true;
            };
            this.prototype._known_aliases.set(name, { fn, query });
        }
        /**
         * Is the given tool member of the given tool family.
         */
        static is_alias_of(tool, name) {
            const spec = this.prototype._known_aliases.get(name);
            return spec?.query(tool.underlying) ?? false;
        }
        static from_string(name) {
            const spec = this.prototype._known_aliases.get(name);
            if (spec != null) {
                return spec.fn();
            }
            else {
                const names = [...this.prototype._known_aliases.keys()];
                throw new Error(`unexpected tool name '${name}', possible tools are ${names.join(", ")}`);
            }
        }
        /**
         * Unifying API with ProxyTool.
         */
        get underlying() {
            return this;
        }
    }
    exports.Tool = Tool;
},
/* models/ui/menus/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var menu_1 = require(122) /* ./menu */;
    __esExport("Menu", menu_1.Menu);
    __esExport("MenuItemLike", menu_1.MenuItemLike);
    var menu_item_1 = require(123) /* ./menu_item */;
    __esExport("MenuItem", menu_item_1.MenuItem);
    var action_item_1 = require(381) /* ./action_item */;
    __esExport("ActionItem", action_item_1.ActionItem);
    var checkable_item_1 = require(382) /* ./checkable_item */;
    __esExport("CheckableItem", checkable_item_1.CheckableItem);
    var divider_item_1 = require(126) /* ./divider_item */;
    __esExport("DividerItem", divider_item_1.DividerItem);
},
/* models/ui/menus/action_item.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const menu_item_1 = require(123) /* ./menu_item */;
    /** @deprecated use MenuItem */
    class ActionItem extends menu_item_1.MenuItem {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ActionItem = ActionItem;
},
/* models/ui/menus/checkable_item.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const menu_item_1 = require(123) /* ./menu_item */;
    /** @deprecated use MenuItem.checkable */
    class CheckableItem extends menu_item_1.MenuItem {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.CheckableItem = CheckableItem;
},
/* models/tools/tool_proxy.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const signaling_1 = require(17) /* ../../core/signaling */;
    const model_1 = require(52) /* ../../model */;
    const menus_1 = require(380) /* ../ui/menus */;
    const tool_1 = require(379) /* ./tool */;
    const iterator_1 = require(15) /* ../../core/util/iterator */;
    const callbacks_1 = require(51) /* ../../core/util/callbacks */;
    class ToolProxy extends model_1.Model {
        constructor(attrs) {
            super(attrs);
            // This is not ideal, because this should be done in connect signals,
            // but that would fail with accessing undefined 'do' attribute.
            this.connect(this.do, () => this.doit());
        }
        static {
            this.define(({ Bool, List, Ref, Or }) => ({
                tools: [List(Or(Ref(tool_1.Tool), Ref(ToolProxy))), []],
                visible: [Bool, (self) => (0, iterator_1.some)(self.tools, (tool) => tool.visible)],
                active: [Bool, (self) => (0, iterator_1.some)(self.tools, (tool) => tool.active)],
                disabled: [Bool, false],
            }));
        }
        do = new signaling_1.Signal0(this, "do");
        // Operates all the tools given only one button
        /**
         * Returns the first real tool this proxy maintains.
         */
        get underlying() {
            const tool = this.tools[0];
            return tool instanceof ToolProxy ? tool.underlying : tool;
        }
        tool_button() {
            const button = this.tools[0].tool_button();
            button.tool = this;
            return button;
        }
        menu_item() {
            return this.tools[0].menu_item();
        }
        get event_type() {
            return this.tools[0].event_type;
        }
        get event_role() {
            return this.tools[0].event_role;
        }
        get event_types() {
            return this.tools[0].event_types;
        }
        get default_order() {
            return this.tools[0].default_order; // only gestures etc.
        }
        get tooltip() {
            return this.tools[0].tooltip;
        }
        get tool_name() {
            return this.tools[0].tool_name;
        }
        get computed_icon() {
            return this.tools[0].computed_icon;
        }
        get toggleable() {
            const tool = this.tools[0];
            return "toggleable" in tool && tool.toggleable;
        }
        get group() {
            const tool = this.tools[0];
            return tool.group;
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.properties.active.change, () => this.set_active());
            for (const tool of this.tools) {
                this.connect(tool.properties.active.change, () => {
                    this.active = tool.active;
                });
            }
        }
        doit() {
            for (const tool of this.tools) {
                tool.do.emit();
            }
        }
        set_active() {
            for (const tool of this.tools) {
                tool.active = this.active;
            }
        }
        get menu() {
            const { menu } = this.tools[0];
            if (menu == null) {
                return null;
            }
            const items = [];
            for (const [item, i] of (0, iterator_1.enumerate)(menu)) {
                if (item == null) {
                    items.push(null);
                }
                else {
                    const action = () => {
                        for (const tool of this.tools) {
                            const { menu } = tool;
                            if (menu == null) {
                                continue;
                            }
                            const item = menu[i];
                            if (item instanceof menus_1.MenuItem && item.action != null) {
                                void (0, callbacks_1.execute)(item.action, new menus_1.Menu(), { item });
                            }
                        }
                    };
                    items.push(item.clone({ action }));
                }
            }
            return items;
        }
        supports_auto() {
            return this.tools[0].supports_auto();
        }
    }
    exports.ToolProxy = ToolProxy;
},
/* models/tools/tool_group.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tool_proxy_1 = require(383) /* ./tool_proxy */;
    class ToolGroup extends tool_proxy_1.ToolProxy {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Bool }) => ({
                show_count: [Bool, false],
            }));
        }
        get tooltip() {
            return this.tools.map((tool) => tool.tooltip).join("\n");
        }
    }
    exports.ToolGroup = ToolGroup;
},
/* models/tools/tool_button.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const ui_element_1 = require(55) /* ../ui/ui_element */;
    const kinds_1 = require(124) /* ../common/kinds */;
    const resolve_1 = require(127) /* ../common/resolve */;
    const tool_1 = require(379) /* ./tool */;
    const tool_proxy_1 = require(383) /* ./tool_proxy */;
    const tool_group_1 = require(384) /* ./tool_group */;
    const ui_gestures_1 = require(386) /* ../../core/ui_gestures */;
    const dom_1 = require(61) /* ../../core/dom */;
    const menus_1 = require(387) /* ../../core/util/menus */;
    const array_1 = require(10) /* ../../core/util/array */;
    const tool_button_css_1 = tslib_1.__importStar(require(389) /* ../../styles/tool_button.css */), tool_button = tool_button_css_1;
    const icons_css_1 = tslib_1.__importDefault(require(76) /* ../../styles/icons.css */);
    class ToolButtonView extends ui_element_1.UIElementView {
        _menu;
        _ui_gestures;
        initialize() {
            super.initialize();
            const { location } = this.parent.model;
            const reverse = location == "left" || location == "above";
            const orientation = this.parent.model.horizontal ? "vertical" : "horizontal";
            const items = this.model.tool.menu ?? [];
            this._menu = new menus_1.ContextMenu(!reverse ? items : (0, array_1.reversed)(items), {
                target: this.parent.el,
                orientation,
                prevent_hide: (event) => {
                    return event.composedPath().includes(this.el);
                },
                labels: false,
            });
            this._ui_gestures = new ui_gestures_1.UIGestures(this.el, {
                on_tap: (event) => {
                    if (this._menu.is_open) {
                        this._menu.hide();
                        return;
                    }
                    if (event.native.composedPath().includes(this.el)) {
                        this.tap();
                    }
                },
                on_press: () => {
                    this.press();
                },
            });
            this.el.addEventListener("keydown", (event) => {
                switch (event.key) {
                    case "Enter": {
                        this.tap();
                        break;
                    }
                    case " ": {
                        this.press();
                        break;
                    }
                    default:
                }
            });
        }
        connect_signals() {
            super.connect_signals();
            this._ui_gestures.connect_signals();
            this.connect(this.model.change, () => this.render());
            this.connect(this.model.tool.change, () => this.render());
        }
        remove() {
            this._ui_gestures.remove();
            this._menu.remove();
            super.remove();
        }
        stylesheets() {
            return [...super.stylesheets(), tool_button_css_1.default, icons_css_1.default];
        }
        render() {
            super.render();
            const { tool } = this.model;
            this.class_list.add(tool_button[this.parent.model.location]);
            this.class_list.toggle(tool_button.hidden, !tool.visible);
            this.class_list.toggle(tool_button.disabled, tool.disabled);
            const icon_el = (0, dom_1.div)({ class: tool_button.tool_icon });
            this.shadow_el.append(icon_el);
            const icon = this.model.icon ?? tool.computed_icon;
            if (icon != null) {
                (0, resolve_1.apply_icon)(icon_el, icon);
            }
            if (tool.menu != null) {
                const chevron_el = (0, dom_1.div)({ class: tool_button.tool_chevron });
                this.shadow_el.append(chevron_el);
            }
            if (tool instanceof tool_group_1.ToolGroup && tool.show_count) {
                const count_el = (0, dom_1.div)({ class: tool_button.count }, `${tool.tools.length}`);
                this.shadow_el.append(count_el);
            }
            const tooltip = this.model.tooltip ?? tool.tooltip;
            this.el.title = tooltip;
            this.el.tabIndex = 0;
        }
        press() {
            const at = (() => {
                switch (this.parent.model.location) {
                    case "right": return { left_of: this.el };
                    case "left": return { right_of: this.el };
                    case "above": return { below: this.el };
                    case "below": return { above: this.el };
                }
            })();
            this._menu.toggle(at);
        }
    }
    exports.ToolButtonView = ToolButtonView;
    class ToolButton extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Str, Ref, Nullable, Or }) => ({
                tool: [Or(Ref(tool_1.Tool), Ref(tool_proxy_1.ToolProxy))],
                icon: [Nullable(kinds_1.IconLike), null],
                tooltip: [Nullable(Str), null],
            }));
        }
    }
    exports.ToolButton = ToolButton;
},
/* core/ui_gestures.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const dom_1 = require(61) /* ./dom */;
    const assert_1 = require(13) /* ./util/assert */;
    class UIGestures {
        hit_area;
        handlers;
        must_be_target;
        constructor(hit_area, handlers, options = {}) {
            this.hit_area = hit_area;
            this.handlers = handlers;
            this.must_be_target = options.must_be_target ?? false;
            this._pointer_over = this._pointer_over.bind(this);
            this._pointer_out = this._pointer_out.bind(this);
            this._pointer_down = this._pointer_down.bind(this);
            this._pointer_move = this._pointer_move.bind(this);
            this._pointer_up = this._pointer_up.bind(this);
            this._pointer_cancel = this._pointer_cancel.bind(this);
        }
        connect_signals() {
            this.hit_area.addEventListener("pointerover", this._pointer_over);
            this.hit_area.addEventListener("pointerout", this._pointer_out);
            this.hit_area.addEventListener("pointerdown", this._pointer_down);
            this.hit_area.addEventListener("pointermove", this._pointer_move);
            this.hit_area.addEventListener("pointerup", this._pointer_up);
            this.hit_area.addEventListener("pointercancel", this._pointer_cancel);
        }
        disconnect_signals() {
            this.hit_area.removeEventListener("pointerover", this._pointer_over);
            this.hit_area.removeEventListener("pointerout", this._pointer_out);
            this.hit_area.removeEventListener("pointerdown", this._pointer_down);
            this.hit_area.removeEventListener("pointermove", this._pointer_move);
            this.hit_area.removeEventListener("pointerup", this._pointer_up);
            this.hit_area.removeEventListener("pointercancel", this._pointer_cancel);
        }
        remove() {
            this.disconnect_signals();
        }
        _self_is_target(event) {
            return event.composedPath()[0] == this.hit_area;
        }
        _is_event_target(event) {
            return !this.must_be_target || this._self_is_target(event);
        }
        phase = "idle";
        pointers = new Map();
        press_timer = null;
        tap_timestamp = -Infinity;
        last_scale = null;
        last_rotation = null;
        reset() {
            this._cancel_timeout();
            this._user_select(true);
            this.phase = "idle";
            this.pointers.clear();
            this.press_timer = null;
            this.tap_timestamp = -Infinity;
            this.last_scale = null;
            this.last_rotation = null;
        }
        _user_select(allow) {
            this.hit_area.style.userSelect = allow ? "" : "none";
        }
        static move_threshold = 5; /*px*/
        static press_threshold = 300; /*ms*/
        static doubletap_threshold = 300; /*ms*/
        static pinch_threshold = 0; /*unit less*/
        static rotate_threshold = 0; /*rad*/
        get _is_multi_gesture() {
            return this.pointers.size >= 2;
        }
        _within_threshold(ptr) {
            const { dx, dy } = this._movement(ptr);
            return dx ** 2 + dy ** 2 <= UIGestures.move_threshold ** 2;
        }
        get _any_movement() {
            return [...this.pointers.values()].some((ptr) => !this._within_threshold(ptr));
        }
        _start_timeout() {
            (0, assert_1.assert)(this.press_timer == null);
            this.press_timer = setTimeout(() => this._pointer_timeout(), UIGestures.press_threshold);
        }
        _cancel_timeout() {
            const { press_timer } = this;
            if (press_timer != null) {
                clearTimeout(press_timer);
                this.press_timer = null;
            }
        }
        _pointer_timeout() {
            (0, assert_1.assert)(this.phase == "started");
            (0, assert_1.assert)(!this._is_multi_gesture);
            this.phase = "pressing";
            this.press_timer = null;
            const [pointer] = this.pointers.values();
            this.on_press(pointer.init);
        }
        _pointer_over(event) {
            if (!this._is_event_target(event)) {
                return;
            }
            if (event.isPrimary) {
                this.on_enter(event);
            }
        }
        _pointer_out(event) {
            if (!this._is_event_target(event)) {
                return;
            }
            if (event.isPrimary) {
                this.on_leave(event);
            }
        }
        _pointer_down(event) {
            if (!this._is_event_target(event)) {
                return;
            }
            if (this._is_multi_gesture) {
                return;
            }
            if (this.pointers.has(event.pointerId)) {
                return;
            }
            if (event.isPrimary && event.pointerType == "mouse" && event.buttons != dom_1.MouseButton.Left) {
                return;
            }
            if (!this.hit_area.isConnected) {
                return;
            }
            this.pointers.set(event.pointerId, { init: event, last: event });
            this.hit_area.setPointerCapture(event.pointerId);
            this._user_select(false);
            switch (this.phase) {
                case "idle": {
                    this.phase = "started";
                    this._start_timeout();
                    break;
                }
                case "started": {
                    this._cancel_timeout();
                    break;
                }
                case "pressing":
                case "panning":
                case "pinching":
                case "rotating":
                case "transitional":
                    break;
            }
        }
        _pointer_move(event) {
            if (!this._is_event_target(event)) {
                return;
            }
            if (event.isPrimary) {
                this.on_move(event);
            }
            const pointer = this.pointers.get(event.pointerId);
            if (pointer == null) {
                return;
            }
            pointer.last = event;
            switch (this.phase) {
                case "idle": {
                    this.reset();
                    (0, assert_1.unreachable)();
                }
                case "started":
                case "transitional": {
                    if (!this._any_movement) {
                        return;
                    }
                    this._cancel_timeout();
                    if (!this._is_multi_gesture) {
                        this.phase = "panning";
                        const [ptr] = this.pointers.values();
                        const { dx, dy } = this._movement(ptr);
                        this.on_pan_start(ptr.init, 0, 0);
                        this.on_pan(ptr.last, dx, dy);
                    }
                    else {
                        const [ptr0, ptr1] = this.pointers.values();
                        const scale = this._scale(ptr0, ptr1);
                        const rotation = this._rotation(ptr0, ptr1);
                        if (Math.abs(scale - 1) > UIGestures.pinch_threshold) {
                            this.phase = "pinching";
                            this.on_pinch_start(ptr0.init, ptr1.init, 1);
                            this.on_pinch(ptr0.last, ptr1.last, scale);
                            this.last_scale = scale;
                        }
                        else if (Math.abs(rotation) > UIGestures.rotate_threshold) {
                            this.phase = "rotating";
                            this.on_rotate_start(ptr0.init, ptr1.init, 0);
                            this.on_rotate(ptr1.last, ptr1.last, rotation);
                            this.last_rotation = rotation;
                        }
                    }
                    break;
                }
                case "pressing": {
                    break;
                }
                case "panning": {
                    const [ptr] = this.pointers.values();
                    const { dx, dy } = this._movement(ptr);
                    this.on_pan(event, dx, dy);
                    break;
                }
                case "pinching": {
                    const [ptr0, ptr1] = this.pointers.values();
                    const scale = this._scale(ptr0, ptr1);
                    if (scale != this.last_scale) {
                        this.on_pinch(ptr0.last, ptr1.last, scale);
                        this.last_scale = scale;
                    }
                    break;
                }
                case "rotating": {
                    const [ptr0, ptr1] = this.pointers.values();
                    const rotation = this._rotation(ptr0, ptr1);
                    if (rotation != this.last_rotation) {
                        this.on_rotate(ptr0.last, ptr1.last, rotation);
                        this.last_rotation = rotation;
                    }
                    break;
                }
            }
        }
        _pointer_up(event) {
            if (!this._is_event_target(event)) {
                return;
            }
            const pointer = this.pointers.get(event.pointerId);
            if (pointer == null) {
                return;
            }
            pointer.last = event;
            this._cancel_timeout();
            switch (this.phase) {
                case "idle": {
                    this.reset();
                    (0, assert_1.unreachable)();
                }
                case "started": {
                    const [ptr] = this.pointers.values();
                    const { tap_timestamp } = this;
                    if (ptr.last.timeStamp - tap_timestamp < UIGestures.doubletap_threshold) {
                        this.tap_timestamp = -Infinity;
                        this.on_doubletap(ptr.last);
                    }
                    else {
                        this.tap_timestamp = ptr.last.timeStamp;
                        this.on_tap(ptr.last);
                    }
                    this.phase = "idle";
                    break;
                }
                case "transitional": {
                    this.phase = "idle";
                    break;
                }
                case "pressing": {
                    const [ptr] = this.pointers.values();
                    this.on_pressup(ptr.last);
                    this.phase = "idle";
                    break;
                }
                case "panning": {
                    const [ptr] = this.pointers.values();
                    const { dx, dy } = this._movement(ptr);
                    this.on_pan_end(event, dx, dy);
                    this.phase = "idle";
                    break;
                }
                case "pinching": {
                    const [ptr0, ptr1] = this.pointers.values();
                    const scale = this._scale(ptr0, ptr1);
                    this.on_pinch_end(ptr0.last, ptr1.last, scale);
                    this.phase = "transitional";
                    this.last_scale = null;
                    break;
                }
                case "rotating": {
                    const [ptr0, ptr1] = this.pointers.values();
                    const rotation = this._rotation(ptr0, ptr1);
                    this.on_rotate_end(ptr0.last, ptr1.last, rotation);
                    this.phase = "transitional";
                    this.last_rotation = null;
                    break;
                }
            }
            this.pointers.delete(event.pointerId);
            if (this.phase == "transitional") {
                const [ptr] = this.pointers.values();
                ptr.init = ptr.last;
            }
            if (this.pointers.size == 0) {
                this._user_select(true);
            }
        }
        _pointer_cancel(event) {
            if (!this.pointers.has(event.pointerId)) {
                return;
            }
            this._cancel_timeout();
            switch (this.phase) {
                case "idle": {
                    this.reset();
                    (0, assert_1.unreachable)();
                }
                case "started":
                case "pressing":
                case "transitional": {
                    this.phase = "idle";
                    break;
                }
                case "panning": {
                    const [ptr] = this.pointers.values();
                    const { dx, dy } = this._movement(ptr);
                    this.on_pan_end(event, dx, dy);
                    this.phase = "idle";
                    break;
                }
                case "pinching": {
                    const [ptr0, ptr1] = this.pointers.values();
                    const scale = this._scale(ptr0, ptr1);
                    this.on_pinch_end(ptr0.last, ptr1.last, scale);
                    this.phase = "transitional";
                    this.last_scale = null;
                    break;
                }
                case "rotating": {
                    const [ptr0, ptr1] = this.pointers.values();
                    const rotation = this._rotation(ptr0, ptr1);
                    this.on_rotate_end(ptr0.last, ptr1.last, rotation);
                    this.phase = "transitional";
                    this.last_rotation = null;
                    break;
                }
            }
            this.pointers.delete(event.pointerId);
            if (this.phase == "transitional") {
                const [ptr] = this.pointers.values();
                ptr.init = ptr.last;
            }
            if (this.pointers.size == 0) {
                this._user_select(true);
            }
        }
        on_tap(ev) {
            const { on_tap } = this.handlers;
            if (on_tap != null) {
                on_tap(this._tap_event("tap", ev));
            }
        }
        on_doubletap(ev) {
            const { on_doubletap } = this.handlers;
            if (on_doubletap != null) {
                on_doubletap(this._tap_event("double_tap", ev));
            }
        }
        on_press(ev) {
            const { on_press } = this.handlers;
            if (on_press != null) {
                on_press(this._tap_event("press", ev));
            }
        }
        on_pressup(ev) {
            const { on_pressup } = this.handlers;
            if (on_pressup != null) {
                on_pressup(this._tap_event("press_up", ev));
            }
        }
        on_enter(ev) {
            const { on_enter } = this.handlers;
            if (on_enter != null) {
                on_enter(this._move_event("enter", ev));
            }
        }
        on_move(ev) {
            const { on_move } = this.handlers;
            if (on_move != null) {
                on_move(this._move_event("move", ev));
            }
        }
        on_leave(ev) {
            const { on_leave } = this.handlers;
            if (on_leave != null) {
                on_leave(this._move_event("leave", ev));
            }
        }
        on_pan_start(ev, dx, dy) {
            const { on_pan_start } = this.handlers;
            if (on_pan_start != null) {
                on_pan_start(this._pan_event("pan_start", ev, dx, dy));
            }
        }
        on_pan(ev, dx, dy) {
            const { on_pan } = this.handlers;
            if (on_pan != null) {
                on_pan(this._pan_event("pan", ev, dx, dy));
            }
        }
        on_pan_end(ev, dx, dy) {
            const { on_pan_end } = this.handlers;
            if (on_pan_end != null) {
                on_pan_end(this._pan_event("pan_end", ev, dx, dy));
            }
        }
        on_pinch_start(ev0, ev1, scale) {
            const { on_pinch_start } = this.handlers;
            if (on_pinch_start != null) {
                on_pinch_start(this._pinch_event("pinch_start", ev0, ev1, scale));
            }
        }
        on_pinch(ev0, ev1, scale) {
            const { on_pinch } = this.handlers;
            if (on_pinch != null) {
                on_pinch(this._pinch_event("pinch", ev0, ev1, scale));
            }
        }
        on_pinch_end(ev0, ev1, scale) {
            const { on_pinch_end } = this.handlers;
            if (on_pinch_end != null) {
                on_pinch_end(this._pinch_event("pinch_end", ev0, ev1, scale));
            }
        }
        on_rotate_start(ev0, ev1, rotation) {
            const { on_rotate_start } = this.handlers;
            if (on_rotate_start != null) {
                on_rotate_start(this._rotate_event("rotate_start", ev0, ev1, rotation));
            }
        }
        on_rotate(ev0, ev1, rotation) {
            const { on_rotate } = this.handlers;
            if (on_rotate != null) {
                on_rotate(this._rotate_event("rotate", ev0, ev1, rotation));
            }
        }
        on_rotate_end(ev0, ev1, rotation) {
            const { on_rotate_end } = this.handlers;
            if (on_rotate_end != null) {
                on_rotate_end(this._rotate_event("rotate_end", ev0, ev1, rotation));
            }
        }
        _get_sxy(event) {
            const { pageX, pageY } = event;
            const { left, top } = (0, dom_1.offset_bbox)(this.hit_area);
            return {
                sx: pageX - left,
                sy: pageY - top,
            };
        }
        _get_modifiers(event) {
            return {
                shift: event.shiftKey,
                ctrl: event.ctrlKey,
                alt: event.altKey,
            };
        }
        _tap_event(type, event) {
            return {
                type,
                ...this._get_sxy(event),
                modifiers: this._get_modifiers(event),
                native: event,
            };
        }
        _move_event(type, event) {
            return {
                type,
                ...this._get_sxy(event),
                modifiers: this._get_modifiers(event),
                native: event,
            };
        }
        _pan_event(type, event, dx, dy) {
            return {
                type,
                ...this._get_sxy(event),
                dx,
                dy,
                modifiers: this._get_modifiers(event),
                native: event,
            };
        }
        _pinch_event(type, event0, event1, scale) {
            const { sx: sx0, sy: sy0 } = this._get_sxy(event0);
            const { sx: sx1, sy: sy1 } = this._get_sxy(event1);
            return {
                type,
                sx: (sx0 + sx1) / 2,
                sy: (sy0 + sy1) / 2,
                scale,
                modifiers: this._get_modifiers(event0),
                native: event0,
            };
        }
        _rotate_event(type, event0, event1, rotation) {
            const { sx: sx0, sy: sy0 } = this._get_sxy(event0);
            const { sx: sx1, sy: sy1 } = this._get_sxy(event1);
            return {
                type,
                sx: (sx0 + sx1) / 2,
                sy: (sy0 + sy1) / 2,
                rotation,
                modifiers: this._get_modifiers(event0),
                native: event0,
            };
        }
        _movement(ptr) {
            return {
                dx: ptr.last.x - ptr.init.x,
                dy: ptr.last.y - ptr.init.y,
            };
        }
        _distance(ev0, ev1) {
            const x = ev1.x - ev0.x;
            const y = ev1.y - ev0.y;
            return Math.sqrt(x ** 2 + y ** 2);
        }
        _angle(ev0, ev1) {
            const x = ev1.x - ev0.x;
            const y = ev1.y - ev0.y;
            return Math.atan2(y, x) * 180 / Math.PI;
        }
        _scale(ptr0, ptr1) {
            return this._distance(ptr0.last, ptr1.last) / this._distance(ptr0.init, ptr1.init);
        }
        _rotation(ptr0, ptr1) {
            return this._angle(ptr1.last, ptr0.last) + this._angle(ptr1.init, ptr0.init);
        }
    }
    exports.UIGestures = UIGestures;
},
/* core/util/menus.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const dom_1 = require(61) /* ../dom */;
    const array_1 = require(10) /* ./array */;
    const types_1 = require(8) /* ./types */;
    const callbacks_1 = require(51) /* ./callbacks */;
    const legacy_menus_css_1 = tslib_1.__importStar(require(388) /* ../../styles/legacy_menus.css */), menus = legacy_menus_css_1;
    const icons_css_1 = tslib_1.__importDefault(require(76) /* ../../styles/icons.css */);
    const base_css_1 = tslib_1.__importDefault(require(70) /* ../../styles/base.css */);
    const menus_1 = require(380) /* ../../models/ui/menus */;
    const resolve_1 = require(127) /* ../../models/common/resolve */;
    class ContextMenu {
        items;
        el = (0, dom_1.div)();
        shadow_el;
        _open = false;
        get is_open() {
            return this._open;
        }
        get can_open() {
            return this.items.length != 0;
        }
        target;
        orientation;
        reversed;
        labels;
        prevent_hide;
        extra_styles;
        class_list;
        constructor(items, options) {
            this.items = items;
            this.target = options.target;
            this.orientation = options.orientation ?? "vertical";
            this.reversed = options.reversed ?? false;
            this.labels = options.labels ?? true;
            this.prevent_hide = options.prevent_hide;
            this.extra_styles = options.extra_styles ?? [];
            this.shadow_el = this.el.attachShadow({ mode: "open" });
            this.class_list = new dom_1.ClassList(this.el.classList);
        }
        _item_click = (entry) => {
            if (entry.action != null) {
                if ((0, types_1.isPlainObject)(entry)) {
                    entry.action();
                }
                else {
                    void (0, callbacks_1.execute)(entry.action, new menus_1.Menu(), { item: entry });
                }
            }
            this.hide();
        };
        _on_mousedown = (event) => {
            if (event.composedPath().includes(this.el)) {
                return;
            }
            if (this.prevent_hide?.(event) ?? false) {
                return;
            }
            this.hide();
        };
        _on_keydown = (event) => {
            if (event.key == "Escape") {
                this.hide();
            }
        };
        _on_blur = () => {
            this.hide();
        };
        remove() {
            this._unlisten();
            this.el.remove();
        }
        _listen() {
            document.addEventListener("mousedown", this._on_mousedown);
            document.addEventListener("keydown", this._on_keydown);
            window.addEventListener("blur", this._on_blur);
        }
        _unlisten() {
            document.removeEventListener("mousedown", this._on_mousedown);
            document.removeEventListener("keydown", this._on_keydown);
            window.removeEventListener("blur", this._on_blur);
        }
        _position(at) {
            const pos = (() => {
                if ("left_of" in at) {
                    const { left, top } = at.left_of.getBoundingClientRect();
                    return { right: left, top };
                }
                if ("right_of" in at) {
                    const { top, right } = at.right_of.getBoundingClientRect();
                    return { left: right, top };
                }
                if ("below" in at) {
                    const { left, bottom } = at.below.getBoundingClientRect();
                    return { left, top: bottom };
                }
                if ("above" in at) {
                    const { left, top } = at.above.getBoundingClientRect();
                    return { left, bottom: top };
                }
                return at;
            })();
            const parent_el = this.el.offsetParent ?? document.body;
            const origin = (() => {
                const rect = parent_el.getBoundingClientRect();
                const style = getComputedStyle(parent_el);
                return {
                    left: rect.left - parseFloat(style.marginLeft),
                    right: rect.right + parseFloat(style.marginRight),
                    top: rect.top - parseFloat(style.marginTop),
                    bottom: rect.bottom + parseFloat(style.marginBottom),
                };
            })();
            const { style } = this.el;
            style.left = pos.left != null ? `${pos.left - origin.left}px` : "auto";
            style.top = pos.top != null ? `${pos.top - origin.top}px` : "auto";
            style.right = pos.right != null ? `${origin.right - pos.right}px` : "auto";
            style.bottom = pos.bottom != null ? `${origin.bottom - pos.bottom}px` : "auto";
        }
        stylesheets() {
            return [base_css_1.default, /*...super.stylesheets(), */ legacy_menus_css_1.default, icons_css_1.default, ...this.extra_styles];
        }
        empty() {
            (0, dom_1.empty)(this.shadow_el);
            this.class_list.clear();
        }
        render() {
            this.empty();
            for (const style of this.stylesheets()) {
                const stylesheet = (0, types_1.isString)(style) ? new dom_1.InlineStyleSheet(style) : style;
                stylesheet.install(this.shadow_el);
            }
            this.class_list.add(menus[this.orientation]);
            const items = this.reversed ? (0, array_1.reversed)(this.items) : this.items;
            for (const item of items) {
                let el;
                if (item == null || item instanceof menus_1.DividerItem) {
                    el = (0, dom_1.div)({ class: menus.divider });
                }
                else if ((0, types_1.isBoolean)(item.disabled) ? item.disabled : item.disabled?.() ?? false) {
                    continue;
                }
                else if ((0, types_1.isPlainObject)(item) && item.custom != null) {
                    el = item.custom;
                }
                else {
                    const icon_el = (() => {
                        if (item.icon != null) {
                            const el = (0, dom_1.div)({ class: menus.menu_icon });
                            (0, resolve_1.apply_icon)(el, item.icon);
                            return el;
                        }
                        else {
                            return null;
                        }
                    })();
                    const checked = (0, types_1.isBoolean)(item.checked) ? item.checked : item.checked?.();
                    const active = checked ?? false ? menus.active : null;
                    const label = this.labels ? item.label : null;
                    el = (0, dom_1.div)({ class: [active], title: item.tooltip, tabIndex: 0 }, icon_el, label);
                    if ((0, types_1.isPlainObject)(item)) {
                        if (item.class != null) {
                            el.classList.add(item.class);
                        }
                        if (item.content != null) {
                            el.append(item.content);
                        }
                    }
                    el.addEventListener("click", () => {
                        this._item_click(item);
                    });
                    el.addEventListener("keydown", (event) => {
                        if (event.key == "Enter") {
                            this._item_click(item);
                        }
                    });
                }
                this.shadow_el.appendChild(el);
            }
        }
        show(at) {
            if (this.items.length == 0) {
                return;
            }
            this.render();
            if (this.shadow_el.children.length == 0) {
                return;
            }
            (this.target.shadowRoot ?? this.target).appendChild(this.el);
            this._position(at ?? { left: 0, top: 0 });
            this._listen();
            this._open = true;
        }
        hide() {
            if (this._open) {
                this._open = false;
                this._unlisten();
                this.el.remove();
            }
        }
        toggle(at) {
            this._open ? this.hide() : this.show(at);
        }
    }
    exports.ContextMenu = ContextMenu;
},
/* styles/legacy_menus.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.menu_icon = "bk-menu-icon";
    exports.horizontal = "bk-horizontal";
    exports.vertical = "bk-vertical";
    exports.divider = "bk-divider";
    exports.active = "bk-active";
    exports.default = `.bk-menu-icon{width:28px;height:28px;mask-size:60% 60%;mask-position:center center;mask-repeat:no-repeat;-webkit-mask-size:60% 60%;-webkit-mask-position:center center;-webkit-mask-repeat:no-repeat;background-size:60%;background-color:transparent;background-repeat:no-repeat;background-position:center center;}:host{position:absolute;display:inline-flex;flex-wrap:nowrap;user-select:none;-webkit-user-select:none;width:auto;height:auto;z-index:var(--bokeh-top-level);cursor:pointer;font-size:var(--font-size);background-color:#fff;border:1px solid #ccc;border-radius:var(--border-radius);box-shadow:2px 4px 8px rgba(0, 0, 0, 0.175);}:host(.bk-horizontal){flex-direction:row;}:host(.bk-vertical){flex-direction:column;}.bk-divider{cursor:default;overflow:hidden;background-color:#e5e5e5;}:host(.bk-horizontal) > .bk-divider{width:1px;margin:5px 0;}:host(.bk-vertical) > .bk-divider{height:1px;margin:0 5px;}:host > :not(.bk-divider){border:1px solid transparent;}:host > :not(.bk-divider).bk-active{border-color:var(--highlight-color);}:host > :not(.bk-divider):hover{background-color:#f9f9f9;}:host > :not(.bk-divider):focus,:host > :not(.bk-divider):focus-visible{outline:1px dotted var(--highlight-color);outline-offset:-1px;}:host > :not(.bk-divider)::-moz-focus-inner{border:0;}:host(.bk-horizontal) > :not(.bk-divider):first-child{border-top-left-radius:var(--border-radius);border-bottom-left-radius:var(--border-radius);}:host(.bk-horizontal) > :not(.bk-divider):last-child{border-top-right-radius:var(--border-radius);border-bottom-right-radius:var(--border-radius);}:host(.bk-vertical) > :not(.bk-divider):first-child{border-top-left-radius:var(--border-radius);border-top-right-radius:var(--border-radius);}:host(.bk-vertical) > :not(.bk-divider):last-child{border-bottom-left-radius:var(--border-radius);border-bottom-right-radius:var(--border-radius);}`;
},
/* styles/tool_button.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.tool_icon = "bk-tool-icon";
    exports.disabled = "bk-disabled";
    exports.hidden = "bk-hidden";
    exports.count = "bk-count";
    exports.tool_chevron = "bk-tool-chevron";
    exports.above = "bk-above";
    exports.below = "bk-below";
    exports.left = "bk-left";
    exports.right = "bk-right";
    exports.active = "bk-active";
    exports.default = `:host{--button-border:2px;--active-tool-border:var(--button-border) solid transparent;}:host{position:relative;width:var(--button-width);height:var(--button-height);cursor:pointer;user-select:none;-webkit-user-select:none;touch-action:none;}.bk-tool-icon{position:relative;top:calc(var(--button-border)/2);width:calc(var(--button-width) - var(--button-border));height:calc(var(--button-height) - var(--button-border));mask-size:60% 60%;mask-position:center center;mask-repeat:no-repeat;-webkit-mask-size:60% 60%;-webkit-mask-position:center center;-webkit-mask-repeat:no-repeat;background-size:60% 60%;background-origin:border-box;background-position:center center;background-repeat:no-repeat;}:host(.bk-disabled) .bk-tool-icon{background-color:var(--icon-color-disabled);cursor:not-allowed;}:host(.bk-hidden){display:none;}.bk-count{position:absolute;top:0;right:0;--height:1.1em;height:var(--height);line-height:var(--height);text-align:center;aspect-ratio:1 / 1;font-size:80%;border-radius:50%;color:white;background-color:var(--icon-color);}.bk-tool-chevron{position:absolute;visibility:hidden;width:8px;height:8px;mask-size:100% 100%;mask-position:center center;mask-repeat:no-repeat;-webkit-mask-size:100% 100%;-webkit-mask-position:center center;-webkit-mask-repeat:no-repeat;}:host(:hover) .bk-tool-chevron{visibility:visible;}:host(.bk-above) .bk-tool-chevron{right:0;bottom:0;background-color:var(--icon-color);mask-image:var(--bokeh-icon-chevron-down);-webkit-mask-image:var(--bokeh-icon-chevron-down);}:host(.bk-below) .bk-tool-chevron{right:0;top:0;background-color:var(--icon-color);mask-image:var(--bokeh-icon-chevron-up);-webkit-mask-image:var(--bokeh-icon-chevron-up);}:host(.bk-left) .bk-tool-chevron{right:0;bottom:0;background-color:var(--icon-color);mask-image:var(--bokeh-icon-chevron-right);-webkit-mask-image:var(--bokeh-icon-chevron-right);}:host(.bk-right) .bk-tool-chevron{left:0;bottom:0;background-color:var(--icon-color);mask-image:var(--bokeh-icon-chevron-left);-webkit-mask-image:var(--bokeh-icon-chevron-left);}:host(:hover){background-color:rgba(192, 192, 192, 0.15);}:host(:focus),:host(:focus-visible){outline:1px dotted var(--highlight-color);outline-offset:-1px;}:host::-moz-focus-inner{border:0;}:host(.bk-above){border-bottom:var(--active-tool-border);}:host(.bk-above.bk-active){border-bottom-color:var(--active-border);}:host(.bk-below){border-top:var(--active-tool-border);}:host(.bk-below.bk-active){border-top-color:var(--active-border);}:host(.bk-right){border-left:var(--active-tool-border);}:host(.bk-right.bk-active){border-left-color:var(--active-border);}:host(.bk-left){border-right:var(--active-tool-border);}:host(.bk-left.bk-active){border-right-color:var(--active-border);}`;
},
/* models/tools/gestures/gesture_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tool_1 = require(379) /* ../tool */;
    const on_off_button_1 = require(391) /* ../on_off_button */;
    class GestureToolView extends tool_1.ToolView {
        get plot_view() {
            return this.parent;
        }
    }
    exports.GestureToolView = GestureToolView;
    class GestureTool extends tool_1.Tool {
        constructor(attrs) {
            super(attrs);
        }
        tool_button() {
            return new on_off_button_1.OnOffButton({ tool: this });
        }
    }
    exports.GestureTool = GestureTool;
},
/* models/tools/on_off_button.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const tool_button_1 = require(385) /* ./tool_button */;
    const tools = tslib_1.__importStar(require(389) /* ../../styles/tool_button.css */);
    class OnOffButtonView extends tool_button_1.ToolButtonView {
        _toggle_active() {
            this.class_list.toggle(tools.active, this.model.tool.active);
        }
        connect_signals() {
            super.connect_signals();
            const { active } = this.model.tool.properties;
            this.on_change(active, () => {
                this._toggle_active();
            });
        }
        render() {
            super.render();
            this._toggle_active();
        }
        tap() {
            const { active } = this.model.tool;
            this.model.tool.active = !active;
        }
    }
    exports.OnOffButtonView = OnOffButtonView;
    class OnOffButton extends tool_button_1.ToolButton {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = OnOffButtonView;
        }
    }
    exports.OnOffButton = OnOffButton;
},
/* models/tools/inspectors/inspect_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const tool_1 = require(379) /* ../tool */;
    const on_off_button_1 = require(391) /* ../on_off_button */;
    const p = tslib_1.__importStar(require(20) /* ../../../core/properties */);
    class InspectToolView extends tool_1.ToolView {
        get plot_view() {
            return this.parent;
        }
    }
    exports.InspectToolView = InspectToolView;
    class InspectTool extends tool_1.Tool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(() => ({
                toggleable: [new p.PropertyAlias("visible")],
            }));
            this.override({
                active: true,
            });
        }
        event_type = "move";
        tool_button() {
            return new on_off_button_1.OnOffButton({ tool: this });
        }
    }
    exports.InspectTool = InspectTool;
},
/* models/tools/actions/action_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tool_1 = require(379) /* ../tool */;
    const click_button_1 = require(394) /* ../click_button */;
    const signaling_1 = require(17) /* ../../../core/signaling */;
    class ActionToolView extends tool_1.ToolView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.do, (arg) => this.doit(arg));
        }
    }
    exports.ActionToolView = ActionToolView;
    class ActionTool extends tool_1.Tool {
        constructor(attrs) {
            super(attrs);
        }
        do = new signaling_1.Signal(this, "do");
        tool_button() {
            return new click_button_1.ClickButton({ tool: this });
        }
        menu_item() {
            const item = super.menu_item();
            item.action = () => this.do.emit(undefined);
            return item;
        }
    }
    exports.ActionTool = ActionTool;
},
/* models/tools/click_button.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const on_off_button_1 = require(391) /* ./on_off_button */;
    class ClickButtonView extends on_off_button_1.OnOffButtonView {
        tap() {
            this.model.tool.do.emit(undefined);
        }
    }
    exports.ClickButtonView = ClickButtonView;
    class ClickButton extends on_off_button_1.OnOffButton {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ClickButtonView;
        }
    }
    exports.ClickButton = ClickButton;
},
/* models/tools/actions/help_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const action_tool_1 = require(393) /* ./action_tool */;
    const icons_css_1 = require(76) /* ../../../styles/icons.css */;
    class HelpToolView extends action_tool_1.ActionToolView {
        doit() {
            window.open(this.model.redirect);
        }
    }
    exports.HelpToolView = HelpToolView;
    class HelpTool extends action_tool_1.ActionTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = HelpToolView;
            this.define(({ Str }) => ({
                redirect: [Str, "https://docs.bokeh.org/en/latest/docs/user_guide/interaction/tools.html"],
            }));
            this.override({
                description: "Click the question mark to learn more about Bokeh plot tools.",
            });
            this.register_alias("help", () => new HelpTool());
        }
        tool_name = "Help";
        tool_icon = icons_css_1.tool_icon_help;
    }
    exports.HelpTool = HelpTool;
},
/* styles/toolbar.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.inner = "bk-inner";
    exports.hidden = "bk-hidden";
    exports.logo = "bk-logo";
    exports.above = "bk-above";
    exports.below = "bk-below";
    exports.left = "bk-left";
    exports.right = "bk-right";
    exports.divider = "bk-divider";
    exports.tool_overflow = "bk-tool-overflow";
    exports.horizontal = "bk-horizontal";
    exports.vertical = "bk-vertical";
    exports.default = `:host{display:flex;flex-wrap:nowrap;align-items:center;user-select:none;-webkit-user-select:none;pointer-events:all;}:host(.bk-inner){background-color:white;opacity:0.8;}:host(.bk-hidden){visibility:hidden;opacity:0;transition:visibility 0.3s linear, opacity 0.3s linear;}.bk-logo{flex-shrink:0;}:host(.bk-above),:host(.bk-below){flex-direction:row;justify-content:flex-end;}:host(.bk-above) .bk-logo,:host(.bk-below) .bk-logo{order:1;margin-left:5px;margin-right:0px;}:host(.bk-left),:host(.bk-right){flex-direction:column;justify-content:flex-start;}:host(.bk-left) .bk-logo,:host(.bk-right) .bk-logo{order:0;margin-bottom:5px;margin-top:0px;}.bk-divider{content:" ";display:inline-block;background-color:var(--button-color);}:host(.bk-above) .bk-divider,:host(.bk-below) .bk-divider{height:10px;width:1px;}:host(.bk-left) .bk-divider,:host(.bk-right) .bk-divider{height:1px;width:10px;}.bk-tool-overflow{color:gray;display:flex;align-items:center;}.bk-tool-overflow:hover{background-color:rgba(192, 192, 192, 0.15);}.bk-tool-overflow:focus,.bk-tool-overflow:focus-visible{outline:var(--outline-width) var(--outline-style) var(--highlight-color);outline-offset:-1px;}.bk-tool-overflow::-moz-focus-inner{border:0;}:host(.bk-above) .bk-tool-overflow,:host(.bk-below) .bk-tool-overflow,:host(.bk-horizontal) .bk-tool-overflow{width:calc(var(--button-width)/2);height:var(--button-height);flex-direction:row;}:host(.bk-left) .bk-tool-overflow,:host(.bk-right) .bk-tool-overflow,:host(.bk-vertical) .bk-tool-overflow{width:var(--button-width);height:calc(var(--button-height)/2);flex-direction:column;}`;
},
/* styles/logo.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.logo = "bk-logo";
    exports.grey = "bk-grey";
    exports.logo_small = "bk-logo-small";
    exports.default = `.bk-logo{margin:5px;position:relative;display:block;background-repeat:no-repeat;}.bk-logo.bk-grey{filter:grayscale(100%);}.bk-logo-small{width:20px;height:20px;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNui8sowAAAOkSURBVDiNjZRtaJVlGMd/1/08zzln5zjP1LWcU9N0NkN8m2CYjpgQYQXqSs0I84OLIC0hkEKoPtiH3gmKoiJDU7QpLgoLjLIQCpEsNJ1vqUOdO7ppbuec5+V+rj4ctwzd8IIbbi6u+8f1539dt3A78eXC7QizUF7gyV1fD1Yqg4JWz84yffhm0qkFqBogB9rM8tZdtwVsPUhWhGcFJngGeWrPzHm5oaMmkfEg1usvLFyc8jLRqDOMru7AyC8saQr7GG7f5fvDeH7Ej8CM66nIF+8yngt6HWaKh7k49Soy9nXurCi1o3qUbS3zWfrYeQDTB/Qj6kX6Ybhw4B+bOYoLKCC9H3Nu/leUTZ1JdRWkkn2ldcCamzrcf47KKXdAJllSlxAOkRgyHsGC/zRday5Qld9DyoM4/q/rUoy/CXh3jzOu3bHUVZeU+DEn8FInkPBFlu3+nW3Nw0mk6vCDiWg8CeJaxEwuHS3+z5RgY+YBR6V1Z1nxSOfoaPa4LASWxxdNp+VWTk7+4vzaou8v8PN+xo+KY2xsw6une2frhw05CTYOmQvsEhjhWjn0bmXPjpE1+kplmmkP3suftwTubK9Vq22qKmrBhpY4jvd5afdRA3wGjFAgcnTK2s4hY0/GPNIb0nErGMCRxWOOX64Z8RAC4oCXdklmEvcL8o0BfkNK4lUg9HTl+oPlQxdNo3Mg4Nv175e/1LDGzZen30MEjRUtmXSfiTVu1kK8W4txyV6BMKlbgk3lMwYCiusNy9fVfvvwMxv8Ynl6vxoByANLTWplvuj/nF9m2+PDtt1eiHPBr1oIfhCChQMBw6Aw0UulqTKZdfVvfG7VcfIqLG9bcldL/+pdWTLxLUy8Qq38heUIjh4XlzZxzQm19lLFlr8vdQ97rjZVOLf8nclzckbcD4wxXMidpX30sFd37Fv/GtwwhzhxGVAprjbg0gCAEeIgwCZyTV2Z1REEW8O4py0wsjeloKoMr6iCY6dP92H6Vw/oTyICIthibxjm/DfN9lVz8IqtqKYLUXfoKVMVQVVJOElGjrnnUt9T9wbgp8AyYKaGlqingHZU/uG2NTZSVqwHQTWkx9hxjkpWDaCg6Ckj5qebgBVbT3V3NNXMSiWSDdGV3hrtzla7J+duwPOToIg42ChPQOQjspnSlp1V+Gjdged7+8UN5CRAV7a5EdFNwCjEaBR27b3W890TE7g24NAP/mMDXRWrGoFPQI9ls/MWO2dWFAar/xcOIImbbpA3zgAAAABJRU5ErkJggg==);}`;
},
/* models/plots/plot_canvas.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const cartesian_frame_1 = require(268) /* ../canvas/cartesian_frame */;
    const canvas_panel_1 = require(269) /* ../canvas/canvas_panel */;
    const canvas_1 = require(399) /* ../canvas/canvas */;
    const renderer_1 = require(98) /* ../renderers/renderer */;
    const composite_renderer_1 = require(97) /* ../renderers/composite_renderer */;
    const tool_proxy_1 = require(383) /* ../tools/tool_proxy */;
    const tool_menu_1 = require(403) /* ../tools/tool_menu */;
    const layout_dom_1 = require(131) /* ../layouts/layout_dom */;
    const annotation_1 = require(96) /* ../annotations/annotation */;
    const title_1 = require(255) /* ../annotations/title */;
    const axis_1 = require(272) /* ../axes/axis */;
    const axis_2 = require(272) /* ../axes/axis */;
    const toolbar_panel_1 = require(404) /* ../annotations/toolbar_panel */;
    const data_range1d_1 = require(118) /* ../ranges/data_range1d */;
    const panel_1 = require(405) /* ../ui/panel */;
    const elements_1 = require(407) /* ../dom/elements */;
    const bokeh_events_1 = require(80) /* ../../core/bokeh_events */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const visuals_1 = require(99) /* ../../core/visuals */;
    const logging_1 = require(11) /* ../../core/logging */;
    const bokeh_events_2 = require(80) /* ../../core/bokeh_events */;
    const signaling_1 = require(17) /* ../../core/signaling */;
    const throttle_1 = require(408) /* ../../core/util/throttle */;
    const types_1 = require(8) /* ../../core/util/types */;
    const array_1 = require(10) /* ../../core/util/array */;
    const iterator_1 = require(15) /* ../../core/util/iterator */;
    const canvas_2 = require(71) /* ../../core/util/canvas */;
    const layout_1 = require(135) /* ../../core/layout */;
    const alignments_1 = require(138) /* ../../core/layout/alignments */;
    const border_1 = require(342) /* ../../core/layout/border */;
    const grid_1 = require(139) /* ../../core/layout/grid */;
    const side_panel_1 = require(257) /* ../../core/layout/side_panel */;
    const bbox_1 = require(62) /* ../../core/util/bbox */;
    const text_1 = require(263) /* ../../core/util/text */;
    const range_manager_1 = require(409) /* ./range_manager */;
    const state_manager_1 = require(410) /* ./state_manager */;
    const settings_1 = require(30) /* ../../core/settings */;
    const dom_1 = require(61) /* ../../core/dom */;
    const node_1 = require(57) /* ../coordinates/node */;
    const plots_css = tslib_1.__importStar(require(411) /* ../../styles/plots.css */);
    const canvas_css = tslib_1.__importStar(require(402) /* ../../styles/canvas.css */);
    const attribution_css = tslib_1.__importStar(require(412) /* ../../styles/attribution.css */);
    const { max } = Math;
    class PlotView extends layout_dom_1.LayoutDOMView {
        visuals;
        _top_panel;
        _bottom_panel;
        _left_panel;
        _right_panel;
        top_panel;
        bottom_panel;
        left_panel;
        right_panel;
        _inner_top_panel;
        _inner_bottom_panel;
        _inner_left_panel;
        _inner_right_panel;
        inner_top_panel;
        inner_bottom_panel;
        inner_left_panel;
        inner_right_panel;
        _frame;
        frame_view;
        get frame() {
            return this.frame_view;
        }
        _canvas;
        canvas_view;
        get canvas() {
            return this.canvas_view;
        }
        _render_count = 0;
        repainted = new signaling_1.Signal0(this, "repainted");
        _computed_style = new dom_1.InlineStyleSheet("", "computed");
        stylesheets() {
            return [...super.stylesheets(), plots_css.default, this._computed_style];
        }
        _title;
        _toolbar;
        _attribution;
        _notifications;
        get toolbar_panel() {
            return this._toolbar != null ? this.views.find_one(this._toolbar) : null;
        }
        _inner_bbox = new bbox_1.BBox();
        _needs_paint = true;
        _invalidated_painters = new Set();
        _invalidate_all = true;
        _state_manager;
        _range_manager;
        get state() {
            return this._state_manager;
        }
        set invalidate_dataranges(value) {
            this._range_manager.invalidate_dataranges = value;
        }
        lod_started;
        _initial_state;
        throttled_paint;
        computed_renderers = [];
        _computed_renderer_views = [];
        get computed_renderer_views() {
            return this._computed_renderer_views;
        }
        get all_renderer_views() {
            const collected = [];
            for (const rv of this.computed_renderer_views) {
                collected.push(rv);
                if (rv instanceof composite_renderer_1.CompositeRendererView) {
                    collected.push(...rv.computed_renderer_views);
                }
            }
            return collected;
        }
        get auto_ranged_renderers() {
            return this.computed_renderer_views.filter(data_range1d_1.is_auto_ranged);
        }
        get base_font_size() {
            const font_size = getComputedStyle(this.el).fontSize;
            const result = (0, text_1.parse_css_font_size)(font_size);
            if (result != null) {
                const { value, unit } = result;
                if (unit == "px") {
                    return value;
                }
            }
            return null;
        }
        /*protected*/ renderer_views = new Map();
        /*protected*/ tool_views = new Map();
        children_views() {
            return [...super.children_views(), ...this.renderer_views.values(), ...this.tool_views.values()];
        }
        get child_models() {
            return [];
        }
        _is_paused = 0;
        get is_paused() {
            return this._is_paused != 0;
        }
        pause() {
            this._is_paused += 1;
        }
        unpause(no_render = false) {
            this._is_paused = max(this._is_paused - 1, 0);
            if (!this.is_paused && !no_render) {
                this.request_repaint();
            }
        }
        _needs_notify = false;
        notify_finished_after_paint() {
            this._needs_notify = true;
        }
        request_repaint() {
            this.request_paint();
        }
        request_paint(...to_invalidate) {
            this.invalidate_painters(...to_invalidate);
            this.schedule_paint();
        }
        invalidate_painters(...to_invalidate) {
            if (to_invalidate.length == 0) {
                this._invalidate_all = true;
                return;
            }
            for (const item of to_invalidate) {
                const view = (() => {
                    if (item instanceof renderer_1.RendererView) {
                        return item;
                    }
                    else {
                        return this.views.get_one(item);
                    }
                })();
                this._invalidated_painters.add(view);
            }
        }
        schedule_paint() {
            if (!this.is_paused) {
                this._await_ready(this.throttled_paint());
            }
        }
        request_layout(force = false) {
            if (force) {
                this._needs_layout = true;
            }
            this.request_repaint();
        }
        reset() {
            if (this.model.reset_policy == "standard") {
                this.state.clear();
                this.reset_range();
                this.reset_selection();
            }
            this.model.trigger_event(new bokeh_events_1.Reset());
        }
        _provide_context_menu() {
            return new tool_menu_1.ToolMenu({ toolbar: this.model.toolbar });
        }
        get_context_menu(xy) {
            const { x, y } = xy;
            for (const rv of (0, array_1.reversed)([...this.renderer_views.values()])) {
                if (rv.context_menu != null && rv.interactive_hit?.(x, y) == true) {
                    return rv.context_menu;
                }
            }
            return super.get_context_menu(xy);
        }
        initialize() {
            this.pause();
            super.initialize();
            this.lod_started = false;
            this.visuals = new visuals_1.Visuals(this);
            this._initial_state = {
                selection: new Map(), // XXX: initial selection?
            };
            this._top_panel = new canvas_panel_1.CanvasPanel({ place: "above" });
            this._bottom_panel = new canvas_panel_1.CanvasPanel({ place: "below" });
            this._left_panel = new canvas_panel_1.CanvasPanel({ place: "left" });
            this._right_panel = new canvas_panel_1.CanvasPanel({ place: "right" });
            this._inner_top_panel = new canvas_panel_1.CanvasPanel({ place: "above", inner: true });
            this._inner_bottom_panel = new canvas_panel_1.CanvasPanel({ place: "below", inner: true });
            this._inner_left_panel = new canvas_panel_1.CanvasPanel({ place: "left", inner: true });
            this._inner_right_panel = new canvas_panel_1.CanvasPanel({ place: "right", inner: true });
            this._frame = new cartesian_frame_1.CartesianFrame({
                place: "center",
                x_scale: this.model.x_scale,
                y_scale: this.model.y_scale,
                x_range: this.model.x_range,
                y_range: this.model.y_range,
                extra_x_ranges: this.model.extra_x_ranges,
                extra_y_ranges: this.model.extra_y_ranges,
                extra_x_scales: this.model.extra_x_scales,
                extra_y_scales: this.model.extra_y_scales,
                aspect_scale: this.model.aspect_scale,
                match_aspect: this.model.match_aspect,
            });
            this._range_manager = new range_manager_1.RangeManager(this);
            this._state_manager = new state_manager_1.StateManager(this, this._initial_state);
            this.throttled_paint = (0, throttle_1.throttle)(() => {
                if (!this.is_destroyed) {
                    this.repaint();
                }
            }, 1000 / 60);
            const { title_location, title } = this.model;
            if (title_location != null && title != null) {
                this._title = title instanceof title_1.Title ? title : new title_1.Title({ text: title });
            }
            const { toolbar_location, toolbar_inner, toolbar } = this.model;
            if (toolbar_location != null) {
                this._toolbar = new toolbar_panel_1.ToolbarPanel({ toolbar });
                toolbar.location = toolbar_location;
                toolbar.inner = toolbar_inner;
            }
            const { hidpi, output_backend } = this.model;
            this._canvas = new canvas_1.Canvas({ hidpi, output_backend });
            this._attribution = new panel_1.Panel({
                position: new node_1.Node({ target: "frame", symbol: "bottom_right" }),
                anchor: "bottom_right",
                elements: [],
                css_variables: {
                    "--max-width": new node_1.Node({ target: "frame", symbol: "width" }),
                },
                stylesheets: [attribution_css.default],
            });
            this._notifications = new panel_1.Panel({
                position: new node_1.Node({ target: this.model, symbol: "top_center" }),
                anchor: "top_center",
                elements: [],
                stylesheets: [`
        :host {
          display: flex;
          flex-direction: column;
          gap: 1em;
          width: max-content;
          max-width: 80%;
        }

        :host:empty {
          display: none;
        }

        :host > div {
          padding: 0.5em;
          border: 1px solid gray;
          border-radius: 0.5em;
          opacity: 0.8;
        }
      `],
            });
        }
        get elements() {
            return [
                this._canvas,
                this._frame,
                this._top_panel,
                this._bottom_panel,
                this._left_panel,
                this._right_panel,
                this._inner_top_panel,
                this._inner_bottom_panel,
                this._inner_left_panel,
                this._inner_right_panel,
                this._attribution,
                this._notifications,
                ...super.elements,
            ];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            this.canvas_view = this._element_views.get(this._canvas);
            this.canvas_view.plot_views = [this];
            this.frame_view = this._element_views.get(this._frame);
            this.top_panel = this._element_views.get(this._top_panel);
            this.bottom_panel = this._element_views.get(this._bottom_panel);
            this.left_panel = this._element_views.get(this._left_panel);
            this.right_panel = this._element_views.get(this._right_panel);
            this.inner_top_panel = this._element_views.get(this._inner_top_panel);
            this.inner_bottom_panel = this._element_views.get(this._inner_bottom_panel);
            this.inner_left_panel = this._element_views.get(this._inner_left_panel);
            this.inner_right_panel = this._element_views.get(this._inner_right_panel);
            await this.build_tool_views();
            await this.build_renderer_views();
            this._range_manager.update_dataranges();
            this._update_touch_action(); // active_changed emits too early, so update manually the first time
        }
        box_sizing() {
            const { width_policy, height_policy, ...sizing } = super.box_sizing();
            const { frame_width, frame_height } = this.model;
            return {
                ...sizing,
                width_policy: frame_width != null && width_policy == "auto" ? "fit" : width_policy,
                height_policy: frame_height != null && height_policy == "auto" ? "fit" : height_policy,
            };
        }
        _intrinsic_display() {
            return { inner: this.model.flow_mode, outer: "grid" };
        }
        _compute_layout_panels() {
            const outer_above = (0, array_1.copy)(this.model.above);
            const outer_below = (0, array_1.copy)(this.model.below);
            const outer_left = (0, array_1.copy)(this.model.left);
            const outer_right = (0, array_1.copy)(this.model.right);
            const inner_above = [];
            const inner_below = [];
            const inner_left = [];
            const inner_right = [];
            const get_side = (side, inner = false) => {
                switch (side) {
                    case "above": return inner ? inner_above : outer_above;
                    case "below": return inner ? inner_below : outer_below;
                    case "left": return inner ? inner_left : outer_left;
                    case "right": return inner ? inner_right : outer_right;
                }
            };
            const { title_location } = this.model;
            if (title_location != null && this._title != null) {
                get_side(title_location).push(this._title);
            }
            if (this._toolbar != null) {
                const { location } = this._toolbar.toolbar;
                if (!this.model.toolbar_inner) {
                    const panels = get_side(location);
                    let push_toolbar = true;
                    if (this.model.toolbar_sticky) {
                        for (let i = 0; i < panels.length; i++) {
                            const panel = panels[i];
                            if (panel instanceof title_1.Title) {
                                if (location == "above" || location == "below") {
                                    panels[i] = [panel, this._toolbar];
                                }
                                else {
                                    panels[i] = [this._toolbar, panel];
                                }
                                push_toolbar = false;
                                break;
                            }
                        }
                    }
                    if (push_toolbar) {
                        panels.push(this._toolbar);
                    }
                }
                else {
                    const panels = get_side(location, true);
                    panels.push(this._toolbar);
                }
            }
            return {
                outer_above,
                outer_below,
                outer_left,
                outer_right,
                inner_above,
                inner_below,
                inner_left,
                inner_right,
            };
        }
        _make_layout() {
            return new border_1.BorderLayout();
        }
        _update_layout() {
            super._update_layout();
            // TODO: invalidating all should imply "needs paint"
            this._invalidate_all = true;
            this._needs_paint = true;
            const layout = this._make_layout();
            const { frame_align } = this.model;
            layout.aligns = (() => {
                if ((0, types_1.isBoolean)(frame_align)) {
                    return { left: frame_align, right: frame_align, top: frame_align, bottom: frame_align };
                }
                else {
                    const { left = true, right = true, top = true, bottom = true } = frame_align;
                    return { left, right, top, bottom };
                }
            })();
            layout.set_sizing({ width_policy: "max", height_policy: "max" });
            if (this.visuals.outline_line.doit) {
                const width = this.visuals.outline_line.line_width.get_value();
                layout.center_border_width = width;
            }
            const set_layout = (side, model) => {
                if (model instanceof annotation_1.Annotation || model instanceof axis_1.Axis) {
                    const view = this.views.get_one(model);
                    view.panel = new side_panel_1.SidePanel(side);
                    view.update_layout?.();
                    return view.layout;
                }
                else {
                    const view = this.views.get_one(model);
                    const layout = new layout_1.ElementLayout(view.el);
                    layout.set_sizing({ width_policy: "fixed", height_policy: "fixed" });
                    return layout;
                }
            };
            const set_layouts = (side, panels) => {
                const horizontal = side == "above" || side == "below";
                const layouts = [];
                for (const panel of panels) {
                    if ((0, types_1.isArray)(panel)) {
                        const items = panel.map((subpanel) => {
                            const item = set_layout(side, subpanel);
                            if (item == null) {
                                return undefined;
                            }
                            if (subpanel instanceof toolbar_panel_1.ToolbarPanel) {
                                const dim = horizontal ? "width_policy" : "height_policy";
                                item.set_sizing({ ...item.sizing, [dim]: "min" });
                            }
                            return item;
                        }).filter((item) => item != null);
                        let layout;
                        if (horizontal) {
                            layout = new grid_1.Row(items);
                            layout.set_sizing({ width_policy: "max", height_policy: "min" });
                        }
                        else {
                            layout = new grid_1.Column(items);
                            layout.set_sizing({ width_policy: "min", height_policy: "max" });
                        }
                        layout.absolute = true;
                        layouts.push(layout);
                    }
                    else {
                        const layout = set_layout(side, panel);
                        if (layout != null) {
                            layouts.push(layout);
                        }
                    }
                }
                return layouts;
            };
            const min_border = this.model.min_border ?? 0;
            layout.min_border = {
                left: this.model.min_border_left ?? min_border,
                top: this.model.min_border_top ?? min_border,
                right: this.model.min_border_right ?? min_border,
                bottom: this.model.min_border_bottom ?? min_border,
            };
            const center_panel = new alignments_1.NodeLayout();
            const top_panel = new alignments_1.VStack();
            const bottom_panel = new alignments_1.VStack();
            const left_panel = new alignments_1.HStack();
            const right_panel = new alignments_1.HStack();
            const inner_top_panel = new alignments_1.VStack();
            const inner_bottom_panel = new alignments_1.VStack();
            const inner_left_panel = new alignments_1.HStack();
            const inner_right_panel = new alignments_1.HStack();
            center_panel.absolute = true;
            top_panel.absolute = true;
            bottom_panel.absolute = true;
            left_panel.absolute = true;
            right_panel.absolute = true;
            inner_top_panel.absolute = true;
            inner_bottom_panel.absolute = true;
            inner_left_panel.absolute = true;
            inner_right_panel.absolute = true;
            center_panel.children =
                this.model.center.filter((obj) => {
                    return obj instanceof annotation_1.Annotation;
                }).map((model) => {
                    const view = this.views.get_one(model);
                    view.update_layout?.();
                    return view.layout;
                }).filter((layout) => layout != null);
            const { frame_width, frame_height } = this.model;
            center_panel.set_sizing({
                ...(frame_width != null ? { width_policy: "fixed", width: frame_width } : { width_policy: "fit" }),
                ...(frame_height != null ? { height_policy: "fixed", height: frame_height } : { height_policy: "fit" }),
            });
            center_panel.on_resize((bbox) => this.frame.set_geometry(bbox));
            top_panel.on_resize((bbox) => this.top_panel.set_geometry(bbox));
            bottom_panel.on_resize((bbox) => this.bottom_panel.set_geometry(bbox));
            left_panel.on_resize((bbox) => this.left_panel.set_geometry(bbox));
            right_panel.on_resize((bbox) => this.right_panel.set_geometry(bbox));
            const { outer_above, outer_below, outer_left, outer_right, inner_above, inner_below, inner_left, inner_right, } = this._compute_layout_panels();
            top_panel.children = (0, array_1.reversed)(set_layouts("above", outer_above));
            bottom_panel.children = set_layouts("below", outer_below);
            left_panel.children = (0, array_1.reversed)(set_layouts("left", outer_left));
            right_panel.children = set_layouts("right", outer_right);
            inner_top_panel.on_resize((bbox) => this.inner_top_panel.set_geometry(bbox));
            inner_bottom_panel.on_resize((bbox) => this.inner_bottom_panel.set_geometry(bbox));
            inner_left_panel.on_resize((bbox) => this.inner_left_panel.set_geometry(bbox));
            inner_right_panel.on_resize((bbox) => this.inner_right_panel.set_geometry(bbox));
            inner_top_panel.children = set_layouts("above", inner_above);
            inner_bottom_panel.children = set_layouts("below", inner_below);
            inner_left_panel.children = set_layouts("left", inner_left);
            inner_right_panel.children = set_layouts("right", inner_right);
            top_panel.set_sizing({ width_policy: "fit", height_policy: "min" /*, min_height: layout.min_border.top*/ });
            bottom_panel.set_sizing({ width_policy: "fit", height_policy: "min" /*, min_height: layout.min_width.bottom*/ });
            left_panel.set_sizing({ width_policy: "min", height_policy: "fit" /*, min_width: layout.min_width.left*/ });
            right_panel.set_sizing({ width_policy: "min", height_policy: "fit" /*, min_width: layout.min_width.right*/ });
            inner_top_panel.set_sizing({ width_policy: "fit", height_policy: "min" });
            inner_bottom_panel.set_sizing({ width_policy: "fit", height_policy: "min" });
            inner_left_panel.set_sizing({ width_policy: "min", height_policy: "fit" });
            inner_right_panel.set_sizing({ width_policy: "min", height_policy: "fit" });
            layout.center_panel = center_panel;
            layout.top_panel = top_panel;
            layout.bottom_panel = bottom_panel;
            layout.left_panel = left_panel;
            layout.right_panel = right_panel;
            layout.inner_top_panel = inner_top_panel;
            layout.inner_bottom_panel = inner_bottom_panel;
            layout.inner_left_panel = inner_left_panel;
            layout.inner_right_panel = inner_right_panel;
            this.layout = layout;
            const wrapper = (flex_direction, children) => {
                return (0, dom_1.div)({
                    style: {
                        display: "flex",
                        flex_direction,
                        width: "100%",
                        height: "100%",
                    },
                }, children);
            };
            const process = (panels, dim) => {
                return panels.map((obj) => {
                    if ((0, types_1.isArray)(obj)) {
                        const els = this.views.select(obj).map((view) => {
                            const { el } = view;
                            // allow to shrink toolbars, but keep everything else content sized
                            el.style.flex = view.model instanceof toolbar_panel_1.ToolbarPanel ? "1" : "none";
                            return el;
                        });
                        switch (dim) {
                            case "x": return wrapper("row", els);
                            case "y": return wrapper("column", els);
                        }
                    }
                    else {
                        return this.views.get_one(obj).el;
                    }
                });
            };
            const above_els = process(outer_above, "x");
            const below_els = process(outer_below, "x");
            const left_els = process(outer_left, "y");
            const right_els = process(outer_right, "y");
            this.top_panel.shadow_el.append(...(0, array_1.reversed)(above_els));
            this.bottom_panel.shadow_el.append(...below_els);
            this.left_panel.shadow_el.append(...(0, array_1.reversed)(left_els));
            this.right_panel.shadow_el.append(...right_els);
            const inner_above_els = process(inner_above, "x");
            const inner_below_els = process(inner_below, "x");
            const inner_left_els = process(inner_left, "y");
            const inner_right_els = process(inner_right, "y");
            this.inner_top_panel.shadow_el.append(...(0, array_1.reversed)(inner_above_els));
            this.inner_bottom_panel.shadow_el.append(...inner_below_els);
            this.inner_left_panel.shadow_el.append(...(0, array_1.reversed)(inner_left_els));
            this.inner_right_panel.shadow_el.append(...inner_right_els);
            const center_els = this.views.select(this.model.center).map((view) => view.el);
            const renderer_els = this.views.select(this.model.renderers).map((view) => view.el);
            this.frame.shadow_el.append(...renderer_els, ...center_els);
        }
        _measure_layout() {
            const { frame_width, frame_height } = this.model;
            const frame = {
                width: frame_width == null ? "1fr" : (0, dom_1.px)(frame_width),
                height: frame_height == null ? "1fr" : (0, dom_1.px)(frame_height),
            };
            const { layout } = this;
            const top = layout.top_panel.measure({ width: Infinity, height: Infinity });
            const bottom = layout.bottom_panel.measure({ width: Infinity, height: Infinity });
            const left = layout.left_panel.measure({ width: Infinity, height: Infinity });
            const right = layout.right_panel.measure({ width: Infinity, height: Infinity });
            const top_height = max(top.height, layout.min_border.top);
            const bottom_height = max(bottom.height, layout.min_border.bottom);
            const left_width = max(left.width, layout.min_border.left);
            const right_width = max(right.width, layout.min_border.right);
            this._computed_style.replace(`
      :host {
        grid-template-rows: ${top_height}px ${frame.height} ${bottom_height}px;
        grid-template-columns: ${left_width}px ${frame.width} ${right_width}px;
      }
    `);
        }
        get axis_views() {
            const views = [];
            for (const [, renderer_view] of this.renderer_views) {
                if (renderer_view instanceof axis_2.AxisView) {
                    views.push(renderer_view);
                }
            }
            return views;
        }
        update_range(range_info, options) {
            this.pause();
            this._range_manager.update(range_info, options);
            this.unpause();
        }
        reset_range() {
            this.pause();
            this._range_manager.reset();
            this.unpause();
            this.trigger_ranges_update_event();
        }
        trigger_ranges_update_event(extra_ranges = []) {
            /**
             * Emits `RangesUpdate` event on all plots linked by all
             * ranges managed by this plot's range manager and linked
             * by additional context dependent ranges (`extra_ranges`).
             */
            const { x_ranges, y_ranges } = this._range_manager.ranges();
            const ranges = [...x_ranges, ...y_ranges, ...extra_ranges];
            const linked_plots = new Set(ranges.flatMap((r) => [...r.linked_plots]));
            for (const plot_view of linked_plots) {
                const { x_range, y_range } = plot_view.model;
                const event = new bokeh_events_2.RangesUpdate(x_range.start, x_range.end, y_range.start, y_range.end);
                plot_view.model.trigger_event(event);
            }
        }
        get_selection() {
            const selection = new Map();
            for (const renderer of this.model.data_renderers) {
                const { selected } = renderer.selection_manager.source;
                selection.set(renderer, selected);
            }
            return selection;
        }
        update_selection(selections) {
            for (const renderer of this.model.data_renderers) {
                const ds = renderer.selection_manager.source;
                if (selections != null) {
                    const selection = selections.get(renderer);
                    if (selection != null) {
                        ds.selected.update(selection, true);
                    }
                }
                else {
                    ds.selection_manager.clear();
                }
            }
        }
        reset_selection() {
            this.update_selection(null);
        }
        _needs_layout = false;
        _invalidate_layout_if_needed() {
            const needs_layout = (() => {
                if (this._needs_layout) {
                    this.invalidate_painters();
                    return true;
                }
                else {
                    for (const panel of this.model.side_panels) {
                        const view = this.renderer_views.get(panel); // TODO
                        if (view != null) {
                            if (view.layout?.has_size_changed() ?? false) {
                                this.invalidate_painters(view);
                                return true;
                            }
                        }
                    }
                    return false;
                }
            })();
            if (needs_layout) {
                this._needs_layout = false;
                this.compute_layout();
            }
        }
        *_compute_renderers() {
            const { above, below, left, right, center, renderers } = this.model;
            yield* renderers;
            yield* [...above, ...below, ...left, ...right, ...center]; // TODO
            if (this._title != null) {
                yield this._title;
            }
            if (this._toolbar != null) {
                yield this._toolbar;
            }
            for (const [, view] of this.tool_views) {
                yield* view.overlays;
            }
        }
        _update_attribution() {
            const attribution = [
                ...this.model.attribution,
                ...this.computed_renderer_views.filter((rv) => rv.displayed).map((rv) => rv.attribution),
            ].filter((rv) => rv != null);
            const elements = attribution.map((attrib) => (0, types_1.isString)(attrib) ? new elements_1.Div({ children: [attrib] }) : attrib);
            this._attribution.elements = elements;
            // TODO this._attribution.title = contents_el.textContent!.replace(/\s*\n\s*/g, " ")
        }
        async _build_renderers() {
            this.computed_renderers = [...this._compute_renderers()];
            const result = await (0, build_views_1.build_views)(this.renderer_views, this.computed_renderers, { parent: (model) => model instanceof layout_dom_1.LayoutDOM ? null : this });
            this._computed_renderer_views = this.computed_renderers.map((r) => this.renderer_views.get(r)).filter((rv) => rv != null); // TODO race condition again
            for (const renderer_view of result.created) {
                this.on_change(renderer_view.model.properties.visible, () => this._update_attribution());
            }
            this._update_attribution();
            return result;
        }
        async _update_renderers() {
            const { created } = await this._build_renderers();
            const created_views = new Set(created);
            // Since appending to a DOM node will move the node to the end if it has
            // already been added appending all the children in order will result in
            // correct ordering.
            for (const view of this.renderer_views.values()) {
                const is_new = created_views.has(view);
                const target = view.rendering_target() ?? this.self_target;
                if (is_new) {
                    view.render_to(target);
                }
                else {
                    target.append(view.el);
                }
            }
            this.r_after_render();
        }
        async build_renderer_views() {
            await this._build_renderers();
        }
        async build_tool_views() {
            const tool_models = (0, iterator_1.flat_map)(this.model.toolbar.tools, (item) => item instanceof tool_proxy_1.ToolProxy ? item.tools : [item]);
            const { created } = await (0, build_views_1.build_views)(this.tool_views, [...tool_models], { parent: this });
            created.map((tool_view) => this.canvas_view.ui_event_bus.register_tool(tool_view));
        }
        connect_signals() {
            super.connect_signals();
            const { x_range, y_range, x_scale, y_scale, extra_x_ranges, extra_y_ranges, extra_x_scales, extra_y_scales, aspect_scale, match_aspect, } = this.model.properties;
            this.on_change([
                x_range, y_range,
                x_scale, y_scale,
                extra_x_ranges, extra_y_ranges,
                extra_x_scales, extra_y_scales,
                aspect_scale, match_aspect,
            ], () => {
                const { x_range, y_range, x_scale, y_scale, extra_x_ranges, extra_y_ranges, extra_x_scales, extra_y_scales, aspect_scale, match_aspect, } = this.model;
                this._frame.setv({
                    x_range, y_range,
                    x_scale, y_scale,
                    extra_x_ranges, extra_y_ranges,
                    extra_x_scales, extra_y_scales,
                    aspect_scale, match_aspect,
                });
            });
            const { above, below, left, right, center, renderers } = this.model.properties;
            this.on_change([above, below, left, right, center, renderers], async () => {
                await this._update_renderers();
                this.invalidate_layout();
            });
            this.connect(this.model.toolbar.properties.tools.change, async () => {
                await this.build_tool_views();
                await this._update_renderers();
            });
            const { frame_width, frame_height, frame_align } = this.model.properties;
            this.on_change([frame_width, frame_height, frame_align], () => this.invalidate_layout());
            const { min_border, min_border_top, min_border_bottom, min_border_left, min_border_right } = this.model.properties;
            this.on_change([min_border, min_border_top, min_border_bottom, min_border_left, min_border_right], () => this.invalidate_layout());
            const connect_range = (range) => {
                this.connect(range.change, () => {
                    this.request_repaint();
                });
                this.connect(range.properties.min_interval.change, () => {
                    this._constrain_range_interval(range);
                });
                this.connect(range.properties.max_interval.change, () => {
                    this._constrain_range_interval(range);
                });
            };
            const { x_ranges, y_ranges } = this.frame;
            for (const [, range] of x_ranges) {
                connect_range(range);
            }
            for (const [, range] of y_ranges) {
                connect_range(range);
            }
            this.connect(this.model.change, () => this.request_repaint());
            this.connect(this.model.reset, () => this.reset());
            const { toolbar_location } = this.model.properties;
            this.on_change(toolbar_location, async () => {
                const { toolbar_location } = this.model;
                if (this._toolbar != null) {
                    if (toolbar_location != null) {
                        this._toolbar.toolbar.location = toolbar_location;
                    }
                    else {
                        this._toolbar = undefined;
                        await this._update_renderers();
                    }
                }
                else {
                    if (toolbar_location != null) {
                        const { toolbar, toolbar_inner } = this.model;
                        this._toolbar = new toolbar_panel_1.ToolbarPanel({ toolbar });
                        toolbar.location = toolbar_location;
                        toolbar.inner = toolbar_inner;
                        await this._update_renderers();
                    }
                }
                this.invalidate_layout();
            });
            const { hold_render } = this.model.properties;
            this.on_change(hold_render, () => {
                if (!this.model.hold_render) {
                    this.request_repaint();
                }
            });
            this.model.toolbar.active_changed.connect(() => this._update_touch_action());
            if (visualViewport != null) {
                visualViewport.addEventListener("resize", () => {
                    if (this.canvas.resize()) {
                        this.request_repaint();
                    }
                }, { signal: this.abort_signal });
            }
        }
        _constrain_range_interval(range) {
            const range_info = this._range_manager.constrain_interval(range);
            if (range_info != null) {
                this.update_range(range_info);
            }
        }
        _update_touch_action() {
            const { toolbar } = this.model;
            let has_pan = false;
            let has_scroll = false;
            for (const tool of toolbar.tools) {
                if (tool.active) {
                    const { event_types } = tool;
                    if (event_types.includes("pan")) {
                        has_pan = true;
                    }
                    if (event_types.includes("scroll")) {
                        has_scroll = true;
                    }
                    if (has_pan && has_scroll) {
                        break;
                    }
                }
            }
            const touch_action = (() => {
                if (!has_pan && !has_scroll) {
                    return "auto";
                }
                else if (!has_pan) {
                    return "pan-x pan-y";
                }
                else if (!has_scroll) {
                    return "pinch-zoom"; // scroll implies pinch where applicable
                }
                else {
                    return "none";
                }
            })();
            this.canvas.touch_action.replace(`
      .${canvas_css.events} {
        touch-action: ${touch_action};
      }
    `);
        }
        has_finished() {
            if (!super.has_finished()) {
                return false;
            }
            if (this.model.visible) {
                for (const [, renderer_view] of this.renderer_views) {
                    if (!renderer_view.has_finished()) {
                        return false;
                    }
                }
            }
            return true;
        }
        _after_layout() {
            super._after_layout();
            this.unpause(true);
            const left = this.layout.left_panel.bbox;
            const right = this.layout.right_panel.bbox;
            const center = this.layout.center_panel.bbox;
            const top = this.layout.top_panel.bbox;
            const bottom = this.layout.bottom_panel.bbox;
            const { bbox } = this;
            const top_height = top.bottom;
            const bottom_height = bbox.height - bottom.top;
            const left_width = left.right;
            const right_width = bbox.width - right.left;
            // TODO: don't replace here; inject stylesheet?
            this.canvas.parent_style.replace(`
      .bk-events {
        grid-template-rows: ${(0, dom_1.px)(top_height)} ${(0, dom_1.px)(center.height)} ${(0, dom_1.px)(bottom_height)};
        grid-template-columns: ${(0, dom_1.px)(left_width)} ${(0, dom_1.px)(center.width)} ${(0, dom_1.px)(right_width)};
      }
    `);
            for (const [, child_view] of this.renderer_views) {
                if (child_view instanceof annotation_1.AnnotationView) {
                    child_view.after_layout?.();
                }
            }
            this.model.setv({
                inner_width: Math.round(this.frame.bbox.width),
                inner_height: Math.round(this.frame.bbox.height),
                outer_width: Math.round(this.bbox.width),
                outer_height: Math.round(this.bbox.height),
            }, { no_change: true });
            if (this.model.match_aspect) {
                this.pause();
                this._range_manager.update_dataranges();
                this.unpause(true);
            }
            if (this.canvas_view.update_bbox()) {
                this._invalidate_all = true;
                this._needs_paint = true;
            }
            const { inner_bbox } = this.layout;
            if (!this._inner_bbox.equals(inner_bbox)) {
                this._inner_bbox = inner_bbox;
                this._invalidate_all = true;
                this._needs_paint = true;
            }
            if (this._needs_paint) {
                // XXX: can't be this.request_paint(), because it would trigger back-and-forth
                // layout recomputing feedback loop between plots. Plots are also much more
                // responsive this way, especially in interactive mode.
                this.paint();
            }
        }
        render() {
            super.render();
            for (const renderer_view of this.computed_renderer_views) {
                const target = renderer_view.rendering_target() ?? this.self_target;
                renderer_view.render_to(target);
            }
        }
        repaint() {
            this._invalidate_layout_if_needed();
            this.paint();
        }
        paint() {
            if (this.is_paused || this.model.hold_render) {
                return;
            }
            if (this.is_displayed) {
                logging_1.logger.trace(`${this.toString()}.paint()`);
                this._actual_paint();
            }
            else {
                // This is possibly the first render cycle, but plot isn't displayed,
                // so all renderers have to be manually marked as finished, because
                // their `render()` method didn't run.
                for (const renderer_view of this.computed_renderer_views) {
                    renderer_view.force_finished();
                }
            }
            if (this._needs_notify) {
                this._needs_notify = false;
                this.notify_finished();
            }
        }
        _actual_paint() {
            logging_1.logger.trace(`${this.toString()}._actual_paint ${this._render_count} start`);
            const { document } = this.model;
            if (document != null) {
                const interactive_duration = document.interactive_duration();
                if (interactive_duration >= 0 && interactive_duration < this.model.lod_interval) {
                    setTimeout(() => {
                        if (document.interactive_duration() > this.model.lod_timeout) {
                            document.interactive_stop();
                        }
                        this.request_repaint(); // TODO: this.schedule_paint()
                    }, this.model.lod_timeout);
                }
                else {
                    document.interactive_stop();
                }
            }
            if (this._range_manager.invalidate_dataranges || this.model.window_axis != "none") {
                this._range_manager.update_dataranges();
                this._invalidate_layout_if_needed();
            }
            let do_primary = false;
            let do_overlays = false;
            if (this._invalidate_all) {
                do_primary = true;
                do_overlays = true;
            }
            else {
                for (const painter of this._invalidated_painters) {
                    const { level } = painter.model;
                    if (level != "overlay") {
                        do_primary = true;
                    }
                    else {
                        do_overlays = true;
                    }
                    if (do_primary && do_overlays) {
                        break;
                    }
                }
            }
            this._invalidated_painters.clear();
            this._invalidate_all = false;
            if (do_primary) {
                const { primary } = this.canvas_view;
                const ctx = primary.prepare();
                this._paint_primary(ctx);
                primary.finish();
            }
            if (do_overlays || settings_1.settings.wireframe) {
                const { overlays } = this.canvas_view;
                const ctx = overlays.prepare();
                this._paint_overlays(ctx);
                overlays.finish();
            }
            if (this._initial_state.range == null) {
                this._initial_state.range = this._range_manager.compute_initial() ?? undefined;
            }
            for (const element_view of this.element_views) {
                element_view.reposition();
            }
            this._needs_paint = false;
            this.repainted.emit();
            logging_1.logger.trace(`${this.toString()}._actual_paint ${this._render_count} end`);
            this._render_count++;
        }
        _paint_primary(ctx) {
            const frame_box = this.frame.bbox;
            this.canvas_view.prepare_webgl(frame_box);
            this._paint_empty(ctx, frame_box);
            this._paint_outline(ctx, frame_box);
            this._paint_levels(ctx, "image", frame_box, true);
            this._paint_levels(ctx, "underlay", frame_box, true);
            this._paint_levels(ctx, "glyph", frame_box, true);
            this._paint_levels(ctx, "guide", frame_box, false);
            this._paint_levels(ctx, "annotation", frame_box, false);
        }
        _paint_overlays(ctx) {
            const frame_box = this.frame.bbox;
            this._paint_levels(ctx, "overlay", frame_box, false);
            if (settings_1.settings.wireframe) {
                this.paint_layout(ctx, this.layout);
            }
        }
        _paint_levels(ctx, level, clip_box, global_clip) {
            for (const renderer_view of this.computed_renderer_views) {
                if (renderer_view.model.level != level) {
                    continue;
                }
                ctx.save();
                if (global_clip || renderer_view.needs_clip) {
                    ctx.beginPath();
                    ctx.rect(...clip_box.args);
                    ctx.clip();
                }
                renderer_view.paint(ctx);
                ctx.restore();
                if (renderer_view.has_webgl) {
                    this.canvas_view.blit_webgl(ctx);
                }
            }
        }
        paint_layout(ctx, layout) {
            const { x, y, width, height } = layout.bbox;
            ctx.strokeStyle = "blue";
            ctx.strokeRect(x, y, width, height);
            for (const child of layout) {
                ctx.save();
                if (!layout.absolute) {
                    ctx.translate(x, y);
                }
                this.paint_layout(ctx, child);
                ctx.restore();
            }
        }
        /**
         * Shrink bbox by 1px to make right and bottom lines visible if they are on the edge of the canvas.
         */
        _shrink_to_canvas(bbox) {
            let { x, y, width, height } = bbox;
            if (width > 0 && x + width == this.bbox.width) {
                width -= 1;
            }
            if (height > 0 && y + height == this.bbox.height) {
                height -= 1;
            }
            return new bbox_1.BBox({ x, y, width, height });
        }
        _paint_empty(ctx, frame_box) {
            const canvas_box = this.bbox.relative();
            const { border_fill, border_hatch } = this.visuals;
            if (border_fill.doit || border_hatch.doit) {
                ctx.save();
                ctx.beginPath();
                ctx.rect_bbox(canvas_box);
                ctx.rect_bbox(frame_box);
                ctx.clip("evenodd");
                ctx.beginPath();
                ctx.rect_bbox(canvas_box);
                border_fill.apply(ctx);
                border_hatch.apply(ctx);
                ctx.restore();
            }
            const { border_line } = this.visuals;
            if (border_line.doit) {
                ctx.beginPath();
                ctx.rect_bbox(this._shrink_to_canvas(canvas_box));
                border_line.apply(ctx);
            }
            const { background_fill, background_hatch } = this.visuals;
            if (background_fill.doit || background_hatch.doit) {
                ctx.beginPath();
                ctx.rect_bbox(frame_box);
                background_fill.apply(ctx);
                background_hatch.apply(ctx);
            }
        }
        _paint_outline(ctx, frame_box) {
            const { outline_line } = this.visuals;
            if (outline_line.doit) {
                ctx.rect_bbox(this._shrink_to_canvas(frame_box));
                outline_line.apply(ctx);
            }
        }
        _force_paint = false;
        get is_forcing_paint() {
            return this._force_paint;
        }
        force_paint(fn) {
            try {
                this._force_paint = true;
                fn();
            }
            finally {
                this._force_paint = false;
            }
        }
        export(type = "auto", hidpi = true) {
            const output_backend = (() => {
                switch (type) {
                    case "auto": return this.canvas_view.model.output_backend;
                    case "png": return "canvas";
                    case "svg": return "svg";
                }
            })();
            const composite = new canvas_2.CanvasLayer(output_backend, hidpi);
            const { width, height } = this.bbox;
            composite.resize(width, height);
            if (width != 0 && height != 0) {
                this.force_paint(() => {
                    const ctx = composite.prepare();
                    this._paint_primary(ctx);
                    this._paint_overlays(ctx);
                    composite.finish();
                });
                for (const view of this.renderer_views.values()) {
                    if ((0, canvas_2.is_Exportable)(view)) {
                        const region = view.export(type, hidpi);
                        const { x, y } = view.bbox.scale(composite.pixel_ratio);
                        composite.ctx.drawImage(region.canvas, x, y);
                    }
                }
            }
            return composite;
        }
        resolve_frame() {
            return this.frame;
        }
        resolve_canvas() {
            return this.canvas;
        }
        resolve_plot() {
            return this;
        }
        resolve_xy(coord) {
            const { x, y } = coord;
            const sx = this.frame.x_scale.compute(x);
            const sy = this.frame.y_scale.compute(y);
            if (this.frame.bbox.contains(sx, sy)) {
                return { x: sx, y: sy };
            }
            else {
                return { x: NaN, y: NaN };
            }
        }
        resolve_indexed(coord) {
            const { index: i, renderer } = coord;
            const rv = this.views.find_one(renderer);
            if (rv != null && rv.has_finished()) {
                const [sx, sy] = rv.glyph.scenterxy(i, NaN, NaN);
                if (this.frame.bbox.contains(sx, sy)) {
                    return { x: sx, y: sy };
                }
            }
            return { x: NaN, y: NaN };
        }
        _messages = new Map();
        notify_about(message) {
            if (this._messages.has(message)) {
                return;
            }
            const el = new elements_1.Div({ children: [message] });
            const timer = setTimeout(() => {
                this._messages.delete(message);
                this._notifications.elements = this._notifications.elements.filter((item) => item != el);
            }, 2000);
            this._messages.set(message, timer);
            this._notifications.elements = [...this._notifications.elements, el];
            logging_1.logger.info(message);
        }
        serializable_children() {
            // TODO temporarily remove CanvasPanel views to reduce baseline noise
            return super.serializable_children().filter((view) => view.model instanceof cartesian_frame_1.CartesianFrame || !(view.model instanceof canvas_panel_1.CanvasPanel));
        }
    }
    exports.PlotView = PlotView;
},
/* models/canvas/canvas.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const settings_1 = require(30) /* ../../core/settings */;
    const logging_1 = require(11) /* ../../core/logging */;
    const dom_1 = require(61) /* ../../core/dom */;
    const enums_1 = require(21) /* ../../core/enums */;
    const ui_events_1 = require(400) /* ../../core/ui_events */;
    const modules_1 = require(265) /* ../../core/util/modules */;
    const canvas_1 = require(71) /* ../../core/util/canvas */;
    const ui_element_1 = require(55) /* ../ui/ui_element */;
    const dom_2 = require(61) /* ../../core/dom */;
    const canvas_css = tslib_1.__importStar(require(402) /* ../../styles/canvas.css */);
    const icons_css_1 = tslib_1.__importDefault(require(76) /* ../../styles/icons.css */);
    async function init_webgl() {
        // We use a global invisible canvas and gl context. By having a global context,
        // we avoid the limitation of max 16 contexts that most browsers have.
        const canvas = document.createElement("canvas");
        const gl = canvas.getContext("webgl", { alpha: true, antialias: false, depth: false, premultipliedAlpha: true });
        // If WebGL is available, we store a reference to the ReGL wrapper on
        // the ctx object, because that's what gets passed everywhere.
        if (gl != null) {
            const webgl = await (0, modules_1.load_module)(Promise.resolve().then(() => tslib_1.__importStar(require(640) /* ../glyphs/webgl */)));
            if (webgl != null) {
                const regl_wrapper = webgl.get_regl(gl);
                if (regl_wrapper.has_webgl) {
                    return { canvas, regl_wrapper };
                }
                else {
                    logging_1.logger.trace("WebGL is supported, but not the required extensions");
                }
            }
            else {
                logging_1.logger.trace("WebGL is supported, but bokehjs(.min).js bundle is not available");
            }
        }
        else {
            logging_1.logger.trace("WebGL is not supported");
        }
        return null;
    }
    const global_webgl = (() => {
        let _global_webgl;
        return async () => {
            if (_global_webgl !== undefined) {
                return _global_webgl;
            }
            else {
                return _global_webgl = await init_webgl();
            }
        };
    })();
    class CanvasView extends ui_element_1.UIElementView {
        webgl = null;
        underlays_el;
        primary;
        overlays;
        overlays_el;
        events_el;
        ui_event_bus;
        _size = new dom_2.InlineStyleSheet("", "size");
        touch_action = new dom_2.InlineStyleSheet("", "touch-action");
        initialize() {
            super.initialize();
            this.underlays_el = (0, dom_1.div)({ class: canvas_css.layer });
            this.primary = this.create_layer();
            this.overlays = this.create_layer();
            this.overlays_el = (0, dom_1.div)({ class: canvas_css.layer });
            this.events_el = (0, dom_1.div)({ class: [canvas_css.layer, canvas_css.events], tabIndex: 0 });
            this.ui_event_bus = new ui_events_1.UIEventBus(this);
        }
        get layers() {
            return [
                this.underlays_el,
                this.primary,
                this.overlays,
                this.overlays_el,
                this.events_el,
            ];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            if (this.model.output_backend == "webgl") {
                this.webgl = await global_webgl();
                if (settings_1.settings.force_webgl && this.webgl == null) {
                    throw new Error("webgl is not available");
                }
            }
        }
        remove() {
            this.ui_event_bus.remove();
            super.remove();
        }
        stylesheets() {
            return [...super.stylesheets(), canvas_css.default, icons_css_1.default, this._size, this.touch_action];
        }
        render() {
            super.render();
            const elements = [
                this.underlays_el,
                this.primary.el,
                this.overlays.el,
                this.overlays_el,
                this.events_el,
            ];
            this.shadow_el.append(...elements);
        }
        get pixel_ratio() {
            return this.primary.pixel_ratio;
        }
        get pixel_ratio_changed() {
            return this.primary.pixel_ratio_changed;
        }
        _update_bbox() {
            const changed = super._update_bbox() || this.pixel_ratio_changed;
            if (changed) {
                const { width, height } = this.bbox;
                this._size.replace(`.${canvas_css.layer}`, {
                    width: (0, dom_1.px)(width),
                    height: (0, dom_1.px)(height),
                });
                this.primary.resize(width, height);
                this.overlays.resize(width, height);
            }
            return changed;
        }
        after_resize() {
            if (this.plot_views.length != 0) {
                // Canvas is being managed by a plot, thus it should not attempt
                // self-resize, as it would result in inconsistent state and
                // possibly invalid layout and/or lack of repaint of a plot.
                this.finish();
            }
            else {
                super.after_resize();
            }
        }
        _after_resize() {
            super._after_resize();
            const { width, height } = this.bbox;
            this.primary.resize(width, height);
            this.overlays.resize(width, height);
        }
        resize() {
            const changed = this._update_bbox();
            this._after_resize();
            return changed;
        }
        prepare_webgl(frame_box) {
            // Prepare WebGL for a drawing pass
            const { webgl } = this;
            if (webgl != null) {
                // Sync canvas size
                const { width, height } = this.bbox;
                webgl.canvas.width = this.pixel_ratio * width;
                webgl.canvas.height = this.pixel_ratio * height;
                const { x: sx, y: sy, width: w, height: h } = frame_box;
                const { xview, yview } = this.bbox;
                const vx = xview.compute(sx);
                const vy = yview.compute(sy + h);
                const ratio = this.pixel_ratio;
                webgl.regl_wrapper.set_scissor(ratio * vx, ratio * vy, ratio * w, ratio * h);
                this._clear_webgl();
            }
        }
        blit_webgl(ctx) {
            // This should be called when the ctx has no state except the HIDPI transform
            const { webgl } = this;
            if (webgl != null && webgl.canvas.width * webgl.canvas.height > 0) {
                // Blit gl canvas into the 2D canvas. To do 1-on-1 blitting, we need
                // to remove the hidpi transform, then blit, then restore.
                // ctx.globalCompositeOperation = "source-over"  -> OK; is the default
                logging_1.logger.debug("Blitting WebGL canvas");
                ctx.restore();
                ctx.drawImage(webgl.canvas, 0, 0);
                // Set back hidpi transform
                ctx.save();
                if (this.model.hidpi) {
                    const ratio = this.pixel_ratio;
                    ctx.scale(ratio, ratio);
                    ctx.translate(0.5, 0.5);
                }
                this._clear_webgl();
            }
        }
        _clear_webgl() {
            const { webgl } = this;
            if (webgl != null) {
                // Prepare GL for drawing
                const { regl_wrapper, canvas } = webgl;
                regl_wrapper.clear(canvas.width, canvas.height);
            }
        }
        compose() {
            const composite = this.create_layer();
            const { width, height } = this.bbox;
            composite.resize(width, height);
            composite.ctx.drawImage(this.primary.canvas, 0, 0);
            composite.ctx.drawImage(this.overlays.canvas, 0, 0);
            return composite;
        }
        create_layer() {
            const { output_backend, hidpi } = this.model;
            return new canvas_1.CanvasLayer(output_backend, hidpi);
        }
        create_layer_svg() {
            const { hidpi } = this.model;
            return new canvas_1.CanvasLayer("svg", hidpi);
        }
        to_blob() {
            return this.compose().to_blob();
        }
        plot_views = [];
    }
    exports.CanvasView = CanvasView;
    class Canvas extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = CanvasView;
            this.define(({ Bool }) => ({
                hidpi: [Bool, true],
                output_backend: [enums_1.OutputBackend, "canvas"],
            }));
        }
    }
    exports.Canvas = Canvas;
},
/* core/ui_events.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.is_Tapable = is_Tapable;
    exports.is_Moveable = is_Moveable;
    exports.is_Pannable = is_Pannable;
    exports.is_Pinchable = is_Pinchable;
    exports.is_Rotatable = is_Rotatable;
    exports.is_Scrollable = is_Scrollable;
    exports.is_Keyable = is_Keyable;
    const tslib_1 = require(1) /* tslib */;
    const ui_gestures_1 = require(386) /* ./ui_gestures */;
    const signaling_1 = require(17) /* ./signaling */;
    const dom_1 = require(61) /* ./dom */;
    const events = tslib_1.__importStar(require(80) /* ./bokeh_events */);
    const wheel_1 = require(401) /* ./util/wheel */;
    const array_1 = require(10) /* ./util/array */;
    const types_1 = require(8) /* ./util/types */;
    function is_Tapable(obj) {
        return (0, types_1.isObject)(obj) && "on_tap" in obj;
    }
    function is_Moveable(obj) {
        return (0, types_1.isObject)(obj) && "on_enter" in obj && "on_move" in obj && "on_leave" in obj;
    }
    function is_Pannable(obj) {
        return (0, types_1.isObject)(obj) && "on_pan_start" in obj && "on_pan" in obj && "on_pan_end" in obj;
    }
    function is_Pinchable(obj) {
        return (0, types_1.isObject)(obj) && "on_pinch_start" in obj && "on_pinch" in obj && "on_pinch_end" in obj;
    }
    function is_Rotatable(obj) {
        return (0, types_1.isObject)(obj) && "on_rotate_start" in obj && "on_rotate" in obj && "on_rotate_end" in obj;
    }
    function is_Scrollable(obj) {
        return (0, types_1.isObject)(obj) && "on_scroll" in obj;
    }
    function is_Keyable(obj) {
        return (0, types_1.isObject)(obj) && "on_keydown" in obj && "on_keyup" in obj;
    }
    class UIEventBus {
        canvas_view;
        pan_start = new signaling_1.Signal(this, "pan:start");
        pan = new signaling_1.Signal(this, "pan");
        pan_end = new signaling_1.Signal(this, "pan:end");
        pinch_start = new signaling_1.Signal(this, "pinch:start");
        pinch = new signaling_1.Signal(this, "pinch");
        pinch_end = new signaling_1.Signal(this, "pinch:end");
        rotate_start = new signaling_1.Signal(this, "rotate:start");
        rotate = new signaling_1.Signal(this, "rotate");
        rotate_end = new signaling_1.Signal(this, "rotate:end");
        tap = new signaling_1.Signal(this, "tap");
        doubletap = new signaling_1.Signal(this, "doubletap");
        press = new signaling_1.Signal(this, "press");
        pressup = new signaling_1.Signal(this, "pressup");
        move_enter = new signaling_1.Signal(this, "move:enter");
        move = new signaling_1.Signal(this, "move");
        move_exit = new signaling_1.Signal(this, "move:exit");
        scroll = new signaling_1.Signal(this, "scroll");
        keydown = new signaling_1.Signal(this, "keydown");
        keyup = new signaling_1.Signal(this, "keyup");
        focus = new signaling_1.Signal0(this, "focus");
        blur = new signaling_1.Signal0(this, "blur");
        hit_area;
        ui_gestures;
        constructor(canvas_view) {
            this.canvas_view = canvas_view;
            this.hit_area = canvas_view.events_el;
            this.on_tap = this.on_tap.bind(this);
            this.on_doubletap = this.on_doubletap.bind(this);
            this.on_press = this.on_press.bind(this);
            this.on_pressup = this.on_pressup.bind(this);
            this.on_enter = this.on_enter.bind(this);
            this.on_move = this.on_move.bind(this);
            this.on_leave = this.on_leave.bind(this);
            this.on_pan_start = this.on_pan_start.bind(this);
            this.on_pan = this.on_pan.bind(this);
            this.on_pan_end = this.on_pan_end.bind(this);
            this.on_pinch_start = this.on_pinch_start.bind(this);
            this.on_pinch = this.on_pinch.bind(this);
            this.on_pinch_end = this.on_pinch_end.bind(this);
            this.on_rotate_start = this.on_rotate_start.bind(this);
            this.on_rotate = this.on_rotate.bind(this);
            this.on_rotate_end = this.on_rotate_end.bind(this);
            this.on_context_menu = this.on_context_menu.bind(this);
            this.on_mouse_wheel = this.on_mouse_wheel.bind(this);
            this.on_key_down = this.on_key_down.bind(this);
            this.on_key_up = this.on_key_up.bind(this);
            this.on_focus = this.on_focus.bind(this);
            this.on_blur = this.on_blur.bind(this);
            this.ui_gestures = new ui_gestures_1.UIGestures(this.hit_area, this, { must_be_target: true });
            this.ui_gestures.connect_signals();
            this.hit_area.addEventListener("contextmenu", this.on_context_menu);
            this.hit_area.addEventListener("wheel", this.on_mouse_wheel);
            this.hit_area.addEventListener("focus", this.on_focus);
            this.hit_area.addEventListener("blur", this.on_blur);
            this.hit_area.addEventListener("keydown", this.on_key_down);
            this.hit_area.addEventListener("keyup", this.on_key_up);
        }
        remove() {
            this.ui_gestures.remove();
            this.hit_area.removeEventListener("contextmenu", this.on_context_menu);
            this.hit_area.removeEventListener("wheel", this.on_mouse_wheel);
            document.removeEventListener("keydown", this.on_key_down);
            document.removeEventListener("keyup", this.on_key_up);
        }
        _tools = new Map();
        register_tool(tool_view) {
            const { model: tool } = tool_view;
            if (this._tools.has(tool)) {
                throw new Error(`${tool} already registered`);
            }
            else {
                this._tools.set(tool, tool_view);
            }
        }
        hit_test_renderers(plot_view, sx, sy) {
            const collected = [];
            for (const view of (0, array_1.reversed)(plot_view.all_renderer_views)) {
                if (view.interactive_hit?.(sx, sy) ?? false) {
                    collected.push(view);
                }
            }
            return collected;
        }
        set_cursor(cursor) {
            this.hit_area.style.cursor = cursor ?? "default";
        }
        hit_test_frame(plot_view, sx, sy) {
            return plot_view.frame.bbox.contains(sx, sy);
        }
        hit_test_plot(sx, sy) {
            // TODO: z-index
            for (const plot_view of this.canvas_view.plot_views) {
                if (plot_view.bbox.relative() /*XXX*/.contains(sx, sy)) {
                    return plot_view;
                }
            }
            return null;
        }
        _prev_move = null;
        _curr_pan = null;
        _curr_pinch = null;
        _curr_rotate = null;
        _trigger(signal, e) {
            if (!this.hit_area.isConnected) {
                return;
            }
            const { sx, sy, native: srcEvent } = e;
            const plot_view = this.hit_test_plot(sx, sy);
            const curr_view = plot_view;
            const relativize_event = (_plot_view) => {
                const [rel_sx, rel_sy] = [sx, sy]; // plot_view.layout.bbox.relativize(sx, sy)
                return { ...e, sx: rel_sx, sy: rel_sy };
            };
            if (e.type == "pan_start" || e.type == "pan" || e.type == "pan_end") {
                let pan_view;
                if (e.type == "pan_start" && curr_view != null) {
                    this._curr_pan = { plot_view: curr_view };
                    pan_view = curr_view;
                }
                else if (e.type == "pan" && this._curr_pan != null) {
                    pan_view = this._curr_pan.plot_view;
                }
                else if (e.type == "pan_end" && this._curr_pan != null) {
                    pan_view = this._curr_pan.plot_view;
                    this._curr_pan = null;
                }
                else {
                    pan_view = null;
                }
                if (pan_view != null) {
                    const event = relativize_event(pan_view);
                    this.__trigger(pan_view, signal, event, srcEvent);
                }
            }
            else if (e.type == "pinch_start" || e.type == "pinch" || e.type == "pinch_end") {
                let pinch_view;
                if (e.type == "pinch_start" && curr_view != null) {
                    this._curr_pinch = { plot_view: curr_view };
                    pinch_view = curr_view;
                }
                else if (e.type == "pinch" && this._curr_pinch != null) {
                    pinch_view = this._curr_pinch.plot_view;
                }
                else if (e.type == "pinch_end" && this._curr_pinch != null) {
                    pinch_view = this._curr_pinch.plot_view;
                    this._curr_pinch = null;
                }
                else {
                    pinch_view = null;
                }
                if (pinch_view != null) {
                    const event = relativize_event(pinch_view);
                    this.__trigger(pinch_view, signal, event, srcEvent);
                }
            }
            else if (e.type == "rotate_start" || e.type == "rotate" || e.type == "rotate_end") {
                let rotate_view;
                if (e.type == "rotate_start" && curr_view != null) {
                    this._curr_rotate = { plot_view: curr_view };
                    rotate_view = curr_view;
                }
                else if (e.type == "rotate" && this._curr_rotate != null) {
                    rotate_view = this._curr_rotate.plot_view;
                }
                else if (e.type == "rotate_end" && this._curr_rotate != null) {
                    rotate_view = this._curr_rotate.plot_view;
                    this._curr_rotate = null;
                }
                else {
                    rotate_view = null;
                }
                if (rotate_view != null) {
                    const event = relativize_event(rotate_view);
                    this.__trigger(rotate_view, signal, event, srcEvent);
                }
            }
            else if (e.type == "enter" || e.type == "move" || e.type == "leave") {
                const prev_view = this._prev_move?.plot_view;
                if (prev_view != null && (e.type == "leave" || prev_view != curr_view)) {
                    const { sx, sy } = relativize_event(prev_view);
                    this.__trigger(prev_view, this.move_exit, { type: "leave", sx, sy, modifiers: { shift: false, ctrl: false, alt: false }, native: srcEvent }, srcEvent);
                }
                if (curr_view != null && (e.type == "enter" || prev_view != curr_view)) {
                    const { sx, sy } = relativize_event(curr_view);
                    this.__trigger(curr_view, this.move_enter, { type: "enter", sx, sy, modifiers: { shift: false, ctrl: false, alt: false }, native: srcEvent }, srcEvent);
                }
                if (curr_view != null && e.type == "move") {
                    const event = relativize_event(curr_view);
                    this.__trigger(curr_view, signal, event, srcEvent);
                }
                this._prev_move = { sx, sy, plot_view: curr_view };
            }
            else {
                if (curr_view != null) {
                    const event = relativize_event(curr_view);
                    this.__trigger(curr_view, signal, event, srcEvent);
                }
            }
        }
        _current_interactive_tool_view = null;
        _current_pan_view = null;
        _current_pinch_view = null;
        _current_rotate_view = null;
        _current_move_views = [];
        __trigger(plot_view, signal, e, srcEvent) {
            const gestures = plot_view.model.toolbar.gestures;
            const event_type = signal.name;
            const base_type = event_type.split(":")[0];
            const views = this.hit_test_renderers(plot_view, e.sx, e.sy);
            if (base_type == "pan") {
                const event = e;
                if (this._current_pan_view == null) {
                    if (event_type == "pan:start") {
                        for (const view of views) {
                            if (!is_Pannable(view)) {
                                continue;
                            }
                            if (view.on_pan_start(event)) {
                                this._current_pan_view = view;
                                srcEvent.preventDefault();
                                return;
                            }
                        }
                    }
                }
                else {
                    if (event_type == "pan") {
                        this._current_pan_view.on_pan(event);
                    }
                    else if (event_type == "pan:end") {
                        this._current_pan_view.on_pan_end(event);
                        this.set_cursor(this._current_pan_view.cursor(event.sx, event.sy));
                        this._current_pan_view = null;
                    }
                    srcEvent.preventDefault();
                    return;
                }
            }
            else if (base_type == "pinch") {
                const event = e;
                if (this._current_pinch_view == null) {
                    if (event_type == "pinch:start") {
                        for (const view of views) {
                            if (!is_Pinchable(view)) {
                                continue;
                            }
                            if (view.on_pinch_start(event)) {
                                this._current_pinch_view = view;
                                srcEvent.preventDefault();
                                return;
                            }
                        }
                    }
                }
                else {
                    if (event_type == "pinch") {
                        this._current_pinch_view.on_pinch(event);
                    }
                    else if (event_type == "pinch:end") {
                        this._current_pinch_view.on_pinch_end(event);
                        this._current_pinch_view = null;
                    }
                    srcEvent.preventDefault();
                    return;
                }
            }
            else if (base_type == "rotate") {
                const event = e;
                if (this._current_rotate_view == null) {
                    if (event_type == "rotate:start") {
                        for (const view of views) {
                            if (!is_Rotatable(view)) {
                                continue;
                            }
                            if (view.on_rotate_start(event)) {
                                this._current_rotate_view = view;
                                srcEvent.preventDefault();
                                return;
                            }
                        }
                    }
                }
                else {
                    if (event_type == "rotate") {
                        this._current_rotate_view.on_rotate(event);
                    }
                    else if (event_type == "rotate:end") {
                        this._current_rotate_view.on_rotate_end(event);
                        this._current_rotate_view = null;
                    }
                    srcEvent.preventDefault();
                    return;
                }
            }
            else if (base_type == "move") {
                const event = e;
                const new_views = new Set(views);
                const current_views = new Set(this._current_move_views);
                this._current_move_views = [];
                for (const view of current_views) {
                    if (!new_views.has(view)) {
                        current_views.delete(view);
                        view.on_leave(event);
                    }
                }
                for (const view of views) {
                    if (!is_Moveable(view)) {
                        continue;
                    }
                    if (!current_views.has(view)) {
                        if (view.on_enter(e)) {
                            this._current_move_views.push(view);
                        }
                    }
                    else {
                        this._current_move_views.push(view);
                        view.on_move(event);
                    }
                }
            }
            function get_tool_view(tool_like) {
                if (tool_like != null) {
                    return plot_view.tool_views.get(tool_like.underlying) ?? null;
                }
                else {
                    return null;
                }
            }
            const top_view = views.at(0);
            switch (base_type) {
                case "move": {
                    const active_gesture = gestures.move.active;
                    if (active_gesture != null) {
                        this.trigger(signal, e, active_gesture);
                    }
                    const active_inspectors = plot_view.model.toolbar.inspectors.filter(t => t.active);
                    const cursor = (() => {
                        const current_view = this._current_interactive_tool_view ??
                            this._current_pan_view ??
                            this._current_pinch_view ??
                            this._current_rotate_view ??
                            this._current_move_views.at(0) ??
                            top_view ??
                            get_tool_view(active_gesture);
                        if (current_view != null) {
                            const cursor = current_view.cursor(e.sx, e.sy);
                            if (cursor != null) {
                                return cursor;
                            }
                        }
                        if (this.hit_test_frame(plot_view, e.sx, e.sy) && !(0, array_1.is_empty)(active_inspectors)) {
                            // the event happened on the plot frame but off a renderer
                            return "crosshair";
                        }
                        return null;
                    })();
                    this.set_cursor(cursor);
                    active_inspectors.map((inspector) => this.trigger(signal, e, inspector));
                    break;
                }
                case "tap": {
                    const path = srcEvent.composedPath();
                    if (path.length != 0 && path[0] != this.hit_area) {
                        return; // don't trigger bokeh events
                    }
                    top_view?.on_hit?.(e.sx, e.sy);
                    if (this.hit_test_frame(plot_view, e.sx, e.sy)) {
                        const active_gesture = gestures.tap.active;
                        if (active_gesture != null) {
                            this.trigger(signal, e, active_gesture);
                        }
                    }
                    break;
                }
                case "doubletap": {
                    if (this.hit_test_frame(plot_view, e.sx, e.sy)) {
                        const active_gesture = gestures.doubletap.active ?? gestures.tap.active;
                        if (active_gesture != null) {
                            this.trigger(signal, e, active_gesture);
                        }
                    }
                    break;
                }
                case "press": {
                    if (this.hit_test_frame(plot_view, e.sx, e.sy)) {
                        const active_gesture = gestures.press.active ?? gestures.tap.active;
                        if (active_gesture != null) {
                            this.trigger(signal, e, active_gesture);
                        }
                    }
                    break;
                }
                case "pinch": {
                    const active_gesture = gestures.pinch.active ?? gestures.scroll.active;
                    if (active_gesture != null) {
                        if (this.trigger(signal, e, active_gesture)) {
                            srcEvent.preventDefault();
                            srcEvent.stopPropagation();
                        }
                    }
                    break;
                }
                case "scroll": {
                    const active_gesture = gestures.scroll.active;
                    if (active_gesture != null) {
                        if (this.trigger(signal, e, active_gesture)) {
                            srcEvent.preventDefault();
                            srcEvent.stopPropagation();
                        }
                    }
                    break;
                }
                case "pan": {
                    const active_gesture = gestures.pan.active;
                    const active_pan_view = get_tool_view(active_gesture);
                    if (active_pan_view != null) {
                        switch (event_type) {
                            case "pan:start": {
                                this._current_interactive_tool_view = active_pan_view;
                                break;
                            }
                            case "pan:end": {
                                this._current_interactive_tool_view = null;
                                break;
                            }
                        }
                        if (this.trigger(signal, e, active_gesture)) {
                            srcEvent.preventDefault();
                            srcEvent.stopPropagation();
                        }
                        const cursor = active_pan_view.cursor(e.sx, e.sy);
                        this.set_cursor(cursor);
                    }
                    break;
                }
                default: {
                    const active_gesture = gestures[base_type].active;
                    if (active_gesture != null) {
                        this.trigger(signal, e, active_gesture);
                    }
                }
            }
            this._trigger_bokeh_event(plot_view, e);
        }
        trigger(signal, e, tool = null) {
            const emit = (tool) => {
                const tool_view = this._tools.get(tool);
                if (tool_view == null) {
                    return false;
                }
                const fn = (() => {
                    switch (signal) {
                        case this.pan_start: return tool_view._pan_start;
                        case this.pan: return tool_view._pan;
                        case this.pan_end: return tool_view._pan_end;
                        case this.pinch_start: return tool_view._pinch_start;
                        case this.pinch: return tool_view._pinch;
                        case this.pinch_end: return tool_view._pinch_end;
                        case this.rotate_start: return tool_view._rotate_start;
                        case this.rotate: return tool_view._rotate;
                        case this.rotate_end: return tool_view._rotate_end;
                        case this.move_enter: return tool_view._move_enter;
                        case this.move: return tool_view._move;
                        case this.move_exit: return tool_view._move_exit;
                        case this.tap: return tool_view._tap;
                        case this.doubletap: return tool_view._doubletap;
                        case this.press: return tool_view._press;
                        case this.pressup: return tool_view._pressup;
                        case this.scroll: return tool_view._scroll;
                        case this.keydown: return tool_view._keydown;
                        case this.keyup: return tool_view._keyup;
                        default: return null;
                    }
                })();
                if (fn == null) {
                    return false;
                }
                const val = fn.bind(tool_view)(e);
                if ((0, types_1.isBoolean)(val)) {
                    return val;
                }
                else {
                    return true;
                }
            };
            if (tool != null) {
                return emit(tool);
            }
            else {
                let result = false;
                for (const tool of this._tools.keys()) {
                    // don't conflate these lines because of short circuiting nature of ||= operator
                    const emitted = emit(tool);
                    result ||= emitted;
                }
                return result;
            }
        }
        /*protected*/ _trigger_bokeh_event(plot_view, ev) {
            const bokeh_event = (() => {
                const { sx, sy, modifiers } = ev;
                const x = plot_view.frame.x_scale.invert(sx);
                const y = plot_view.frame.y_scale.invert(sy);
                switch (ev.type) {
                    case "wheel": return new events.MouseWheel(sx, sy, x, y, ev.delta, modifiers);
                    case "enter": return new events.MouseEnter(sx, sy, x, y, modifiers);
                    case "move": return new events.MouseMove(sx, sy, x, y, modifiers);
                    case "leave": return new events.MouseLeave(sx, sy, x, y, modifiers);
                    case "tap": return new events.Tap(sx, sy, x, y, modifiers);
                    case "double_tap": return new events.DoubleTap(sx, sy, x, y, modifiers);
                    case "press": return new events.Press(sx, sy, x, y, modifiers);
                    case "press_up": return new events.PressUp(sx, sy, x, y, modifiers);
                    case "pan_start": return new events.PanStart(sx, sy, x, y, modifiers);
                    case "pan": return new events.Pan(sx, sy, x, y, ev.dx, ev.dy, modifiers);
                    case "pan_end": return new events.PanEnd(sx, sy, x, y, modifiers);
                    case "pinch_start": return new events.PinchStart(sx, sy, x, y, modifiers);
                    case "pinch": return new events.Pinch(sx, sy, x, y, ev.scale, modifiers);
                    case "pinch_end": return new events.PinchEnd(sx, sy, x, y, modifiers);
                    case "rotate_start": return new events.RotateStart(sx, sy, x, y, modifiers);
                    case "rotate": return new events.Rotate(sx, sy, x, y, ev.rotation, modifiers);
                    case "rotate_end": return new events.RotateEnd(sx, sy, x, y, modifiers);
                    default: return null;
                }
            })();
            if (bokeh_event != null) {
                plot_view.model.trigger_event(bokeh_event);
            }
        }
        _get_sxy(event) {
            const { pageX, pageY } = event;
            const { left, top } = (0, dom_1.offset_bbox)(this.hit_area);
            return {
                sx: pageX - left,
                sy: pageY - top,
            };
        }
        _get_modifiers(event) {
            return {
                shift: event.shiftKey,
                ctrl: event.ctrlKey,
                alt: event.altKey,
            };
        }
        _scroll_event(event) {
            return {
                type: event.type,
                ...this._get_sxy(event),
                delta: (0, wheel_1.getDeltaY)(event),
                modifiers: this._get_modifiers(event),
                native: event,
            };
        }
        _key_event(event) {
            return {
                type: event.type,
                key: event.key,
                modifiers: this._get_modifiers(event),
                native: event,
            };
        }
        on_tap(event) {
            this._trigger(this.tap, event);
        }
        on_doubletap(event) {
            this._trigger(this.doubletap, event);
        }
        on_press(event) {
            this._trigger(this.press, event);
        }
        on_pressup(event) {
            this._trigger(this.pressup, event);
        }
        on_enter(event) {
            this._trigger(this.move_enter, event);
        }
        on_move(event) {
            this._trigger(this.move, event);
        }
        on_leave(event) {
            this._trigger(this.move_exit, event);
        }
        on_pan_start(event) {
            this._trigger(this.pan_start, event);
        }
        on_pan(event) {
            this._trigger(this.pan, event);
        }
        on_pan_end(event) {
            this._trigger(this.pan_end, event);
        }
        on_pinch_start(event) {
            this._trigger(this.pinch_start, event);
        }
        on_pinch(event) {
            this._trigger(this.pinch, event);
        }
        on_pinch_end(event) {
            this._trigger(this.pinch_end, event);
        }
        on_rotate_start(event) {
            this._trigger(this.rotate_start, event);
        }
        on_rotate(event) {
            this._trigger(this.rotate, event);
        }
        on_rotate_end(event) {
            this._trigger(this.rotate_end, event);
        }
        on_mouse_wheel(event) {
            this._trigger(this.scroll, this._scroll_event(event));
        }
        on_context_menu(_event) {
            // TODO
        }
        on_key_down(event) {
            // NOTE: keyup event triggered unconditionally
            this.trigger(this.keydown, this._key_event(event));
        }
        on_key_up(event) {
            // NOTE: keyup event triggered unconditionally
            this.trigger(this.keyup, this._key_event(event));
        }
        on_focus() {
            this.focus.emit();
        }
        on_blur() {
            this.blur.emit();
        }
    }
    exports.UIEventBus = UIEventBus;
},
/* core/util/wheel.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.getDeltaY = getDeltaY;
    /*!
     * jQuery Mousewheel 3.1.13
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license
     * http://jquery.org/license
     */
    function fontSize(element) {
        const value = getComputedStyle(element).fontSize;
        const size = parseInt(value, 10);
        return isNaN(size) ? null : size;
    }
    function lineHeight(element) {
        const parent = element.offsetParent ?? document.body;
        return fontSize(parent) ?? fontSize(element) ?? 16;
    }
    function pageHeight(element) {
        return element.clientHeight; // XXX: should be content height?
    }
    function getDeltaY(event) {
        let deltaY = -event.deltaY;
        if (event.target instanceof HTMLElement) {
            switch (event.deltaMode) {
                case event.DOM_DELTA_LINE:
                    deltaY *= lineHeight(event.target);
                    break;
                case event.DOM_DELTA_PAGE:
                    deltaY *= pageHeight(event.target);
                    break;
            }
        }
        return deltaY;
    }
},
/* styles/canvas.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.layer = "bk-layer";
    exports.events = "bk-events";
    exports.default = `.bk-layer{position:absolute;top:0;left:0;width:100%;height:100%;overflow:hidden;}.bk-events{display:grid;grid-template-areas:".    above  .    " "left center right" ".    below  .    ";touch-action:none;overflow:visible;cursor:default;}.bk-events:focus,.bk-events:focus-visible{outline:var(--outline-width) var(--outline-style) var(--highlight-color);outline-offset:-1px;}`;
},
/* models/tools/tool_menu.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const menu_1 = require(122) /* ../ui/menus/menu */;
    const toolbar_1 = require(378) /* ./toolbar */;
    class ToolMenuView extends menu_1.MenuView {
        _compute_menu_items() {
            const { items } = this.model.toolbar.to_menu();
            return items;
        }
        connect_signals() {
            super.connect_signals();
            const { toolbar } = this.model.properties;
            this.on_transitive_change(toolbar, () => this._update_menu_items());
        }
    }
    exports.ToolMenuView = ToolMenuView;
    class ToolMenu extends menu_1.Menu {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ToolMenuView;
            this.define(({ Ref }) => ({
                toolbar: [Ref(toolbar_1.Toolbar)],
            }));
        }
    }
    exports.ToolMenu = ToolMenu;
},
/* models/annotations/toolbar_panel.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const annotation_1 = require(96) /* ./annotation */;
    const toolbar_1 = require(378) /* ../tools/toolbar */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const side_panel_1 = require(257) /* ../../core/layout/side_panel */;
    class ToolbarPanelView extends annotation_1.AnnotationView {
        update_layout() {
            this.layout = new side_panel_1.SideLayout(this.panel, () => this.get_size(), true);
        }
        after_layout() {
            this.toolbar_view.after_render();
        }
        has_finished() {
            return super.has_finished() && this.toolbar_view.has_finished();
        }
        children_views() {
            return [...super.children_views(), this.toolbar_view];
        }
        toolbar_view;
        async lazy_initialize() {
            await super.lazy_initialize();
            this.toolbar_view = await (0, build_views_1.build_view)(this.model.toolbar, { parent: this.canvas });
        }
        connect_signals() {
            super.connect_signals();
            this.plot_view.mouseenter.connect(() => {
                this.toolbar_view.set_visibility(true);
            });
            this.plot_view.mouseleave.connect(() => {
                this.toolbar_view.set_visibility(false);
            });
            this.plot_view.canvas.ui_event_bus.focus.connect(() => {
                this.toolbar_view.toggle_auto_scroll(true);
            });
            this.plot_view.canvas.ui_event_bus.blur.connect(() => {
                this.toolbar_view.toggle_auto_scroll(false);
            });
        }
        render() {
            super.render();
            this.toolbar_view.render_to(this.shadow_el);
        }
        get is_horizontal() {
            return this.toolbar_view.model.horizontal;
        }
        _paint() {
            const { style } = this.toolbar_view.el;
            if (this.is_horizontal) {
                style.width = "100%";
                style.height = "unset";
            }
            else {
                style.width = "unset";
                style.height = "100%";
            }
            // allow shrinking past content size in flex layouts
            if (this.is_horizontal) {
                this.el.style.minWidth = "0";
                this.el.style.minHeight = "unset";
            }
            else {
                this.el.style.minWidth = "unset";
                this.el.style.minHeight = "0";
            }
        }
        _get_size() {
            const { tools, logo } = this.model.toolbar;
            return {
                width: tools.length * 30 + (logo != null ? 25 : 0) + 15, // TODO: approximate, use a proper layout instead.
                height: 30,
            };
        }
    }
    exports.ToolbarPanelView = ToolbarPanelView;
    class ToolbarPanel extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ToolbarPanelView;
            this.define(({ Ref }) => ({
                toolbar: [Ref(toolbar_1.Toolbar)],
            }));
        }
    }
    exports.ToolbarPanel = ToolbarPanel;
},
/* models/ui/panel.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const pane_1 = require(132) /* ../ui/pane */;
    const coordinate_1 = require(58) /* ../coordinates/coordinate */;
    const node_1 = require(57) /* ../coordinates/node */;
    const kinds_1 = require(124) /* ../common/kinds */;
    const resolve = tslib_1.__importStar(require(127) /* ../common/resolve */);
    const dom_1 = require(61) /* ../../core/dom */;
    const panels_css_1 = tslib_1.__importDefault(require(406) /* ../../styles/panels.css */);
    class PanelView extends pane_1.PaneView {
        stylesheets() {
            return [...super.stylesheets(), panels_css_1.default];
        }
        connect_signals() {
            super.connect_signals();
            const { position, anchor, width, height, elements } = this.model.properties;
            this.on_change([anchor, width, height, elements], () => this.reposition());
            this.on_transitive_change(position, () => this.reposition());
        }
        reposition(displayed) {
            super.reposition(displayed);
            const { position, visible, anchor, elements } = this.model;
            if (displayed == false || !visible || elements.length == 0) {
                this.el.remove();
                return;
            }
            const { x: left, y: top } = this.resolve_as_xy(position);
            if (!isFinite(left + top)) {
                this.el.remove();
                return;
            }
            const parent_el = this.parent?.el ?? document.body;
            const target_el = parent_el.shadowRoot ?? parent_el;
            if (!this.el.isConnected) {
                target_el.append(this.el);
            }
            this.el.style.left = (0, dom_1.px)(left);
            this.el.style.top = (0, dom_1.px)(top);
            const xy = resolve.anchor(anchor);
            this.el.style.transform = `translate(${-100 * xy.x}%, ${-100 * xy.y}%)`;
        }
    }
    exports.PanelView = PanelView;
    class Panel extends pane_1.Pane {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = PanelView;
            this.define(({ Ref, Or, Auto, Int }) => ({
                position: [Ref(coordinate_1.Coordinate)],
                anchor: [kinds_1.Anchor, "top_left"],
                width: [Or(Auto, Int, Ref(node_1.Node)), "auto"],
                height: [Or(Auto, Int, Ref(node_1.Node)), "auto"],
            }));
        }
    }
    exports.Panel = Panel;
},
/* styles/panels.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = `:host{position:absolute;background-color:var(--background-color);}`;
},
/* models/dom/elements.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const dom_element_1 = require(134) /* ./dom_element */;
    class SpanView extends dom_element_1.DOMElementView {
        static tag_name = "span";
    }
    exports.SpanView = SpanView;
    class Span extends dom_element_1.DOMElement {
        static {
            this.prototype.default_view = SpanView;
        }
    }
    exports.Span = Span;
    class DivView extends dom_element_1.DOMElementView {
        static tag_name = "div";
    }
    exports.DivView = DivView;
    class Div extends dom_element_1.DOMElement {
        static {
            this.prototype.default_view = DivView;
        }
    }
    exports.Div = Div;
    class TableView extends dom_element_1.DOMElementView {
        static tag_name = "table";
    }
    exports.TableView = TableView;
    class Table extends dom_element_1.DOMElement {
        static {
            this.prototype.default_view = TableView;
        }
    }
    exports.Table = Table;
    class TableRowView extends dom_element_1.DOMElementView {
        static tag_name = "tr";
    }
    exports.TableRowView = TableRowView;
    class TableRow extends dom_element_1.DOMElement {
        static {
            this.prototype.default_view = TableRowView;
        }
    }
    exports.TableRow = TableRow;
},
/* core/util/throttle.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.throttle = throttle;
    function throttle(func, wait) {
        let timeout = null;
        let request = null;
        let previous = 0;
        let pending = false;
        let resolver;
        const fn = function () {
            return new Promise((resolve, reject) => {
                resolver = resolve;
                const later = function () {
                    previous = Date.now();
                    timeout = null;
                    request = null;
                    pending = false;
                    try {
                        func();
                        resolve();
                    }
                    catch (error) {
                        reject(error);
                    }
                };
                const now = Date.now();
                const remaining = wait - (now - previous);
                if (remaining <= 0 && !pending) {
                    if (timeout != null) {
                        clearTimeout(timeout);
                    }
                    pending = true;
                    request = requestAnimationFrame(later);
                }
                else if (timeout == null && !pending) {
                    timeout = setTimeout(() => request = requestAnimationFrame(later), remaining);
                }
                else {
                    resolve();
                }
            });
        };
        fn.stop = function () {
            if (timeout != null) {
                clearTimeout(timeout);
            }
            if (request != null) {
                cancelAnimationFrame(request);
            }
            resolver();
        };
        return fn;
    }
},
/* models/plots/range_manager.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const data_range1d_1 = require(118) /* ../ranges/data_range1d */;
    const logging_1 = require(11) /* ../../core/logging */;
    const math_1 = require(12) /* ../../core/util/math */;
    class RangeManager {
        parent;
        constructor(parent) {
            this.parent = parent;
        }
        get frame() {
            return this.parent.frame;
        }
        warn_initial_ranges = true;
        invalidate_dataranges = true;
        update(range_info, options = {}) {
            const panning = options.panning ?? false;
            const scrolling = options.scrolling ?? false;
            const maintain_focus = options.maintain_focus ?? false;
            const range_state = new Map();
            for (const [range, interval] of range_info.xrs) {
                range_state.set(range, interval);
            }
            for (const [range, interval] of range_info.yrs) {
                range_state.set(range, interval);
            }
            if (scrolling && maintain_focus) {
                this._update_ranges_together(range_state); // apply interval bounds while keeping aspect
            }
            this._update_ranges_individually(range_state, { panning, scrolling, maintain_focus });
        }
        ranges() {
            const x_ranges = new Set();
            const y_ranges = new Set();
            for (const range of this.frame.x_ranges.values()) {
                x_ranges.add(range);
            }
            for (const range of this.frame.y_ranges.values()) {
                y_ranges.add(range);
            }
            for (const renderer of this.parent.model.data_renderers) {
                const { coordinates } = renderer;
                if (coordinates != null) {
                    x_ranges.add(coordinates.x_source);
                    y_ranges.add(coordinates.y_source);
                }
            }
            return {
                x_ranges: [...x_ranges],
                y_ranges: [...y_ranges],
            };
        }
        reset() {
            const { x_ranges, y_ranges } = this.ranges();
            for (const range of x_ranges) {
                range.reset();
            }
            for (const range of y_ranges) {
                range.reset();
            }
            this.update_dataranges();
        }
        _update_dataranges(frame) {
            // Update any DataRange1ds here
            const bounds = new Map();
            const log_bounds = new Map();
            let calculate_log_bounds = false;
            for (const [, xr] of frame.x_ranges) {
                if (xr instanceof data_range1d_1.DataRange1d && xr.scale_hint == "log") {
                    calculate_log_bounds = true;
                }
            }
            for (const [, yr] of frame.y_ranges) {
                if (yr instanceof data_range1d_1.DataRange1d && yr.scale_hint == "log") {
                    calculate_log_bounds = true;
                }
            }
            for (const renderer of this.parent.auto_ranged_renderers) {
                const bds = renderer.bounds(this.parent.model.window_axis);
                bounds.set(renderer.model, bds);
                if (calculate_log_bounds) {
                    const log_bds = renderer.log_bounds();
                    log_bounds.set(renderer.model, log_bds);
                }
            }
            let follow_enabled = false;
            let has_bounds = false;
            //const {width, height} = frame.bbox
            const width = frame.x_target.span;
            const height = frame.y_target.span;
            let r;
            if (this.parent.model.match_aspect !== false && width != 0 && height != 0) {
                r = (1 / this.parent.model.aspect_scale) * (width / height);
            }
            for (const [, xr] of frame.x_ranges) {
                if (xr instanceof data_range1d_1.DataRange1d) {
                    const bounds_to_use = xr.scale_hint == "log" ? log_bounds : bounds;
                    xr.update(bounds_to_use, 0, this.parent, r);
                    if (xr.follow != null) {
                        follow_enabled = true;
                    }
                }
                if (xr.bounds != null) {
                    has_bounds = true;
                }
            }
            for (const [, yr] of frame.y_ranges) {
                if (yr instanceof data_range1d_1.DataRange1d) {
                    const bounds_to_use = yr.scale_hint == "log" ? log_bounds : bounds;
                    yr.update(bounds_to_use, 1, this.parent, r);
                    if (yr.follow != null) {
                        follow_enabled = true;
                    }
                }
                if (yr.bounds != null) {
                    has_bounds = true;
                }
            }
            if (follow_enabled && has_bounds) {
                logging_1.logger.warn("Follow enabled so bounds are unset.");
                for (const [, xr] of frame.x_ranges) {
                    xr.bounds = null;
                }
                for (const [, yr] of frame.y_ranges) {
                    yr.bounds = null;
                }
            }
        }
        update_dataranges() {
            this._update_dataranges(this.frame);
            for (const renderer of this.parent.auto_ranged_renderers) {
                const { coordinates } = renderer.model;
                if (coordinates != null) {
                    this._update_dataranges(coordinates);
                }
            }
            if (this.compute_initial() != null) {
                this.invalidate_dataranges = false;
            }
        }
        constrain_interval(rng) {
            const range_info = this._constrain_interval(rng);
            if (range_info == null) {
                return null;
            }
            const { x_ranges, y_ranges } = this.ranges();
            const xrs = new Map();
            const yrs = new Map();
            if (x_ranges.includes(rng)) {
                xrs.set(rng, range_info);
            }
            if (y_ranges.includes(rng)) {
                yrs.set(rng, range_info);
            }
            return { xrs, yrs };
        }
        compute_initial() {
            // check for good values for ranges before setting initial range
            let good_vals = true;
            const { x_ranges, y_ranges } = this.frame;
            const xrs = new Map();
            const yrs = new Map();
            for (const [, range] of x_ranges) {
                const { start, end } = range;
                if (isNaN(start + end)) {
                    good_vals = false;
                    break;
                }
                xrs.set(range, { start, end });
            }
            if (good_vals) {
                for (const [, range] of y_ranges) {
                    const { start, end } = range;
                    if (isNaN(start + end)) {
                        good_vals = false;
                        break;
                    }
                    yrs.set(range, { start, end });
                }
            }
            if (good_vals) {
                return { xrs, yrs };
            }
            else {
                if (this.warn_initial_ranges) {
                    logging_1.logger.warn("could not set initial ranges");
                }
                return null;
            }
        }
        _constrain_interval(rng) {
            const old_interval = Math.abs(rng.end - rng.start);
            const min_interval = rng.min_interval ?? 0;
            let max_interval = rng.max_interval ?? Infinity;
            const [min_bound, max_bound] = rng.computed_bounds;
            if (rng.bounds != null) {
                if (isFinite(min_bound) && isFinite(max_bound)) {
                    max_interval = Math.min(max_interval, Math.abs(max_bound - min_bound));
                }
            }
            const new_interval = (0, math_1.clamp)(old_interval, Math.min(min_interval, max_interval), max_interval);
            if (new_interval == old_interval) {
                return null;
            }
            const half_interval = new_interval / 2;
            let center = (rng.start + rng.end) / 2;
            if (rng.bounds != null) {
                center = (0, math_1.clamp)(center, min_bound + half_interval, max_bound - half_interval);
            }
            const sign = rng.is_reversed ? -1 : 1;
            return {
                start: center - sign * half_interval,
                end: center + sign * half_interval,
            };
        }
        _update_ranges_together(range_state) {
            // Get weight needed to scale the diff of the range to honor interval limits
            let weight = 1.0;
            for (const [rng, range_info] of range_state) {
                weight = Math.min(weight, this._get_weight_to_constrain_interval(rng, range_info));
            }
            // Apply shared weight to all ranges
            if (weight < 1) {
                for (const [rng, range_info] of range_state) {
                    range_info.start = weight * range_info.start + (1 - weight) * rng.start;
                    range_info.end = weight * range_info.end + (1 - weight) * rng.end;
                }
            }
        }
        _update_ranges_individually(range_state, options) {
            const { panning, scrolling, maintain_focus } = options;
            let hit_bound = false;
            for (const [rng, range_info] of range_state) {
                // Limit range interval first. Note that for scroll events,
                // the interval has already been limited for all ranges simultaneously
                if (!scrolling || maintain_focus) {
                    const weight = this._get_weight_to_constrain_interval(rng, range_info);
                    if (weight < 1) {
                        range_info.start = weight * range_info.start + (1 - weight) * rng.start;
                        range_info.end = weight * range_info.end + (1 - weight) * rng.end;
                    }
                }
                // Prevent range from going outside limits
                // Also ensure that range keeps the same delta when panning/scrolling
                if (rng.bounds != null) {
                    const [min, max] = rng.computed_bounds;
                    // Make sure the "new_interval" isn't larger than the distance between the bounds, otherwise
                    // the bound could be ignored, see issue #14568
                    const new_interval = Math.min(Math.abs(range_info.end - range_info.start), Math.abs(max - min));
                    if (rng.is_reversed) {
                        if (min > range_info.end) {
                            hit_bound = true;
                            range_info.end = min;
                            if (panning || scrolling) {
                                range_info.start = min + new_interval;
                            }
                        }
                        if (max < range_info.start) {
                            hit_bound = true;
                            range_info.start = max;
                            if (panning || scrolling) {
                                range_info.end = max - new_interval;
                            }
                        }
                    }
                    else {
                        if (min > range_info.start) {
                            hit_bound = true;
                            range_info.start = min;
                            if (panning || scrolling) {
                                range_info.end = min + new_interval;
                            }
                        }
                        if (max < range_info.end) {
                            hit_bound = true;
                            range_info.end = max;
                            if (panning || scrolling) {
                                range_info.start = max - new_interval;
                            }
                        }
                    }
                }
            }
            // Cancel the event when hitting a bound while scrolling. This ensures that
            // the scroll-zoom tool maintains its focus position. Setting `maintain_focus`
            // to false results in a more "gliding" behavior, allowing one to
            // zoom out more smoothly, at the cost of losing the focus position.
            if (scrolling && hit_bound && maintain_focus) {
                return;
            }
            for (const [rng, range_info] of range_state) {
                rng.have_updated_interactively = true;
                if (rng.start != range_info.start || rng.end != range_info.end) {
                    rng.setv(range_info);
                }
            }
        }
        _get_weight_to_constrain_interval(rng, range_info) {
            // Get the weight by which a range-update can be applied
            // to still honor the interval limits (including the implicit
            // max interval imposed by the bounds)
            const { min_interval } = rng;
            let { max_interval } = rng;
            // Express bounds as a max_interval. By doing this, the application of
            // bounds and interval limits can be applied independent from each-other.
            if (rng.bounds != null && rng.bounds != "auto") { // check `auto` for type-checking purpose
                const [min, max] = rng.bounds;
                if (min != null && max != null) {
                    const max_interval2 = Math.abs(max - min);
                    max_interval = max_interval != null ? Math.min(max_interval, max_interval2) : max_interval2;
                }
            }
            let weight = 1.0;
            if (min_interval != null || max_interval != null) {
                const old_interval = Math.abs(rng.end - rng.start);
                const new_interval = Math.abs(range_info.end - range_info.start);
                if (min_interval != null && min_interval > 0 && new_interval < min_interval) {
                    weight = (old_interval - min_interval) / (old_interval - new_interval);
                }
                if (max_interval != null && max_interval > 0 && new_interval > max_interval) {
                    weight = (max_interval - old_interval) / (new_interval - old_interval);
                }
                weight = Math.max(0.0, Math.min(1.0, weight));
            }
            return weight;
        }
    }
    exports.RangeManager = RangeManager;
},
/* models/plots/state_manager.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const signaling_1 = require(17) /* ../../core/signaling */;
    class StateManager {
        parent;
        initial_state;
        changed;
        constructor(parent, initial_state) {
            this.parent = parent;
            this.initial_state = initial_state;
            this.changed = new signaling_1.Signal0(this.parent, "state_changed");
        }
        history = [];
        index = -1;
        _do_state_change(index) {
            const state = index in this.history ? this.history[index].state : this.initial_state;
            if (state.range != null) {
                this.parent.update_range(state.range);
            }
            if (state.selection != null) {
                this.parent.update_selection(state.selection);
            }
            return state;
        }
        peek() {
            return this.can_undo ? this.history[this.index] : null;
        }
        push(type, new_state) {
            const { history, index } = this;
            const prev_state = index in history ? history[index].state : {};
            const state = { ...this.initial_state, ...prev_state, ...new_state };
            this.history = this.history.slice(0, this.index + 1);
            this.history.push({ type, state });
            this.index = this.history.length - 1;
            this.changed.emit();
        }
        clear() {
            this.history = [];
            this.index = -1;
            this.changed.emit();
        }
        undo() {
            if (this.can_undo) {
                this.index -= 1;
                const state = this._do_state_change(this.index);
                this.changed.emit();
                return state;
            }
            return null;
        }
        redo() {
            if (this.can_redo) {
                this.index += 1;
                const state = this._do_state_change(this.index);
                this.changed.emit();
                return state;
            }
            return null;
        }
        get can_undo() {
            return this.index >= 0;
        }
        get can_redo() {
            return this.index < this.history.length - 1;
        }
    }
    exports.StateManager = StateManager;
},
/* styles/plots.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.Canvas = "bk-Canvas";
    exports.default = `:host{display:grid;grid-template-areas:".    above  .    " "left center right" ".    below  .    ";grid-template-rows:0px 1fr 0px;grid-template-columns:0px 1fr 0px;}.bk-Canvas{grid-row-start:1;grid-row-end:span 3;grid-column-start:1;grid-column-end:span 3;}`;
},
/* styles/attribution.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = `:host{display:flex;flex-direction:column;flex-wrap:nowrap;padding:2px;background-color:rgba(255, 255, 255, 0.5);font-size:0.5625rem;line-height:1.05;white-space:nowrap;max-width:var(--max-width);}:host > *{overflow:hidden;text-overflow:ellipsis;text-align:right;}a{color:var(--color);}`;
},
/* models/glyphs/circle.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const radial_glyph_1 = require(375) /* ./radial_glyph */;
    const hittest = tslib_1.__importStar(require(311) /* ../../core/hittest */);
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const selection_1 = require(144) /* ../selections/selection */;
    class CircleView extends radial_glyph_1.RadialGlyphView {
        async load_glglyph() {
            const { CircleGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(664) /* ./webgl/circle */));
            return CircleGL;
        }
        _paint(ctx, indices, data) {
            const { sx, sy, sradius } = { ...this, ...data };
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const sradius_i = sradius[i];
                if (!isFinite(sx_i + sy_i + sradius_i)) {
                    continue;
                }
                ctx.beginPath();
                ctx.arc(sx_i, sy_i, sradius_i, 0, 2 * Math.PI, false);
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            const { hit_dilation } = this.model;
            const [x0, x1, y0, y1] = (() => {
                if (this.model.properties.radius.units == "data") {
                    const dr = this.max_radius * hit_dilation;
                    const x0 = x - dr;
                    const x1 = x + dr;
                    const y0 = y - dr;
                    const y1 = y + dr;
                    return [x0, x1, y0, y1];
                }
                else {
                    const ds = this.max_radius * hit_dilation;
                    const sx0 = sx - ds;
                    const sx1 = sx + ds;
                    const sy0 = sy - ds;
                    const sy1 = sy + ds;
                    const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
                    const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
                    return [x0, x1, y0, y1];
                }
            })();
            const candidates = this.index.indices({ x0, x1, y0, y1 });
            const indices = [];
            if (this.model.properties.radius.units == "data") {
                for (const i of candidates) {
                    const r2 = (this.sradius[i] * hit_dilation) ** 2;
                    const [sx0, sx1] = this.renderer.xscale.r_compute(x, this.x[i]);
                    const [sy0, sy1] = this.renderer.yscale.r_compute(y, this.y[i]);
                    const dist = (sx0 - sx1) ** 2 + (sy0 - sy1) ** 2;
                    if (dist <= r2) {
                        indices.push(i);
                    }
                }
            }
            else {
                for (const i of candidates) {
                    const r2 = (this.sradius[i] * hit_dilation) ** 2;
                    const dist = (this.sx[i] - sx) ** 2 + (this.sy[i] - sy) ** 2;
                    if (dist <= r2) {
                        indices.push(i);
                    }
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const { sx, sy } = geometry;
            const bounds = this.bounds();
            const [x0, x1, y0, y1] = (() => {
                const dr = this.max_radius;
                if (geometry.direction == "h") {
                    // use circle bounds instead of current pointer y coordinates
                    const sx0 = sx - dr;
                    const sx1 = sx + dr;
                    const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
                    const { y0, y1 } = bounds;
                    return [x0, x1, y0, y1];
                }
                else {
                    // use circle bounds instead of current pointer x coordinates
                    const sy0 = sy - dr;
                    const sy1 = sy + dr;
                    const { x0, x1 } = bounds;
                    const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
                    return [x0, x1, y0, y1];
                }
            })();
            const indices = [...this.index.indices({ x0, x1, y0, y1 })];
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const { sx0, sx1, sy0, sy1 } = geometry;
            const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
            const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            const candidates = this.index.indices({ x0, x1, y0, y1 }).ones();
            const indices = [];
            for (const i of candidates) {
                const sx_i = this.sx[i];
                const sy_i = this.sy[i];
                if (sx0 <= sx_i && sx_i <= sx1 && sy0 <= sy_i && sy_i <= sy1) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_poly(geometry) {
            const { sx: sxs, sy: sys } = geometry;
            const candidates = (() => {
                const [sx0, sx1, sy0, sy1] = (0, arrayable_1.minmax2)(sxs, sys);
                const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
                const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
                return this.index.indices({ x0, x1, y0, y1 });
            })();
            const indices = [];
            for (const i of candidates) {
                if (hittest.point_in_poly(this.sx[i], this.sy[i], sxs, sys)) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
    }
    exports.CircleView = CircleView;
    class Circle extends radial_glyph_1.RadialGlyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = CircleView;
            this.define(({ Float }) => ({
                hit_dilation: [Float, 1.0],
            }));
        }
    }
    exports.Circle = Circle;
},
/* models/annotations/slope.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(96) /* ./annotation */;
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    class SlopeView extends annotation_1.AnnotationView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.request_paint());
        }
        _paint(ctx) {
            const { gradient, y_intercept } = this.model;
            if (gradient == null || y_intercept == null) {
                return;
            }
            const { frame } = this.plot_view;
            const xscale = this.coordinates.x_scale;
            const yscale = this.coordinates.y_scale;
            const [sx0, sx1, sy0, sy1] = (() => {
                if (gradient == 0) {
                    const sy_start = yscale.compute(y_intercept);
                    const sy_end = sy_start;
                    const sx_start = frame.bbox.left;
                    const sx_end = frame.bbox.right;
                    return [sx_start, sx_end, sy_start, sy_end];
                }
                else {
                    const sy_start = frame.bbox.top;
                    const sy_end = frame.bbox.bottom;
                    const y_start = yscale.invert(sy_start);
                    const y_end = yscale.invert(sy_end);
                    const x_start = (y_start - y_intercept) / gradient;
                    const x_end = (y_end - y_intercept) / gradient;
                    const sx_start = xscale.compute(x_start);
                    const sx_end = xscale.compute(x_end);
                    if (sx_start <= sx_end) {
                        return [sx_start, sx_end, sy_start, sy_end];
                    }
                    else {
                        return [sx_end, sx_start, sy_end, sy_start];
                    }
                }
            })();
            ctx.save();
            if (this.visuals.above_fill.doit || this.visuals.above_hatch.doit) {
                const { left, right, top, bottom } = frame.bbox;
                ctx.beginPath();
                ctx.moveTo(sx0, sy0);
                ctx.lineTo(sx0, sy0);
                ctx.lineTo(sx1, sy1);
                ctx.lineTo(sx1, sy1);
                if (sy0 <= sy1) {
                    if (sx1 < right) {
                        ctx.lineTo(right, bottom);
                    }
                    ctx.lineTo(right, top);
                    ctx.lineTo(left, top);
                }
                else {
                    ctx.lineTo(right, top);
                    ctx.lineTo(left, top);
                    if (sx0 > left) {
                        ctx.lineTo(left, bottom);
                    }
                }
                ctx.closePath();
                this.visuals.above_fill.apply(ctx);
                this.visuals.above_hatch.apply(ctx);
            }
            if (this.visuals.below_fill.doit || this.visuals.below_hatch.doit) {
                const { left, right, top, bottom } = frame.bbox;
                ctx.beginPath();
                ctx.moveTo(sx0, sy0);
                ctx.lineTo(sx0, sy0);
                ctx.lineTo(sx1, sy1);
                if (sy0 <= sy1) {
                    ctx.lineTo(right, bottom);
                    ctx.lineTo(left, bottom);
                    if (sx0 > left) {
                        ctx.lineTo(left, top);
                    }
                }
                else {
                    if (sx1 < right) {
                        ctx.lineTo(right, top);
                    }
                    ctx.lineTo(right, bottom);
                    ctx.lineTo(left, bottom);
                }
                ctx.closePath();
                this.visuals.below_fill.apply(ctx);
                this.visuals.below_hatch.apply(ctx);
            }
            ctx.beginPath();
            ctx.moveTo(sx0, sy0);
            ctx.lineTo(sx1, sy1);
            this.visuals.line.apply(ctx);
            ctx.restore();
        }
    }
    exports.SlopeView = SlopeView;
    class Slope extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = SlopeView;
            this.mixins([
                mixins.Line,
                ["above_", mixins.Fill],
                ["above_", mixins.Hatch],
                ["below_", mixins.Fill],
                ["below_", mixins.Hatch],
            ]);
            this.define(({ Float, Nullable }) => ({
                gradient: [Nullable(Float), null],
                y_intercept: [Nullable(Float), null],
            }));
            this.override({
                line_color: "black",
                above_fill_color: null,
                above_fill_alpha: 0.4,
                below_fill_color: null,
                below_fill_alpha: 0.4,
            });
        }
    }
    exports.Slope = Slope;
},
/* models/annotations/span.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(96) /* ./annotation */;
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    const enums_1 = require(21) /* ../../core/enums */;
    const hittest_1 = require(311) /* ../../core/hittest */;
    const signaling_1 = require(17) /* ../../core/signaling */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    const EDGE_TOLERANCE = 2.5;
    class Line {
        p0;
        p1;
        constructor(p0, p1) {
            this.p0 = p0;
            this.p1 = p1;
        }
        clone() {
            return new Line({ ...this.p0 }, { ...this.p1 });
        }
        hit_test(pt, tolerance = EDGE_TOLERANCE) {
            return (0, hittest_1.dist_to_segment)(pt, this.p0, this.p1) < tolerance;
        }
        translate(dx, dy) {
            const { p0, p1 } = this;
            const dp0 = { x: p0.x + dx, y: p0.y + dy };
            const dp1 = { x: p1.x + dx, y: p1.y + dy };
            return new Line(dp0, dp1);
        }
    }
    class SpanView extends annotation_1.AnnotationView {
        line;
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.plot_view.request_paint(this));
        }
        _paint(ctx) {
            const { location, location_units } = this.model;
            if (location == null) {
                return;
            }
            function compute(value, units, scale, view, canvas) {
                switch (units) {
                    case "canvas": return canvas.compute(value);
                    case "screen": return view.compute(value);
                    case "data": return scale.compute(value);
                }
            }
            const { frame, canvas } = this.plot_view;
            const { x_scale, y_scale } = this.coordinates;
            let height, sleft, stop, width;
            if (this.model.dimension == "width") {
                stop = compute(location, location_units, y_scale, frame.bbox.yview, canvas.bbox.y_screen);
                sleft = frame.bbox.left;
                width = frame.bbox.width;
                height = this.model.line_width;
            }
            else {
                stop = frame.bbox.top;
                sleft = compute(location, location_units, x_scale, frame.bbox.xview, canvas.bbox.y_screen);
                width = this.model.line_width;
                height = frame.bbox.height;
            }
            const p0 = { x: sleft, y: stop };
            const p1 = { x: sleft + width, y: stop + height };
            this.line = new Line(p0, p1);
            const { _is_hovered, visuals } = this;
            const line = _is_hovered && visuals.hover_line.doit ? visuals.hover_line : visuals.line;
            ctx.save();
            ctx.beginPath();
            this.visuals.line.set_value(ctx);
            ctx.moveTo(sleft, stop);
            if (this.model.dimension == "width") {
                ctx.lineTo(sleft + width, stop);
            }
            else {
                ctx.lineTo(sleft, stop + height);
            }
            line.apply(ctx);
            ctx.restore();
        }
        interactive_hit(sx, sy) {
            if (!this.model.visible || !this.model.editable) {
                return false;
            }
            return this._hit_test(sx, sy) != null;
        }
        _hit_test(sx, sy) {
            const tolerance = Math.max(EDGE_TOLERANCE, this.model.line_width / 2);
            return this.line.hit_test({ x: sx, y: sy }, tolerance) ? "edge" : null;
        }
        _can_hit(_target) {
            return true;
        }
        _pan_state = null;
        on_pan_start(ev) {
            if (this.model.visible && this.model.editable) {
                const { sx, sy } = ev;
                const target = this._hit_test(sx, sy);
                if (target != null && this._can_hit(target)) {
                    this._pan_state = {
                        line: this.line.clone(),
                        target,
                    };
                    this.model.pan.emit(["pan:start", ev.modifiers]);
                    return true;
                }
            }
            return false;
        }
        on_pan(ev) {
            (0, assert_1.assert)(this._pan_state != null);
            function invert(sv, units, scale, view, canvas) {
                switch (units) {
                    case "canvas": return canvas.invert(sv);
                    case "screen": return view.invert(sv);
                    case "data": return scale.invert(sv);
                }
            }
            const sloc = (() => {
                const { dx, dy } = ev;
                const { line } = this._pan_state;
                if (this.model.dimension == "width") {
                    return line.translate(0, dy).p0.y;
                }
                else {
                    return line.translate(dx, 0).p0.x;
                }
            })();
            const loc = (() => {
                const { location_units } = this.model;
                const { frame, canvas } = this.plot_view;
                const { x_scale, y_scale } = this.coordinates;
                if (this.model.dimension == "width") {
                    return invert(sloc, location_units, y_scale, frame.bbox.yview, canvas.bbox.y_screen);
                }
                else {
                    return invert(sloc, location_units, x_scale, frame.bbox.xview, canvas.bbox.y_screen);
                }
            })();
            this.model.location = loc;
            this.model.pan.emit(["pan", ev.modifiers]);
        }
        on_pan_end(ev) {
            this._pan_state = null;
            this.model.pan.emit(["pan:end", ev.modifiers]);
        }
        get _has_hover() {
            const { hover_line } = this.visuals;
            return hover_line.doit;
        }
        _is_hovered = false;
        on_enter(_ev) {
            const { _has_hover } = this;
            if (_has_hover) {
                this._is_hovered = true;
                this.request_paint();
            }
            return _has_hover;
        }
        on_move(_ev) { }
        on_leave(_ev) {
            if (this._has_hover) {
                this._is_hovered = false;
                this.request_paint();
            }
        }
        cursor(sx, sy) {
            const target = this._pan_state?.target ?? this._hit_test(sx, sy);
            if (target == null || !this._can_hit(target)) {
                return null;
            }
            return this.model.dimension == "width" ? "ns-resize" : "ew-resize";
        }
    }
    exports.SpanView = SpanView;
    class Span extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = SpanView;
            this.mixins([
                mixins.Line,
                ["hover_", mixins.Line],
            ]);
            this.define(({ Bool, Float, Nullable }) => ({
                location: [Nullable(Float), null],
                location_units: [enums_1.CoordinateUnits, "data"],
                dimension: [enums_1.Dimension, "width"],
                editable: [Bool, false],
            }));
            this.override({
                line_color: "black",
                hover_line_color: null,
                hover_line_alpha: 0.3,
            });
        }
        pan = new signaling_1.Signal(this, "pan");
    }
    exports.Span = Span;
},
/* models/annotations/whisker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const upper_lower_1 = require(344) /* ./upper_lower */;
    const arrow_head_1 = require(252) /* ./arrow_head */;
    const types_1 = require(25) /* ../../core/types */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const property_mixins_1 = require(95) /* ../../core/property_mixins */;
    class WhiskerView extends upper_lower_1.UpperLowerView {
        lower_head;
        upper_head;
        children_views() {
            return [...super.children_views(), this.lower_head, this.upper_head];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const { lower_head, upper_head } = this.model;
            if (lower_head != null) {
                this.lower_head = await (0, build_views_1.build_view)(lower_head, { parent: this });
            }
            if (upper_head != null) {
                this.upper_head = await (0, build_views_1.build_view)(upper_head, { parent: this });
            }
        }
        set_data(source) {
            super.set_data(source);
            const indices = types_1.Indices.all_set(this._lower.length);
            this.lower_head?.set_data(source, indices);
            this.upper_head?.set_data(source, indices);
        }
        _paint_data(ctx) {
            if (this.visuals.line.doit) {
                for (let i = 0, end = this._lower_sx.length; i < end; i++) {
                    ctx.beginPath();
                    ctx.moveTo(this._lower_sx[i], this._lower_sy[i]);
                    ctx.lineTo(this._upper_sx[i], this._upper_sy[i]);
                    this.visuals.line.apply(ctx, i);
                }
            }
            const angle = this.model.dimension == "height" ? 0 : Math.PI / 2;
            if (this.lower_head != null) {
                for (let i = 0, end = this._lower_sx.length; i < end; i++) {
                    ctx.save();
                    ctx.translate(this._lower_sx[i], this._lower_sy[i]);
                    ctx.rotate(angle + Math.PI);
                    this.lower_head.paint(ctx, i);
                    ctx.restore();
                }
            }
            if (this.upper_head != null) {
                for (let i = 0, end = this._upper_sx.length; i < end; i++) {
                    ctx.save();
                    ctx.translate(this._upper_sx[i], this._upper_sy[i]);
                    ctx.rotate(angle);
                    this.upper_head.paint(ctx, i);
                    ctx.restore();
                }
            }
        }
    }
    exports.WhiskerView = WhiskerView;
    class Whisker extends upper_lower_1.UpperLower {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = WhiskerView;
            this.mixins(property_mixins_1.LineVector);
            this.define(({ Ref, Nullable }) => ({
                lower_head: [Nullable(Ref(arrow_head_1.ArrowHead)), () => new arrow_head_1.TeeHead({ size: 10 })],
                upper_head: [Nullable(Ref(arrow_head_1.ArrowHead)), () => new arrow_head_1.TeeHead({ size: 10 })],
            }));
            this.override({
                level: "underlay",
            });
        }
    }
    exports.Whisker = Whisker;
},
/* models/annotations/html/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var label_1 = require(418) /* ./label */;
    __esExport("HTMLLabel", label_1.HTMLLabel);
    var label_set_1 = require(420) /* ./label_set */;
    __esExport("HTMLLabelSet", label_set_1.HTMLLabelSet);
    var title_1 = require(421) /* ./title */;
    __esExport("HTMLTitle", title_1.HTMLTitle);
},
/* models/annotations/html/label.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const text_annotation_1 = require(419) /* ./text_annotation */;
    const math_1 = require(12) /* ../../../core/util/math */;
    const enums_1 = require(21) /* ../../../core/enums */;
    const graphics_1 = require(262) /* ../../../core/graphics */;
    const side_panel_1 = require(257) /* ../../../core/layout/side_panel */;
    const mixins = tslib_1.__importStar(require(95) /* ../../../core/property_mixins */);
    class HTMLLabelView extends text_annotation_1.TextAnnotationView {
        update_layout() {
            const { panel } = this;
            if (panel != null) {
                this.layout = new side_panel_1.SideLayout(panel, () => this.get_size(), false);
            }
            else {
                this.layout = undefined;
            }
        }
        // XXX: this needs to use CSS computed styles
        _get_size() {
            const { text } = this.model;
            const graphics = new graphics_1.TextBox({ text });
            const { angle, angle_units } = this.model;
            graphics.angle = (0, math_1.compute_angle)(angle, angle_units);
            graphics.visuals = this.visuals.text.values();
            const size = graphics.size();
            const { padding } = this;
            const width = size.width + padding.left + padding.right;
            const height = size.height + padding.top + padding.bottom;
            return { width, height };
        }
        _paint(ctx) {
            const { angle, angle_units } = this.model;
            const rotation = (0, math_1.compute_angle)(angle, angle_units);
            const panel = this.layout != null ? this.layout : this.plot_view.frame;
            const xscale = this.coordinates.x_scale;
            const yscale = this.coordinates.y_scale;
            let sx = (() => {
                switch (this.model.x_units) {
                    case "canvas": return this.model.x;
                    case "screen": return panel.bbox.xview.compute(this.model.x);
                    case "data": return xscale.compute(this.model.x);
                }
            })();
            let sy = (() => {
                switch (this.model.y_units) {
                    case "canvas": return this.model.y;
                    case "screen": return panel.bbox.yview.compute(this.model.y);
                    case "data": return yscale.compute(this.model.y);
                }
            })();
            sx += this.model.x_offset;
            sy -= this.model.y_offset;
            this._paint_text(ctx, this.model.text, sx, sy, rotation);
        }
    }
    exports.HTMLLabelView = HTMLLabelView;
    class HTMLLabel extends text_annotation_1.TextAnnotation {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = HTMLLabelView;
            this.mixins([
                mixins.Text,
                ["border_", mixins.Line],
                ["background_", mixins.Fill],
                ["background_", mixins.Hatch],
            ]);
            this.define(({ Float, Str, Angle }) => ({
                x: [Float],
                x_units: [enums_1.CoordinateUnits, "data"],
                y: [Float],
                y_units: [enums_1.CoordinateUnits, "data"],
                text: [Str, ""],
                angle: [Angle, 0],
                angle_units: [enums_1.AngleUnits, "rad"],
                x_offset: [Float, 0],
                y_offset: [Float, 0],
            }));
            this.override({
                background_fill_color: null,
                background_hatch_color: null,
                border_line_color: null,
            });
        }
    }
    exports.HTMLLabel = HTMLLabel;
},
/* models/annotations/html/text_annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(96) /* ../annotation */;
    const dom_1 = require(61) /* ../../../core/dom */;
    const side_panel_1 = require(257) /* ../../../core/layout/side_panel */;
    const kinds_1 = require(124) /* ../../common/kinds */;
    const resolve = tslib_1.__importStar(require(127) /* ../../common/resolve */);
    class TextAnnotationView extends annotation_1.AnnotationView {
        text_el;
        rendering_target() {
            return this.plot_view.canvas_view.overlays_el;
        }
        update_layout() {
            const { panel } = this;
            if (panel != null) {
                this.layout = new side_panel_1.SideLayout(panel, () => this.get_size(), true);
            }
            else {
                this.layout = undefined;
            }
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.paint(this.layer.ctx));
        }
        paint(ctx) {
            if (!this.model.visible) {
                (0, dom_1.undisplay)(this.el);
                return;
            }
            super.paint(ctx);
        }
        get padding() {
            return resolve.padding(this.model.padding);
        }
        get border_radius() {
            return resolve.border_radius(this.model.border_radius);
        }
        render() {
            super.render();
            this.text_el = document.createTextNode("");
            this.shadow_el.append(this.text_el);
        }
        _paint_text(ctx, text, sx, sy, angle) {
            const { el } = this;
            (0, dom_1.undisplay)(el);
            this.text_el.textContent = text;
            this.visuals.text.set_value(ctx);
            const { padding, border_radius } = this;
            if (this.layout != null) {
                this.position.replace(`
      :host {
        position: relative;
      }
      `);
            }
            else {
                const panel = this.plot_view.frame;
                const [rsx, rsy] = panel.bbox.relativize(sx, sy);
                this.position.replace(`
      :host {
        position: absolute;
        left: ${rsx}px;
        top: ${rsy}px;
      }
      `);
            }
            this.style.replace(`
    :host {
      width: max-content;
      height: max-content;

      color: ${ctx.fillStyle};
      -webkit-text-stroke: ${ctx.lineWidth}px ${ctx.strokeStyle};
      font: ${ctx.font};
      white-space: pre;

      padding-left: ${padding.left}px;
      padding-right: ${padding.right}px;
      padding-top: ${padding.top}px;
      padding-bottom: ${padding.bottom}px;

      border-top-left-radius: ${border_radius.top_left}px;
      border-top-right-radius: ${border_radius.top_right}px;
      border-bottom-right-radius: ${border_radius.bottom_right}px;
      border-bottom-left-radius: ${border_radius.bottom_left}px;
    }
    `);
            if (this.layout != null) {
                if (angle != 0) {
                    this.style.append(`
        :host {
          writing-mode: vertical-rl;
          rotate: 180deg;
          align-self: end;
        }
        `);
                }
            }
            else {
                const x_anchor = (() => {
                    switch (this.visuals.text.text_align.get_value()) {
                        case "left": return "0%";
                        case "center": return "50%";
                        case "right": return "100%";
                    }
                })();
                const y_anchor = (() => {
                    switch (this.visuals.text.text_baseline.get_value()) {
                        case "top": return "0%";
                        case "middle": return "50%";
                        case "bottom": return "100%";
                        default: return "50%"; // "baseline"
                    }
                })();
                this.style.append(`
      :host {
        transform-origin: ${x_anchor} ${y_anchor};
        transform: translate(-${x_anchor}, -${y_anchor}) rotate(${angle}rad);
      }
      `);
            }
            if (this.visuals.background_fill.doit) {
                this.visuals.background_fill.set_value(ctx);
                this.style.append(`
      :host {
        background-color: ${ctx.fillStyle};
      }
      `);
            }
            if (this.visuals.border_line.doit) {
                this.visuals.border_line.set_value(ctx);
                // attempt to support vector-style ("8 4 8") line dashing for css mode
                this.style.append(`
      :host {
        border-style: ${ctx.getLineDash().length < 2 ? "solid" : "dashed"};
        border-width: ${ctx.lineWidth}px;
        border-color: ${ctx.strokeStyle};
      }
      `);
            }
            (0, dom_1.display)(el);
        }
    }
    exports.TextAnnotationView = TextAnnotationView;
    class TextAnnotation extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(() => ({
                padding: [kinds_1.Padding, 0],
                border_radius: [kinds_1.BorderRadius, 0],
            }));
        }
    }
    exports.TextAnnotation = TextAnnotation;
},
/* models/annotations/html/label_set.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const data_annotation_1 = require(141) /* ../data_annotation */;
    const mixins = tslib_1.__importStar(require(95) /* ../../../core/property_mixins */);
    const enums_1 = require(21) /* ../../../core/enums */;
    const dom_1 = require(61) /* ../../../core/dom */;
    const p = tslib_1.__importStar(require(20) /* ../../../core/properties */);
    const types_1 = require(25) /* ../../../core/types */;
    const assert_1 = require(13) /* ../../../core/util/assert */;
    class HTMLLabelSetView extends data_annotation_1.DataAnnotationView {
        _x;
        _y;
        sx;
        sy;
        text;
        angle;
        x_offset;
        y_offset;
        els = [];
        set_data(source) {
            super.set_data(source);
            this.els.forEach((el) => el.remove());
            this.els = [...this.text.map(() => (0, dom_1.div)({ style: { display: "none" } }))];
            this.plot_view.canvas_view.overlays_el.append(...this.els);
        }
        remove() {
            this.els.forEach((el) => el.remove());
            this.els = [];
            super.remove();
        }
        _rerender() {
            this.paint(this.layer.ctx);
        }
        map_data() {
            const { x_scale, y_scale } = this.coordinates;
            const panel = this.layout != null ? this.layout : this.plot_view.frame;
            this.sx = (() => {
                switch (this.model.x_units) {
                    case "canvas":
                        return new types_1.ScreenArray(this._x);
                    case "screen":
                        return panel.bbox.xview.v_compute(this._x);
                    case "data":
                        return x_scale.v_compute(this._x);
                }
            })();
            this.sy = (() => {
                switch (this.model.y_units) {
                    case "canvas":
                        return new types_1.ScreenArray(this._y);
                    case "screen":
                        return panel.bbox.yview.v_compute(this._y);
                    case "data":
                        return y_scale.v_compute(this._y);
                }
            })();
        }
        _paint_data(ctx) {
            for (let i = 0, end = this.text.length; i < end; i++) {
                const x_offset_i = this.x_offset.get(i);
                const y_offset_i = this.y_offset.get(i);
                const sx_i = this.sx[i] + x_offset_i;
                const sy_i = this.sy[i] - y_offset_i;
                const angle_i = this.angle.get(i);
                const text_i = this.text.get(i);
                if (!isFinite(sx_i + sy_i + angle_i) || text_i == null) {
                    continue;
                }
                this._paint_text(ctx, i, text_i, sx_i, sy_i, angle_i);
            }
        }
        _paint_text(ctx, i, text, sx, sy, angle) {
            (0, assert_1.assert)(i in this.els);
            const el = this.els[i];
            el.textContent = text;
            this.visuals.text.set_vectorize(ctx, i);
            el.style.position = "absolute";
            el.style.left = `${sx}px`;
            el.style.top = `${sy}px`;
            el.style.color = ctx.fillStyle;
            el.style.webkitTextStroke = `${ctx.lineWidth}px ${ctx.strokeStyle}`;
            el.style.font = ctx.font;
            el.style.lineHeight = "normal"; // needed to prevent ipynb css override
            el.style.whiteSpace = "pre";
            const [x_anchor, x_t] = (() => {
                switch (this.visuals.text.text_align.get(i)) {
                    case "left": return ["left", "0%"];
                    case "center": return ["center", "-50%"];
                    case "right": return ["right", "-100%"];
                }
            })();
            const [y_anchor, y_t] = (() => {
                switch (this.visuals.text.text_baseline.get(i)) {
                    case "top": return ["top", "0%"];
                    case "middle": return ["center", "-50%"];
                    case "bottom": return ["bottom", "-100%"];
                    default: return ["center", "-50%"]; // "baseline"
                }
            })();
            let transform = `translate(${x_t}, ${y_t})`;
            if (angle != 0) {
                transform += `rotate(${angle}rad)`;
            }
            el.style.transformOrigin = `${x_anchor} ${y_anchor}`;
            el.style.transform = transform;
            if (this.layout == null) {
                // const {bbox} = this.plot_view.frame
                // const {left, right, top, bottom} = bbox
                // el.style.clipPath = ???
            }
            if (this.visuals.background_fill.doit) {
                this.visuals.background_fill.set_vectorize(ctx, i);
                el.style.backgroundColor = ctx.fillStyle;
            }
            if (this.visuals.border_line.doit) {
                this.visuals.border_line.set_vectorize(ctx, i);
                // attempt to support vector-style ("8 4 8") line dashing for css mode
                el.style.borderStyle = ctx.getLineDash().length < 2 ? "solid" : "dashed";
                el.style.borderWidth = `${ctx.lineWidth}px`;
                el.style.borderColor = ctx.strokeStyle;
            }
            (0, dom_1.display)(el);
        }
    }
    exports.HTMLLabelSetView = HTMLLabelSetView;
    class HTMLLabelSet extends data_annotation_1.DataAnnotation {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = HTMLLabelSetView;
            this.mixins([
                mixins.TextVector,
                ["border_", mixins.LineVector],
                ["background_", mixins.FillVector],
            ]);
            this.define(() => ({
                x: [p.XCoordinateSpec, { field: "x" }],
                y: [p.YCoordinateSpec, { field: "y" }],
                x_units: [enums_1.CoordinateUnits, "data"],
                y_units: [enums_1.CoordinateUnits, "data"],
                text: [p.NullStringSpec, { field: "text" }],
                angle: [p.AngleSpec, 0],
                x_offset: [p.NumberSpec, { value: 0 }],
                y_offset: [p.NumberSpec, { value: 0 }],
            }));
            this.override({
                background_fill_color: null,
                border_line_color: null,
            });
        }
    }
    exports.HTMLLabelSet = HTMLLabelSet;
},
/* models/annotations/html/title.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const text_annotation_1 = require(419) /* ./text_annotation */;
    const enums_1 = require(21) /* ../../../core/enums */;
    const graphics_1 = require(262) /* ../../../core/graphics */;
    const mixins = tslib_1.__importStar(require(95) /* ../../../core/property_mixins */);
    class HTMLTitleView extends text_annotation_1.TextAnnotationView {
        _get_location() {
            const hmargin = this.model.offset;
            const vmargin = this.model.standoff / 2;
            let sx, sy;
            const { bbox } = this.layout;
            switch (this.panel.side) {
                case "above":
                case "below": {
                    switch (this.model.vertical_align) {
                        case "top":
                            sy = bbox.top + vmargin;
                            break;
                        case "middle":
                            sy = bbox.vcenter;
                            break;
                        case "bottom":
                            sy = bbox.bottom - vmargin;
                            break;
                    }
                    switch (this.model.align) {
                        case "left":
                            sx = bbox.left + hmargin;
                            break;
                        case "center":
                            sx = bbox.hcenter;
                            break;
                        case "right":
                            sx = bbox.right - hmargin;
                            break;
                    }
                    break;
                }
                case "left": {
                    switch (this.model.vertical_align) {
                        case "top":
                            sx = bbox.left + vmargin;
                            break;
                        case "middle":
                            sx = bbox.hcenter;
                            break;
                        case "bottom":
                            sx = bbox.right - vmargin;
                            break;
                    }
                    switch (this.model.align) {
                        case "left":
                            sy = bbox.bottom - hmargin;
                            break;
                        case "center":
                            sy = bbox.vcenter;
                            break;
                        case "right":
                            sy = bbox.top + hmargin;
                            break;
                    }
                    break;
                }
                case "right": {
                    switch (this.model.vertical_align) {
                        case "top":
                            sx = bbox.right - vmargin;
                            break;
                        case "middle":
                            sx = bbox.hcenter;
                            break;
                        case "bottom":
                            sx = bbox.left + vmargin;
                            break;
                    }
                    switch (this.model.align) {
                        case "left":
                            sy = bbox.top + hmargin;
                            break;
                        case "center":
                            sy = bbox.vcenter;
                            break;
                        case "right":
                            sy = bbox.bottom - hmargin;
                            break;
                    }
                    break;
                }
            }
            return [sx, sy];
        }
        _paint(ctx) {
            const { text } = this.model;
            if (text.length == 0) {
                return;
            }
            this.model.text_baseline = this.model.vertical_align;
            this.model.text_align = this.model.align;
            const [sx, sy] = this._get_location();
            const angle = this.panel.get_label_angle_heuristic("parallel");
            this._paint_text(ctx, text, sx, sy, angle);
        }
        // XXX: this needs to use CSS computed styles
        _get_size() {
            const { text } = this.model;
            const graphics = new graphics_1.TextBox({ text });
            graphics.visuals = this.visuals.text.values();
            const size = graphics.size();
            const { padding } = this;
            const width = size.width + padding.left + padding.right;
            const height = size.height + padding.top + padding.bottom;
            // XXX: The magic 2px is for backwards compatibility. This will be removed at
            // some point, but currently there is no point breaking half of visual tests.
            return { width, height: height == 0 ? 0 : 2 + height + this.model.standoff };
        }
    }
    exports.HTMLTitleView = HTMLTitleView;
    class HTMLTitle extends text_annotation_1.TextAnnotation {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = HTMLTitleView;
            this.mixins([
                mixins.Text,
                ["border_", mixins.Line],
                ["background_", mixins.Fill],
                ["background_", mixins.Hatch],
            ]);
            this.define(({ Float, Str }) => ({
                text: [Str, ""],
                vertical_align: [enums_1.VerticalAlign, "bottom"],
                align: [enums_1.TextAlign, "left"],
                offset: [Float, 0],
                standoff: [Float, 10],
            }));
            this.prototype._props.text_align.options.internal = true;
            this.prototype._props.text_baseline.options.internal = true;
            this.override({
                text_font_size: "13px",
                text_font_style: "bold",
                text_line_height: 1.0,
                background_fill_color: null,
                background_hatch_color: null,
                border_line_color: null,
            });
        }
    }
    exports.HTMLTitle = HTMLTitle;
},
/* models/callbacks/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var customjs_1 = require(423) /* ./customjs */;
    __esExport("CustomJS", customjs_1.CustomJS);
    var open_url_1 = require(424) /* ./open_url */;
    __esExport("OpenURL", open_url_1.OpenURL);
    var set_value_1 = require(425) /* ./set_value */;
    __esExport("SetValue", set_value_1.SetValue);
    var toggle_visibility_1 = require(426) /* ./toggle_visibility */;
    __esExport("ToggleVisibility", toggle_visibility_1.ToggleVisibility);
    var open_dialog_1 = require(427) /* ./open_dialog */;
    __esExport("OpenDialog", open_dialog_1.OpenDialog);
    var close_dialog_1 = require(431) /* ./close_dialog */;
    __esExport("CloseDialog", close_dialog_1.CloseDialog);
},
/* models/callbacks/customjs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const callback_1 = require(125) /* ./callback */;
    const object_1 = require(9) /* ../../core/util/object */;
    const array_1 = require(10) /* ../../core/util/array */;
    const string_1 = require(41) /* ../../core/util/string */;
    const logging_1 = require(11) /* ../../core/logging */;
    const types_1 = require(8) /* ../../core/util/types */;
    const standalone_1 = require(81) /* ../../embed/standalone */;
    class CustomJS extends callback_1.Callback {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Unknown, Str, Dict, Auto, Or, Bool }) => ({
                args: [Dict(Unknown), {}],
                code: [Str],
                module: [Or(Auto, Bool), "auto"],
            }));
        }
        connect_signals() {
            super.connect_signals();
            const { args, code, module } = this.properties;
            this.on_change([args, code, module], () => this._state = null);
        }
        async _compile_module() {
            const url = URL.createObjectURL(new Blob([this.code], { type: "text/javascript" }));
            try {
                // XXX: eval() to work around transpilation to require()
                // https://github.com/microsoft/TypeScript/issues/43329
                const module = await eval(`import("${url}")`);
                // TODO const module = await import(`${url}`)
                if ((0, types_1.isFunction)(module.default)) {
                    return module.default;
                }
                else {
                    logging_1.logger.warn("custom ES module didn't export a default function");
                    return () => undefined;
                }
            }
            finally {
                URL.revokeObjectURL(url);
            }
        }
        async _compile_function() {
            const [names = [], values = []] = (0, array_1.unzip)((0, object_1.entries)(this.args));
            const code = (0, string_1.use_strict)(this.code);
            const func = new Function(...names, "cb_obj", "cb_data", "cb_context", code);
            return function (...args) {
                return func.call(this, ...values, ...args);
            };
        }
        _is_es_module(code) {
            return code.split("\n").some((line) => line.trimStart().startsWith("export default"));
        }
        async _compile() {
            const module = (() => {
                if (this.module == "auto") {
                    return this._is_es_module(this.code);
                }
                else {
                    return this.module;
                }
            })();
            if (module) {
                return { func: await this._compile_module(), module };
            }
            else {
                return { func: await this._compile_function(), module };
            }
        }
        async compile() {
            if (this._state == null) {
                this._state = await this._compile();
            }
        }
        _state = null;
        async state() {
            if (this._state == null) {
                this._state = await this._compile();
            }
            return this._state;
        }
        async execute(obj, data = {}) {
            const { func, module } = await this.state();
            const context = { index: standalone_1.index };
            if (module) {
                return func((0, object_1.to_object)(this.args), obj, data, context);
            }
            else {
                return func.call(obj, obj, data, context);
            }
        }
        execute_sync(obj, data = {}) {
            if (this._state == null) {
                throw new Error(`${this.type} needs to be compiled first`);
            }
            const { func, module } = this._state;
            const context = { index: standalone_1.index };
            if (module) {
                return func((0, object_1.to_object)(this.args), obj, data, context);
            }
            else {
                return func.call(obj, obj, data, context);
            }
        }
    }
    exports.CustomJS = CustomJS;
},
/* models/callbacks/open_url.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const callback_1 = require(125) /* ./callback */;
    const templating_1 = require(329) /* ../../core/util/templating */;
    const types_1 = require(8) /* ../../core/util/types */;
    class OpenURL extends callback_1.Callback {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Bool, Str }) => ({
                url: [Str, "http://"],
                same_tab: [Bool, false],
            }));
        }
        navigate(url) {
            if (this.same_tab) {
                window.location.href = url;
            }
            else {
                window.open(url);
            }
        }
        execute(_cb_obj, { source }) {
            const open_url = (i) => {
                const url = (0, templating_1.replace_placeholders)(this.url, source, i, undefined, undefined, encodeURI);
                if (!(0, types_1.isString)(url)) {
                    throw new Error("HTML output is not supported in this context");
                }
                this.navigate(url);
            };
            const { selected } = source;
            for (const i of selected.indices) {
                open_url(i);
            }
            for (const i of selected.line_indices) {
                open_url(i);
            }
            // TODO: multiline_indices: {[key: string]: number[]}
        }
    }
    exports.OpenURL = OpenURL;
},
/* models/callbacks/set_value.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const callback_1 = require(125) /* ./callback */;
    const has_props_1 = require(16) /* ../../core/has_props */;
    const logging_1 = require(11) /* ../../core/logging */;
    class SetValue extends callback_1.Callback {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Str, Unknown, Ref }) => ({
                obj: [Ref(has_props_1.HasProps)],
                attr: [Str],
                value: [Unknown],
            }));
        }
        execute() {
            const { obj, attr, value } = this;
            if (attr in obj.properties) {
                obj.setv({ [attr]: value });
            }
            else {
                logging_1.logger.error(`${obj.type}.${attr} is not a property`);
            }
        }
    }
    exports.SetValue = SetValue;
},
/* models/callbacks/toggle_visibility.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const callback_1 = require(125) /* ./callback */;
    const ui_element_1 = require(55) /* ../ui/ui_element */;
    class ToggleVisibility extends callback_1.Callback {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Ref }) => ({
                target: [Ref(ui_element_1.UIElement)],
            }));
        }
        execute() {
            const { target } = this;
            target.visible = !target.visible;
        }
    }
    exports.ToggleVisibility = ToggleVisibility;
},
/* models/callbacks/open_dialog.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const callback_1 = require(125) /* ./callback */;
    const dialog_1 = require(428) /* ../ui/dialog */;
    class OpenDialog extends callback_1.Callback {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Ref }) => ({
                dialog: [Ref(dialog_1.Dialog)],
            }));
        }
        async execute() {
            const { dialog } = this;
            const views = dialog.document?.views_manager;
            if (views != null) {
                let dialog_view = views.find_one(dialog);
                if (dialog_view == null) {
                    dialog_view = await views.build_view(dialog);
                }
                dialog_view.open();
            }
        }
    }
    exports.OpenDialog = OpenDialog;
},
/* models/ui/dialog.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const ui_element_1 = require(55) /* ../ui/ui_element */;
    const dom_node_1 = require(130) /* ../dom/dom_node */;
    const text_1 = require(429) /* ../dom/text */;
    const signaling_1 = require(17) /* ../../core/signaling */;
    const dom_1 = require(61) /* ../../core/dom */;
    const types_1 = require(8) /* ../../core/util/types */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const bbox_1 = require(62) /* ../../core/util/bbox */;
    const array_1 = require(10) /* ../../core/util/array */;
    const iterator_1 = require(15) /* ../../core/util/iterator */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    const Box = tslib_1.__importStar(require(346) /* ../common/box_kinds */);
    const coordinate_1 = require(58) /* ../coordinates/coordinate */;
    const kinds_1 = require(22) /* ../../core/kinds */;
    const dialogs_css_1 = tslib_1.__importStar(require(430) /* ../../styles/dialogs.css */), dialogs = dialogs_css_1;
    const icons_css_1 = tslib_1.__importDefault(require(76) /* ../../styles/icons.css */);
    // Make sure this at least an order of magnitude lower than --bokeh-top-level.
    const base_z_index = 1000;
    const UIElementLike = (0, kinds_1.Or)((0, kinds_1.Ref)(ui_element_1.UIElement), (0, kinds_1.Ref)(dom_node_1.DOMNode));
    const _stacking_order = [];
    const _minimization_area = (() => {
        const el = (0, dom_1.div)();
        const shadow_el = el.attachShadow({ mode: "open" });
        const stylesheet = new dom_1.InlineStyleSheet(`
:host {
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  position: fixed;
  left: 0;
  bottom: 0;
  width: max-content;
  height: max-content;
}
:host:empty {
  display: none;
}
`);
        stylesheet.install(shadow_el);
        void (0, dom_1.dom_ready)().then(() => document.body.append(el));
        return el;
    })();
    class DialogView extends ui_element_1.UIElementView {
        _title;
        _content;
        children_views() {
            return [...super.children_views(), this._title, this._content];
        }
        _position = new dom_1.InlineStyleSheet();
        _stacking = new dom_1.InlineStyleSheet();
        stylesheets() {
            return [...super.stylesheets(), dialogs_css_1.default, icons_css_1.default, this._position, this._stacking];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const title = (() => {
                const { title } = this.model;
                return (0, types_1.isString)(title) || title == null ? new text_1.Text({ content: title ?? "" }) : title;
            })();
            const content = (() => {
                const { content } = this.model;
                return (0, types_1.isString)(content) ? new text_1.Text({ content }) : content;
            })();
            this._title = await (0, build_views_1.build_view)(title, { parent: this });
            this._content = await (0, build_views_1.build_view)(content, { parent: this });
        }
        connect_signals() {
            super.connect_signals();
            const { visible } = this.model.properties;
            this.connect(visible.change, () => this._toggle(this.model.visible));
        }
        remove() {
            (0, array_1.remove)(_stacking_order, this);
            super.remove();
        }
        _has_rendered = false;
        _handles;
        _pin_el;
        _collapse_el;
        _minimize_el;
        _maximize_el;
        _close_el;
        _reposition(position) {
            this._position.replace(":host", {
                left: "left" in position ? (0, dom_1.px)(position.left) : "unset",
                right: "right" in position ? (0, dom_1.px)(position.right) : "unset",
                top: "top" in position ? (0, dom_1.px)(position.top) : "unset",
                bottom: "bottom" in position ? (0, dom_1.px)(position.bottom) : "unset",
                width: "width" in position ? (0, dom_1.px)(position.width) : "unset",
                height: "height" in position ? (0, dom_1.px)(position.height) : "unset",
            });
            this.update_bbox();
        }
        render() {
            super.render();
            this._title.render();
            this._content.render();
            const inner_el = (0, dom_1.div)({ class: dialogs.inner });
            this.shadow_el.append(inner_el);
            const header_el = (0, dom_1.div)({ class: dialogs.header });
            const content_el = (0, dom_1.div)({ class: dialogs.content }, this._content.el);
            const footer_el = (0, dom_1.div)({ class: dialogs.footer });
            inner_el.append(header_el);
            inner_el.append(content_el);
            inner_el.append(footer_el);
            const grip_el = (0, dom_1.div)({ class: dialogs.grip });
            const title_el = (0, dom_1.div)({ class: dialogs.title }, grip_el, this._title.el);
            const controls_el = (0, dom_1.div)({ class: dialogs.controls });
            header_el.append(title_el, controls_el);
            const pin_el = (0, dom_1.div)({ class: [dialogs.ctrl, dialogs.pin], title: "Pin" });
            pin_el.addEventListener("click", () => this.pin());
            this._pin_el = pin_el;
            const collapse_el = (0, dom_1.div)({ class: [dialogs.ctrl, dialogs.collapse], title: "Collapse" });
            collapse_el.addEventListener("click", () => this.collapse());
            this._collapse_el = collapse_el;
            const minimize_el = (0, dom_1.div)({ class: [dialogs.ctrl, dialogs.minimize], title: "Minimize" });
            minimize_el.addEventListener("click", () => this.minimize());
            this._minimize_el = minimize_el;
            const maximize_el = (0, dom_1.div)({ class: [dialogs.ctrl, dialogs.maximize], title: "Maximize" });
            maximize_el.addEventListener("click", () => this.maximize());
            this._maximize_el = maximize_el;
            const close_el = (0, dom_1.div)({ class: [dialogs.ctrl, dialogs.close], title: "Close" });
            close_el.addEventListener("click", () => this.close());
            this._close_el = close_el;
            if (this.model.pinnable) {
                controls_el.append(pin_el);
            }
            if (this.model.collapsible) {
                controls_el.append(collapse_el);
            }
            if (this.model.minimizable) {
                controls_el.append(minimize_el);
            }
            if (this.model.maximizable) {
                controls_el.append(maximize_el);
            }
            if (this.model.closable) {
                controls_el.append(close_el);
            }
            const handles = this._handles = {
                // area
                area: title_el,
                // edges
                top: (0, dom_1.div)({ class: [dialogs.handle, dialogs.resize_top] }),
                bottom: (0, dom_1.div)({ class: [dialogs.handle, dialogs.resize_bottom] }),
                left: (0, dom_1.div)({ class: [dialogs.handle, dialogs.resize_left] }),
                right: (0, dom_1.div)({ class: [dialogs.handle, dialogs.resize_right] }),
                // corners
                top_left: (0, dom_1.div)({ class: [dialogs.handle, dialogs.resize_top_left] }),
                top_right: (0, dom_1.div)({ class: [dialogs.handle, dialogs.resize_top_right] }),
                bottom_left: (0, dom_1.div)({ class: [dialogs.handle, dialogs.resize_bottom_left] }),
                bottom_right: (0, dom_1.div)({ class: [dialogs.handle, dialogs.resize_bottom_right] }),
            };
            this.shadow_el.append(handles.top, handles.bottom, handles.left, handles.right, handles.top_left, handles.top_right, handles.bottom_left, handles.bottom_right);
            let state = null;
            const cancel = () => {
                state = null;
                document.removeEventListener("pointermove", pointer_move);
                document.removeEventListener("pointerup", pointer_up);
                document.removeEventListener("keydown", key_press);
                this.el.classList.remove(dialogs.interacting);
            };
            const pointer_move = (event) => {
                (0, assert_1.assert)(state != null);
                event.preventDefault();
                this.el.classList.add(dialogs.interacting);
                const dx = event.x - state.xy.x;
                const dy = event.y - state.xy.y;
                const { target, bbox } = state;
                const delta_bbox = this._move_bbox(target, bbox, dx, dy);
                this._reposition(delta_bbox);
            };
            const pointer_up = (event) => {
                (0, assert_1.assert)(state != null);
                event.preventDefault();
                cancel();
            };
            const key_press = (event) => {
                if (event.key == "Escape") {
                    (0, assert_1.assert)(state != null);
                    event.preventDefault();
                    const { left, top, width, height } = state.bbox;
                    this._reposition({ left, top, width, height });
                    cancel();
                }
            };
            this.el.addEventListener("pointerdown", (event) => {
                (0, assert_1.assert)(state == null);
                this.bring_to_front();
                const target = this._hit_target(event.composedPath());
                if (target == null || !this._can_hit(target)) {
                    return;
                }
                event.preventDefault();
                const { x, y } = event;
                state = {
                    bbox: (0, dom_1.bounding_box)(this.el),
                    xy: { x, y },
                    target,
                };
                document.addEventListener("pointermove", pointer_move, { signal: this.abort_signal });
                document.addEventListener("pointerup", pointer_up, { signal: this.abort_signal });
                document.addEventListener("keydown", key_press, { signal: this.abort_signal });
                const target_el = this._handles[target];
                target_el.setPointerCapture(event.pointerId);
            });
            title_el.addEventListener("wheel", (event) => {
                const dy = event.deltaY;
                if ((dy < 0 && !this._collapsed) || (dy > 0 && this._collapsed)) {
                    event.preventDefault();
                    event.stopPropagation();
                    this.collapse();
                }
            });
            this._has_rendered = true;
            if (this.model.visible) {
                this.bring_to_front();
            }
        }
        get resizable() {
            const { resizable } = this.model;
            return {
                left: resizable == "left" || resizable == "x" || resizable == "all",
                right: resizable == "right" || resizable == "x" || resizable == "all",
                top: resizable == "top" || resizable == "y" || resizable == "all",
                bottom: resizable == "bottom" || resizable == "y" || resizable == "all",
            };
        }
        _hit_target(path) {
            const { _handles } = this;
            for (const el of path) {
                switch (el) {
                    case _handles.area: return "area";
                    case _handles.top: return "top";
                    case _handles.bottom: return "bottom";
                    case _handles.left: return "left";
                    case _handles.right: return "right";
                    case _handles.top_left: return "top_left";
                    case _handles.top_right: return "top_right";
                    case _handles.bottom_left: return "bottom_left";
                    case _handles.bottom_right: return "bottom_right";
                }
            }
            return null;
        }
        _can_hit(target) {
            if (this._minimized || this._maximized) {
                return false;
            }
            const { left, right, top, bottom } = this.resizable;
            switch (target) {
                case "top_left": return top && left;
                case "top_right": return top && right;
                case "bottom_left": return bottom && left;
                case "bottom_right": return bottom && right;
                case "left": return left;
                case "right": return right;
                case "top": return top;
                case "bottom": return bottom;
                case "area": return this.model.movable != "none";
            }
        }
        _move_bbox(target, bbox, dx, dy) {
            const resolve = (dim, limit) => {
                if (limit instanceof coordinate_1.Coordinate) {
                    return this.resolve_as_scalar(limit, dim);
                }
                else {
                    return NaN;
                }
            };
            const slimits = bbox_1.BBox.from_lrtb({
                left: resolve("x", this.model.left_limit),
                right: resolve("x", this.model.right_limit),
                top: resolve("y", this.model.top_limit),
                bottom: resolve("y", this.model.bottom_limit),
            });
            const [dl, dr, dt, db] = (() => {
                const { symmetric } = this.model;
                const [Dx, Dy] = symmetric ? [-dx, -dy] : [0, 0];
                switch (target) {
                    // corners
                    case "top_left": return [dx, Dx, dy, Dy];
                    case "top_right": return [Dx, dx, dy, Dy];
                    case "bottom_left": return [dx, Dx, Dy, dy];
                    case "bottom_right": return [Dx, dx, Dy, dy];
                    // edges
                    case "left": return [dx, Dx, 0, 0];
                    case "right": return [Dx, dx, 0, 0];
                    case "top": return [0, 0, dy, Dy];
                    case "bottom": return [0, 0, Dy, dy];
                    // area
                    case "area": {
                        switch (this.model.movable) {
                            case "both": return [dx, dx, dy, dy];
                            case "x": return [dx, dx, 0, 0];
                            case "y": return [0, 0, dy, dy];
                            case "none": return [0, 0, 0, 0];
                        }
                    }
                }
            })();
            const min = (a, b) => (0, array_1.min)([a, b]);
            const sgn = (v) => v < 0 ? -1 : (v > 0 ? 1 : 0);
            let { left, right, left_sign, right_sign } = (() => {
                const left = bbox.left + dl;
                const right = bbox.right + dr;
                const left_sign = sgn(dl);
                const right_sign = sgn(dr);
                if (left <= right) {
                    return { left, right, left_sign, right_sign };
                }
                else {
                    return { left: right, right: left, left_sign: right_sign, right_sign: left_sign };
                }
            })();
            let { top, bottom, top_sign, bottom_sign } = (() => {
                const top = bbox.top + dt;
                const bottom = bbox.bottom + db;
                const top_sign = sgn(dt);
                const bottom_sign = sgn(db);
                if (top <= bottom) {
                    return { top, bottom, top_sign, bottom_sign };
                }
                else {
                    return { top: bottom, bottom: top, top_sign: bottom_sign, bottom_sign: top_sign };
                }
            })();
            const Dl = left - slimits.left;
            const Dr = slimits.right - right;
            const Dh = min(Dl < 0 ? Dl : NaN, Dr < 0 ? Dr : NaN);
            if (isFinite(Dh) && Dh < 0) {
                left += -left_sign * (-Dh);
                right += -right_sign * (-Dh);
            }
            const Dt = top - slimits.top;
            const Db = slimits.bottom - bottom;
            const Dv = min(Dt < 0 ? Dt : NaN, Db < 0 ? Db : NaN);
            if (isFinite(Dv) && Dv < 0) {
                top += -top_sign * (-Dv);
                bottom += -bottom_sign * (-Dv);
            }
            return bbox_1.BBox.from_lrtb({ left, right, top, bottom });
        }
        _pinned = false;
        pin() {
            const { _pinned } = this;
            for (const dialog_view of _stacking_order) {
                if (dialog_view == this) {
                    this._pin(!_pinned);
                }
                else {
                    dialog_view._pin(false);
                }
            }
            if (!_pinned) {
                this.bring_to_front();
            }
        }
        _pin(value) {
            if (this._pinned != value) {
                this._pinned = value;
                this.el.classList.toggle(dialogs.pinned, this._pinned);
                this._pin_el.title = this._pinned ? "Unpin" : "Pin";
            }
        }
        _normal_bbox = null;
        _collapsed = false;
        collapse() {
            const position = (() => {
                if (!this._collapsed) {
                    this._minimize(false);
                    this._maximize(false);
                    if (this._normal_bbox == null) {
                        this._normal_bbox = (0, dom_1.bounding_box)(this.el);
                    }
                    const { left, top, width } = this._normal_bbox;
                    return { left, top, width, height: "max-content" };
                }
                else {
                    const { _normal_bbox } = this;
                    (0, assert_1.assert)(_normal_bbox != null);
                    this._normal_bbox = null;
                    return _normal_bbox;
                }
            })();
            this._reposition(position);
            this._collapse(!this._collapsed);
        }
        _collapse(value) {
            if (this._collapsed != value) {
                this._collapsed = value;
                this.el.classList.toggle(dialogs.collapsed, this._collapsed);
                this._collapse_el.title = this._collapsed ? "Restore" : "Collapse";
            }
        }
        _minimized = false;
        minimize() {
            const position = (() => {
                if (!this._minimized) {
                    this._pin(false);
                    this._collapse(false);
                    this._maximize(false);
                    if (this._normal_bbox == null) {
                        this._normal_bbox = (0, dom_1.bounding_box)(this.el);
                    }
                    return { width: "auto", height: "max-content" };
                }
                else {
                    const { _normal_bbox } = this;
                    (0, assert_1.assert)(_normal_bbox != null);
                    this._normal_bbox = null;
                    return _normal_bbox;
                }
            })();
            this._reposition(position);
            this._minimize(!this._minimized);
        }
        _minimize(value) {
            if (this._minimized != value) {
                this._minimized = value;
                const target = value ? (_minimization_area.shadowRoot ?? _minimization_area) : document.body;
                target.append(this.el);
                this.el.classList.toggle(dialogs.minimized, this._minimized);
                this._minimize_el.title = this._minimized ? "Restore" : "Minimize";
            }
        }
        _maximized = false;
        maximize() {
            const position = (() => {
                if (!this._maximized) {
                    this._collapse(false);
                    this._minimize(false);
                    if (this._normal_bbox == null) {
                        this._normal_bbox = (0, dom_1.bounding_box)(this.el);
                    }
                    return { left: 0, top: 0, width: "100%", height: "100%" };
                }
                else {
                    const { _normal_bbox } = this;
                    (0, assert_1.assert)(_normal_bbox != null);
                    this._normal_bbox = null;
                    return _normal_bbox;
                }
            })();
            this._reposition(position);
            this._maximize(!this._maximized);
        }
        _maximize(value) {
            if (this._maximized != value) {
                this._maximized = value;
                this.el.classList.toggle(dialogs.maximized, this._maximized);
                this._maximize_el.title = this._maximized ? "Restore" : "Maximize";
            }
        }
        restore() {
            this._collapse(false);
            this._minimize(false);
            this._maximize(false);
            const { _normal_bbox } = this;
            if (_normal_bbox != null) {
                this._reposition(_normal_bbox);
                this._normal_bbox = null;
            }
        }
        _toggle(show) {
            if (show) {
                const target = document.body;
                if (!this._has_rendered) {
                    this.render_to(target);
                    this.r_after_render();
                }
                if (!this.el.isConnected) {
                    target.append(this.el);
                }
                this.bring_to_front();
            }
            else {
                (0, array_1.remove)(_stacking_order, this);
                this.el.remove();
            }
        }
        displayed = new signaling_1.Signal(this, "displayed");
        get is_open() {
            return this.model.visible;
        }
        toggle(force) {
            const visible = force ?? !this.model.visible;
            this.model.setv({ visible }, { check_eq: false });
            this.displayed.emit(visible);
        }
        open() {
            this.toggle(true);
        }
        close() {
            switch (this.model.close_action) {
                case "hide": {
                    this.toggle(false);
                    break;
                }
                case "destroy": {
                    this.remove();
                    break;
                }
            }
        }
        bring_to_front() {
            if (!_stacking_order.includes(this)) {
                _stacking_order.push(this);
            }
            const pinned = (0, array_1.find)(_stacking_order, (view) => view._pinned);
            if (pinned != null) {
                (0, array_1.remove)(_stacking_order, pinned);
            }
            (0, array_1.remove)(_stacking_order, this);
            _stacking_order.push(this);
            if (pinned != null) {
                _stacking_order.push(pinned);
            }
            for (const [dialog_view, i] of (0, iterator_1.enumerate)(_stacking_order)) {
                dialog_view._stacking.replace(":host", {
                    "z-index": `${base_z_index + i}`,
                });
            }
        }
    }
    exports.DialogView = DialogView;
    class Dialog extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = DialogView;
            this.define(({ Bool, Str, Ref, Or, Nullable, Enum }) => ({
                title: [Nullable(Or(Str, Ref(dom_node_1.DOMNode), Ref(ui_element_1.UIElement))), null],
                content: [Or(Str, Ref(dom_node_1.DOMNode), Ref(ui_element_1.UIElement))],
                pinnable: [Bool, true],
                collapsible: [Bool, true],
                minimizable: [Bool, true],
                maximizable: [Bool, true],
                closable: [Bool, true],
                close_action: [Enum("hide", "destroy"), "destroy"],
                resizable: [Box.Resizable, "all"],
                movable: [Box.Movable, "both"],
                symmetric: [Bool, false],
                top_limit: [Box.Limit, null],
                bottom_limit: [Box.Limit, null],
                left_limit: [Box.Limit, null],
                right_limit: [Box.Limit, null],
            }));
        }
    }
    exports.Dialog = Dialog;
},
/* models/dom/text.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const dom_node_1 = require(130) /* ./dom_node */;
    class TextView extends dom_node_1.DOMNodeView {
        connect_signals() {
            super.connect_signals();
            const { content } = this.model.properties;
            this.on_change(content, () => this.render());
        }
        render() {
            this.el.textContent = this.model.content;
        }
        // TODO This shouldn't be here.
        after_render() {
            this.finish();
        }
        _create_element() {
            return document.createTextNode("");
        }
    }
    exports.TextView = TextView;
    class Text extends dom_node_1.DOMNode {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = TextView;
            this.define(({ Str }) => ({
                content: [Str, ""],
            }));
        }
    }
    exports.Text = Text;
},
/* styles/dialogs.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.interacting = "bk-interacting";
    exports.inner = "bk-inner";
    exports.header = "bk-header";
    exports.content = "bk-content";
    exports.collapsed = "bk-collapsed";
    exports.minimized = "bk-minimized";
    exports.footer = "bk-footer";
    exports.grip = "bk-grip";
    exports.title = "bk-title";
    exports.controls = "bk-controls";
    exports.ctrl = "bk-ctrl";
    exports.pin = "bk-pin";
    exports.pinned = "bk-pinned";
    exports.collapse = "bk-collapse";
    exports.minimize = "bk-minimize";
    exports.maximize = "bk-maximize";
    exports.maximized = "bk-maximized";
    exports.close = "bk-close";
    exports.handle = "bk-handle";
    exports.resize_top = "bk-resize-top";
    exports.resize_bottom = "bk-resize-bottom";
    exports.resize_left = "bk-resize-left";
    exports.resize_right = "bk-resize-right";
    exports.resize_top_left = "bk-resize-top-left";
    exports.resize_top_right = "bk-resize-top-right";
    exports.resize_bottom_left = "bk-resize-bottom-left";
    exports.resize_bottom_right = "bk-resize-bottom-right";
    exports.default = `:host{--bokeh-bg-color:var(--background-color);--bokeh-border-color:var(--divider-color);--bokeh-shadow-color:var(--divider-color);--bokeh-ctrl-size:16px;--bokeh-ctrl-color:var(--shortcut-color);}:host{position:fixed;left:200px;top:200px;width:600px;height:600px;width:80vw;height:60vh;}:host(.bk-interacting){opacity:0.9;}.bk-inner{position:relative;display:flex;flex-direction:column;flex-wrap:nowrap;width:100%;height:100%;overflow:hidden;border-radius:4px;background-color:var(--bokeh-bg-color);border:1px solid var(--bokeh-border-color);box-shadow:5px 5px 10px var(--bokeh-shadow-color);}.bk-header{position:relative;display:flex;flex:0;gap:1em;padding:5px;background-color:var(--border-color);}.bk-content{position:relative;display:flex;flex:1;overflow:auto;}:host(.bk-collapsed) .bk-content,:host(.bk-minimized) .bk-content,:host(.bk-collapsed) .bk-footer,:host(.bk-minimized) .bk-footer{display:none;}.bk-footer{position:relative;display:flex;flex:0;}.bk-grip{width:var(--bokeh-ctrl-size);height:var(--bokeh-ctrl-size);background-color:var(--bokeh-ctrl-color);background-color:var(--color);mask-image:var(--bokeh-icon-y-grip);mask-size:contain;mask-repeat:no-repeat;-webkit-mask-image:var(--bokeh-icon-y-grip);-webkit-mask-size:contain;-webkit-mask-repeat:no-repeat;}.bk-title{position:relative;display:flex;flex:1;cursor:move;white-space:nowrap;}.bk-controls{position:relative;display:flex;flex:0;}.bk-ctrl{width:var(--bokeh-ctrl-size);height:var(--bokeh-ctrl-size);cursor:pointer;mask-size:100% 100%;-webkit-mask-size:100% 100%;mask-position:center center;-webkit-mask-position:center center;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat;background-color:var(--bokeh-ctrl-color);}.bk-ctrl:hover{background-color:var(--hover-color);}.bk-pin{mask-image:var(--bokeh-icon-pin);-webkit-mask-image:var(--bokeh-icon-pin);}:host(.bk-pinned) .bk-pin{mask-image:var(--bokeh-icon-unpin);-webkit-mask-image:var(--bokeh-icon-unpin);}.bk-collapse{mask-image:var(--bokeh-icon-chevron-up);-webkit-mask-image:var(--bokeh-icon-chevron-up);}:host(.bk-collapsed) .bk-collapse{mask-image:var(--bokeh-icon-chevron-down);-webkit-mask-image:var(--bokeh-icon-chevron-down);}.bk-minimize{mask-image:var(--bokeh-icon-arrow-down-to-bar);-webkit-mask-image:var(--bokeh-icon-arrow-down-to-bar);}:host(.bk-minimized) .bk-minimize{mask-image:var(--bokeh-icon-arrow-up-from-bar);-webkit-mask-image:var(--bokeh-icon-arrow-up-from-bar);}.bk-maximize{mask-image:var(--bokeh-icon-maximize);-webkit-mask-image:var(--bokeh-icon-maximize);}:host(.bk-maximized) .bk-maximize{mask-image:var(--bokeh-icon-minimize);-webkit-mask-image:var(--bokeh-icon-minimize);}.bk-close{mask-image:var(--bokeh-icon-x);-webkit-mask-image:var(--bokeh-icon-x);}:host{--resize-radius:6px;--resize-depth:calc(2*var(--resize-radius));}:host(.bk-minimized){position:relative;}:host(.bk-minimized) .bk-handle,:host(.bk-maximized) .bk-handle{display:none;}:host(.bk-minimized) .bk-title,:host(.bk-maximized) .bk-title{cursor:default;}.bk-resize-top{position:absolute;top:0;left:var(--resize-radius);width:calc(100% - var(--resize-depth));height:var(--resize-depth);transform:translate(0, -50%);cursor:ns-resize;}.bk-resize-bottom{position:absolute;bottom:0;left:var(--resize-radius);width:calc(100% - var(--resize-depth));height:var(--resize-depth);transform:translate(0, 50%);cursor:ns-resize;}.bk-resize-left{position:absolute;left:0;top:var(--resize-radius);width:var(--resize-depth);height:calc(100% - var(--resize-depth));transform:translate(-50%, 0);cursor:ew-resize;}.bk-resize-right{position:absolute;right:0;top:var(--resize-radius);width:var(--resize-depth);height:calc(100% - var(--resize-depth));transform:translate(50%, 0);cursor:ew-resize;}.bk-resize-top-left{position:absolute;top:0;left:0;width:var(--resize-depth);height:var(--resize-depth);transform:translate(-50%, -50%);cursor:nw-resize;}.bk-resize-top-right{position:absolute;top:0;right:0;width:var(--resize-depth);height:var(--resize-depth);transform:translate(50%, -50%);cursor:ne-resize;}.bk-resize-bottom-left{position:absolute;bottom:0;left:0;width:var(--resize-depth);height:var(--resize-depth);transform:translate(-50%, 50%);cursor:sw-resize;}.bk-resize-bottom-right{position:absolute;bottom:0;right:0;width:var(--resize-depth);height:var(--resize-depth);transform:translate(50%, 50%);cursor:se-resize;}`;
},
/* models/callbacks/close_dialog.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const callback_1 = require(125) /* ./callback */;
    const dialog_1 = require(428) /* ../ui/dialog */;
    class CloseDialog extends callback_1.Callback {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Ref }) => ({
                dialog: [Ref(dialog_1.Dialog)],
            }));
        }
        async execute() {
            const { dialog } = this;
            dialog.document?.views_manager?.find_one(dialog)?.close();
        }
    }
    exports.CloseDialog = CloseDialog;
},
/* models/canvas/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var canvas_1 = require(399) /* ./canvas */;
    __esExport("Canvas", canvas_1.Canvas);
    var cartesian_frame_1 = require(268) /* ./cartesian_frame */;
    __esExport("CartesianFrame", cartesian_frame_1.CartesianFrame);
},
/* models/comparisons/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var comparison_1 = require(434) /* ./comparison */;
    __esExport("Comparison", comparison_1.Comparison);
    var customjs_compare_1 = require(435) /* ./customjs_compare */;
    __esExport("CustomJSCompare", customjs_compare_1.CustomJSCompare);
    var nan_compare_1 = require(436) /* ./nan_compare */;
    __esExport("NanCompare", nan_compare_1.NanCompare);
},
/* models/comparisons/comparison.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    class Comparison extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Comparison = Comparison;
},
/* models/comparisons/customjs_compare.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const comparison_1 = require(434) /* ./comparison */;
    const object_1 = require(9) /* ../../core/util/object */;
    const string_1 = require(41) /* ../../core/util/string */;
    class CustomJSCompare extends comparison_1.Comparison {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Unknown, Str, Dict }) => ({
                args: [Dict(Unknown), {}],
                code: [Str, ""],
            }));
        }
        get names() {
            return (0, object_1.keys)(this.args);
        }
        get values() {
            return (0, object_1.values)(this.args);
        }
        _make_func() {
            const code = (0, string_1.use_strict)(this.code);
            return new Function("x", "y", ...this.names, code);
        }
        compute(x, y) {
            const func = this._make_func();
            return func(x, y, this.values);
        }
    }
    exports.CustomJSCompare = CustomJSCompare;
},
/* models/comparisons/nan_compare.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const comparison_1 = require(434) /* ./comparison */;
    const types_1 = require(8) /* ../../core/util/types */;
    class NanCompare extends comparison_1.Comparison {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Bool }) => ({
                ascending_first: [Bool, false],
            }));
        }
        compute(x, y) {
            if ((0, types_1.isNumber)(x) && isNaN(x)) {
                return this.ascending_first ? -1 : 1;
            }
            if ((0, types_1.isNumber)(y) && isNaN(y)) {
                return this.ascending_first ? 1 : -1;
            }
            if ((0, types_1.isNumber)(x) && (0, types_1.isNumber)(y)) {
                return x == y ? 0 : x < y ? -1 : 1;
            }
            return 0;
        }
    }
    exports.NanCompare = NanCompare;
},
/* models/coordinates/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var coordinate_mapping_1 = require(107) /* ./coordinate_mapping */;
    __esExport("CoordinateMapping", coordinate_mapping_1.CoordinateMapping);
    var node_1 = require(57) /* ./node */;
    __esExport("Node", node_1.Node);
    var xy_1 = require(66) /* ./xy */;
    __esExport("XY", xy_1.XY);
    var indexed_1 = require(67) /* ./indexed */;
    __esExport("Indexed", indexed_1.Indexed);
},
/* models/expressions/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var expression_1 = require(439) /* ./expression */;
    __esExport("Expression", expression_1.Expression);
    var customjs_expr_1 = require(440) /* ./customjs_expr */;
    __esExport("CustomJSExpr", customjs_expr_1.CustomJSExpr);
    var stack_1 = require(441) /* ./stack */;
    __esExport("Stack", stack_1.Stack);
    var cumsum_1 = require(442) /* ./cumsum */;
    __esExport("CumSum", cumsum_1.CumSum);
    var expression_2 = require(439) /* ./expression */;
    __esExport("ScalarExpression", expression_2.ScalarExpression);
    var minimum_1 = require(443) /* ./minimum */;
    __esExport("Minimum", minimum_1.Minimum);
    var maximum_1 = require(444) /* ./maximum */;
    __esExport("Maximum", maximum_1.Maximum);
    var coordinate_transform_1 = require(445) /* ./coordinate_transform */;
    __esExport("XComponent", coordinate_transform_1.XComponent);
    __esExport("YComponent", coordinate_transform_1.YComponent);
    var polar_1 = require(446) /* ./polar */;
    __esExport("PolarTransform", polar_1.PolarTransform);
},
/* models/expressions/expression.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    class Expression extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        _result = new Map();
        v_compute(source) {
            let result = this._result.get(source);
            if (result === undefined || source.changed_for(this)) {
                result = this._v_compute(source);
                this._result.set(source, result);
            }
            return result;
        }
    }
    exports.Expression = Expression;
    class ScalarExpression extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        _result = new Map();
        compute(source) {
            let result = this._result.get(source);
            if (result === undefined || source.changed_for(this)) {
                result = this._compute(source);
                this._result.set(source, result);
            }
            return result;
        }
    }
    exports.ScalarExpression = ScalarExpression;
},
/* models/expressions/customjs_expr.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const has_props_1 = require(16) /* ../../core/has_props */;
    const expression_1 = require(439) /* ./expression */;
    const types_1 = require(25) /* ../../core/types */;
    const array_1 = require(10) /* ../../core/util/array */;
    const object_1 = require(9) /* ../../core/util/object */;
    const string_1 = require(41) /* ../../core/util/string */;
    const types_2 = require(8) /* ../../core/util/types */;
    class CustomJSExpr extends expression_1.Expression {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Unknown, Str, Dict }) => ({
                args: [Dict(Unknown), {}],
                code: [Str, ""],
            }));
        }
        connect_signals() {
            super.connect_signals();
            for (const value of (0, object_1.values)(this.args)) {
                if (value instanceof has_props_1.HasProps) {
                    value.change.connect(() => {
                        this._result.clear();
                        this.change.emit();
                    });
                }
            }
        }
        get names() {
            return (0, object_1.keys)(this.args);
        }
        get values() {
            return (0, object_1.values)(this.args);
        }
        get func() {
            const code = (0, string_1.use_strict)(this.code);
            return new types_1.GeneratorFunction(...this.names, code);
        }
        _v_compute(source) {
            const generator = this.func.apply(source, this.values);
            let result = generator.next();
            if ((result.done ?? false) && result.value !== undefined) {
                const { value } = result;
                if ((0, types_2.isArray)(value) || (0, types_2.isTypedArray)(value)) {
                    return value;
                }
                else if ((0, types_2.isIterable)(value)) {
                    return [...value];
                }
                else {
                    return (0, array_1.repeat)(value, source.length);
                }
            }
            else {
                const array = [];
                do {
                    array.push(result.value);
                    result = generator.next();
                } while (!(result.done ?? false));
                return array;
            }
        }
    }
    exports.CustomJSExpr = CustomJSExpr;
},
/* models/expressions/stack.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const expression_1 = require(439) /* ./expression */;
    const object_1 = require(9) /* ../../core/util/object */;
    class Stack extends expression_1.Expression {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Str, List }) => ({
                fields: [List(Str), []],
            }));
        }
        _v_compute(source) {
            const n = source.get_length() ?? 0;
            const result = new Float64Array(n);
            for (const f of this.fields) {
                const column = (0, object_1.dict)(source.data).get(f);
                if (column != null) {
                    const k = Math.min(n, column.length);
                    for (let i = 0; i < k; i++) {
                        result[i] += column[i];
                    }
                }
            }
            return result;
        }
    }
    exports.Stack = Stack;
},
/* models/expressions/cumsum.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const expression_1 = require(439) /* ./expression */;
    const object_1 = require(9) /* ../../core/util/object */;
    class CumSum extends expression_1.Expression {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Bool, Str }) => ({
                field: [Str],
                include_zero: [Bool, false],
            }));
        }
        _v_compute(source) {
            const result = new Float64Array(source.get_length() ?? 0);
            const column = ((0, object_1.dict)(source.data).get(this.field) ?? []);
            const offset = this.include_zero ? 1 : 0;
            result[0] = this.include_zero ? 0 : column[0];
            for (let i = 1; i < result.length; i++) {
                result[i] = result[i - 1] + column[i - offset];
            }
            return result;
        }
    }
    exports.CumSum = CumSum;
},
/* models/expressions/minimum.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const expression_1 = require(439) /* ./expression */;
    const object_1 = require(9) /* ../../core/util/object */;
    const array_1 = require(10) /* ../../core/util/array */;
    class Minimum extends expression_1.ScalarExpression {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Float, Str }) => ({
                field: [Str],
                initial: [Float, Infinity],
            }));
        }
        _compute(source) {
            const column = (0, object_1.dict)(source.data).get(this.field) ?? [];
            return Math.min(this.initial, (0, array_1.min)(column));
        }
    }
    exports.Minimum = Minimum;
},
/* models/expressions/maximum.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const expression_1 = require(439) /* ./expression */;
    const object_1 = require(9) /* ../../core/util/object */;
    const array_1 = require(10) /* ../../core/util/array */;
    class Maximum extends expression_1.ScalarExpression {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Float, Str }) => ({
                field: [Str],
                initial: [Float, -Infinity],
            }));
        }
        _compute(source) {
            const column = (0, object_1.dict)(source.data).get(this.field) ?? [];
            return Math.max(this.initial, (0, array_1.max)(column));
        }
    }
    exports.Maximum = Maximum;
},
/* models/expressions/coordinate_transform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const expression_1 = require(439) /* ../expressions/expression */;
    class CoordinateTransform extends expression_1.Expression {
        constructor(attrs) {
            super(attrs);
        }
        get x() {
            return new XComponent({ transform: this });
        }
        get y() {
            return new YComponent({ transform: this });
        }
    }
    exports.CoordinateTransform = CoordinateTransform;
    class XYComponent extends expression_1.Expression {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Ref }) => ({
                transform: [Ref(CoordinateTransform)],
            }));
        }
    }
    exports.XYComponent = XYComponent;
    class XComponent extends XYComponent {
        constructor(attrs) {
            super(attrs);
        }
        _v_compute(source) {
            return this.transform.v_compute(source).x;
        }
    }
    exports.XComponent = XComponent;
    class YComponent extends XYComponent {
        constructor(attrs) {
            super(attrs);
        }
        _v_compute(source) {
            return this.transform.v_compute(source).y;
        }
    }
    exports.YComponent = YComponent;
},
/* models/expressions/polar.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const coordinate_transform_1 = require(445) /* ../expressions/coordinate_transform */;
    const enums_1 = require(21) /* ../../core/enums */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    class PolarTransform extends coordinate_transform_1.CoordinateTransform {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({}) => ({
                radius: [p.DistanceSpec, { field: "radius" }],
                angle: [p.AngleSpec, { field: "angle" }],
                direction: [enums_1.Direction, "anticlock"],
            }));
        }
        _v_compute(source) {
            const radius = this.properties.radius.uniform(source);
            const angle = this.properties.angle.uniform(source);
            const coeff = this.direction == "anticlock" ? -1 : 1;
            const n = Math.min(radius.length, angle.length);
            const x = new Float64Array(n);
            const y = new Float64Array(n);
            for (let i = 0; i < n; i++) {
                const radius_i = radius.get(i);
                const angle_i = angle.get(i) * coeff;
                x[i] = radius_i * Math.cos(angle_i);
                y[i] = radius_i * Math.sin(angle_i);
            }
            return { x, y };
        }
    }
    exports.PolarTransform = PolarTransform;
},
/* models/filters/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var boolean_filter_1 = require(448) /* ./boolean_filter */;
    __esExport("BooleanFilter", boolean_filter_1.BooleanFilter);
    var customjs_filter_1 = require(449) /* ./customjs_filter */;
    __esExport("CustomJSFilter", customjs_filter_1.CustomJSFilter);
    var filter_1 = require(322) /* ./filter */;
    __esExport("Filter", filter_1.Filter);
    var group_filter_1 = require(450) /* ./group_filter */;
    __esExport("GroupFilter", group_filter_1.GroupFilter);
    var index_filter_1 = require(451) /* ./index_filter */;
    __esExport("IndexFilter", index_filter_1.IndexFilter);
    var all_indices_1 = require(323) /* ./all_indices */;
    __esExport("AllIndices", all_indices_1.AllIndices);
    var inversion_filter_1 = require(452) /* ./inversion_filter */;
    __esExport("InversionFilter", inversion_filter_1.InversionFilter);
    var intersection_filter_1 = require(324) /* ./intersection_filter */;
    __esExport("IntersectionFilter", intersection_filter_1.IntersectionFilter);
    var union_filter_1 = require(453) /* ./union_filter */;
    __esExport("UnionFilter", union_filter_1.UnionFilter);
    var difference_filter_1 = require(454) /* ./difference_filter */;
    __esExport("DifferenceFilter", difference_filter_1.DifferenceFilter);
    var symmetric_difference_filter_1 = require(455) /* ./symmetric_difference_filter */;
    __esExport("SymmetricDifferenceFilter", symmetric_difference_filter_1.SymmetricDifferenceFilter);
},
/* models/filters/boolean_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const filter_1 = require(322) /* ./filter */;
    const types_1 = require(25) /* ../../core/types */;
    class BooleanFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Bool, Iterable, Nullable }) => ({
                booleans: [Nullable(Iterable(Bool)), null],
            }));
        }
        compute_indices(source) {
            const size = source.get_length() ?? 1;
            const { booleans } = this;
            if (booleans == null) {
                return types_1.Indices.all_set(size);
            }
            else {
                return types_1.Indices.from_booleans(size, booleans);
            }
        }
    }
    exports.BooleanFilter = BooleanFilter;
},
/* models/filters/customjs_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const filter_1 = require(322) /* ./filter */;
    const types_1 = require(25) /* ../../core/types */;
    const object_1 = require(9) /* ../../core/util/object */;
    const types_2 = require(8) /* ../../core/util/types */;
    const string_1 = require(41) /* ../../core/util/string */;
    class CustomJSFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Unknown, Str, Dict }) => ({
                args: [Dict(Unknown), {}],
                code: [Str, ""],
            }));
        }
        get names() {
            return (0, object_1.keys)(this.args);
        }
        get values() {
            return (0, object_1.values)(this.args);
        }
        get func() {
            const code = (0, string_1.use_strict)(this.code);
            return new Function(...this.names, "source", code);
        }
        compute_indices(source) {
            const size = source.get_length() ?? 1;
            const filter = this.func(...this.values, source);
            if (filter == null) {
                return types_1.Indices.all_set(size);
            }
            else if ((0, types_2.isArrayOf)(filter, types_2.isInteger)) {
                return types_1.Indices.from_indices(size, filter);
            }
            else if ((0, types_2.isArrayOf)(filter, types_2.isBoolean)) {
                return types_1.Indices.from_booleans(size, filter);
            }
            else {
                throw new Error(`expect an array of integers or booleans, or null, got ${filter}`);
            }
        }
    }
    exports.CustomJSFilter = CustomJSFilter;
},
/* models/filters/group_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const filter_1 = require(322) /* ./filter */;
    const types_1 = require(25) /* ../../core/types */;
    const logging_1 = require(11) /* ../../core/logging */;
    const eq_1 = require(27) /* ../../core/util/eq */;
    class GroupFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Str, Unknown }) => ({
                column_name: [Str],
                group: [Unknown],
            }));
        }
        compute_indices(source) {
            const column = source.get_column(this.column_name);
            const size = source.get_length() ?? 1;
            if (column == null) {
                logging_1.logger.warn(`${this}: groupby column '${this.column_name}' not found in the data source`);
                return types_1.Indices.all_set(size);
            }
            else {
                const indices = new types_1.Indices(size, 0);
                const cmp = new eq_1.Comparator();
                for (let i = 0; i < indices.size; i++) {
                    if (cmp.eq(column[i], this.group)) {
                        indices.set(i);
                    }
                }
                return indices;
            }
        }
    }
    exports.GroupFilter = GroupFilter;
},
/* models/filters/index_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const filter_1 = require(322) /* ./filter */;
    const types_1 = require(25) /* ../../core/types */;
    class IndexFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Int, Iterable, Nullable }) => ({
                indices: [Nullable(Iterable(Int)), null],
            }));
        }
        compute_indices(source) {
            const size = source.get_length() ?? 1;
            const { indices } = this;
            if (indices == null) {
                return types_1.Indices.all_set(size);
            }
            else {
                return types_1.Indices.from_indices(size, indices);
            }
        }
    }
    exports.IndexFilter = IndexFilter;
},
/* models/filters/inversion_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const filter_1 = require(322) /* ./filter */;
    class InversionFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Ref }) => ({
                operand: [Ref(filter_1.Filter)],
            }));
        }
        connect_signals() {
            super.connect_signals();
            const emit_changed = () => {
                this.change.emit();
            };
            const connect_operands = (operands) => {
                for (const operand of operands) {
                    this.connect(operand.change, emit_changed);
                }
            };
            const disconnect_operands = (operands) => {
                for (const operand of operands) {
                    this.disconnect(operand.change, emit_changed);
                }
            };
            let operands = (() => {
                const { operand } = this.properties;
                return operand.is_unset ? [] : [operand.get_value()];
            })();
            connect_operands(operands);
            this.on_change(this.properties.operand, () => {
                disconnect_operands(operands);
                operands = [this.operand];
                connect_operands(operands);
            });
        }
        compute_indices(source) {
            const index = this.operand.compute_indices(source);
            index.invert();
            return index;
        }
    }
    exports.InversionFilter = InversionFilter;
},
/* models/filters/union_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const composite_filter_1 = require(325) /* ./composite_filter */;
    class UnionFilter extends composite_filter_1.CompositeFilter {
        constructor(attrs) {
            super(attrs);
        }
        _inplace_op(index, op) {
            index.add(op);
        }
    }
    exports.UnionFilter = UnionFilter;
},
/* models/filters/difference_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const composite_filter_1 = require(325) /* ./composite_filter */;
    class DifferenceFilter extends composite_filter_1.CompositeFilter {
        constructor(attrs) {
            super(attrs);
        }
        _inplace_op(index, op) {
            index.subtract(op);
        }
    }
    exports.DifferenceFilter = DifferenceFilter;
},
/* models/filters/symmetric_difference_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const composite_filter_1 = require(325) /* ./composite_filter */;
    class SymmetricDifferenceFilter extends composite_filter_1.CompositeFilter {
        constructor(attrs) {
            super(attrs);
        }
        _inplace_op(index, op) {
            index.symmetric_subtract(op);
        }
    }
    exports.SymmetricDifferenceFilter = SymmetricDifferenceFilter;
},
/* models/glyphs/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var annular_wedge_1 = require(457) /* ./annular_wedge */;
    __esExport("AnnularWedge", annular_wedge_1.AnnularWedge);
    var annulus_1 = require(458) /* ./annulus */;
    __esExport("Annulus", annulus_1.Annulus);
    var arc_1 = require(459) /* ./arc */;
    __esExport("Arc", arc_1.Arc);
    var bezier_1 = require(460) /* ./bezier */;
    __esExport("Bezier", bezier_1.Bezier);
    var block_1 = require(462) /* ./block */;
    __esExport("Block", block_1.Block);
    var circle_1 = require(413) /* ./circle */;
    __esExport("Circle", circle_1.Circle);
    var ellipse_1 = require(464) /* ./ellipse */;
    __esExport("Ellipse", ellipse_1.Ellipse);
    var glyph_1 = require(306) /* ./glyph */;
    __esExport("Glyph", glyph_1.Glyph);
    var harea_1 = require(317) /* ./harea */;
    __esExport("HArea", harea_1.HArea);
    var harea_step_1 = require(314) /* ./harea_step */;
    __esExport("HAreaStep", harea_step_1.HAreaStep);
    var hbar_1 = require(466) /* ./hbar */;
    __esExport("HBar", hbar_1.HBar);
    var hex_tile_1 = require(467) /* ./hex_tile */;
    __esExport("HexTile", hex_tile_1.HexTile);
    var hspan_1 = require(468) /* ./hspan */;
    __esExport("HSpan", hspan_1.HSpan);
    var hstrip_1 = require(469) /* ./hstrip */;
    __esExport("HStrip", hstrip_1.HStrip);
    var image_1 = require(470) /* ./image */;
    __esExport("Image", image_1.Image);
    var image_rgba_1 = require(472) /* ./image_rgba */;
    __esExport("ImageRGBA", image_rgba_1.ImageRGBA);
    var image_stack_1 = require(473) /* ./image_stack */;
    __esExport("ImageStack", image_stack_1.ImageStack);
    var image_url_1 = require(474) /* ./image_url */;
    __esExport("ImageURL", image_url_1.ImageURL);
    var line_1 = require(304) /* ./line */;
    __esExport("Line", line_1.Line);
    var mathml_glyph_1 = require(475) /* ./mathml_glyph */;
    __esExport("MathMLGlyph", mathml_glyph_1.MathMLGlyph);
    var multi_line_1 = require(478) /* ./multi_line */;
    __esExport("MultiLine", multi_line_1.MultiLine);
    var multi_polygons_1 = require(479) /* ./multi_polygons */;
    __esExport("MultiPolygons", multi_polygons_1.MultiPolygons);
    var ngon_1 = require(480) /* ./ngon */;
    __esExport("Ngon", ngon_1.Ngon);
    var patch_1 = require(313) /* ./patch */;
    __esExport("Patch", patch_1.Patch);
    var patches_1 = require(481) /* ./patches */;
    __esExport("Patches", patches_1.Patches);
    var quad_1 = require(482) /* ./quad */;
    __esExport("Quad", quad_1.Quad);
    var quadratic_1 = require(483) /* ./quadratic */;
    __esExport("Quadratic", quadratic_1.Quadratic);
    var ray_1 = require(484) /* ./ray */;
    __esExport("Ray", ray_1.Ray);
    var rect_1 = require(485) /* ./rect */;
    __esExport("Rect", rect_1.Rect);
    var scatter_1 = require(486) /* ./scatter */;
    __esExport("Scatter", scatter_1.Scatter);
    var segment_1 = require(489) /* ./segment */;
    __esExport("Segment", segment_1.Segment);
    var spline_1 = require(490) /* ./spline */;
    __esExport("Spline", spline_1.Spline);
    var step_1 = require(312) /* ./step */;
    __esExport("Step", step_1.Step);
    var tex_glyph_1 = require(492) /* ./tex_glyph */;
    __esExport("TeXGlyph", tex_glyph_1.TeXGlyph);
    var text_1 = require(477) /* ./text */;
    __esExport("Text", text_1.Text);
    var varea_1 = require(319) /* ./varea */;
    __esExport("VArea", varea_1.VArea);
    var varea_step_1 = require(318) /* ./varea_step */;
    __esExport("VAreaStep", varea_step_1.VAreaStep);
    var vbar_1 = require(493) /* ./vbar */;
    __esExport("VBar", vbar_1.VBar);
    var vspan_1 = require(494) /* ./vspan */;
    __esExport("VSpan", vspan_1.VSpan);
    var vstrip_1 = require(495) /* ./vstrip */;
    __esExport("VStrip", vstrip_1.VStrip);
    var wedge_1 = require(496) /* ./wedge */;
    __esExport("Wedge", wedge_1.Wedge);
},
/* models/glyphs/annular_wedge.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(305) /* ./xy_glyph */;
    const glyph_1 = require(306) /* ./glyph */;
    const utils_1 = require(310) /* ./utils */;
    const property_mixins_1 = require(95) /* ../../core/property_mixins */;
    const types_1 = require(25) /* ../../core/types */;
    const enums_1 = require(21) /* ../../core/enums */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const math_1 = require(12) /* ../../core/util/math */;
    const selection_1 = require(144) /* ../selections/selection */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    class AnnularWedgeView extends xy_glyph_1.XYGlyphView {
        async load_glglyph() {
            const { AnnularWedgeGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(655) /* ./webgl/annular_wedge */));
            return AnnularWedgeGL;
        }
        _index_data(index) {
            const { x, y, outer_radius, data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const x_i = x[i];
                const y_i = y[i];
                const r_i = outer_radius.get(i);
                index.add_rect(x_i - r_i, y_i - r_i, x_i + r_i, y_i + r_i);
            }
        }
        _map_data() {
            this._define_or_inherit_attr("sinner_radius", () => {
                if (this.model.properties.inner_radius.units == "data") {
                    if (this.inherited_x && this.inherited_inner_radius) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.xscale, this.x, this.inner_radius);
                    }
                }
                else {
                    return this.inherited_inner_radius ? glyph_1.inherit : (0, types_1.to_screen)(this.inner_radius);
                }
            });
            this._define_or_inherit_attr("souter_radius", () => {
                if (this.model.properties.outer_radius.units == "data") {
                    if (this.inherited_x && this.inherited_outer_radius) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.xscale, this.x, this.outer_radius);
                    }
                }
                else {
                    return this.inherited_outer_radius ? glyph_1.inherit : (0, types_1.to_screen)(this.outer_radius);
                }
            });
            this._define_or_inherit_attr("max_souter_radius", () => (0, arrayable_1.max)(this.souter_radius));
        }
        _paint(ctx, indices, data) {
            const { sx, sy, start_angle, end_angle, sinner_radius, souter_radius } = { ...this, ...data };
            const anticlock = this.model.direction == "anticlock";
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const sinner_radius_i = sinner_radius[i];
                const souter_radius_i = souter_radius[i];
                const start_angle_i = start_angle.get(i);
                const end_angle_i = end_angle.get(i);
                if (!isFinite(sx_i + sy_i + sinner_radius_i + souter_radius_i + start_angle_i + end_angle_i)) {
                    continue;
                }
                const angle_i = end_angle_i - start_angle_i;
                ctx.save();
                ctx.translate(sx_i, sy_i);
                ctx.rotate(start_angle_i);
                ctx.beginPath();
                ctx.moveTo(souter_radius_i, 0);
                ctx.arc(0, 0, souter_radius_i, 0, angle_i, anticlock);
                ctx.rotate(angle_i);
                ctx.lineTo(sinner_radius_i, 0);
                ctx.arc(0, 0, sinner_radius_i, 0, -angle_i, !anticlock);
                ctx.closePath();
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                this.visuals.line.apply(ctx, i);
                ctx.restore();
            }
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            // check radius first
            const sx0 = sx - this.max_souter_radius;
            const sx1 = sx + this.max_souter_radius;
            const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
            const sy0 = sy - this.max_souter_radius;
            const sy1 = sy + this.max_souter_radius;
            const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            const candidates = [];
            for (const i of this.index.indices({ x0, x1, y0, y1 })) {
                const or2 = this.souter_radius[i] ** 2;
                const ir2 = this.sinner_radius[i] ** 2;
                const [sx0, sx1] = this.renderer.xscale.r_compute(x, this.x[i]);
                const [sy0, sy1] = this.renderer.yscale.r_compute(y, this.y[i]);
                const dist = (sx0 - sx1) ** 2 + (sy0 - sy1) ** 2;
                if (dist <= or2 && dist >= ir2) {
                    candidates.push(i);
                }
            }
            const anticlock = this.model.direction == "anticlock";
            const indices = [];
            for (const i of candidates) {
                // NOTE: minus the angle because JS uses non-mathy convention for angles
                const angle = Math.atan2(sy - this.sy[i], sx - this.sx[i]);
                const is_full_circle = Math.abs(this.start_angle.get(i) - this.end_angle.get(i)) >= 2 * Math.PI;
                if (is_full_circle || (0, math_1.angle_between)(-angle, -this.start_angle.get(i), -this.end_angle.get(i), anticlock)) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
        scenterxy(i) {
            const r = (this.sinner_radius[i] + this.souter_radius[i]) / 2;
            const a = (this.start_angle.get(i) + this.end_angle.get(i)) / 2;
            const scx = this.sx[i] + r * Math.cos(a);
            const scy = this.sy[i] + r * Math.sin(a);
            return [scx, scy];
        }
    }
    exports.AnnularWedgeView = AnnularWedgeView;
    class AnnularWedge extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = AnnularWedgeView;
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
            this.define(({}) => ({
                direction: [enums_1.Direction, "anticlock"],
                inner_radius: [p.DistanceSpec, { field: "inner_radius" }],
                outer_radius: [p.DistanceSpec, { field: "outer_radius" }],
                start_angle: [p.AngleSpec, { field: "start_angle" }],
                end_angle: [p.AngleSpec, { field: "end_angle" }],
            }));
        }
    }
    exports.AnnularWedge = AnnularWedge;
},
/* models/glyphs/annulus.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(305) /* ./xy_glyph */;
    const glyph_1 = require(306) /* ./glyph */;
    const types_1 = require(25) /* ../../core/types */;
    const property_mixins_1 = require(95) /* ../../core/property_mixins */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const selection_1 = require(144) /* ../selections/selection */;
    class AnnulusView extends xy_glyph_1.XYGlyphView {
        async load_glglyph() {
            const { AnnulusGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(662) /* ./webgl/annulus */));
            return AnnulusGL;
        }
        _index_data(index) {
            const { x, y, outer_radius, data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const x_i = x[i];
                const y_i = y[i];
                const r_i = outer_radius.get(i);
                index.add_rect(x_i - r_i, y_i - r_i, x_i + r_i, y_i + r_i);
            }
        }
        _map_data() {
            this._define_or_inherit_attr("sinner_radius", () => {
                if (this.model.properties.inner_radius.units == "data") {
                    if (this.inherited_x && this.inherited_inner_radius) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.xscale, this.x, this.inner_radius);
                    }
                }
                else {
                    return this.inherited_inner_radius ? glyph_1.inherit : (0, types_1.to_screen)(this.inner_radius);
                }
            });
            this._define_or_inherit_attr("souter_radius", () => {
                if (this.model.properties.outer_radius.units == "data") {
                    if (this.inherited_x && this.inherited_outer_radius) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.xscale, this.x, this.outer_radius);
                    }
                }
                else {
                    return this.inherited_outer_radius ? glyph_1.inherit : (0, types_1.to_screen)(this.outer_radius);
                }
            });
        }
        _paint(ctx, indices, data) {
            const { sx, sy, sinner_radius, souter_radius } = { ...this, ...data };
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const sinner_radius_i = sinner_radius[i];
                const souter_radius_i = souter_radius[i];
                if (!isFinite(sx_i + sy_i + sinner_radius_i + souter_radius_i)) {
                    continue;
                }
                ctx.beginPath();
                ctx.arc(sx_i, sy_i, sinner_radius_i, 0, 2 * Math.PI, true);
                ctx.moveTo(sx_i + souter_radius_i, sy_i);
                ctx.arc(sx_i, sy_i, souter_radius_i, 2 * Math.PI, 0, false);
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            let x0, y0;
            let x1, y1;
            if (this.model.properties.outer_radius.units == "data") {
                x0 = x - this.max_outer_radius;
                x1 = x + this.max_outer_radius;
                y0 = y - this.max_outer_radius;
                y1 = y + this.max_outer_radius;
            }
            else {
                const sx0 = sx - this.max_outer_radius;
                const sx1 = sx + this.max_outer_radius;
                [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
                const sy0 = sy - this.max_outer_radius;
                const sy1 = sy + this.max_outer_radius;
                [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            }
            const indices = [];
            for (const i of this.index.indices({ x0, x1, y0, y1 })) {
                const or2 = this.souter_radius[i] ** 2;
                const ir2 = this.sinner_radius[i] ** 2;
                const [sx0, sx1] = this.renderer.xscale.r_compute(x, this.x[i]);
                const [sy0, sy1] = this.renderer.yscale.r_compute(y, this.y[i]);
                const dist = (sx0 - sx1) ** 2 + (sy0 - sy1) ** 2;
                if (dist <= or2 && dist >= ir2) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, { x0, y0, x1, y1 }, index) {
            const len = index + 1;
            const sx = new Array(len);
            sx[index] = (x0 + x1) / 2;
            const sy = new Array(len);
            sy[index] = (y0 + y1) / 2;
            const r = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.5;
            const sinner_radius = new Array(len);
            sinner_radius[index] = r * 0.4;
            const souter_radius = new Array(len);
            souter_radius[index] = r * 0.8;
            this._paint(ctx, [index], { sx, sy, sinner_radius, souter_radius });
        }
    }
    exports.AnnulusView = AnnulusView;
    class Annulus extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = AnnulusView;
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
            this.define(({}) => ({
                inner_radius: [p.DistanceSpec, { field: "inner_radius" }],
                outer_radius: [p.DistanceSpec, { field: "outer_radius" }],
            }));
        }
    }
    exports.Annulus = Annulus;
},
/* models/glyphs/arc.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(305) /* ./xy_glyph */;
    const glyph_1 = require(306) /* ./glyph */;
    const utils_1 = require(310) /* ./utils */;
    const property_mixins_1 = require(95) /* ../../core/property_mixins */;
    const types_1 = require(25) /* ../../core/types */;
    const enums_1 = require(21) /* ../../core/enums */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    class ArcView extends xy_glyph_1.XYGlyphView {
        _map_data() {
            this._define_or_inherit_attr("sradius", () => {
                if (this.model.properties.radius.units == "data") {
                    if (this.inherited_x && this.inherited_radius) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.xscale, this.x, this.radius);
                    }
                }
                else {
                    return this.inherited_radius ? glyph_1.inherit : (0, types_1.to_screen)(this.radius);
                }
            });
        }
        _paint(ctx, indices, data) {
            if (!this.visuals.line.doit) {
                return;
            }
            const { sx, sy, sradius, start_angle, end_angle } = { ...this, ...data };
            const anticlock = this.model.direction == "anticlock";
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const sradius_i = sradius[i];
                const start_angle_i = start_angle.get(i);
                const end_angle_i = end_angle.get(i);
                if (!isFinite(sx_i + sy_i + sradius_i + start_angle_i + end_angle_i)) {
                    continue;
                }
                this._render_decorations(ctx, i, sx_i, sy_i, sradius_i, start_angle_i, end_angle_i, anticlock);
                ctx.beginPath();
                ctx.arc(sx_i, sy_i, sradius_i, start_angle_i, end_angle_i, anticlock);
                this.visuals.line.apply(ctx, i);
            }
        }
        _render_decorations(ctx, i, sx, sy, sradius, start_angle, end_angle, _anticlock) {
            const { sin, cos, PI } = Math;
            for (const decoration of this.decorations.values()) {
                ctx.save();
                if (decoration.model.node == "start") {
                    const x = sradius * cos(start_angle) + sx;
                    const y = sradius * sin(start_angle) + sy;
                    ctx.translate(x, y);
                    ctx.rotate(start_angle + PI);
                }
                else if (decoration.model.node == "end") {
                    const x = sradius * Math.cos(end_angle) + sx;
                    const y = sradius * Math.sin(end_angle) + sy;
                    ctx.translate(x, y);
                    ctx.rotate(end_angle);
                }
                decoration.marking.paint(ctx, i);
                ctx.restore();
            }
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.ArcView = ArcView;
    class Arc extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ArcView;
            this.mixins(property_mixins_1.LineVector);
            this.define(({}) => ({
                direction: [enums_1.Direction, "anticlock"],
                radius: [p.DistanceSpec, { field: "radius" }],
                start_angle: [p.AngleSpec, { field: "start_angle" }],
                end_angle: [p.AngleSpec, { field: "end_angle" }],
            }));
        }
    }
    exports.Arc = Arc;
},
/* models/glyphs/bezier.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const property_mixins_1 = require(95) /* ../../core/property_mixins */;
    const glyph_1 = require(306) /* ./glyph */;
    const utils_1 = require(310) /* ./utils */;
    const algorithms_1 = require(461) /* ../../core/util/algorithms */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    class BezierView extends glyph_1.GlyphView {
        _project_data() {
            this._project_xy("x0", this.x0, "y0", this.y0);
            this._project_xy("x1", this.x1, "y1", this.y1);
        }
        _index_data(index) {
            const { data_size, x0, y0, x1, y1, cx0, cy0, cx1, cy1 } = this;
            for (let i = 0; i < data_size; i++) {
                const x0_i = x0[i];
                const y0_i = y0[i];
                const x1_i = x1[i];
                const y1_i = y1[i];
                const cx0_i = cx0[i];
                const cy0_i = cy0[i];
                const cx1_i = cx1[i];
                const cy1_i = cy1[i];
                if (!isFinite(x0_i + x1_i + y0_i + y1_i + cx0_i + cy0_i + cx1_i + cy1_i)) {
                    index.add_empty();
                }
                else {
                    const { x0, y0, x1, y1 } = (0, algorithms_1.cbb)(x0_i, y0_i, cx0_i, cy0_i, cx1_i, cy1_i, x1_i, y1_i);
                    index.add_rect(x0, y0, x1, y1);
                }
            }
        }
        _paint(ctx, indices, data) {
            if (!this.visuals.line.doit) {
                return;
            }
            const { sx0, sy0, sx1, sy1, scx0, scy0, scx1, scy1 } = { ...this, ...data };
            for (const i of indices) {
                const sx0_i = sx0[i];
                const sy0_i = sy0[i];
                const sx1_i = sx1[i];
                const sy1_i = sy1[i];
                const scx0_i = scx0[i];
                const scy0_i = scy0[i];
                const scx1_i = scx1[i];
                const scy1_i = scy1[i];
                if (!isFinite(sx0_i + sy0_i + sx1_i + sy1_i + scx0_i + scy0_i + scx1_i + scy1_i)) {
                    continue;
                }
                ctx.beginPath();
                ctx.moveTo(sx0_i, sy0_i);
                ctx.bezierCurveTo(scx0_i, scy0_i, scx1_i, scy1_i, sx1_i, sy1_i);
                this.visuals.line.apply(ctx, i);
            }
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
        scenterxy() {
            throw new Error(`${this}.scenterxy() is not implemented`);
        }
    }
    exports.BezierView = BezierView;
    class Bezier extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = BezierView;
            this.define(({}) => ({
                x0: [p.XCoordinateSpec, { field: "x0" }],
                y0: [p.YCoordinateSpec, { field: "y0" }],
                x1: [p.XCoordinateSpec, { field: "x1" }],
                y1: [p.YCoordinateSpec, { field: "y1" }],
                cx0: [p.XCoordinateSpec, { field: "cx0" }],
                cy0: [p.YCoordinateSpec, { field: "cy0" }],
                cx1: [p.XCoordinateSpec, { field: "cx1" }],
                cy1: [p.YCoordinateSpec, { field: "cy1" }],
            }));
            this.mixins(property_mixins_1.LineVector);
        }
    }
    exports.Bezier = Bezier;
},
/* core/util/algorithms.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.qbb = qbb;
    exports.cbb = cbb;
    const arrayable_1 = require(14) /* ./arrayable */;
    const { abs, sqrt, min, max } = Math;
    /**
     * Formula from: http://pomax.nihongoresources.com/pages/bezier/
     *
     * if segment is quadratic bezier do:
     *   for both directions do:
     *     if control between start and end, compute linear bounding box
     *     otherwise, compute
     *       bound = u(1-t)^2 + 2v(1-t)t + wt^2
     *         (with t = ((u-v) / (u-2v+w)), with {u = start, v = control, w = end})
     *       if control precedes start, min = bound, otherwise max = bound
     */
    function qbb(x0, y0, cx, cy, x1, y1) {
        function _qbb(u, v, w) {
            if (v == (u + w) / 2) {
                return [u, w];
            }
            else {
                const t = (u - v) / (u - 2 * v + w);
                const bd = u * (1 - t) ** 2 + 2 * v * (1 - t) * t + w * t ** 2;
                return [min(u, w, bd), max(u, w, bd)];
            }
        }
        const [x_min, x_max] = _qbb(x0, cx, x1);
        const [y_min, y_max] = _qbb(y0, cy, y1);
        return {
            x0: x_min, x1: x_max,
            y0: y_min, y1: y_max,
        };
    }
    // algorithm adapted from http://stackoverflow.com/a/14429749/3406693
    function cbb(x0, y0, cx0, cy0, cx1, cy1, x1, y1) {
        const x3 = x1;
        const y3 = y1;
        x1 = cx0;
        y1 = cy0;
        const x2 = cx1;
        const y2 = cy1;
        const tvalues = [];
        for (let i = 0; i <= 2; i++) {
            let a, b, c;
            if (i == 0) {
                b = 6 * x0 - 12 * x1 + 6 * x2;
                a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
                c = 3 * x1 - 3 * x0;
            }
            else {
                b = 6 * y0 - 12 * y1 + 6 * y2;
                a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
                c = 3 * y1 - 3 * y0;
            }
            // Numerical robustness
            if (abs(a) < 1e-12) {
                if (abs(b) < 1e-12) {
                    continue;
                }
                const t = -c / b;
                if (0 < t && t < 1) {
                    tvalues.push(t);
                }
                continue;
            }
            const b2ac = b ** 2 - 4 * c * a;
            const sqrtb2ac = sqrt(b2ac);
            if (b2ac < 0) {
                continue;
            }
            const t1 = (-b + sqrtb2ac) / (2 * a);
            if (0 < t1 && t1 < 1) {
                tvalues.push(t1);
            }
            const t2 = (-b - sqrtb2ac) / (2 * a);
            if (0 < t2 && t2 < 1) {
                tvalues.push(t2);
            }
        }
        const n = tvalues.length;
        let j = n;
        const x_bounds = Array(n + 2);
        const y_bounds = Array(n + 2);
        while (j-- > 0) {
            const t = tvalues[j];
            const mt = 1 - t;
            const x = mt ** 3 * x0 + 3 * mt ** 2 * t * x1 + 3 * mt * t ** 2 * x2 + t ** 3 * x3;
            const y = mt ** 3 * y0 + 3 * mt ** 2 * t * y1 + 3 * mt * t ** 2 * y2 + t ** 3 * y3;
            x_bounds[j] = x;
            y_bounds[j] = y;
        }
        x_bounds[n] = x0;
        y_bounds[n] = y0;
        x_bounds[n + 1] = x3;
        y_bounds[n + 1] = y3;
        const [x_min, x_max, y_min, y_max] = (0, arrayable_1.minmax2)(x_bounds, y_bounds);
        return { x0: x_min, x1: x_max, y0: y_min, y1: y_max };
    }
},
/* models/glyphs/block.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const lrtb_1 = require(463) /* ./lrtb */;
    const math_1 = require(12) /* ../../core/util/math */;
    const types_1 = require(25) /* ../../core/types */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    class BlockView extends lrtb_1.LRTBView {
        scenterxy(i) {
            const scx = this.sleft[i] / 2 + this.sright[i] / 2;
            const scy = this.stop[i] / 2 + this.sbottom[i] / 2;
            return [scx, scy];
        }
        _lrtb(i) {
            const x_i = this.x[i];
            const y_i = this.y[i];
            const width_i = this.width.get(i);
            const height_i = this.height.get(i);
            const [l, r] = (0, math_1.minmax)(x_i, x_i + width_i);
            const [b, t] = (0, math_1.minmax)(y_i, y_i + height_i);
            return { l, r, t, b };
        }
        _map_data() {
            const { sx, sy } = this;
            const n = sx.length;
            const x_reversed = this.renderer.xscale.source_range.is_reversed;
            const y_reversed = this.renderer.yscale.source_range.is_reversed;
            if (this.inherited_x && this.inherited_width) {
                this._inherit_attr("sleft");
                this._inherit_attr("sright");
            }
            else {
                const sw = this.sdist(this.renderer.xscale, this.x, this.width, "edge");
                const sleft = new types_1.ScreenArray(n);
                const sright = new types_1.ScreenArray(n);
                for (let i = 0; i < n; i++) {
                    if (x_reversed) {
                        sleft[i] = sx[i] - sw[i];
                        sright[i] = sx[i];
                    }
                    else {
                        sleft[i] = sx[i];
                        sright[i] = sx[i] + sw[i];
                    }
                }
                this._define_attr("sleft", sleft);
                this._define_attr("sright", sright);
            }
            if (this.inherited_y && this.inherited_height) {
                this._inherit_attr("stop");
                this._inherit_attr("sbottom");
            }
            else {
                const sh = this.sdist(this.renderer.yscale, this.y, this.height, "edge");
                const stop = new types_1.ScreenArray(n);
                const sbottom = new types_1.ScreenArray(n);
                for (let i = 0; i < n; i++) {
                    if (y_reversed) {
                        stop[i] = sy[i];
                        sbottom[i] = sy[i] + sh[i];
                    }
                    else {
                        stop[i] = sy[i] - sh[i];
                        sbottom[i] = sy[i];
                    }
                }
                this._define_attr("stop", stop);
                this._define_attr("sbottom", sbottom);
            }
            this._clamp_to_viewport();
        }
    }
    exports.BlockView = BlockView;
    class Block extends lrtb_1.LRTB {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = BlockView;
            this.define(({}) => ({
                x: [p.XCoordinateSpec, { field: "x" }],
                y: [p.YCoordinateSpec, { field: "y" }],
                width: [p.DistanceSpec, { value: 1 }],
                height: [p.DistanceSpec, { value: 1 }],
            }));
        }
    }
    exports.Block = Block;
},
/* models/glyphs/lrtb.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const property_mixins_1 = require(95) /* ../../core/property_mixins */;
    const glyph_1 = require(306) /* ./glyph */;
    const utils_1 = require(310) /* ./utils */;
    const selection_1 = require(144) /* ../selections/selection */;
    const bbox_1 = require(62) /* ../../core/util/bbox */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const kinds_1 = require(124) /* ../common/kinds */;
    const resolve = tslib_1.__importStar(require(127) /* ../common/resolve */);
    const painting_1 = require(267) /* ../common/painting */;
    class LRTBView extends glyph_1.GlyphView {
        async load_glglyph() {
            const { LRTBGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(670) /* ./webgl/lrtb */));
            return LRTBGL;
        }
        get_anchor_point(anchor, i, _spt) {
            const left = Math.min(this.sleft[i], this.sright[i]);
            const right = Math.max(this.sright[i], this.sleft[i]);
            const top = Math.min(this.stop[i], this.sbottom[i]); // screen coordinates !!!
            const bottom = Math.max(this.sbottom[i], this.stop[i]); //
            switch (anchor) {
                case "top_left": return { x: left, y: top };
                case "top":
                case "top_center": return { x: (left + right) / 2, y: top };
                case "top_right": return { x: right, y: top };
                case "bottom_left": return { x: left, y: bottom };
                case "bottom":
                case "bottom_center": return { x: (left + right) / 2, y: bottom };
                case "bottom_right": return { x: right, y: bottom };
                case "left":
                case "center_left": return { x: left, y: (top + bottom) / 2 };
                case "center":
                case "center_center": return { x: (left + right) / 2, y: (top + bottom) / 2 };
                case "right":
                case "center_right": return { x: right, y: (top + bottom) / 2 };
            }
        }
        _set_data(indices) {
            super._set_data(indices);
            this.border_radius = resolve.border_radius(this.model.border_radius);
        }
        _index_data(index) {
            const { min, max } = Math;
            const { data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const { l, r, t, b } = this._lrtb(i);
                index.add_rect(min(l, r), min(t, b), max(r, l), max(t, b));
            }
        }
        _paint(ctx, indices, data) {
            const { sleft, sright, stop, sbottom, border_radius } = { ...this, ...data };
            for (const i of indices) {
                const sleft_i = sleft[i];
                const stop_i = stop[i];
                const sright_i = sright[i];
                const sbottom_i = sbottom[i];
                if (!isFinite(sleft_i + stop_i + sright_i + sbottom_i)) {
                    continue;
                }
                ctx.beginPath();
                const box = bbox_1.BBox.from_lrtb({ left: sleft_i, right: sright_i, top: stop_i, bottom: sbottom_i });
                (0, painting_1.round_rect)(ctx, box, border_radius);
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                this.visuals.line.apply(ctx, i);
            }
        }
        // We need to clamp the endpoints inside the viewport, because various browser canvas
        // implementations have issues drawing rects with endpoints far outside the viewport
        _clamp_to_viewport() {
            const { min, max } = Math;
            const { h_range, v_range } = this.renderer.plot_view.frame.bbox;
            if (!this.inherited_sleft) {
                (0, arrayable_1.inplace_map)(this.sleft, (left) => max(left, h_range.start));
            }
            if (!this.inherited_sright) {
                (0, arrayable_1.inplace_map)(this.sright, (right) => min(right, h_range.end));
            }
            if (!this.inherited_stop) {
                (0, arrayable_1.inplace_map)(this.stop, (top) => max(top, v_range.start));
            }
            if (!this.inherited_sbottom) {
                (0, arrayable_1.inplace_map)(this.sbottom, (bottom) => min(bottom, v_range.end));
            }
        }
        _hit_rect(geometry) {
            return this._hit_rect_against_index(geometry);
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            const indices = [...this.index.indices({ x0: x, y0: y, x1: x, y1: y })];
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const { sx, sy } = geometry;
            let indices;
            if (geometry.direction == "v") {
                const y = this.renderer.yscale.invert(sy);
                const hr = this.renderer.plot_view.frame.bbox.h_range;
                const [x0, x1] = this.renderer.xscale.r_invert(hr.start, hr.end);
                indices = [...this.index.indices({ x0, y0: y, x1, y1: y })];
            }
            else {
                const x = this.renderer.xscale.invert(sx);
                const vr = this.renderer.plot_view.frame.bbox.v_range;
                const [y0, y1] = this.renderer.yscale.r_invert(vr.start, vr.end);
                indices = [...this.index.indices({ x0: x, y0, x1: x, y1 })];
            }
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.LRTBView = LRTBView;
    class LRTB extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
            this.define(() => ({
                border_radius: [kinds_1.BorderRadius, 0],
            }));
        }
    }
    exports.LRTB = LRTB;
},
/* models/glyphs/ellipse.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const center_rotatable_1 = require(465) /* ./center_rotatable */;
    const glyph_1 = require(306) /* ./glyph */;
    const hittest = tslib_1.__importStar(require(311) /* ../../core/hittest */);
    const types_1 = require(25) /* ../../core/types */;
    const selection_1 = require(144) /* ../selections/selection */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    class EllipseView extends center_rotatable_1.CenterRotatableView {
        _map_data() {
            this._define_or_inherit_attr("swidth", () => {
                if (this.model.properties.width.units == "data") {
                    if (this.inherited_x && this.inherited_width) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.xscale, this.x, this.width, "center");
                    }
                }
                else {
                    return this.inherited_width ? glyph_1.inherit : (0, types_1.to_screen)(this.width);
                }
            });
            this._define_or_inherit_attr("sheight", () => {
                if (this.model.properties.height.units == "data") {
                    if (this.inherited_y && this.inherited_height) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.yscale, this.y, this.height, "center");
                    }
                }
                else {
                    return this.inherited_height ? glyph_1.inherit : (0, types_1.to_screen)(this.height);
                }
            });
        }
        _paint(ctx, indices, data) {
            const { sx, sy, swidth, sheight, angle } = { ...this, ...data };
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const swidth_i = swidth[i];
                const sheight_i = sheight[i];
                const angle_i = angle.get(i);
                if (!isFinite(sx_i + sy_i + swidth_i + sheight_i + angle_i)) {
                    continue;
                }
                ctx.beginPath();
                ctx.ellipse(sx_i, sy_i, swidth_i / 2, sheight_i / 2, angle_i, 0, 2 * Math.PI);
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _hit_point(geometry) {
            let x0, x1, y0, y1, cond, sx0, sx1, sy0, sy1;
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            if (this.model.properties.width.units == "data") {
                x0 = x - this.max_width;
                x1 = x + this.max_width;
            }
            else {
                sx0 = sx - this.max_width;
                sx1 = sx + this.max_width;
                [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
            }
            if (this.model.properties.height.units == "data") {
                y0 = y - this.max_height;
                y1 = y + this.max_height;
            }
            else {
                sy0 = sy - this.max_height;
                sy1 = sy + this.max_height;
                [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            }
            const candidates = this.index.indices({ x0, x1, y0, y1 });
            const indices = [];
            for (const i of candidates) {
                cond = hittest.point_in_ellipse(sx, sy, this.angle.get(i), this.sheight[i] / 2, this.swidth[i] / 2, this.sx[i], this.sy[i]);
                if (cond) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, { x0, y0, x1, y1 }, index) {
            const n = index + 1;
            const sx = new Array(n);
            sx[index] = (x0 + x1) / 2;
            const sy = new Array(n);
            sy[index] = (y0 + y1) / 2;
            const scale = this.swidth[index] / this.sheight[index];
            const d = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.8;
            const swidth = new Array(n);
            const sheight = new Array(n);
            if (scale > 1) {
                swidth[index] = d;
                sheight[index] = d / scale;
            }
            else {
                swidth[index] = d * scale;
                sheight[index] = d;
            }
            const angle = new p.UniformScalar(0, n); // don't attempt to match glyph angle
            this._paint(ctx, [index], { sx, sy, swidth, sheight, angle });
        }
    }
    exports.EllipseView = EllipseView;
    class Ellipse extends center_rotatable_1.CenterRotatable {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = EllipseView;
        }
    }
    exports.Ellipse = Ellipse;
},
/* models/glyphs/center_rotatable.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(305) /* ./xy_glyph */;
    const property_mixins_1 = require(95) /* ../../core/property_mixins */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    class CenterRotatableView extends xy_glyph_1.XYGlyphView {
        get max_w2() {
            return this.model.properties.width.units == "data" ? this.max_width / 2 : 0;
        }
        get max_h2() {
            return this.model.properties.height.units == "data" ? this.max_height / 2 : 0;
        }
        _bounds({ x0, x1, y0, y1 }) {
            const { max_w2, max_h2 } = this;
            return {
                x0: x0 - max_w2,
                x1: x1 + max_w2,
                y0: y0 - max_h2,
                y1: y1 + max_h2,
            };
        }
    }
    exports.CenterRotatableView = CenterRotatableView;
    class CenterRotatable extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
            this.define(({}) => ({
                angle: [p.AngleSpec, 0],
                width: [p.DistanceSpec, { field: "width" }],
                height: [p.DistanceSpec, { field: "height" }],
            }));
        }
    }
    exports.CenterRotatable = CenterRotatable;
},
/* models/glyphs/hbar.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const lrtb_1 = require(463) /* ./lrtb */;
    const types_1 = require(25) /* ../../core/types */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    class HBarView extends lrtb_1.LRTBView {
        scenterxy(i) {
            const scx = (this.sleft[i] + this.sright[i]) / 2;
            const scy = this.sy[i];
            return [scx, scy];
        }
        _lrtb(i) {
            const left_i = this.left[i];
            const right_i = this.right[i];
            const y_i = this.y[i];
            const half_height_i = this.height.get(i) / 2;
            const l = Math.min(left_i, right_i);
            const r = Math.max(left_i, right_i);
            const t = y_i + half_height_i;
            const b = y_i - half_height_i;
            return { l, r, t, b };
        }
        _map_data() {
            if (this.inherited_y && this.inherited_height) {
                this._inherit_attr("sheight");
                this._inherit_attr("stop");
                this._inherit_attr("sbottom");
            }
            else {
                const sheight = this.sdist(this.renderer.yscale, this.y, this.height, "center");
                const { sy } = this;
                const n = this.sy.length;
                const stop = new types_1.ScreenArray(n);
                const sbottom = new types_1.ScreenArray(n);
                for (let i = 0; i < n; i++) {
                    const sy_i = sy[i];
                    const sheight_i = sheight[i];
                    stop[i] = sy_i - sheight_i / 2;
                    sbottom[i] = sy_i + sheight_i / 2;
                }
                this._define_attr("sheight", sheight);
                this._define_attr("stop", stop);
                this._define_attr("sbottom", sbottom);
            }
            this._clamp_to_viewport();
        }
    }
    exports.HBarView = HBarView;
    class HBar extends lrtb_1.LRTB {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = HBarView;
            this.define(({}) => ({
                left: [p.XCoordinateSpec, { value: 0 }],
                y: [p.YCoordinateSpec, { field: "y" }],
                height: [p.DistanceSpec, { value: 1 }],
                right: [p.XCoordinateSpec, { field: "right" }],
            }));
        }
    }
    exports.HBar = HBar;
},
/* models/glyphs/hex_tile.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(306) /* ./glyph */;
    const hittest = tslib_1.__importStar(require(311) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const property_mixins_1 = require(95) /* ../../core/property_mixins */;
    const enums_1 = require(21) /* ../../core/enums */;
    const utils_1 = require(310) /* ./utils */;
    const selection_1 = require(144) /* ../selections/selection */;
    class HexTileView extends glyph_1.GlyphView {
        async load_glglyph() {
            const { HexTileGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(666) /* ./webgl/hex_tile */));
            return HexTileGL;
        }
        scenterxy(i) {
            const scx = this.sx[i];
            const scy = this.sy[i];
            return [scx, scy];
        }
        _set_data() {
            const { orientation, size, aspect_scale } = this.model;
            const { q, r } = this;
            const n = this.q.length;
            const x = new Float64Array(n);
            const y = new Float64Array(n);
            const sqrt3 = Math.sqrt(3);
            if (orientation == "pointytop") {
                for (let i = 0; i < n; i++) {
                    const q_i = q.get(i);
                    const r2_i = r.get(i) / 2;
                    x[i] = size * sqrt3 * (q_i + r2_i) / aspect_scale;
                    y[i] = -3 * size * r2_i;
                }
            }
            else {
                for (let i = 0; i < n; i++) {
                    const q2_i = q.get(i) / 2;
                    const r_i = r.get(i);
                    x[i] = 3 * size * q2_i;
                    y[i] = -size * sqrt3 * (r_i + q2_i) * aspect_scale;
                }
            }
            this._define_attr("x", x);
            this._define_attr("y", y);
        }
        _project_data() {
            this._project_xy("x", this.x, "y", this.y);
        }
        _index_data(index) {
            let ysize = this.model.size;
            let xsize = Math.sqrt(3) * ysize / 2;
            if (this.model.orientation == "flattop") {
                [xsize, ysize] = [ysize, xsize];
                ysize *= this.model.aspect_scale;
            }
            else {
                xsize /= this.model.aspect_scale;
            }
            const { x, y, data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const x_i = x[i];
                const y_i = y[i];
                index.add_rect(x_i - xsize, y_i - ysize, x_i + xsize, y_i + ysize);
            }
        }
        // overriding map_data instead of _map_data because the default automatic mappings
        // for other glyphs (with cartesian coordinates) is not useful
        map_data() {
            const [sx, sy] = this.renderer.coordinates.map_to_screen(this.x, this.y);
            const [svx, svy] = this._get_unscaled_vertices();
            this._define_attr("sx", sx);
            this._define_attr("sy", sy);
            this._define_attr("svx", svx);
            this._define_attr("svy", svy);
            // From overridden GlyphView.map_data()
            if (this.has_webgl()) {
                this.glglyph.set_data_mapped();
            }
        }
        _get_unscaled_vertices() {
            const size = this.model.size;
            const aspect_scale = this.model.aspect_scale;
            if (this.model.orientation == "pointytop") {
                const rscale = this.renderer.yscale;
                const hscale = this.renderer.xscale;
                const r = Math.abs(rscale.compute(0) - rscale.compute(size)); // assumes linear scale
                const h = Math.sqrt(3) / 2 * Math.abs(hscale.compute(0) - hscale.compute(size)) / aspect_scale; // assumes linear scale
                const r2 = r / 2.0;
                const svx = [0, -h, -h, 0, h, h];
                const svy = [r, r2, -r2, -r, -r2, r2];
                return [svx, svy];
            }
            else {
                const rscale = this.renderer.xscale;
                const hscale = this.renderer.yscale;
                const r = Math.abs(rscale.compute(0) - rscale.compute(size)); // assumes linear scale
                const h = Math.sqrt(3) / 2 * Math.abs(hscale.compute(0) - hscale.compute(size)) * aspect_scale; // assumes linear scale
                const r2 = r / 2.0;
                const svx = [r, r2, -r2, -r, -r2, r2];
                const svy = [0, -h, -h, 0, h, h];
                return [svx, svy];
            }
        }
        _paint(ctx, indices, data) {
            const { sx, sy, svx, svy, scale } = { ...this, ...data };
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const scale_i = scale.get(i);
                if (!isFinite(sx_i + sy_i + scale_i)) {
                    continue;
                }
                ctx.translate(sx_i, sy_i);
                ctx.beginPath();
                for (let j = 0; j < 6; j++) {
                    ctx.lineTo(svx[j] * scale_i, svy[j] * scale_i);
                }
                ctx.closePath();
                ctx.translate(-sx_i, -sy_i);
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            const candidates = this.index.indices({ x0: x, y0: y, x1: x, y1: y });
            const indices = [];
            for (const i of candidates) {
                if (hittest.point_in_poly(sx - this.sx[i], sy - this.sy[i], this.svx, this.svy)) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const rect = (() => {
                if (geometry.direction == "v") {
                    const { sy } = geometry;
                    const y = this.renderer.yscale.invert(sy);
                    const hr = this.renderer.plot_view.frame.bbox.h_range;
                    const [x0, x1] = this.renderer.xscale.r_invert(hr.start, hr.end);
                    return { x0, y0: y, x1, y1: y };
                }
                else {
                    const { sx } = geometry;
                    const x = this.renderer.xscale.invert(sx);
                    const vr = this.renderer.plot_view.frame.bbox.v_range;
                    const [y0, y1] = this.renderer.yscale.r_invert(vr.start, vr.end);
                    return { x0: x, y0, x1: x, y1 };
                }
            })();
            const indices = [...this.index.indices(rect)];
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const { sx0, sx1, sy0, sy1 } = geometry;
            const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
            const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            const indices = [...this.index.indices({ x0, x1, y0, y1 })];
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.HexTileView = HexTileView;
    class HexTile extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = HexTileView;
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
            this.define(({ Float }) => ({
                r: [p.NumberSpec, { field: "r" }],
                q: [p.NumberSpec, { field: "q" }],
                scale: [p.NumberSpec, 1.0],
                size: [Float, 1.0],
                aspect_scale: [Float, 1.0],
                orientation: [enums_1.HexTileOrientation, "pointytop"],
            }));
            this.override({ line_color: null });
        }
    }
    exports.HexTile = HexTile;
},
/* models/glyphs/hspan.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(306) /* ./glyph */;
    const utils_1 = require(310) /* ./utils */;
    const selection_1 = require(144) /* ../selections/selection */;
    const property_mixins_1 = require(95) /* ../../core/property_mixins */;
    const uniforms = tslib_1.__importStar(require(40) /* ../../core/uniforms */);
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const array_1 = require(10) /* ../../core/util/array */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const { abs, max } = Math;
    const UNUSED = 0;
    class HSpanView extends glyph_1.GlyphView {
        after_visuals() {
            super.after_visuals();
            this.max_line_width = uniforms.max(this.line_width);
        }
        _index_data(index) {
            for (const y_i of this.y) {
                index.add_point(UNUSED, y_i);
            }
        }
        _bounds(bounds) {
            const { y0, y1 } = bounds;
            return { x0: NaN, x1: NaN, y0, y1 };
        }
        _map_data() {
            super._map_data();
            const { round } = Math;
            if (!this.inherited_sy) {
                const sy = (0, arrayable_1.map)(this.sy, (yi) => round(yi));
                this._define_attr("sy", sy);
            }
        }
        scenterxy(i) {
            const { hcenter } = this.renderer.plot_view.frame.bbox;
            return [hcenter, this.sy[i]];
        }
        _paint(ctx, indices, data) {
            const { sy } = { ...this, ...data };
            const { left, right } = this.renderer.plot_view.frame.bbox;
            for (const i of indices) {
                const sy_i = sy[i];
                if (!isFinite(sy_i)) {
                    continue;
                }
                ctx.beginPath();
                ctx.moveTo(left, sy_i);
                ctx.lineTo(right, sy_i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _get_candidates(sy0, sy1) {
            const { max_line_width } = this;
            const [y0, y1] = this.renderer.yscale.r_invert(sy0 - max_line_width, (sy1 ?? sy0) + max_line_width);
            return this.index.indices({ x0: 0, x1: 0, y0, y1 });
        }
        _find_spans(candidates, fn) {
            const { sy, line_width } = this;
            const indices = [];
            for (const i of candidates) {
                const sy_i = sy[i];
                const line_width_i = line_width.get(i);
                if (fn(sy_i, line_width_i)) {
                    indices.push(i);
                }
            }
            return indices;
        }
        _hit_point(geometry) {
            const { sy: gsy } = geometry;
            const candidates = this._get_candidates(gsy);
            const indices = this._find_spans(candidates, (sy, line_width) => {
                return abs(sy - gsy) <= max(line_width / 2, 2 /*px*/);
            });
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const indices = (() => {
                if (geometry.direction == "v") {
                    return (0, array_1.range)(0, this.data_size);
                }
                else {
                    const { sy: gsy } = geometry;
                    const candidates = this._get_candidates(gsy);
                    return this._find_spans(candidates, (sy, line_width) => {
                        return abs(sy - gsy) <= max(line_width / 2, 2 /*px*/);
                    });
                }
            })();
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const indices = (() => {
                const { sy0: gsy0, sy1: gsy1 } = geometry;
                const candidates = this._get_candidates(gsy0, gsy1);
                return this._find_spans(candidates, (sy, line_width) => {
                    return gsy0 - line_width / 2 <= sy && sy <= gsy1 + line_width / 2;
                });
            })();
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.HSpanView = HSpanView;
    class HSpan extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = HSpanView;
            this.mixins([property_mixins_1.LineVector]);
            this.define(() => ({
                y: [p.YCoordinateSpec, { field: "y" }],
            }));
        }
    }
    exports.HSpan = HSpan;
},
/* models/glyphs/hstrip.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(306) /* ./glyph */;
    const utils_1 = require(310) /* ./utils */;
    const selection_1 = require(144) /* ../selections/selection */;
    const property_mixins_1 = require(95) /* ../../core/property_mixins */;
    const types_1 = require(25) /* ../../core/types */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const iter = tslib_1.__importStar(require(15) /* ../../core/util/iterator */);
    const array_1 = require(10) /* ../../core/util/array */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const UNUSED = 0;
    class HStripView extends glyph_1.GlyphView {
        async lazy_initialize() {
            await super.lazy_initialize();
            const { webgl } = this.renderer.plot_view.canvas_view;
            if (webgl != null && webgl.regl_wrapper.has_webgl) {
                const { LRTBGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(670) /* ./webgl/lrtb */));
                this.glglyph = new LRTBGL(webgl.regl_wrapper, this);
            }
        }
        get sleft() {
            const { left } = this.renderer.plot_view.frame.bbox;
            const n = this.data_size;
            const sleft = new types_1.ScreenArray(n);
            sleft.fill(left);
            return sleft;
        }
        get sright() {
            const { right } = this.renderer.plot_view.frame.bbox;
            const n = this.data_size;
            const sright = new types_1.ScreenArray(n);
            sright.fill(right);
            return sright;
        }
        get stop() {
            return this.sy0;
        }
        get sbottom() {
            return this.sy1;
        }
        _set_data(indices) {
            super._set_data(indices);
            const { abs } = Math;
            const { max, map, zip } = iter;
            const { y0, y1 } = this;
            if (this.inherited_y0 && this.inherited_y1) {
                this._inherit_attr("max_height");
            }
            else {
                const max_height = max(map(zip(y0, y1), ([y0_i, y1_i]) => abs(y0_i - y1_i)));
                this._define_attr("max_height", max_height);
            }
        }
        _index_data(index) {
            const { y0, y1, data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const y0_i = y0[i];
                const y1_i = y1[i];
                index.add_rect(UNUSED, y0_i, UNUSED, y1_i);
            }
        }
        _bounds(bounds) {
            const { y0, y1 } = bounds;
            return { x0: NaN, x1: NaN, y0, y1 };
        }
        _map_data() {
            super._map_data();
            const { round } = Math;
            if (!this.inherited_sy0) {
                const sy0 = (0, arrayable_1.map)(this.sy0, (yi) => round(yi));
                this._define_attr("sy0", sy0);
            }
            if (!this.inherited_sy1) {
                const sy1 = (0, arrayable_1.map)(this.sy1, (yi) => round(yi));
                this._define_attr("sy1", sy1);
            }
        }
        scenterxy(i) {
            const { hcenter } = this.renderer.plot_view.frame.bbox;
            return [hcenter, (this.sy0[i] + this.sy1[i]) / 2];
        }
        _paint(ctx, indices, data) {
            const { sy0, sy1 } = { ...this, ...data };
            const { left, right, width } = this.renderer.plot_view.frame.bbox;
            for (const i of indices) {
                const sy0_i = sy0[i];
                const sy1_i = sy1[i];
                if (!isFinite(sy0_i + sy1_i)) {
                    continue;
                }
                ctx.beginPath();
                ctx.rect(left, sy0_i, width, sy1_i - sy0_i);
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                ctx.beginPath();
                ctx.moveTo(left, sy0_i);
                ctx.lineTo(right, sy0_i);
                ctx.moveTo(left, sy1_i);
                ctx.lineTo(right, sy1_i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _get_candidates(sy0, sy1) {
            const { max_height } = this;
            const [dy0, dy1] = this.renderer.yscale.r_invert(sy0, sy1 ?? sy0);
            const y0 = dy0 - max_height;
            const y1 = dy1 + max_height;
            return this.index.indices({ x0: 0, x1: 0, y0, y1 });
        }
        _find_strips(candidates, fn) {
            function contains(sy0, sy1) {
                return sy0 <= sy1 ? fn(sy0, sy1) : fn(sy1, sy0);
            }
            const { sy0, sy1 } = this;
            const indices = [];
            for (const i of candidates) {
                const sy0_i = sy0[i];
                const sy1_i = sy1[i];
                if (contains(sy0_i, sy1_i)) {
                    indices.push(i);
                }
            }
            return indices;
        }
        _hit_point(geometry) {
            const { sy } = geometry;
            const candidates = this._get_candidates(sy);
            const indices = this._find_strips(candidates, (sy0, sy1) => sy0 <= sy && sy <= sy1);
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const indices = (() => {
                if (geometry.direction == "v") {
                    return (0, array_1.range)(0, this.data_size);
                }
                else {
                    const { sy } = geometry;
                    const candidates = this._get_candidates(sy);
                    return this._find_strips(candidates, (sy0, sy1) => sy0 <= sy && sy <= sy1);
                }
            })();
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const indices = (() => {
                const { sy0: gsy0, sy1: gsy1 } = geometry;
                const candidates = this._get_candidates(gsy0, gsy1);
                return this._find_strips(candidates, (sy0, sy1) => {
                    return gsy0 <= sy0 && sy0 <= gsy1 && gsy0 <= sy1 && sy1 <= gsy1;
                });
            })();
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.HStripView = HStripView;
    class HStrip extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = HStripView;
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
            this.define(() => ({
                y0: [p.YCoordinateSpec, { field: "y0" }],
                y1: [p.YCoordinateSpec, { field: "y1" }],
            }));
        }
    }
    exports.HStrip = HStrip;
},
/* models/glyphs/image.js */ function _(require, module, exports, __esModule, __esExport) {
    var __createBinding = (this && this.__createBinding) || (Object.create ? (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        var desc = Object.getOwnPropertyDescriptor(m, k);
        if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
            desc = { enumerable: true, get: function () { return m[k]; } };
        }
        Object.defineProperty(o, k2, desc);
    }) : (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        o[k2] = m[k];
    }));
    var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function (o, v) {
        o["default"] = v;
    });
    var __importStar = (this && this.__importStar) || (function () {
        var ownKeys = function (o) {
            ownKeys = Object.getOwnPropertyNames || function (o) {
                var ar = [];
                for (var k in o)
                    if (Object.prototype.hasOwnProperty.call(o, k))
                        ar[ar.length] = k;
                return ar;
            };
            return ownKeys(o);
        };
        return function (mod) {
            if (mod && mod.__esModule)
                return mod;
            var result = {};
            if (mod != null)
                for (var k = ownKeys(mod), i = 0; i < k.length; i++)
                    if (k[i] !== "default")
                        __createBinding(result, mod, k[i]);
            __setModuleDefault(result, mod);
            return result;
        };
    })();
    __esModule();
    const image_base_1 = require(471) /* ./image_base */;
    const color_mapper_1 = require(300) /* ../mappers/color_mapper */;
    const linear_color_mapper_1 = require(359) /* ../mappers/linear_color_mapper */;
    class ImageView extends image_base_1.ImageBaseView {
        async load_glglyph() {
            const { ImageGL } = await Promise.resolve().then(() => __importStar(require(667) /* ./webgl/image */));
            return ImageGL;
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.color_mapper.change, () => this._update_image());
        }
        _update_image() {
            if (this.has_webgl()) {
                this.glglyph.set_image_changed();
            }
            // Only reset image_data if already initialized
            if (this.image_data != null) {
                this._set_data(null);
                this.renderer.request_paint();
            }
        }
        get _can_inherit_image_data() {
            return super._can_inherit_image_data &&
                this._can_inherit_from(this.model.properties.color_mapper, this.base);
        }
        _flat_img_to_buf8(img) {
            const cmap = this.model.color_mapper.rgba_mapper;
            return cmap.v_compute(img);
        }
    }
    exports.ImageView = ImageView;
    // NOTE: this needs to be redefined here, because palettes are located in bokeh-api.js bundle
    const Greys9 = () => ["#000000", "#252525", "#525252", "#737373", "#969696", "#bdbdbd", "#d9d9d9", "#f0f0f0", "#ffffff"];
    class Image extends image_base_1.ImageBase {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ImageView;
            this.define(({ Ref }) => ({
                color_mapper: [Ref(color_mapper_1.ColorMapper), () => new linear_color_mapper_1.LinearColorMapper({ palette: Greys9() })],
            }));
        }
    }
    exports.Image = Image;
},
/* models/glyphs/image_base.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(305) /* ./xy_glyph */;
    const glyph_1 = require(306) /* ./glyph */;
    const types_1 = require(25) /* ../../core/types */;
    const enums_1 = require(21) /* ../../core/enums */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    const selection_1 = require(144) /* ../selections/selection */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    const kinds_1 = require(124) /* ../common/kinds */;
    const resolve_1 = require(127) /* ../common/resolve */;
    const log_scale_1 = require(115) /* ../scales/log_scale */;
    class ImageBaseView extends xy_glyph_1.XYGlyphView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.properties.global_alpha.change, () => this.renderer.request_paint());
        }
        get image_dimension() {
            return 2;
        }
        get xy_scale() {
            switch (this.model.origin) {
                case "bottom_left": return { x: 1, y: -1 };
                case "top_left": return { x: 1, y: 1 };
                case "bottom_right": return { x: -1, y: -1 };
                case "top_right": return { x: -1, y: 1 };
            }
        }
        get xy_offset() {
            switch (this.model.origin) {
                case "bottom_left": return { x: 0.0, y: 1.0 };
                case "top_left": return { x: 0.0, y: 0.0 };
                case "bottom_right": return { x: 1.0, y: 1.0 };
                case "top_right": return { x: 1.0, y: 0.0 };
            }
        }
        get xy_anchor() {
            return (0, resolve_1.anchor)(this.model.anchor);
        }
        get xy_sign() {
            const xr = this.renderer.xscale.source_range;
            const yr = this.renderer.yscale.source_range;
            return {
                x: xr.is_reversed ? -1 : 1,
                y: yr.is_reversed ? -1 : 1,
            };
        }
        _paint(ctx, indices, data) {
            const { image_data, sx, sy, sdw, sdh } = { ...this, ...data };
            const { xy_sign, xy_scale, xy_offset, xy_anchor } = this;
            (0, assert_1.assert)(image_data != null);
            ctx.save();
            ctx.imageSmoothingEnabled = false;
            if (this.visuals.image.doit) {
                for (const i of indices) {
                    const image_data_i = image_data[i];
                    const sx_i = sx[i];
                    const sy_i = sy[i];
                    const sdw_i = sdw[i];
                    const sdh_i = sdh[i];
                    if (image_data_i == null || !isFinite(sx_i + sy_i + sdw_i + sdh_i)) {
                        continue;
                    }
                    const tx_i = xy_sign.x * xy_anchor.x * sdw_i;
                    const ty_i = xy_sign.y * xy_anchor.y * sdh_i;
                    ctx.save();
                    ctx.translate(sx_i - tx_i, sy_i - ty_i);
                    ctx.scale(xy_sign.x * xy_scale.x, xy_sign.y * xy_scale.y);
                    this.visuals.image.set_vectorize(ctx, i);
                    ctx.drawImage(image_data_i, -xy_offset.x * sdw_i, -xy_offset.y * sdh_i, sdw_i, sdh_i);
                    ctx.restore();
                }
            }
            ctx.restore();
        }
        get _can_inherit_image_data() {
            return this.inherited_image;
        }
        _set_data(indices) {
            const n = this.data_size;
            if (!this._can_inherit_image_data) {
                if (typeof this.image_data === "undefined" || this.image_data.length != n) {
                    this._define_attr("image_data", new Array(n).fill(null));
                    this._define_attr("image_width", new Uint32Array(n));
                    this._define_attr("image_height", new Uint32Array(n));
                }
                const { image_dimension } = this;
                for (let i = 0; i < n; i++) {
                    if (indices != null && !indices.includes(i)) {
                        continue;
                    }
                    const img = this.image.get(i);
                    (0, assert_1.assert)(img.dimension == image_dimension, `expected a ${image_dimension}D array, not ${img.dimension}D`);
                    const [height, width] = img.shape;
                    this.image_width[i] = width;
                    this.image_height[i] = height;
                    const buf8 = this._flat_img_to_buf8(img);
                    this._set_image_data_from_buffer(i, buf8);
                }
            }
            else {
                this._inherit_attr("image_data");
                this._inherit_attr("image_width");
                this._inherit_attr("image_height");
            }
        }
        _index_data(index) {
            const { data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const [l, r, t, b] = this._lrtb(i);
                index.add_rect(l, b, r, t);
            }
        }
        _lrtb(i) {
            const dw_i = this.dw.get(i);
            const dh_i = this.dh.get(i);
            const x_i = this.x[i];
            const y_i = this.y[i];
            const { xy_anchor } = this;
            const [x0, x1] = [x_i - xy_anchor.x * dw_i, x_i + (1 - xy_anchor.x) * dw_i];
            const [y0, y1] = [y_i + xy_anchor.y * dh_i, y_i - (1 - xy_anchor.y) * dh_i];
            const [l, r] = x0 <= x1 ? [x0, x1] : [x1, x0];
            const [b, t] = y0 <= y1 ? [y0, y1] : [y1, y0];
            return [l, r, t, b];
        }
        _get_or_create_canvas(i) {
            (0, assert_1.assert)(this.image_data != null);
            const image_data_i = this.image_data[i];
            if (image_data_i != null && image_data_i.width == this.image_width[i]
                && image_data_i.height == this.image_height[i]) {
                return image_data_i;
            }
            else {
                const canvas = document.createElement("canvas");
                canvas.width = this.image_width[i];
                canvas.height = this.image_height[i];
                return canvas;
            }
        }
        _set_image_data_from_buffer(i, buf8) {
            (0, assert_1.assert)(this.image_data != null);
            // This creates a software 2D canvas, which is good for frequent getImageData() and
            // putImageData(), but not for general rendering due to lack of hardware acceleration.
            const canvas = this._get_or_create_canvas(i);
            const ctx = canvas.getContext("2d", { willReadFrequently: true });
            (0, assert_1.assert)(ctx != null);
            const image_data = ctx.getImageData(0, 0, this.image_width[i], this.image_height[i]);
            image_data.data.set(buf8);
            ctx.putImageData(image_data, 0, 0);
            this.image_data[i] = canvas;
        }
        _map_data() {
            this._define_or_inherit_attr("sdw", () => {
                if (this.model.properties.dw.units == "data") {
                    if (this.inherited_x && this.inherited_dw) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.xscale, this.x, this.dw, "edge", this.model.dilate);
                    }
                }
                else {
                    return this.inherited_dw ? glyph_1.inherit : (0, types_1.to_screen)(this.dw);
                }
            });
            this._define_or_inherit_attr("sdh", () => {
                if (this.model.properties.dh.units == "data") {
                    if (this.inherited_y && this.inherited_dh) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.yscale, this.y, this.dh, "edge", this.model.dilate);
                    }
                }
                else {
                    return this.inherited_dh ? glyph_1.inherit : (0, types_1.to_screen)(this.dh);
                }
            });
        }
        _image_index(index, x, y) {
            const [l, r, t, b] = this._lrtb(index);
            const nx = this.image_width[index];
            const ny = this.image_height[index];
            // The handling of log scales here assumes that users themselves have
            // generated images that are "pre-transformed", e.g. an np.meshgrid where
            // np.logspace was used for one or both inputs. Bokeh images always assume
            // square pixels and do not do any sort of transformation on the canvas
            const dx = (() => {
                if (this.renderer.xscale instanceof log_scale_1.LogScale) {
                    return Math.log(x / l) / Math.log(r / l);
                }
                return (x - l) / (r - l);
            })();
            const dy = (() => {
                if (this.renderer.yscale instanceof log_scale_1.LogScale) {
                    return Math.log(y / b) / Math.log(t / b);
                }
                return (y - b) / (t - b);
            })();
            const i = Math.floor(dx * nx);
            const j = Math.floor(dy * ny);
            return { index, i, j, flat_index: j * nx + i };
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            const candidates = this.index.indices({ x0: x, x1: x, y0: y, y1: y });
            const result = new selection_1.Selection();
            const indices = [];
            for (const index of candidates) {
                if (isFinite(sx) && isFinite(sy)) {
                    indices.push(index);
                    result.image_indices.push(this._image_index(index, x, y));
                }
            }
            result.indices = indices;
            return result;
        }
    }
    exports.ImageBaseView = ImageBaseView;
    class ImageBase extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.mixins(mixins.ImageVector);
            this.define(({ Bool }) => ({
                image: [p.NDArraySpec, { field: "image" }],
                dw: [p.DistanceSpec, { field: "dw" }],
                dh: [p.DistanceSpec, { field: "dh" }],
                dilate: [Bool, false],
                origin: [enums_1.ImageOrigin, "bottom_left"],
                anchor: [kinds_1.Anchor, "bottom_left"],
            }));
        }
    }
    exports.ImageBase = ImageBase;
},
/* models/glyphs/image_rgba.js */ function _(require, module, exports, __esModule, __esExport) {
    var __createBinding = (this && this.__createBinding) || (Object.create ? (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        var desc = Object.getOwnPropertyDescriptor(m, k);
        if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
            desc = { enumerable: true, get: function () { return m[k]; } };
        }
        Object.defineProperty(o, k2, desc);
    }) : (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        o[k2] = m[k];
    }));
    var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function (o, v) {
        o["default"] = v;
    });
    var __importStar = (this && this.__importStar) || (function () {
        var ownKeys = function (o) {
            ownKeys = Object.getOwnPropertyNames || function (o) {
                var ar = [];
                for (var k in o)
                    if (Object.prototype.hasOwnProperty.call(o, k))
                        ar[ar.length] = k;
                return ar;
            };
            return ownKeys(o);
        };
        return function (mod) {
            if (mod && mod.__esModule)
                return mod;
            var result = {};
            if (mod != null)
                for (var k = ownKeys(mod), i = 0; i < k.length; i++)
                    if (k[i] !== "default")
                        __createBinding(result, mod, k[i]);
            __setModuleDefault(result, mod);
            return result;
        };
    })();
    __esModule();
    const image_base_1 = require(471) /* ./image_base */;
    const types_1 = require(8) /* ../../core/util/types */;
    class ImageRGBAView extends image_base_1.ImageBaseView {
        async load_glglyph() {
            const { ImageGL } = await Promise.resolve().then(() => __importStar(require(667) /* ./webgl/image */));
            return ImageGL;
        }
        _flat_img_to_buf8(img) {
            const array = (0, types_1.isTypedArray)(img) ? img : new Uint32Array(img);
            return new Uint8ClampedArray(array.buffer);
        }
    }
    exports.ImageRGBAView = ImageRGBAView;
    class ImageRGBA extends image_base_1.ImageBase {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ImageRGBAView;
        }
    }
    exports.ImageRGBA = ImageRGBA;
},
/* models/glyphs/image_stack.js */ function _(require, module, exports, __esModule, __esExport) {
    var __createBinding = (this && this.__createBinding) || (Object.create ? (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        var desc = Object.getOwnPropertyDescriptor(m, k);
        if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
            desc = { enumerable: true, get: function () { return m[k]; } };
        }
        Object.defineProperty(o, k2, desc);
    }) : (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        o[k2] = m[k];
    }));
    var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function (o, v) {
        o["default"] = v;
    });
    var __importStar = (this && this.__importStar) || (function () {
        var ownKeys = function (o) {
            ownKeys = Object.getOwnPropertyNames || function (o) {
                var ar = [];
                for (var k in o)
                    if (Object.prototype.hasOwnProperty.call(o, k))
                        ar[ar.length] = k;
                return ar;
            };
            return ownKeys(o);
        };
        return function (mod) {
            if (mod && mod.__esModule)
                return mod;
            var result = {};
            if (mod != null)
                for (var k = ownKeys(mod), i = 0; i < k.length; i++)
                    if (k[i] !== "default")
                        __createBinding(result, mod, k[i]);
            __setModuleDefault(result, mod);
            return result;
        };
    })();
    __esModule();
    const image_base_1 = require(471) /* ./image_base */;
    const stack_color_mapper_1 = require(362) /* ../mappers/stack_color_mapper */;
    class ImageStackView extends image_base_1.ImageBaseView {
        async load_glglyph() {
            const { ImageGL } = await Promise.resolve().then(() => __importStar(require(667) /* ./webgl/image */));
            return ImageGL;
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.color_mapper.change, () => this._update_image());
        }
        get image_dimension() {
            return 3;
        }
        _update_image() {
            if (this.has_webgl()) {
                this.glglyph.set_image_changed();
            }
            // Only reset image_data if already initialized
            if (this.image_data != null) {
                this._set_data(null);
                this.renderer.request_paint();
            }
        }
        get _can_inherit_image_data() {
            return super._can_inherit_image_data &&
                this._can_inherit_from(this.model.properties.color_mapper, this.base);
        }
        _flat_img_to_buf8(img) {
            const cmap = this.model.color_mapper.rgba_mapper;
            return cmap.v_compute(img);
        }
    }
    exports.ImageStackView = ImageStackView;
    class ImageStack extends image_base_1.ImageBase {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ImageStackView;
            this.define(({ Ref }) => ({
                color_mapper: [Ref(stack_color_mapper_1.StackColorMapper)],
            }));
        }
    }
    exports.ImageStack = ImageStack;
},
/* models/glyphs/image_url.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(305) /* ./xy_glyph */;
    const glyph_1 = require(306) /* ./glyph */;
    const types_1 = require(25) /* ../../core/types */;
    const enums_1 = require(21) /* ../../core/enums */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const array_1 = require(10) /* ../../core/util/array */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const image_1 = require(261) /* ../../core/util/image */;
    const resolve = tslib_1.__importStar(require(127) /* ../common/resolve */);
    class ImageURLView extends xy_glyph_1.XYGlyphView {
        _images_rendered = false;
        _bounds_rect;
        anchor;
        /*protected*/ image = new Array(0);
        loaders;
        resolved;
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.properties.global_alpha.change, () => this.renderer.request_paint());
        }
        _index_data(index) {
            const { data_size } = this;
            for (let i = 0; i < data_size; i++) {
                // TODO: add a proper implementation (same as ImageBase?)
                index.add_empty();
            }
        }
        _set_data_iteration = 0;
        _set_data() {
            if (this.inherited_url) {
                return;
            }
            this._set_data_iteration++;
            const { url } = this;
            const n_url = url.length;
            this.image = (0, array_1.resize)(this.image, n_url, null);
            this.loaders = new Array(n_url).fill(null);
            this.resolved = new types_1.Indices(n_url);
            const { retry_attempts, retry_timeout } = this.model;
            const { _set_data_iteration } = this;
            for (let i = 0; i < n_url; i++) {
                const url_i = url.get(i);
                if (url_i == "") {
                    continue;
                }
                const loader = new image_1.ImageLoader(url_i, {
                    loaded: (image_i) => {
                        if (this._set_data_iteration == _set_data_iteration && !this.resolved.get(i)) {
                            this.resolved.set(i);
                            this.image[i] = image_i;
                            this.loaders[i] = null;
                            this.renderer.request_paint();
                        }
                    },
                    failed: () => {
                        if (this._set_data_iteration == _set_data_iteration) {
                            this.resolved.set(i);
                            this.loaders[i] = null;
                            const image_i = this.image[i];
                            if (image_i != null) {
                                this.image[i] = null;
                                this.renderer.request_paint();
                            }
                        }
                    },
                    attempts: retry_attempts + 1,
                    timeout: retry_timeout,
                });
                this.loaders[i] = loader;
            }
            const w_data = this.model.properties.w.units == "data";
            const h_data = this.model.properties.h.units == "data";
            const n = this.data_size;
            const xs = new types_1.ScreenArray(w_data ? 2 * n : n);
            const ys = new types_1.ScreenArray(h_data ? 2 * n : n);
            this.anchor = resolve.anchor(this.model.anchor);
            const { x: x_anchor, y: y_anchor } = this.anchor;
            function x0x1(x, w) {
                const x0 = x - x_anchor * w;
                return [x0, x0 + w];
            }
            function y0y1(y, h) {
                const y0 = y + y_anchor * h;
                return [y0, y0 - h];
            }
            // if the width/height are in screen units, don't try to include them in bounds
            if (w_data) {
                for (let i = 0; i < n; i++) {
                    [xs[i], xs[n + i]] = x0x1(this.x[i], this.w.get(i) ?? 0);
                }
            }
            else {
                xs.set(this.x, 0);
            }
            if (h_data) {
                for (let i = 0; i < n; i++) {
                    [ys[i], ys[n + i]] = y0y1(this.y[i], this.h.get(i) ?? 0);
                }
            }
            else {
                ys.set(this.y, 0);
            }
            const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(xs, ys);
            this._bounds_rect = { x0, x1, y0, y1 };
        }
        has_finished() {
            return super.has_finished() && this._images_rendered;
        }
        _map_data() {
            const w = () => this.w.map((w_i) => w_i ?? NaN);
            const h = () => this.h.map((h_i) => h_i ?? NaN);
            this._define_or_inherit_attr("sw", () => {
                if (this.model.properties.w.units == "data") {
                    if (this.inherited_x && this.inherited_w) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.xscale, this.x, w(), "edge", this.model.dilate);
                    }
                }
                else {
                    return this.inherited_w ? glyph_1.inherit : (0, types_1.to_screen)(w());
                }
            });
            this._define_or_inherit_attr("sh", () => {
                if (this.model.properties.h.units == "data") {
                    if (this.inherited_y && this.inherited_h) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.yscale, this.y, h(), "edge", this.model.dilate);
                    }
                }
                else {
                    return this.inherited_h ? glyph_1.inherit : (0, types_1.to_screen)(h());
                }
            });
        }
        _paint(ctx, indices, data) {
            const { sx, sy, sw, sh, angle, global_alpha } = { ...this, ...data };
            const { image, loaders, resolved } = this;
            // TODO (bev): take actual border width into account when clipping
            const { frame } = this.renderer.plot_view;
            const { left, top, width, height } = frame.bbox;
            ctx.beginPath();
            ctx.rect(left + 1, top + 1, width - 2, height - 2);
            ctx.clip();
            let finished = true;
            for (const i of indices) {
                const loader_i = loaders[i];
                if (!isFinite(sx[i] + sy[i] + angle.get(i) + global_alpha.get(i))) {
                    continue;
                }
                if (!resolved.get(i)) {
                    if (loader_i != null && loader_i.image.complete) {
                        image[i] = loader_i.image;
                        loaders[i] = null;
                        resolved.set(i);
                    }
                    else {
                        finished = false;
                    }
                }
                const image_i = image[i];
                if (image_i == null) {
                    continue;
                }
                if (image_i.naturalWidth == 0 && image_i.naturalHeight == 0) { // dumb way of detecting broken images
                    continue;
                }
                this._render_image(ctx, i, image_i, sx, sy, sw, sh, angle, global_alpha);
            }
            if (finished && !this._images_rendered) {
                this._images_rendered = true;
                this.notify_finished();
            }
        }
        _render_image(ctx, i, image, sx, sy, sw, sh, angle, alpha) {
            if (!isFinite(sw[i])) {
                sw[i] = image.width;
            }
            if (!isFinite(sh[i])) {
                sh[i] = image.height;
            }
            const sw_i = sw[i];
            const sh_i = sh[i];
            const { anchor } = this;
            const dx_i = anchor.x * sw_i;
            const dy_i = anchor.y * sh_i;
            const sx_i = sx[i] - dx_i;
            const sy_i = sy[i] - dy_i;
            const angle_i = angle.get(i);
            const alpha_i = alpha.get(i);
            ctx.save();
            ctx.globalAlpha = alpha_i;
            const sw2 = sw_i / 2;
            const sh2 = sh_i / 2;
            if (angle_i != 0) {
                ctx.translate(sx_i, sy_i);
                //rotation about center of image
                ctx.translate(sw2, sh2);
                ctx.rotate(angle_i);
                ctx.translate(-sw2, -sh2);
                ctx.drawImage(image, 0, 0, sw_i, sh_i);
                ctx.translate(sw2, sh2);
                ctx.rotate(-angle_i);
                ctx.translate(-sw2, -sh2);
                ctx.translate(-sx_i, -sy_i);
            }
            else {
                ctx.drawImage(image, sx_i, sy_i, sw_i, sh_i);
            }
            ctx.restore();
        }
        bounds() {
            return this._bounds_rect;
        }
    }
    exports.ImageURLView = ImageURLView;
    class ImageURL extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ImageURLView;
            this.define(({ Bool, Int }) => ({
                url: [p.StringSpec, { field: "url" }],
                anchor: [enums_1.Anchor, "top_left"],
                global_alpha: [p.NumberSpec, { value: 1.0 }],
                angle: [p.AngleSpec, 0],
                w: [p.NullDistanceSpec, null],
                h: [p.NullDistanceSpec, null],
                dilate: [Bool, false],
                retry_attempts: [Int, 0],
                retry_timeout: [Int, 0],
            }));
        }
    }
    exports.ImageURL = ImageURL;
},
/* models/glyphs/mathml_glyph.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const math_text_glyph_1 = require(476) /* ./math_text_glyph */;
    const math_text_1 = require(260) /* ../text/math_text */;
    class MathMLGlyphView extends math_text_glyph_1.MathTextGlyphView {
        _build_label(text) {
            return new math_text_1.MathML({ text });
        }
    }
    exports.MathMLGlyphView = MathMLGlyphView;
    class MathMLGlyph extends math_text_glyph_1.MathTextGlyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = MathMLGlyphView;
        }
    }
    exports.MathMLGlyph = MathMLGlyph;
},
/* models/glyphs/math_text_glyph.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const text_1 = require(477) /* ./text */;
    const math_text_1 = require(260) /* ../text/math_text */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const iterator_1 = require(15) /* ../../core/util/iterator */;
    class MathTextGlyphView extends text_1.TextView {
        _label_views = new Map();
        children_views() {
            return [...super.children_views(), ...this._label_views.values()];
        }
        has_finished() {
            if (!super.has_finished()) {
                return false;
            }
            for (const view of this._label_views.values()) {
                if (!view.has_finished()) {
                    return false;
                }
            }
            return true;
        }
        async _build_labels(text) {
            const labels = Array.from(text, (text_i) => {
                return text_i == null ? null : this._build_label(text_i);
            });
            await (0, build_views_1.build_views)(this._label_views, labels.filter((v) => v != null), { parent: this.renderer });
            return labels.map((label_i) => {
                return label_i == null ? null : this._label_views.get(label_i).graphics();
            });
        }
        async after_lazy_visuals() {
            await super.after_lazy_visuals();
            const promises = [...this._label_views.values()].map((label_view) => {
                if (label_view instanceof math_text_1.MathTextView) {
                    return label_view.request_image();
                }
                else {
                    return null;
                }
            });
            await Promise.allSettled(promises);
            const { left, right, top, bottom } = this.padding;
            for (const [label, i] of (0, iterator_1.enumerate)(this.labels)) {
                if (label == null) {
                    continue;
                }
                if (!(label instanceof math_text_1.MathTextView)) {
                    continue;
                }
                const size = label.size();
                const width = left + size.width + right;
                const height = top + size.height + bottom;
                this.swidth[i] = width;
                this.sheight[i] = height;
            }
        }
    }
    exports.MathTextGlyphView = MathTextGlyphView;
    class MathTextGlyph extends text_1.Text {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.MathTextGlyph = MathTextGlyph;
},
/* models/glyphs/text.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(305) /* ./xy_glyph */;
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const uniforms_1 = require(40) /* ../../core/uniforms */;
    const selection_1 = require(144) /* ../selections/selection */;
    const bbox_1 = require(62) /* ../../core/util/bbox */;
    const iterator_1 = require(15) /* ../../core/util/iterator */;
    const affine_1 = require(73) /* ../../core/util/affine */;
    const graphics_1 = require(262) /* ../../core/graphics */;
    const kinds_1 = require(124) /* ../common/kinds */;
    const resolve = tslib_1.__importStar(require(127) /* ../common/resolve */);
    const painting_1 = require(267) /* ../common/painting */;
    const math_1 = require(12) /* ../../core/util/math */;
    class TextAnchorSpec extends p.DataSpec {
    }
    class OutlineShapeSpec extends p.DataSpec {
    }
    class TextView extends xy_glyph_1.XYGlyphView {
        async _build_labels(text) {
            return Array.from(text, (value) => {
                if (value == null) {
                    return null;
                }
                else {
                    const text = `${value}`; // TODO: guarantee correct types earlier
                    return new graphics_1.TextBox({ text });
                }
            });
        }
        async _set_lazy_data() {
            if (this.inherited_text) {
                this._inherit_attr("labels");
            }
            else {
                this._define_attr("labels", await this._build_labels(this.text));
            }
        }
        after_visuals() {
            super.after_visuals();
            const n = this.data_size;
            const { anchor } = this.base ?? this;
            const { padding, border_radius } = this.model;
            const { text_align, text_baseline } = this.visuals.text;
            if (anchor.is_Scalar() && anchor.value != "auto") {
                this.anchor_ = new uniforms_1.UniformScalar(resolve.anchor(anchor.value), n);
            }
            else if (anchor.is_Scalar() && text_align.is_Scalar() && text_baseline.is_Scalar()) {
                this.anchor_ = new uniforms_1.UniformScalar(resolve.text_anchor(anchor.value, text_align.value, text_baseline.value), n);
            }
            else {
                const anchors = new Array(n);
                for (let i = 0; i < n; i++) {
                    const anchor_i = anchor.get(i);
                    const align_i = text_align.get(i);
                    const baseline_i = text_baseline.get(i);
                    anchors[i] = resolve.text_anchor(anchor_i, align_i, baseline_i);
                }
                this.anchor_ = new uniforms_1.UniformVector(anchors);
            }
            this.padding = resolve.padding(padding);
            this.border_radius = resolve.border_radius(border_radius);
            this.swidth = new Float32Array(n);
            this.sheight = new Float32Array(n);
            const { left, right, top, bottom } = this.padding;
            for (const [label, i] of (0, iterator_1.enumerate)(this.labels)) {
                if (label == null) {
                    continue;
                }
                label.visuals = this.visuals.text.values(i);
                label.position = { sx: 0, sy: 0, x_anchor: "left", y_anchor: "top" };
                label.align = "auto";
                const size = label.size();
                const width = left + size.width + right;
                const height = top + size.height + bottom;
                this.swidth[i] = width;
                this.sheight[i] = height;
            }
        }
        _paint(ctx, indices, data) {
            const { sx, sy, x_offset, y_offset, angle, outline_shape } = { ...this, ...data };
            const { text, background_fill, background_hatch, border_line } = this.visuals;
            const { anchor_: anchor, border_radius, padding } = this;
            const { labels, swidth, sheight } = this;
            for (const i of indices) {
                const sx_i = sx[i] + x_offset.get(i);
                const sy_i = sy[i] + y_offset.get(i);
                const angle_i = angle.get(i);
                const label_i = labels[i];
                const shape_i = outline_shape.get(i);
                if (!isFinite(sx_i + sy_i + angle_i) || label_i == null) {
                    continue;
                }
                const swidth_i = swidth[i];
                const sheight_i = sheight[i];
                const anchor_i = anchor.get(i);
                const dx_i = anchor_i.x * swidth_i;
                const dy_i = anchor_i.y * sheight_i;
                ctx.translate(sx_i, sy_i);
                ctx.rotate(angle_i);
                ctx.translate(-dx_i, -dy_i);
                if (shape_i != "none" && (background_fill.v_doit(i) || background_hatch.v_doit(i) || border_line.v_doit(i))) {
                    const bbox = new bbox_1.BBox({ x: 0, y: 0, width: swidth_i, height: sheight_i });
                    const visuals = {
                        fill: background_fill,
                        hatch: background_hatch,
                        line: border_line,
                    };
                    this._paint_shape(ctx, i, shape_i, bbox, visuals, border_radius);
                }
                if (text.v_doit(i)) {
                    const { left, top } = padding;
                    ctx.translate(left, top);
                    label_i.visuals = text.values(i);
                    label_i.paint(ctx);
                    ctx.translate(-left, -top);
                }
                ctx.translate(dx_i, dy_i);
                ctx.rotate(-angle_i);
                ctx.translate(-sx_i, -sy_i);
            }
        }
        _paint_shape(ctx, i, shape, bbox, visuals, border_radius) {
            ctx.beginPath();
            switch (shape) {
                case "none": {
                    break;
                }
                case "box":
                case "rectangle": {
                    (0, painting_1.round_rect)(ctx, bbox, border_radius);
                    break;
                }
                case "square": {
                    const square = (() => {
                        const { x, y, width, height } = bbox;
                        if (width > height) {
                            const dy = (width - height) / 2;
                            return new bbox_1.BBox({ x, y: y - dy, width, height: width });
                        }
                        else {
                            const dx = (height - width) / 2;
                            return new bbox_1.BBox({ x: x - dx, y, width: height, height });
                        }
                    })();
                    (0, painting_1.round_rect)(ctx, square, border_radius);
                    break;
                }
                case "circle": {
                    const cx = bbox.x_center;
                    const cy = bbox.y_center;
                    const radius = (0, math_1.sqrt)(bbox.width ** 2 + bbox.height ** 2) / 2;
                    ctx.arc(cx, cy, radius, 0, 2 * math_1.PI, false);
                    break;
                }
                case "ellipse": {
                    const cx = bbox.x_center;
                    const cy = bbox.y_center;
                    const rx = bbox.width / 2;
                    const ry = bbox.height / 2;
                    const n = 1.5;
                    const x_0 = rx;
                    const y_0 = ry;
                    const a = (0, math_1.sqrt)(x_0 ** 2 + x_0 ** (2 / n) * y_0 ** (2 - 2 / n));
                    const b = (0, math_1.sqrt)(y_0 ** 2 + y_0 ** (2 / n) * x_0 ** (2 - 2 / n));
                    ctx.ellipse(cx, cy, a, b, 0, 0, 2 * math_1.PI);
                    break;
                }
                case "trapezoid": {
                    const { left, right, top, bottom, width } = bbox;
                    const ext = 0.2 * width;
                    ctx.moveTo(left, top);
                    ctx.lineTo(right, top);
                    ctx.lineTo(right + ext, bottom);
                    ctx.lineTo(left - ext, bottom);
                    ctx.closePath();
                    break;
                }
                case "parallelogram": {
                    const { left, right, top, bottom, width } = bbox;
                    const ext = 0.2 * width;
                    ctx.moveTo(left, top);
                    ctx.lineTo(right + ext, top);
                    ctx.lineTo(right, bottom);
                    ctx.lineTo(left - ext, bottom);
                    ctx.closePath();
                    break;
                }
                case "diamond": {
                    const { x_center, y_center, width, height } = bbox;
                    ctx.moveTo(x_center, y_center - height);
                    ctx.lineTo(width + width / 2, y_center);
                    ctx.lineTo(x_center, y_center + height);
                    ctx.lineTo(-width / 2, y_center);
                    ctx.closePath();
                    break;
                }
                case "triangle": {
                    const w = bbox.width;
                    const h = bbox.height;
                    const l = (0, math_1.sqrt)(3) / 2 * w;
                    const H = h + l;
                    ctx.translate(w / 2, -l);
                    ctx.moveTo(0, 0);
                    ctx.lineTo(H / 2, H);
                    ctx.lineTo(-H / 2, H);
                    ctx.closePath();
                    ctx.translate(-w / 2, l);
                    break;
                }
            }
            visuals.fill.apply(ctx, i);
            visuals.hatch.apply(ctx, i);
            visuals.line.apply(ctx, i);
        }
        _hit_point(geometry) {
            const hit_xy = { x: geometry.sx, y: geometry.sy };
            const { sx, sy, x_offset, y_offset, angle, labels } = this;
            const { anchor_: anchor } = this;
            const { swidth, sheight } = this;
            const n = this.data_size;
            const indices = [];
            for (let i = 0; i < n; i++) {
                const sx_i = sx[i] + x_offset.get(i);
                const sy_i = sy[i] + y_offset.get(i);
                const angle_i = angle.get(i);
                const label_i = labels[i];
                if (!isFinite(sx_i + sy_i + angle_i) || label_i == null) {
                    continue;
                }
                const swidth_i = swidth[i];
                const sheight_i = sheight[i];
                const anchor_i = anchor.get(i);
                const dx_i = anchor_i.x * swidth_i;
                const dy_i = anchor_i.y * sheight_i;
                const { x, y } = (0, affine_1.rotate_around)(hit_xy, { x: sx_i, y: sy_i }, -angle_i);
                const left = sx_i - dx_i;
                const top = sy_i - dy_i;
                const right = left + swidth_i;
                const bottom = top + sheight_i;
                // TODO: consider round corners
                if (left <= x && x <= right && top <= y && y <= bottom) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        rect_i(i) {
            const { sx, sy, x_offset, y_offset, angle, labels } = this;
            const { anchor_: anchor } = this;
            const { swidth, sheight } = this;
            const sx_i = sx[i] + x_offset.get(i);
            const sy_i = sy[i] + y_offset.get(i);
            const angle_i = angle.get(i);
            const label_i = labels[i];
            if (!isFinite(sx_i + sy_i + angle_i) || label_i == null) {
                return {
                    p0: { x: NaN, y: NaN },
                    p1: { x: NaN, y: NaN },
                    p2: { x: NaN, y: NaN },
                    p3: { x: NaN, y: NaN },
                };
            }
            const swidth_i = swidth[i];
            const sheight_i = sheight[i];
            const anchor_i = anchor.get(i);
            const dx_i = anchor_i.x * swidth_i;
            const dy_i = anchor_i.y * sheight_i;
            const bbox = new bbox_1.BBox({
                x: sx_i - dx_i,
                y: sy_i - dy_i,
                width: swidth_i,
                height: sheight_i,
            });
            const { rect } = bbox;
            if (angle_i == 0) {
                return rect;
            }
            else {
                const tr = new affine_1.AffineTransform();
                tr.rotate_around(sx_i, sy_i, angle_i);
                return tr.apply_rect(rect);
            }
        }
        scenterxy(i) {
            const { p0, p1, p2, p3 } = this.rect_i(i);
            const sx = (p0.x + p1.x + p2.x + p3.x) / 4;
            const sy = (p0.y + p1.y + p2.y + p3.y) / 4;
            return [sx, sy];
        }
    }
    exports.TextView = TextView;
    class Text extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = TextView;
            this.mixins([
                mixins.TextVector,
                ["border_", mixins.LineVector],
                ["background_", mixins.FillVector],
                ["background_", mixins.HatchVector],
            ]);
            this.define(() => ({
                text: [p.NullStringSpec, { field: "text" }],
                angle: [p.AngleSpec, 0],
                x_offset: [p.NumberSpec, 0],
                y_offset: [p.NumberSpec, 0],
                anchor: [TextAnchorSpec, { value: "auto" }],
                padding: [kinds_1.Padding, 0],
                border_radius: [kinds_1.BorderRadius, 0],
                outline_shape: [OutlineShapeSpec, "box"],
            }));
            this.override({
                border_line_color: null,
                background_fill_color: null,
                background_hatch_color: null,
            });
        }
    }
    exports.Text = Text;
},
/* models/glyphs/multi_line.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const property_mixins_1 = require(95) /* ../../core/property_mixins */;
    const hittest = tslib_1.__importStar(require(311) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const glyph_1 = require(306) /* ./glyph */;
    const utils_1 = require(310) /* ./utils */;
    const selection_1 = require(144) /* ../selections/selection */;
    class MultiLineView extends glyph_1.GlyphView {
        async load_glglyph() {
            const { MultiLineGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(671) /* ./webgl/multi_line */));
            return MultiLineGL;
        }
        _project_data() {
            this._project_xy("xs", this.xs.data, "ys", this.ys.data);
        }
        _index_data(index) {
            const { data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const xsi = this.xs.get(i);
                const ysi = this.ys.get(i);
                const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(xsi, ysi);
                index.add_rect(x0, y0, x1, y1);
            }
        }
        _paint(ctx, indices, data) {
            const { sxs, sys } = { ...this, ...data };
            for (const i of indices) {
                const sx = sxs.get(i);
                const sy = sys.get(i);
                const n = Math.min(sx.length, sy.length);
                let move = true;
                ctx.beginPath();
                for (let j = 0; j < n; j++) {
                    const sx_j = sx[j];
                    const sy_j = sy[j];
                    if (!isFinite(sx_j + sy_j)) {
                        move = true;
                    }
                    else {
                        if (move) {
                            ctx.moveTo(sx_j, sy_j);
                            move = false;
                        }
                        else {
                            ctx.lineTo(sx_j, sy_j);
                        }
                    }
                }
                this.visuals.line.set_vectorize(ctx, i);
                ctx.stroke();
            }
        }
        _hit_point(geometry) {
            const point = { x: geometry.sx, y: geometry.sy };
            let shortest = 9999;
            const hits = new Map();
            for (let i = 0, end = this.sxs.length; i < end; i++) {
                const threshold = Math.max(2, this.line_width.get(i) / 2);
                const sxsi = this.sxs.get(i);
                const sysi = this.sys.get(i);
                let points = null;
                for (let j = 0, endj = sxsi.length - 1; j < endj; j++) {
                    const p0 = { x: sxsi[j], y: sysi[j] };
                    const p1 = { x: sxsi[j + 1], y: sysi[j + 1] };
                    const dist = hittest.dist_to_segment(point, p0, p1);
                    if (dist < threshold && dist < shortest) {
                        shortest = dist;
                        points = [j];
                    }
                }
                if (points != null) {
                    hits.set(i, points);
                }
            }
            return new selection_1.Selection({
                indices: [...hits.keys()],
                multiline_indices: hits,
            });
        }
        _hit_span(geometry) {
            const { sx, sy } = geometry;
            let val;
            let vs;
            if (geometry.direction == "v") {
                val = this.renderer.yscale.invert(sy);
                vs = this.ys;
            }
            else {
                val = this.renderer.xscale.invert(sx);
                vs = this.xs;
            }
            const hits = new Map();
            for (let i = 0, end = vs.length; i < end; i++) {
                const vsi = vs.get(i);
                const points = [];
                for (let j = 0, endj = vsi.length - 1; j < endj; j++) {
                    if ((vsi[j] <= val && val <= vsi[j + 1]) || (vsi[j + 1] <= val && val <= vsi[j])) {
                        points.push(j);
                    }
                }
                if (points.length > 0) {
                    hits.set(i, points);
                }
            }
            return new selection_1.Selection({
                indices: [...hits.keys()],
                multiline_indices: hits,
            });
        }
        get_interpolation_hit(i, point_i, geometry) {
            const xsi = this.xs.get(i);
            const ysi = this.ys.get(i);
            const x2 = xsi[point_i];
            const y2 = ysi[point_i];
            const x3 = xsi[point_i + 1];
            const y3 = ysi[point_i + 1];
            return (0, utils_1.line_interpolation)(this.renderer, geometry, x2, y2, x3, y3);
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
        scenterxy() {
            throw new Error(`${this}.scenterxy() is not implemented`);
        }
    }
    exports.MultiLineView = MultiLineView;
    class MultiLine extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = MultiLineView;
            this.define(({}) => ({
                xs: [p.XCoordinateSeqSpec, { field: "xs" }],
                ys: [p.YCoordinateSeqSpec, { field: "ys" }],
            }));
            this.mixins(property_mixins_1.LineVector);
        }
    }
    exports.MultiLine = MultiLine;
},
/* models/glyphs/multi_polygons.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const spatial_1 = require(308) /* ../../core/util/spatial */;
    const glyph_1 = require(306) /* ./glyph */;
    const utils_1 = require(310) /* ./utils */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const arrayable_2 = require(14) /* ../../core/util/arrayable */;
    const property_mixins_1 = require(95) /* ../../core/property_mixins */;
    const hittest = tslib_1.__importStar(require(311) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const selection_1 = require(144) /* ../selections/selection */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    class MultiPolygonsView extends glyph_1.GlyphView {
        _hole_index;
        _project_data() {
            // TODO
        }
        _index_data(index) {
            const { min, max } = Math;
            const { data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const xsi = this.xs[i];
                const ysi = this.ys[i];
                if (xsi.length == 0 || ysi.length == 0) {
                    index.add_empty();
                    continue;
                }
                let xi0 = +Infinity;
                let xi1 = -Infinity;
                let yi0 = +Infinity;
                let yi1 = -Infinity;
                for (let j = 0, endj = xsi.length; j < endj; j++) {
                    const xsij = xsi[j][0]; // do not use holes
                    const ysij = ysi[j][0]; // do not use holes
                    if (xsij.length != 0 && ysij.length != 0) {
                        const [xij0, xij1, yij0, yij1] = (0, arrayable_1.minmax2)(xsij, ysij);
                        xi0 = min(xi0, xij0);
                        xi1 = max(xi1, xij1);
                        yi0 = min(yi0, yij0);
                        yi1 = max(yi1, yij1);
                    }
                }
                index.add_rect(xi0, yi0, xi1, yi1);
            }
            this._hole_index = this._index_hole_data();
        }
        _index_hole_data() {
            const { min, max } = Math;
            const { data_size } = this;
            const index = new spatial_1.SpatialIndex(data_size);
            for (let i = 0; i < data_size; i++) {
                const xsi = this.xs[i];
                const ysi = this.ys[i];
                if (xsi.length == 0 || ysi.length == 0) {
                    index.add_empty();
                    continue;
                }
                let xi0 = +Infinity;
                let xi1 = -Infinity;
                let yi0 = +Infinity;
                let yi1 = -Infinity;
                for (let j = 0, endj = xsi.length; j < endj; j++) {
                    const xsij = xsi[j];
                    const ysij = ysi[j];
                    if (xsij.length > 1 && ysij.length > 1) {
                        for (let k = 1, endk = xsij.length; k < endk; k++) {
                            const [xij0, xij1, yij0, yij1] = (0, arrayable_1.minmax2)(xsij[k], ysij[k]);
                            xi0 = min(xi0, xij0);
                            xi1 = max(xi1, xij1);
                            yi0 = min(yi0, yij0);
                            yi1 = max(yi1, yij1);
                        }
                    }
                }
                index.add_rect(xi0, yi0, xi1, yi1);
            }
            index.finish();
            return index;
        }
        _mask_data() {
            const { x_source, y_source } = this.renderer.coordinates;
            return this.index.indices({
                x0: x_source.min, x1: x_source.max,
                y0: y_source.min, y1: y_source.max,
            });
        }
        _paint(ctx, indices, data) {
            if (!this.visuals.fill.doit && !this.visuals.line.doit) {
                return;
            }
            const { sxs, sys } = { ...this, ...data };
            for (const i of indices) {
                ctx.beginPath();
                const sx_i = sxs[i];
                const sy_i = sys[i];
                const nj = Math.min(sx_i.length, sy_i.length);
                for (let j = 0; j < nj; j++) {
                    const sx_ij = sx_i[j];
                    const sy_ij = sy_i[j];
                    const nk = Math.min(sx_ij.length, sy_ij.length);
                    for (let k = 0; k < nk; k++) {
                        const sx_ijk = sx_ij[k];
                        const sy_ijk = sy_ij[k];
                        const nl = Math.min(sx_ijk.length, sy_ijk.length);
                        for (let l = 0; l < nl; l++) {
                            const sx_ijkl = sx_ijk[l];
                            const sy_ijkl = sy_ijk[l];
                            if (l == 0) {
                                ctx.moveTo(sx_ijkl, sy_ijkl);
                            }
                            else {
                                ctx.lineTo(sx_ijkl, sy_ijkl);
                            }
                        }
                        ctx.closePath();
                    }
                }
                this.visuals.fill.apply(ctx, i, "evenodd");
                this.visuals.hatch.apply(ctx, i, "evenodd");
                this.visuals.line.apply(ctx, i);
            }
        }
        _hit_poly(geometry) {
            const { sx: sxs, sy: sys, greedy = false } = geometry;
            const candidates = (() => {
                const xs = this.renderer.xscale.v_invert(sxs);
                const ys = this.renderer.yscale.v_invert(sys);
                const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(xs, ys);
                return this.index.indices({ x0, x1, y0, y1 });
            })();
            const indices = [];
            for (const i of candidates) {
                const sxs_i = this.sxs[i];
                const sys_i = this.sys[i];
                let hit = !greedy;
                const nj = sxs_i.length;
                for (let j = 0; j < nj; j++) {
                    const sxs_ij0 = sxs_i[j][0];
                    const sys_ij0 = sys_i[j][0];
                    const nk = sxs_ij0.length;
                    for (let k = 0; k < nk; k++) {
                        const sxs_ij0k = sxs_ij0[k];
                        const sys_ij0k = sys_ij0[k];
                        if (!hittest.point_in_poly(sxs_ij0k, sys_ij0k, sxs, sys)) {
                            if (!greedy) {
                                hit = false;
                                break;
                            }
                        }
                        else {
                            if (greedy) {
                                hit = true;
                                break;
                            }
                        }
                    }
                    if (!greedy) {
                        if (!hit) {
                            break;
                        }
                    }
                    else {
                        if (hit) {
                            break;
                        }
                    }
                }
                if (hit) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const { sx0, sx1, sy0, sy1, greedy } = geometry;
            const sxs = [sx0, sx1, sx1, sx0];
            const sys = [sy0, sy0, sy1, sy1];
            return this._hit_poly({ type: "poly", sx: sxs, sy: sys, greedy });
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            const candidates = this.index.indices({ x0: x, y0: y, x1: x, y1: y });
            const hole_candidates = this._hole_index.indices({ x0: x, y0: y, x1: x, y1: y });
            const indices = [];
            for (const index of candidates) {
                const sxs = this.sxs[index];
                const sys = this.sys[index];
                for (let j = 0, endj = sxs.length; j < endj; j++) {
                    const nk = sxs[j].length;
                    if (hittest.point_in_poly(sx, sy, sxs[j][0], sys[j][0])) {
                        if (nk == 1) {
                            indices.push(index);
                        }
                        else if (!hole_candidates.get(index)) {
                            indices.push(index);
                        }
                        else if (nk > 1) {
                            let in_a_hole = false;
                            for (let k = 1; k < nk; k++) {
                                const sxs_k = sxs[j][k];
                                const sys_k = sys[j][k];
                                if (hittest.point_in_poly(sx, sy, sxs_k, sys_k)) {
                                    in_a_hole = true;
                                    break;
                                }
                                else {
                                    continue;
                                }
                            }
                            if (!in_a_hole) {
                                indices.push(index);
                            }
                        }
                    }
                }
            }
            return new selection_1.Selection({ indices });
        }
        _get_snap_coord(array) {
            return (0, arrayable_2.sum)(array) / array.length;
        }
        scenterxy(i, sx, sy) {
            if (this.sxs[i].length == 1) {
                // We don't have discontinuous objects so we're ok
                const scx = this._get_snap_coord(this.sxs[i][0][0]);
                const scy = this._get_snap_coord(this.sys[i][0][0]);
                return [scx, scy];
            }
            else {
                // We have discontinuous objects, so we need to find which
                // one we're in, we can use point_in_poly again
                const sxs = this.sxs[i];
                const sys = this.sys[i];
                for (let j = 0, end = sxs.length; j < end; j++) {
                    if (hittest.point_in_poly(sx, sy, sxs[j][0], sys[j][0])) {
                        const scx = this._get_snap_coord(sxs[j][0]);
                        const scy = this._get_snap_coord(sys[j][0]);
                        return [scx, scy];
                    }
                }
            }
            (0, assert_1.unreachable)();
        }
        map_data() {
            if (this.inherited_xs && this.inherited_ys) {
                this._inherit_attr("sxs");
                this._inherit_attr("sys");
            }
            else {
                const { xs, ys } = this;
                const n_i = xs.length;
                const sxs = new Array(n_i);
                const sys = new Array(n_i);
                for (let i = 0; i < n_i; i++) {
                    const n_j = xs[i].length;
                    sxs[i] = new Array(n_j);
                    sys[i] = new Array(n_j);
                    for (let j = 0; j < n_j; j++) {
                        const n_k = xs[i][j].length;
                        sxs[i][j] = new Array(n_k);
                        sys[i][j] = new Array(n_k);
                        for (let k = 0; k < n_k; k++) {
                            const [sx, sy] = this.renderer.coordinates.map_to_screen(xs[i][j][k], ys[i][j][k]);
                            sxs[i][j][k] = sx;
                            sys[i][j][k] = sy;
                        }
                    }
                }
                this._define_attr("sxs", sxs);
                this._define_attr("sys", sys);
            }
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.MultiPolygonsView = MultiPolygonsView;
    class MultiPolygons extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = MultiPolygonsView;
            this.define(({}) => ({
                xs: [p.XCoordinateSeqSeqSeqSpec, { field: "xs" }],
                ys: [p.YCoordinateSeqSeqSeqSpec, { field: "ys" }],
            }));
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        }
    }
    exports.MultiPolygons = MultiPolygons;
},
/* models/glyphs/ngon.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const radial_glyph_1 = require(375) /* ./radial_glyph */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const hittest_1 = require(311) /* ../../core/hittest */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const selection_1 = require(144) /* ../selections/selection */;
    function ngon(x, y, r, n, angle) {
        const xs = new Float32Array(n);
        const ys = new Float32Array(n);
        const alpha_i = 2 * Math.PI / n;
        for (let i = 0; i < n; i++) {
            const alpha = i * alpha_i + angle;
            xs[i] = x + r * Math.sin(alpha);
            ys[i] = y + r * -Math.cos(alpha);
        }
        return [xs, ys];
    }
    class NgonView extends radial_glyph_1.RadialGlyphView {
        async load_glglyph() {
            const { NgonGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(677) /* ./webgl/ngon */));
            return NgonGL;
        }
        _paint(ctx, indices, data) {
            const { sx, sy, sradius, angle, n } = { ...this, ...data };
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const sradius_i = sradius[i];
                const angle_i = angle.get(i);
                const n_i = n.get(i);
                if (n_i < 3 || !isFinite(sx_i + sy_i + sradius_i + angle_i + n_i)) {
                    continue;
                }
                const [sxs, sys] = ngon(sx_i, sy_i, sradius_i, n_i, angle_i);
                ctx.beginPath();
                ctx.moveTo(sxs[0], sys[0]);
                for (let i = 1; i <= n_i; i++) {
                    ctx.lineTo(sxs[i], sys[i]);
                }
                ctx.closePath();
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _ngon(index) {
            const { sx, sy, sradius, angle, n } = { ...this };
            const sx_i = sx[index];
            const sy_i = sy[index];
            const sradius_i = sradius[index];
            const angle_i = angle.get(index);
            const n_i = n.get(index);
            return ngon(sx_i, sy_i, sradius_i, n_i, angle_i);
        }
        _hit_point(geometry) {
            const x = this.renderer.xscale.invert(geometry.sx);
            const y = this.renderer.yscale.invert(geometry.sy);
            const candidates = this.index.indices({ x0: x, y0: y, x1: x, y1: y });
            const indices = [];
            for (const index of candidates) {
                const [sxs, sys] = this._ngon(index);
                if ((0, hittest_1.point_in_poly)(geometry.sx, geometry.sy, sxs, sys)) {
                    indices.push(index);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const { sx, sy } = geometry;
            const { x0, x1, y0, y1 } = this.bounds();
            const [val, dim, candidates] = (() => {
                switch (geometry.direction) {
                    case "v": {
                        const y = this.renderer.yscale.invert(sy);
                        const candidates = this.index.indices({ x0, y0: y, x1, y1: y });
                        return [sy, 1, candidates];
                    }
                    case "h": {
                        const x = this.renderer.xscale.invert(sx);
                        const candidates = this.index.indices({ x0: x, y0, x1: x, y1 });
                        return [sx, 0, candidates];
                    }
                }
            })();
            const indices = [];
            for (const index of candidates) {
                const coords = this._ngon(index)[dim];
                for (let i = 0; i < coords.length - 1; i++) {
                    if ((coords[i] <= val && val <= coords[i + 1]) || (coords[i + 1] <= val && val <= coords[i])) {
                        indices.push(index);
                        break;
                    }
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_poly(geometry) {
            const { sx: gsx, sy: gsy } = geometry;
            const candidates = (() => {
                const xs = this.renderer.xscale.v_invert(gsx);
                const ys = this.renderer.yscale.v_invert(gsy);
                const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(xs, ys);
                return this.index.indices({ x0, x1, y0, y1 });
            })();
            const indices = [];
            for (const index of candidates) {
                const [sxs, sys] = this._ngon(index);
                if ((0, hittest_1.vertex_overlap)(sxs, sys, gsx, gsy)) {
                    indices.push(index);
                    continue;
                }
                if ((0, hittest_1.edge_intersection)(sxs, sys, gsx, gsy)) {
                    indices.push(index);
                    continue;
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const { sx0, sx1, sy0, sy1 } = geometry;
            const sxs = [sx0, sx1, sx1, sx0];
            const sys = [sy0, sy0, sy1, sy1];
            return this._hit_poly({ type: "poly", sx: sxs, sy: sys });
        }
    }
    exports.NgonView = NgonView;
    class Ngon extends radial_glyph_1.RadialGlyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = NgonView;
            this.define(() => ({
                angle: [p.AngleSpec, 0],
                n: [p.NumberSpec, { field: "n" }],
            }));
        }
    }
    exports.Ngon = Ngon;
},
/* models/glyphs/patches.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(306) /* ./glyph */;
    const utils_1 = require(310) /* ./utils */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const property_mixins_1 = require(95) /* ../../core/property_mixins */;
    const hittest = tslib_1.__importStar(require(311) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const selection_1 = require(144) /* ../selections/selection */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    class PatchesView extends glyph_1.GlyphView {
        async load_glglyph() {
            const { PatchesGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(675) /* ./webgl/patches */));
            return PatchesGL;
        }
        _project_data() {
            this._project_xy("xs", this.xs.data, "ys", this.ys.data);
        }
        _index_data(index) {
            const { data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const xsi = this.xs.get(i);
                const ysi = this.ys.get(i);
                const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(xsi, ysi);
                index.add_rect(x0, y0, x1, y1);
            }
        }
        _mask_data() {
            const { x_source, y_source } = this.renderer.coordinates;
            return this.index.indices({
                x0: x_source.min, x1: x_source.max,
                y0: y_source.min, y1: y_source.max,
            });
        }
        _paint(ctx, indices, data) {
            const { sxs, sys } = { ...this, ...data };
            for (const i of indices) {
                const sx_i = sxs.get(i);
                const sy_i = sys.get(i);
                let move = true;
                ctx.beginPath();
                const n = Math.min(sx_i.length, sy_i.length);
                for (let j = 0; j < n; j++) {
                    const sx_j = sx_i[j];
                    const sy_j = sy_i[j];
                    if (!isFinite(sx_j + sy_j)) {
                        ctx.closePath();
                        move = true;
                    }
                    else {
                        if (move) {
                            ctx.moveTo(sx_j, sy_j);
                            move = false;
                        }
                        else {
                            ctx.lineTo(sx_j, sy_j);
                        }
                    }
                }
                ctx.closePath();
                this.visuals.fill.apply(ctx, i, "evenodd");
                this.visuals.hatch.apply(ctx, i, "evenodd");
                this.visuals.line.apply(ctx, i);
            }
        }
        _hit_poly(geometry) {
            const { sx: sxs, sy: sys, greedy = false } = geometry;
            const candidates = (() => {
                const xs = this.renderer.xscale.v_invert(sxs);
                const ys = this.renderer.yscale.v_invert(sys);
                const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(xs, ys);
                return this.index.indices({ x0, x1, y0, y1 });
            })();
            const indices = [];
            for (const i of candidates) {
                const sxs_i = this.sxs.get(i);
                const sys_i = this.sys.get(i);
                const n = sxs_i.length;
                if (n == 0) {
                    continue;
                }
                let hit = !greedy;
                for (let j = 0; j < n; j++) {
                    const sx = sxs_i[j];
                    const sy = sys_i[j];
                    if (!hittest.point_in_poly(sx, sy, sxs, sys)) {
                        if (!greedy) {
                            hit = false;
                            break;
                        }
                    }
                    else {
                        if (greedy) {
                            hit = true;
                            break;
                        }
                    }
                }
                if (hit) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const { sx0, sx1, sy0, sy1, greedy } = geometry;
            const sxs = [sx0, sx1, sx1, sx0];
            const sys = [sy0, sy0, sy1, sy1];
            return this._hit_poly({ type: "poly", sx: sxs, sy: sys, greedy });
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            const candidates = this.index.indices({ x0: x, y0: y, x1: x, y1: y });
            const indices = [];
            for (const index of candidates) {
                const sxsi = this.sxs.get(index);
                const sysi = this.sys.get(index);
                // Collect NaN-separated sub-paths
                const sub_paths_sx = [];
                const sub_paths_sy = [];
                const n = sxsi.length;
                let k = 0;
                for (let j = 0; j <= n; j++) {
                    if (j == n || isNaN(sxsi[j])) {
                        if (j > k) {
                            sub_paths_sx.push(sxsi.subarray(k, j));
                            sub_paths_sy.push(sysi.subarray(k, j));
                        }
                        k = j + 1;
                    }
                }
                if (sub_paths_sx.length == 0) {
                    continue;
                }
                // Use "evenodd" fill rule (matches Canvas2D rendering):
                // A point is inside the filled region if it's contained by an odd number of sub-paths.
                // This handles both holes (even count = outside) and disjoint polygons (each adds to count).
                let inside_count = 0;
                for (let i = 0; i < sub_paths_sx.length; i++) {
                    if (hittest.point_in_poly(sx, sy, sub_paths_sx[i], sub_paths_sy[i])) {
                        inside_count++;
                    }
                }
                // Odd count = inside filled region, Even count = inside hole or outside
                if (inside_count % 2 === 1) {
                    indices.push(index);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _get_snap_coord(array) {
            return (0, arrayable_1.sum)(array) / array.length;
        }
        scenterxy(i, sx, sy) {
            const sxsi = this.sxs.get(i);
            const sysi = this.sys.get(i);
            const n = sxsi.length;
            let has_nan = false;
            for (let k = 0, j = 0;; j++) {
                const this_nan = isNaN(sxsi[j]);
                has_nan = has_nan || this_nan;
                if (j == n && !has_nan) {
                    const scx = this._get_snap_coord(sxsi);
                    const scy = this._get_snap_coord(sysi);
                    return [scx, scy];
                }
                if (this_nan || j == n) {
                    const sxsi_kj = sxsi.subarray(k, j);
                    const sysi_kj = sysi.subarray(k, j);
                    if (hittest.point_in_poly(sx, sy, sxsi_kj, sysi_kj)) {
                        const scx = this._get_snap_coord(sxsi_kj);
                        const scy = this._get_snap_coord(sysi_kj);
                        return [scx, scy];
                    }
                    k = j + 1;
                }
                if (j == n) {
                    break;
                }
            }
            (0, assert_1.unreachable)();
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.PatchesView = PatchesView;
    class Patches extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = PatchesView;
            this.define(({}) => ({
                xs: [p.XCoordinateSeqSpec, { field: "xs" }],
                ys: [p.YCoordinateSeqSpec, { field: "ys" }],
            }));
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        }
    }
    exports.Patches = Patches;
},
/* models/glyphs/quad.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const lrtb_1 = require(463) /* ./lrtb */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    class QuadView extends lrtb_1.LRTBView {
        scenterxy(i) {
            const scx = this.sleft[i] / 2 + this.sright[i] / 2;
            const scy = this.stop[i] / 2 + this.sbottom[i] / 2;
            return [scx, scy];
        }
        _lrtb(i) {
            const l = this.left[i];
            const r = this.right[i];
            const t = this.top[i];
            const b = this.bottom[i];
            return { l, r, t, b };
        }
    }
    exports.QuadView = QuadView;
    class Quad extends lrtb_1.LRTB {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = QuadView;
            this.define(({}) => ({
                right: [p.XCoordinateSpec, { field: "right" }],
                bottom: [p.YCoordinateSpec, { field: "bottom" }],
                left: [p.XCoordinateSpec, { field: "left" }],
                top: [p.YCoordinateSpec, { field: "top" }],
            }));
        }
    }
    exports.Quad = Quad;
},
/* models/glyphs/quadratic.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const property_mixins_1 = require(95) /* ../../core/property_mixins */;
    const glyph_1 = require(306) /* ./glyph */;
    const utils_1 = require(310) /* ./utils */;
    const algorithms_1 = require(461) /* ../../core/util/algorithms */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    class QuadraticView extends glyph_1.GlyphView {
        _project_data() {
            this._project_xy("x0", this.x0, "y0", this.y0);
            this._project_xy("x1", this.x1, "y1", this.y1);
        }
        _index_data(index) {
            const { x0, x1, y0, y1, cx, cy, data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const x0_i = x0[i];
                const x1_i = x1[i];
                const y0_i = y0[i];
                const y1_i = y1[i];
                const cx_i = cx[i];
                const cy_i = cy[i];
                if (!isFinite(x0_i + x1_i + y0_i + y1_i + cx_i + cy_i)) {
                    index.add_empty();
                }
                else {
                    const { x0, y0, x1, y1 } = (0, algorithms_1.qbb)(x0_i, y0_i, cx_i, cy_i, x1_i, y1_i);
                    index.add_rect(x0, y0, x1, y1);
                }
            }
        }
        _paint(ctx, indices, data) {
            if (!this.visuals.line.doit) {
                return;
            }
            const { sx0, sy0, sx1, sy1, scx, scy } = { ...this, ...data };
            for (const i of indices) {
                const sx0_i = sx0[i];
                const sy0_i = sy0[i];
                const sx1_i = sx1[i];
                const sy1_i = sy1[i];
                const scx_i = scx[i];
                const scy_i = scy[i];
                if (!isFinite(sx0_i + sy0_i + sx1_i + sy1_i + scx_i + scy_i)) {
                    continue;
                }
                ctx.beginPath();
                ctx.moveTo(sx0_i, sy0_i);
                ctx.quadraticCurveTo(scx_i, scy_i, sx1_i, sy1_i);
                this.visuals.line.apply(ctx, i);
            }
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
        scenterxy() {
            throw new Error(`${this}.scenterxy() is not implemented`);
        }
    }
    exports.QuadraticView = QuadraticView;
    class Quadratic extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = QuadraticView;
            this.define(({}) => ({
                x0: [p.XCoordinateSpec, { field: "x0" }],
                y0: [p.YCoordinateSpec, { field: "y0" }],
                x1: [p.XCoordinateSpec, { field: "x1" }],
                y1: [p.YCoordinateSpec, { field: "y1" }],
                cx: [p.XCoordinateSpec, { field: "cx" }],
                cy: [p.YCoordinateSpec, { field: "cy" }],
            }));
            this.mixins(property_mixins_1.LineVector);
        }
    }
    exports.Quadratic = Quadratic;
},
/* models/glyphs/ray.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(305) /* ./xy_glyph */;
    const glyph_1 = require(306) /* ./glyph */;
    const utils_1 = require(310) /* ./utils */;
    const property_mixins_1 = require(95) /* ../../core/property_mixins */;
    const types_1 = require(25) /* ../../core/types */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    class RayView extends xy_glyph_1.XYGlyphView {
        _map_data() {
            this._define_or_inherit_attr("slength", () => {
                if (this.model.properties.length.units == "data") {
                    if (this.inherited_x && this.inherited_length) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.xscale, this.x, this.length);
                    }
                }
                else {
                    return this.inherited_length ? glyph_1.inherit : (0, types_1.to_screen)(this.length);
                }
            });
            if (!this.inherited_slength) {
                const { width, height } = this.renderer.plot_view.frame.bbox;
                const inf_len = 2 * (width + height);
                const { slength } = this;
                const n = slength.length;
                for (let i = 0; i < n; i++) {
                    if (slength[i] == 0) {
                        slength[i] = inf_len;
                    }
                }
            }
        }
        _paint(ctx, indices, data) {
            if (!this.visuals.line.doit) {
                return;
            }
            const { sx, sy, slength, angle } = { ...this, ...data };
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const angle_i = angle.get(i);
                const slength_i = slength[i];
                if (!isFinite(sx_i + sy_i + angle_i + slength_i)) {
                    continue;
                }
                ctx.translate(sx_i, sy_i);
                ctx.rotate(angle_i);
                ctx.beginPath();
                ctx.moveTo(0, 0);
                ctx.lineTo(slength_i, 0);
                this.visuals.line.apply(ctx, i);
                ctx.rotate(-angle_i);
                ctx.translate(-sx_i, -sy_i);
            }
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.RayView = RayView;
    class Ray extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = RayView;
            this.mixins(property_mixins_1.LineVector);
            this.define(({}) => ({
                length: [p.DistanceSpec, 0],
                angle: [p.AngleSpec, 0],
            }));
        }
    }
    exports.Ray = Ray;
},
/* models/glyphs/rect.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const center_rotatable_1 = require(465) /* ./center_rotatable */;
    const utils_1 = require(310) /* ./utils */;
    const types_1 = require(25) /* ../../core/types */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const selection_1 = require(144) /* ../selections/selection */;
    const bbox_1 = require(62) /* ../../core/util/bbox */;
    const affine_1 = require(73) /* ../../core/util/affine */;
    const kinds_1 = require(124) /* ../common/kinds */;
    const resolve = tslib_1.__importStar(require(127) /* ../common/resolve */);
    const painting_1 = require(267) /* ../common/painting */;
    const { abs, sqrt } = Math;
    class RectView extends center_rotatable_1.CenterRotatableView {
        async load_glglyph() {
            const { RectGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(678) /* ./webgl/rect */));
            return RectGL;
        }
        _set_data(indices) {
            super._set_data(indices);
            this.border_radius = resolve.border_radius(this.model.border_radius);
        }
        _map_data() {
            const n = this.data_size;
            if (this.inherited_x && this.inherited_width) {
                this._inherit_attr("swidth");
                this._inherit_attr("sx0");
            }
            else {
                let swidth;
                let sx0;
                if (this.model.properties.width.units == "data") {
                    [swidth, sx0] = this._map_dist_corner_for_data_side_length(this.x, this.width, this.renderer.xscale);
                }
                else {
                    swidth = (0, types_1.to_screen)(this.width);
                    sx0 = new types_1.ScreenArray(n);
                    const { sx } = this;
                    for (let i = 0; i < n; i++) {
                        sx0[i] = sx[i] - swidth[i] / 2;
                    }
                }
                this._define_attr("swidth", swidth);
                this._define_attr("sx0", sx0);
            }
            if (this.inherited_y && this.inherited_height) {
                this._inherit_attr("sheight");
                this._inherit_attr("sy1");
            }
            else {
                let sheight;
                let sy1;
                if (this.model.properties.height.units == "data") {
                    [sheight, sy1] = this._map_dist_corner_for_data_side_length(this.y, this.height, this.renderer.yscale);
                }
                else {
                    sheight = (0, types_1.to_screen)(this.height);
                    sy1 = new types_1.ScreenArray(n);
                    const { sy } = this;
                    for (let i = 0; i < n; i++) {
                        sy1[i] = sy[i] - sheight[i] / 2;
                    }
                }
                this._define_attr("sheight", sheight);
                this._define_attr("sy1", sy1);
            }
            if (this.inherited_swidth && this.inherited_sheight) {
                this._inherit_attr("max_x2_ddist");
                this._inherit_attr("max_y2_ddist");
            }
            else {
                const { sx0, sy1, swidth, sheight } = this;
                const ssemi_diag = new types_1.ScreenArray(n);
                for (let i = 0; i < n; i++) {
                    const swidth_i = swidth[i];
                    const sheight_i = sheight[i];
                    ssemi_diag[i] = sqrt(swidth_i ** 2 + sheight_i ** 2) / 2;
                }
                const scenter_x = new types_1.ScreenArray(n);
                const scenter_y = new types_1.ScreenArray(n);
                for (let i = 0; i < n; i++) {
                    scenter_x[i] = sx0[i] + swidth[i] / 2;
                    scenter_y[i] = sy1[i] + sheight[i] / 2;
                }
                const max_x2_ddist = (0, arrayable_1.max)(this._ddist(0, scenter_x, ssemi_diag));
                const max_y2_ddist = (0, arrayable_1.max)(this._ddist(1, scenter_y, ssemi_diag));
                this._define_attr("max_x2_ddist", max_x2_ddist);
                this._define_attr("max_y2_ddist", max_y2_ddist);
            }
        }
        _paint(ctx, indices, data) {
            const { sx, sy, sx0, sy1, swidth, sheight, angle, border_radius } = { ...this, ...data };
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const sx0_i = sx0[i];
                const sy1_i = sy1[i];
                const swidth_i = swidth[i];
                const sheight_i = sheight[i];
                const angle_i = angle.get(i);
                if (!isFinite(sx_i + sy_i + sx0_i + sy1_i + swidth_i + sheight_i + angle_i)) {
                    continue;
                }
                if (swidth_i == 0 || sheight_i == 0) {
                    continue;
                }
                ctx.beginPath();
                if (angle_i != 0) {
                    ctx.translate(sx_i, sy_i);
                    ctx.rotate(angle_i);
                    const box = new bbox_1.BBox({ x: -swidth_i / 2, y: -sheight_i / 2, width: swidth_i, height: sheight_i });
                    (0, painting_1.round_rect)(ctx, box, border_radius);
                    ctx.rotate(-angle_i);
                    ctx.translate(-sx_i, -sy_i);
                }
                else {
                    const box = new bbox_1.BBox({ x: sx0_i, y: sy1_i, width: swidth_i, height: sheight_i });
                    (0, painting_1.round_rect)(ctx, box, border_radius);
                }
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _hit_rect(geometry) {
            return this._hit_rect_against_index(geometry);
        }
        _hit_point(geometry) {
            const hit_xy = { x: geometry.sx, y: geometry.sy };
            const x = this.renderer.xscale.invert(hit_xy.x);
            const y = this.renderer.yscale.invert(hit_xy.y);
            const candidates = this.index.indices({
                x0: x - this.max_x2_ddist,
                x1: x + this.max_x2_ddist,
                y0: y - this.max_y2_ddist,
                y1: y + this.max_y2_ddist,
            });
            const { sx, sy, sx0, sy1, swidth: sw, sheight: sh, angle } = this;
            const indices = [];
            for (const i of candidates) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const sx0_i = sx0[i];
                const sy1_i = sy1[i];
                const sw_i = sw[i];
                const sh_i = sh[i];
                const angle_i = angle.get(i);
                const hit_rxy = (0, affine_1.rotate_around)(hit_xy, { x: sx_i, y: sy_i }, -angle_i);
                const x = hit_rxy.x - sx0_i;
                const y = hit_rxy.y - sy1_i;
                // TODO: consider round corners
                if (0 <= x && x <= sw_i && 0 <= y && y <= sh_i) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _map_dist_corner_for_data_side_length(coord, side_length, scale) {
            const n = coord.length;
            const pt0 = new Float64Array(n);
            const pt1 = new Float64Array(n);
            for (let i = 0; i < n; i++) {
                const coord_i = coord[i];
                const half_side_length_i = side_length.get(i) / 2;
                pt0[i] = coord_i - half_side_length_i;
                pt1[i] = coord_i + half_side_length_i;
            }
            const spt0 = scale.v_compute(pt0);
            const spt1 = scale.v_compute(pt1);
            const sside_length = this.sdist(scale, pt0, side_length, "edge", this.model.dilate);
            let spt_corner = spt0;
            for (let i = 0; i < n; i++) {
                const spt0i = spt0[i];
                const spt1i = spt1[i];
                if (!isNaN(spt0i + spt1i) && spt0i != spt1i) {
                    spt_corner = spt0i < spt1i ? spt0 : spt1;
                    break;
                }
            }
            return [sside_length, spt_corner];
        }
        _ddist(dim, spts, spans) {
            const ArrayType = (0, types_1.infer_type)(spts, spans);
            const scale = dim == 0 ? this.renderer.xscale : this.renderer.yscale;
            const spt0 = spts;
            const m = spt0.length;
            const spt1 = new ArrayType(m);
            for (let i = 0; i < m; i++) {
                spt1[i] = spt0[i] + spans[i];
            }
            const pt0 = scale.v_invert(spt0);
            const pt1 = scale.v_invert(spt1);
            const n = pt0.length;
            const ddist = new ArrayType(n);
            for (let i = 0; i < n; i++) {
                ddist[i] = abs(pt1[i] - pt0[i]);
            }
            return ddist;
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.RectView = RectView;
    class Rect extends center_rotatable_1.CenterRotatable {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = RectView;
            this.define(({ Bool }) => ({
                border_radius: [kinds_1.BorderRadius, 0],
                dilate: [Bool, false],
            }));
        }
    }
    exports.Rect = Rect;
},
/* models/glyphs/scatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const marker_1 = require(487) /* ./marker */;
    const enums_1 = require(21) /* ../../core/enums */;
    const defs_1 = require(488) /* ./defs */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const u = tslib_1.__importStar(require(40) /* ../../core/uniforms */);
    const customjs_1 = require(423) /* ../callbacks/customjs */;
    const callbacks_1 = require(51) /* ../../core/util/callbacks */;
    const object_1 = require(9) /* ../../core/util/object */;
    function is_MarkerType(type) {
        return enums_1.MarkerType.valid(type);
    }
    class ScatterView extends marker_1.MarkerView {
        async load_glglyph() {
            const { MultiMarkerGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(676) /* ./webgl/multi_marker */));
            return MultiMarkerGL;
        }
        _compute_can_use_webgl() {
            return (0, object_1.is_empty)(this.model.defs) || u.every(this.marker, is_MarkerType);
        }
        async _update_defs() {
            for (const cb of (0, object_1.dict)(this.model.defs).values()) {
                if (cb instanceof customjs_1.CustomJS) {
                    await cb.compile();
                }
            }
        }
        connect_signals() {
            super.connect_signals();
            const { defs } = this.model.properties;
            this.on_change(defs, () => this._update_defs());
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._update_defs();
        }
        _paint(ctx, indices, data) {
            const { sx, sy, size, angle, marker } = { ...this, ...data };
            const defs = (0, object_1.dict)(this.model.defs);
            const { visuals } = this;
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const size_i = size.get(i);
                const angle_i = angle.get(i);
                const marker_i = marker.get(i);
                if (!isFinite(sx_i + sy_i + size_i + angle_i) || marker_i == null) {
                    continue;
                }
                ctx.beginPath();
                ctx.translate(sx_i, sy_i);
                if (angle_i != 0) {
                    ctx.rotate(angle_i);
                }
                const r = size_i / 2;
                if (is_MarkerType(marker_i)) {
                    defs_1.marker_funcs[marker_i](ctx, i, r, visuals);
                }
                else {
                    const fn = defs.get(marker_i);
                    if (fn != null) {
                        const path = (0, callbacks_1.execute_sync)(fn, this.model, { ctx, i, r, visuals });
                        if (path instanceof Path2D) {
                            this.visuals.fill.apply(ctx, i, path);
                            this.visuals.hatch.apply(ctx, i, path);
                            this.visuals.line.apply(ctx, i, path);
                        }
                    }
                }
                if (angle_i != 0) {
                    ctx.rotate(-angle_i);
                }
                ctx.translate(-sx_i, -sy_i);
            }
        }
        draw_legend_for_index(ctx, { x0, x1, y0, y1 }, index) {
            const n = index + 1;
            const marker = this.marker.get(index);
            const args = {
                ...this._get_legend_args({ x0, x1, y0, y1 }, index),
                marker: new p.UniformScalar(marker, n),
            };
            this._paint(ctx, [index], args);
        }
    }
    exports.ScatterView = ScatterView;
    class Scatter extends marker_1.Marker {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ScatterView;
            this.define(({ KeyVal, Or, Func, Ref }) => ({
                marker: [p.MarkerSpec, { value: "circle" }],
                defs: [KeyVal(p.ExtMarkerType, Or(Func(), Ref(customjs_1.CustomJS))), {}],
            }));
        }
    }
    exports.Scatter = Scatter;
},
/* models/glyphs/marker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(305) /* ./xy_glyph */;
    const property_mixins_1 = require(95) /* ../../core/property_mixins */;
    const hittest = tslib_1.__importStar(require(311) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const selection_1 = require(144) /* ../selections/selection */;
    class MarkerView extends xy_glyph_1.XYGlyphView {
        _render_one;
        _paint(ctx, indices, data) {
            const { sx, sy, size, angle } = { ...this, ...data };
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const size_i = size.get(i);
                const angle_i = angle.get(i);
                if (!isFinite(sx_i + sy_i + size_i + angle_i)) {
                    continue;
                }
                const r = size_i / 2;
                ctx.beginPath();
                ctx.translate(sx_i, sy_i);
                if (angle_i != 0) {
                    ctx.rotate(angle_i);
                }
                this._render_one(ctx, i, r, this.visuals);
                if (angle_i != 0) {
                    ctx.rotate(-angle_i);
                }
                ctx.translate(-sx_i, -sy_i);
            }
        }
        _mask_data() {
            // dilate the inner screen region by max_size and map back to data space for use in spatial query
            const { x_target, y_target } = this.renderer.plot_view.frame;
            const hr = x_target.widen(this.max_size).map((x) => this.renderer.xscale.invert(x));
            const vr = y_target.widen(this.max_size).map((y) => this.renderer.yscale.invert(y));
            return this.index.indices({
                x0: hr.start, x1: hr.end,
                y0: vr.start, y1: vr.end,
            });
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const { max_size } = this;
            const { hit_dilation } = this.model;
            const sx0 = sx - max_size * hit_dilation;
            const sx1 = sx + max_size * hit_dilation;
            const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
            const sy0 = sy - max_size * hit_dilation;
            const sy1 = sy + max_size * hit_dilation;
            const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            const candidates = this.index.indices({ x0, x1, y0, y1 });
            const indices = [];
            for (const i of candidates) {
                const s2 = this.size.get(i) / 2 * hit_dilation;
                if (Math.abs(this.sx[i] - sx) <= s2 && Math.abs(this.sy[i] - sy) <= s2) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const { sx, sy } = geometry;
            const bounds = this.bounds();
            const half_size = this.max_size / 2;
            const [x0, x1, y0, y1] = (() => {
                if (geometry.direction == "h") {
                    const { y0, y1 } = bounds;
                    const sx0 = sx - half_size;
                    const sx1 = sx + half_size;
                    const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
                    return [x0, x1, y0, y1];
                }
                else {
                    const { x0, x1 } = bounds;
                    const sy0 = sy - half_size;
                    const sy1 = sy + half_size;
                    const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
                    return [x0, x1, y0, y1];
                }
            })();
            const indices = [...this.index.indices({ x0, x1, y0, y1 })];
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const { sx0, sx1, sy0, sy1 } = geometry;
            const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
            const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            const indices = this.index.indices({ x0, x1, y0, y1 }).ones();
            return new selection_1.Selection({ indices });
        }
        _hit_poly(geometry) {
            const { sx: sxs, sy: sys } = geometry;
            const candidates = (() => {
                const xs = this.renderer.xscale.v_invert(sxs);
                const ys = this.renderer.yscale.v_invert(sys);
                const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(xs, ys);
                return this.index.indices({ x0, x1, y0, y1 });
            })();
            const indices = [];
            for (const i of candidates) {
                if (hittest.point_in_poly(this.sx[i], this.sy[i], sxs, sys)) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _get_legend_args({ x0, x1, y0, y1 }, index) {
            // using objects like this seems a little wonky, since the keys are coerced to strings, but it works
            const n = index + 1;
            const sx = new Array(n);
            const sy = new Array(n);
            sx[index] = (x0 + x1) / 2;
            sy[index] = (y0 + y1) / 2;
            const vsize = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.4;
            const size = new p.UniformScalar(vsize, n);
            const angle = new p.UniformScalar(0, n); // don't attempt to match glyph angle
            return { sx, sy, size, angle };
        }
        draw_legend_for_index(ctx, { x0, x1, y0, y1 }, index) {
            const args = this._get_legend_args({ x0, x1, y0, y1 }, index);
            this._paint(ctx, [index], args);
        }
    }
    exports.MarkerView = MarkerView;
    class Marker extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
            this.define(({ Float }) => ({
                size: [p.ScreenSizeSpec, { value: 4 }],
                angle: [p.AngleSpec, 0],
                hit_dilation: [Float, 1.0],
            }));
        }
    }
    exports.Marker = Marker;
},
/* models/glyphs/defs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const SQ3 = Math.sqrt(3);
    const SQ5 = Math.sqrt(5);
    const c36 = (SQ5 + 1) / 4;
    const s36 = Math.sqrt((5 - SQ5) / 8);
    const c72 = (SQ5 - 1) / 4;
    const s72 = Math.sqrt((5 + SQ5) / 8);
    function _one_line(ctx, r) {
        ctx.moveTo(-r, 0);
        ctx.lineTo(r, 0);
    }
    function _one_x(ctx, r) {
        ctx.rotate(Math.PI / 4);
        _one_cross(ctx, r);
        ctx.rotate(-Math.PI / 4);
    }
    function _one_y(ctx, r) {
        const h = r * SQ3;
        const a = h / 3;
        ctx.moveTo(-h / 2, -a);
        ctx.lineTo(0, 0);
        ctx.lineTo(h / 2, -a);
        ctx.lineTo(0, 0);
        ctx.lineTo(0, r);
    }
    function _one_cross(ctx, r) {
        ctx.moveTo(0, r);
        ctx.lineTo(0, -r);
        ctx.moveTo(-r, 0);
        ctx.lineTo(r, 0);
    }
    function _one_dot(ctx, r) {
        ctx.beginPath();
        ctx.arc(0, 0, r / 4, 0, 2 * Math.PI, false);
        ctx.closePath();
    }
    function _one_diamond(ctx, r) {
        ctx.moveTo(0, r);
        ctx.lineTo(r / 1.5, 0);
        ctx.lineTo(0, -r);
        ctx.lineTo(-r / 1.5, 0);
        ctx.closePath();
    }
    function _one_hex(ctx, r) {
        const r2 = r / 2;
        const h = SQ3 * r2;
        ctx.moveTo(r, 0);
        ctx.lineTo(r2, -h);
        ctx.lineTo(-r2, -h);
        ctx.lineTo(-r, 0);
        ctx.lineTo(-r2, h);
        ctx.lineTo(r2, h);
        ctx.closePath();
    }
    function _one_star(ctx, r) {
        const a = Math.sqrt(5 - 2 * SQ5) * r;
        ctx.moveTo(0, -r);
        ctx.lineTo(a * c72, -r + a * s72);
        ctx.lineTo(a * (1 + c72), -r + a * s72);
        ctx.lineTo(a * (1 + c72 - c36), -r + a * (s72 + s36));
        ctx.lineTo(a * (1 + 2 * c72 - c36), -r + a * (2 * s72 + s36));
        ctx.lineTo(0, -r + a * 2 * s72);
        ctx.lineTo(-a * (1 + 2 * c72 - c36), -r + a * (2 * s72 + s36));
        ctx.lineTo(-a * (1 + c72 - c36), -r + a * (s72 + s36));
        ctx.lineTo(-a * (1 + c72), -r + a * s72);
        ctx.lineTo(-a * c72, -r + a * s72);
        ctx.closePath();
    }
    function _one_tri(ctx, r) {
        const h = r * SQ3;
        const a = h / 3;
        ctx.moveTo(-r, a);
        ctx.lineTo(r, a);
        ctx.lineTo(0, a - h);
        ctx.closePath();
    }
    function asterisk(ctx, i, r, visuals) {
        _one_cross(ctx, r);
        _one_x(ctx, r);
        visuals.line.apply(ctx, i);
    }
    function circle(ctx, i, r, visuals) {
        ctx.arc(0, 0, r, 0, 2 * Math.PI, false);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function circle_cross(ctx, i, r, visuals) {
        ctx.arc(0, 0, r, 0, 2 * Math.PI, false);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        _one_cross(ctx, r);
        visuals.line.apply(ctx, i);
    }
    function circle_dot(ctx, i, r, visuals) {
        circle(ctx, i, r, visuals);
        dot(ctx, i, r, visuals);
    }
    function circle_y(ctx, i, r, visuals) {
        ctx.arc(0, 0, r, 0, 2 * Math.PI, false);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        _one_y(ctx, r);
        visuals.line.apply(ctx, i);
    }
    function circle_x(ctx, i, r, visuals) {
        ctx.arc(0, 0, r, 0, 2 * Math.PI, false);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        _one_x(ctx, r);
        visuals.line.apply(ctx, i);
    }
    function cross(ctx, i, r, visuals) {
        _one_cross(ctx, r);
        visuals.line.apply(ctx, i);
    }
    function diamond(ctx, i, r, visuals) {
        _one_diamond(ctx, r);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function diamond_cross(ctx, i, r, visuals) {
        _one_diamond(ctx, r);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        ctx.moveTo(0, r);
        ctx.lineTo(0, -r);
        ctx.moveTo(-r / 1.5, 0);
        ctx.lineTo(r / 1.5, 0);
        visuals.line.apply(ctx, i);
    }
    function diamond_dot(ctx, i, r, visuals) {
        diamond(ctx, i, r, visuals);
        dot(ctx, i, r, visuals);
    }
    function dot(ctx, i, r, visuals) {
        _one_dot(ctx, r);
        visuals.line.set_vectorize(ctx, i);
        ctx.fillStyle = ctx.strokeStyle; // NOTE: dots use line color for fill to match
        ctx.fill();
    }
    function hex(ctx, i, r, visuals) {
        _one_hex(ctx, r);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function hex_dot(ctx, i, r, visuals) {
        hex(ctx, i, r, visuals);
        dot(ctx, i, r, visuals);
    }
    function inverted_triangle(ctx, i, r, visuals) {
        ctx.rotate(Math.PI);
        _one_tri(ctx, r);
        ctx.rotate(-Math.PI);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function plus(ctx, i, r, visuals) {
        const a = 3 * r / 8;
        const b = r;
        const xs = [a, a, b, b, a, a, -a, -a, -b, -b, -a, -a];
        const ys = [b, a, a, -a, -a, -b, -b, -a, -a, a, a, b];
        ctx.beginPath();
        for (let j = 0; j < 12; j++) {
            ctx.lineTo(xs[j], ys[j]);
        }
        ctx.closePath();
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function square(ctx, i, r, visuals) {
        const size = 2 * r;
        ctx.rect(-r, -r, size, size);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function square_pin(ctx, i, r, visuals) {
        const a = 3 * r / 8;
        ctx.moveTo(-r, -r);
        /* eslint-disable @stylistic/space-in-parens */
        ctx.quadraticCurveTo(0, -a, r, -r);
        ctx.quadraticCurveTo(a, 0, r, r);
        ctx.quadraticCurveTo(0, a, -r, r);
        ctx.quadraticCurveTo(-a, 0, -r, -r);
        /* eslint-enable @stylistic/space-in-parens */
        ctx.closePath();
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function square_cross(ctx, i, r, visuals) {
        const size = 2 * r;
        ctx.rect(-r, -r, size, size);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        _one_cross(ctx, r);
        visuals.line.apply(ctx, i);
    }
    function square_dot(ctx, i, r, visuals) {
        square(ctx, i, r, visuals);
        dot(ctx, i, r, visuals);
    }
    function square_x(ctx, i, r, visuals) {
        const size = 2 * r;
        ctx.rect(-r, -r, size, size);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        ctx.moveTo(-r, r);
        ctx.lineTo(r, -r);
        ctx.moveTo(-r, -r);
        ctx.lineTo(r, r);
        visuals.line.apply(ctx, i);
    }
    function star(ctx, i, r, visuals) {
        _one_star(ctx, r);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function star_dot(ctx, i, r, visuals) {
        star(ctx, i, r, visuals);
        dot(ctx, i, r, visuals);
    }
    function triangle(ctx, i, r, visuals) {
        _one_tri(ctx, r);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function triangle_dot(ctx, i, r, visuals) {
        triangle(ctx, i, r, visuals);
        dot(ctx, i, r, visuals);
    }
    function triangle_pin(ctx, i, r, visuals) {
        const h = r * SQ3;
        const a = h / 3;
        const b = 3 * a / 8;
        ctx.moveTo(-r, a);
        ctx.quadraticCurveTo(0, b, r, a);
        ctx.quadraticCurveTo(SQ3 * b / 2, b / 2, 0, a - h);
        ctx.quadraticCurveTo(-SQ3 * b / 2, b / 2, -r, a);
        ctx.closePath();
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function dash(ctx, i, r, visuals) {
        _one_line(ctx, r);
        visuals.line.apply(ctx, i);
    }
    function x(ctx, i, r, visuals) {
        _one_x(ctx, r);
        visuals.line.apply(ctx, i);
    }
    function y(ctx, i, r, visuals) {
        _one_y(ctx, r);
        visuals.line.apply(ctx, i);
    }
    exports.marker_funcs = {
        asterisk,
        circle,
        circle_cross,
        circle_dot,
        circle_y,
        circle_x,
        cross,
        diamond,
        diamond_dot,
        diamond_cross,
        dot,
        hex,
        hex_dot,
        inverted_triangle,
        plus,
        square,
        square_cross,
        square_dot,
        square_pin,
        square_x,
        star,
        star_dot,
        triangle,
        triangle_dot,
        triangle_pin,
        dash,
        x,
        y,
    };
},
/* models/glyphs/segment.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const hittest = tslib_1.__importStar(require(311) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const property_mixins_1 = require(95) /* ../../core/property_mixins */;
    const math_1 = require(12) /* ../../core/util/math */;
    const glyph_1 = require(306) /* ./glyph */;
    const utils_1 = require(310) /* ./utils */;
    const selection_1 = require(144) /* ../selections/selection */;
    class SegmentView extends glyph_1.GlyphView {
        _project_data() {
            this._project_xy("x0", this.x0, "y0", this.y0);
            this._project_xy("x1", this.x1, "y1", this.y1);
        }
        _index_data(index) {
            const { min, max } = Math;
            const { x0, x1, y0, y1, data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const x0_i = x0[i];
                const x1_i = x1[i];
                const y0_i = y0[i];
                const y1_i = y1[i];
                index.add_rect(min(x0_i, x1_i), min(y0_i, y1_i), max(x0_i, x1_i), max(y0_i, y1_i));
            }
        }
        _paint(ctx, indices, data) {
            if (!this.visuals.line.doit) {
                return;
            }
            const { sx0, sy0, sx1, sy1 } = { ...this, ...data };
            for (const i of indices) {
                const sx0_i = sx0[i];
                const sy0_i = sy0[i];
                const sx1_i = sx1[i];
                const sy1_i = sy1[i];
                if (!isFinite(sx0_i + sy0_i + sx1_i + sy1_i)) {
                    continue;
                }
                this._render_decorations(ctx, i, sx0_i, sy0_i, sx1_i, sy1_i);
                ctx.beginPath();
                ctx.moveTo(sx0_i, sy0_i);
                ctx.lineTo(sx1_i, sy1_i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _render_decorations(ctx, i, sx0, sy0, sx1, sy1) {
            const { PI } = Math;
            const angle = (0, math_1.atan2)([sx0, sy0], [sx1, sy1]) + PI / 2;
            for (const decoration of this.decorations.values()) {
                ctx.save();
                if (decoration.model.node == "start") {
                    ctx.translate(sx0, sy0);
                    ctx.rotate(angle + PI);
                }
                else if (decoration.model.node == "end") {
                    ctx.translate(sx1, sy1);
                    ctx.rotate(angle);
                }
                decoration.marking.paint(ctx, i);
                ctx.restore();
            }
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const point = { x: sx, y: sy };
            const lw_voffset = 2; // FIXME: Use maximum of segments line_width/2 instead of magic constant 2
            const [x0, x1] = this.renderer.xscale.r_invert(sx - lw_voffset, sx + lw_voffset);
            const [y0, y1] = this.renderer.yscale.r_invert(sy - lw_voffset, sy + lw_voffset);
            const candidates = this.index.indices({ x0, y0, x1, y1 });
            const indices = [];
            for (const i of candidates) {
                const threshold2 = Math.max(2, this.line_width.get(i) / 2) ** 2;
                const p0 = { x: this.sx0[i], y: this.sy0[i] };
                const p1 = { x: this.sx1[i], y: this.sy1[i] };
                const dist2 = hittest.dist_to_segment_squared(point, p0, p1);
                if (dist2 < threshold2) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const [hr, vr] = this.renderer.plot_view.frame.bbox.ranges;
            const { sx, sy } = geometry;
            let v0;
            let v1;
            let val;
            if (geometry.direction == "v") {
                val = this.renderer.yscale.invert(sy);
                [v0, v1] = [this.y0, this.y1];
            }
            else {
                val = this.renderer.xscale.invert(sx);
                [v0, v1] = [this.x0, this.x1];
            }
            const indices = [];
            const [x0, x1] = this.renderer.xscale.r_invert(hr.start, hr.end);
            const [y0, y1] = this.renderer.yscale.r_invert(vr.start, vr.end);
            const candidates = this.index.indices({ x0, y0, x1, y1 });
            for (const i of candidates) {
                if ((v0[i] <= val && val <= v1[i]) || (v1[i] <= val && val <= v0[i])) {
                    indices.push(i);
                }
                const threshold = 1.5 + (this.line_width.get(i) / 2); // Maximum pixel difference to detect hit
                if (v0[i] == v1[i]) {
                    if (geometry.direction == "h") {
                        if (Math.abs(this.sx0[i] - sx) <= threshold) {
                            indices.push(i);
                        }
                    }
                    else {
                        if (Math.abs(this.sy0[i] - sy) <= threshold) {
                            indices.push(i);
                        }
                    }
                }
            }
            return new selection_1.Selection({ indices });
        }
        scenterxy(i) {
            const scx = this.sx0[i] / 2 + this.sx1[i] / 2;
            const scy = this.sy0[i] / 2 + this.sy1[i] / 2;
            return [scx, scy];
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.SegmentView = SegmentView;
    class Segment extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = SegmentView;
            this.define(({}) => ({
                x0: [p.XCoordinateSpec, { field: "x0" }],
                y0: [p.YCoordinateSpec, { field: "y0" }],
                x1: [p.XCoordinateSpec, { field: "x1" }],
                y1: [p.YCoordinateSpec, { field: "y1" }],
            }));
            this.mixins(property_mixins_1.LineVector);
        }
    }
    exports.Segment = Segment;
},
/* models/glyphs/spline.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(305) /* ./xy_glyph */;
    const mixins = tslib_1.__importStar(require(95) /* ../../core/property_mixins */);
    const interpolation_1 = require(491) /* ../../core/util/interpolation */;
    class SplineView extends xy_glyph_1.XYGlyphView {
        _set_data() {
            const { tension, closed } = this.model;
            const [xt, yt] = (0, interpolation_1.catmullrom_spline)(this.x, this.y, 20, tension, closed);
            this._define_attr("xt", xt);
            this._define_attr("yt", yt);
        }
        _map_data() {
            const { x_scale, y_scale } = this.renderer.coordinates;
            const sxt = x_scale.v_compute(this.xt);
            const syt = y_scale.v_compute(this.yt);
            this._define_attr("sxt", sxt);
            this._define_attr("syt", syt);
        }
        _paint(ctx, _indices, data) {
            const { sxt, syt } = { ...this, ...data };
            let move = true;
            ctx.beginPath();
            const n = sxt.length;
            for (let j = 0; j < n; j++) {
                const sx_i = sxt[j];
                const sy_i = syt[j];
                if (!isFinite(sx_i + sy_i)) {
                    move = true;
                }
                else {
                    if (move) {
                        ctx.moveTo(sx_i, sy_i);
                        move = false;
                    }
                    else {
                        ctx.lineTo(sx_i, sy_i);
                    }
                }
            }
            this.visuals.line.set_value(ctx);
            ctx.stroke();
        }
    }
    exports.SplineView = SplineView;
    class Spline extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = SplineView;
            this.mixins(mixins.LineScalar);
            this.define(({ Bool, Float }) => ({
                tension: [Float, 0.5],
                closed: [Bool, false],
            }));
        }
    }
    exports.Spline = Spline;
},
/* core/util/interpolation.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.catmullrom_spline = catmullrom_spline;
    const types_1 = require(25) /* ../types */;
    const assert_1 = require(13) /* ./assert */;
    function catmullrom_spline(x, y, T = 10, tension = 0.5, closed = false) {
        /** Centripetal Catmull-Rom spline. */
        (0, assert_1.assert)(x.length == y.length);
        const n = x.length;
        const N = closed ? n + 1 : n;
        const ArrayType = (0, types_1.infer_type)(x, y);
        const xx = new ArrayType(N + 2);
        const yy = new ArrayType(N + 2);
        xx.set(x, 1);
        yy.set(y, 1);
        if (closed) {
            xx[0] = x[n - 1];
            yy[0] = y[n - 1];
            xx[N] = x[0];
            yy[N] = y[0];
            xx[N + 1] = x[1];
            yy[N + 1] = y[1];
        }
        else {
            xx[0] = x[0];
            yy[0] = y[0];
            xx[N + 1] = x[n - 1];
            yy[N + 1] = y[n - 1];
        }
        const basis = new ArrayType(4 * (T + 1));
        for (let j = 0, k = 0; j <= T; j++) {
            const t = j / T;
            const t_2 = t ** 2;
            const t_3 = t * t_2;
            basis[k++] = 2 * t_3 - 3 * t_2 + 1; // h00
            basis[k++] = -2 * t_3 + 3 * t_2; // h01
            basis[k++] = t_3 - 2 * t_2 + t; // h10
            basis[k++] = t_3 - t_2; // h11
        }
        const xt = new ArrayType((N - 1) * (T + 1));
        const yt = new ArrayType((N - 1) * (T + 1));
        for (let i = 1, k = 0; i < N; i++) {
            const t0x = (xx[i + 1] - xx[i - 1]) * tension;
            const t0y = (yy[i + 1] - yy[i - 1]) * tension;
            const t1x = (xx[i + 2] - xx[i]) * tension;
            const t1y = (yy[i + 2] - yy[i]) * tension;
            for (let j = 0; j <= 4 * T; k++) {
                const h00 = basis[j++];
                const h01 = basis[j++];
                const h10 = basis[j++];
                const h11 = basis[j++];
                xt[k] = h00 * xx[i] + h01 * xx[i + 1] + h10 * t0x + h11 * t1x;
                yt[k] = h00 * yy[i] + h01 * yy[i + 1] + h10 * t0y + h11 * t1y;
            }
        }
        return [xt, yt];
    }
},
/* models/glyphs/tex_glyph.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const math_text_glyph_1 = require(476) /* ./math_text_glyph */;
    const math_text_1 = require(260) /* ../text/math_text */;
    const kinds_1 = require(22) /* ../../core/kinds */;
    const utils_1 = require(259) /* ../text/utils */;
    exports.DisplayMode = (0, kinds_1.Or)((0, kinds_1.Enum)("inline", "block"), kinds_1.Auto);
    class TeXGlyphView extends math_text_glyph_1.MathTextGlyphView {
        _build_label(text) {
            const { macros, display } = this.model;
            if (display == "auto") {
                const obj = (0, utils_1.parse_delimited_string)(text);
                if (obj instanceof math_text_1.TeX) {
                    obj.macros = macros;
                }
                return obj;
            }
            else {
                return new math_text_1.TeX({ text, macros, inline: display == "inline" });
            }
        }
    }
    exports.TeXGlyphView = TeXGlyphView;
    class TeXGlyph extends math_text_glyph_1.MathTextGlyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = TeXGlyphView;
            this.define(({ Float, Str, Dict, Tuple, Or }) => ({
                macros: [Dict(Or(Str, Tuple(Str, Float))), {}],
                display: [exports.DisplayMode, "auto"],
            }));
        }
    }
    exports.TeXGlyph = TeXGlyph;
},
/* models/glyphs/vbar.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const lrtb_1 = require(463) /* ./lrtb */;
    const types_1 = require(25) /* ../../core/types */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    class VBarView extends lrtb_1.LRTBView {
        scenterxy(i) {
            const scx = this.sx[i];
            const scy = (this.stop[i] + this.sbottom[i]) / 2;
            return [scx, scy];
        }
        _lrtb(i) {
            const half_width_i = this.width.get(i) / 2;
            const x_i = this.x[i];
            const top_i = this.top[i];
            const bottom_i = this.bottom[i];
            const l = x_i - half_width_i;
            const r = x_i + half_width_i;
            const t = Math.max(top_i, bottom_i);
            const b = Math.min(top_i, bottom_i);
            return { l, r, t, b };
        }
        _map_data() {
            if (this.inherited_x && this.inherited_width) {
                this._inherit_attr("swidth");
                this._inherit_attr("sleft");
                this._inherit_attr("sright");
            }
            else {
                const swidth = this.sdist(this.renderer.xscale, this.x, this.width, "center");
                const { sx } = this;
                const n = sx.length;
                const sleft = new types_1.ScreenArray(n);
                const sright = new types_1.ScreenArray(n);
                for (let i = 0; i < n; i++) {
                    const sx_i = sx[i];
                    const swidth_i = swidth[i];
                    sleft[i] = sx_i - swidth_i / 2;
                    sright[i] = sx_i + swidth_i / 2;
                }
                this._define_attr("swidth", swidth);
                this._define_attr("sleft", sleft);
                this._define_attr("sright", sright);
            }
            this._clamp_to_viewport();
        }
    }
    exports.VBarView = VBarView;
    class VBar extends lrtb_1.LRTB {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = VBarView;
            this.define(({}) => ({
                x: [p.XCoordinateSpec, { field: "x" }],
                bottom: [p.YCoordinateSpec, { value: 0 }],
                width: [p.DistanceSpec, { value: 1 }],
                top: [p.YCoordinateSpec, { field: "top" }],
            }));
        }
    }
    exports.VBar = VBar;
},
/* models/glyphs/vspan.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(306) /* ./glyph */;
    const utils_1 = require(310) /* ./utils */;
    const selection_1 = require(144) /* ../selections/selection */;
    const property_mixins_1 = require(95) /* ../../core/property_mixins */;
    const uniforms = tslib_1.__importStar(require(40) /* ../../core/uniforms */);
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const array_1 = require(10) /* ../../core/util/array */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const { abs, max } = Math;
    const UNUSED = 0;
    class VSpanView extends glyph_1.GlyphView {
        after_visuals() {
            super.after_visuals();
            this.max_line_width = uniforms.max(this.line_width);
        }
        _index_data(index) {
            for (const x_i of this.x) {
                index.add_point(x_i, UNUSED);
            }
        }
        _bounds(bounds) {
            const { x0, x1 } = bounds;
            return { x0, x1, y0: NaN, y1: NaN };
        }
        _map_data() {
            super._map_data();
            const { round } = Math;
            if (!this.inherited_sx) {
                const sx = (0, arrayable_1.map)(this.sx, (xi) => round(xi));
                this._define_attr("sx", sx);
            }
        }
        scenterxy(i) {
            const { vcenter } = this.renderer.plot_view.frame.bbox;
            return [this.sx[i], vcenter];
        }
        _paint(ctx, indices, data) {
            const { sx } = { ...this, ...data };
            const { top, bottom } = this.renderer.plot_view.frame.bbox;
            for (const i of indices) {
                const sx_i = sx[i];
                if (!isFinite(sx_i)) {
                    continue;
                }
                ctx.beginPath();
                ctx.moveTo(sx_i, top);
                ctx.lineTo(sx_i, bottom);
                this.visuals.line.apply(ctx, i);
            }
        }
        _get_candidates(sx0, sx1) {
            const { max_line_width } = this;
            const [x0, x1] = this.renderer.xscale.r_invert(sx0 - max_line_width, (sx1 ?? sx0) + max_line_width);
            return this.index.indices({ x0, x1, y0: 0, y1: 0 });
        }
        _find_spans(candidates, fn) {
            const { sx, line_width } = this;
            const indices = [];
            for (const i of candidates) {
                const sx_i = sx[i];
                const line_width_i = line_width.get(i);
                if (fn(sx_i, line_width_i)) {
                    indices.push(i);
                }
            }
            return indices;
        }
        _hit_point(geometry) {
            const { sx: gsx } = geometry;
            const candidates = this._get_candidates(gsx);
            const indices = this._find_spans(candidates, (sx, line_width) => {
                return abs(sx - gsx) <= max(line_width, 2 /*px*/);
            });
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const indices = (() => {
                if (geometry.direction == "h") {
                    return (0, array_1.range)(0, this.data_size);
                }
                else {
                    const { sx: gsx } = geometry;
                    const candidates = this._get_candidates(gsx);
                    return this._find_spans(candidates, (sx, line_width) => {
                        return abs(sx - gsx) <= max(line_width / 2, 2 /*px*/);
                    });
                }
            })();
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const indices = (() => {
                const { sx0: gsx0, sx1: gsx1 } = geometry;
                const candidates = this._get_candidates(gsx0, gsx1);
                return this._find_spans(candidates, (sx, line_width) => {
                    return gsx0 - line_width / 2 <= sx && sx <= gsx1 + line_width / 2;
                });
            })();
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.VSpanView = VSpanView;
    class VSpan extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = VSpanView;
            this.mixins([property_mixins_1.LineVector]);
            this.define(() => ({
                x: [p.XCoordinateSpec, { field: "x" }],
            }));
        }
    }
    exports.VSpan = VSpan;
},
/* models/glyphs/vstrip.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(306) /* ./glyph */;
    const utils_1 = require(310) /* ./utils */;
    const selection_1 = require(144) /* ../selections/selection */;
    const property_mixins_1 = require(95) /* ../../core/property_mixins */;
    const types_1 = require(25) /* ../../core/types */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const iter = tslib_1.__importStar(require(15) /* ../../core/util/iterator */);
    const array_1 = require(10) /* ../../core/util/array */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const UNUSED = 0;
    class VStripView extends glyph_1.GlyphView {
        async lazy_initialize() {
            await super.lazy_initialize();
            const { webgl } = this.renderer.plot_view.canvas_view;
            if (webgl != null && webgl.regl_wrapper.has_webgl) {
                const { LRTBGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(670) /* ./webgl/lrtb */));
                this.glglyph = new LRTBGL(webgl.regl_wrapper, this);
            }
        }
        get sleft() {
            return this.sx0;
        }
        get sright() {
            return this.sx1;
        }
        get stop() {
            const { top } = this.renderer.plot_view.frame.bbox;
            const n = this.data_size;
            const stop = new types_1.ScreenArray(n);
            stop.fill(top);
            return stop;
        }
        get sbottom() {
            const { bottom } = this.renderer.plot_view.frame.bbox;
            const n = this.data_size;
            const sbottom = new types_1.ScreenArray(n);
            sbottom.fill(bottom);
            return sbottom;
        }
        _set_data(indices) {
            super._set_data(indices);
            const { abs } = Math;
            const { max, map, zip } = iter;
            const { x0, x1 } = this;
            if (this.inherited_x0 && this.inherited_x1) {
                this._inherit_attr("max_width");
            }
            else {
                const max_width = max(map(zip(x0, x1), ([x0_i, x1_i]) => abs(x0_i - x1_i)));
                this._define_attr("max_width", max_width);
            }
        }
        _index_data(index) {
            const { x0, x1, data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const x0_i = x0[i];
                const x1_i = x1[i];
                index.add_rect(x0_i, UNUSED, x1_i, UNUSED);
            }
        }
        _bounds(bounds) {
            const { x0, x1 } = bounds;
            return { x0, x1, y0: NaN, y1: NaN };
        }
        _map_data() {
            super._map_data();
            const { round } = Math;
            if (!this.inherited_sx0) {
                const sx0 = (0, arrayable_1.map)(this.sx0, (xi) => round(xi));
                this._define_attr("sx0", sx0);
            }
            if (!this.inherited_sx1) {
                const sx1 = (0, arrayable_1.map)(this.sx1, (xi) => round(xi));
                this._define_attr("sx1", sx1);
            }
        }
        scenterxy(i) {
            const { vcenter } = this.renderer.plot_view.frame.bbox;
            return [(this.sx0[i] + this.sx1[i]) / 2, vcenter];
        }
        _paint(ctx, indices, data) {
            const { sx0, sx1 } = { ...this, ...data };
            const { top, bottom, height } = this.renderer.plot_view.frame.bbox;
            for (const i of indices) {
                const sx0_i = sx0[i];
                const sx1_i = sx1[i];
                if (!isFinite(sx0_i + sx1_i)) {
                    continue;
                }
                ctx.beginPath();
                ctx.rect(sx0_i, top, sx1_i - sx0_i, height);
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                ctx.beginPath();
                ctx.moveTo(sx0_i, top);
                ctx.lineTo(sx0_i, bottom);
                ctx.moveTo(sx1_i, top);
                ctx.lineTo(sx1_i, bottom);
                this.visuals.line.apply(ctx, i);
            }
        }
        _get_candidates(sx0, sx1) {
            const { max_width } = this;
            const [dx0, dx1] = this.renderer.xscale.r_invert(sx0, sx1 ?? sx0);
            const x0 = dx0 - max_width;
            const x1 = dx1 + max_width;
            return this.index.indices({ x0, x1, y0: 0, y1: 0 });
        }
        _find_strips(candidates, fn) {
            function contains(sx0, sx1) {
                return sx0 <= sx1 ? fn(sx0, sx1) : fn(sx1, sx0);
            }
            const { sx0, sx1 } = this;
            const indices = [];
            for (const i of candidates) {
                const sx0_i = sx0[i];
                const sx1_i = sx1[i];
                if (contains(sx0_i, sx1_i)) {
                    indices.push(i);
                }
            }
            return indices;
        }
        _hit_point(geometry) {
            const { sx } = geometry;
            const candidates = this._get_candidates(sx);
            const indices = this._find_strips(candidates, (sx0, sx1) => sx0 <= sx && sx <= sx1);
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const indices = (() => {
                if (geometry.direction == "h") {
                    return (0, array_1.range)(0, this.data_size);
                }
                else {
                    const { sx } = geometry;
                    const candidates = this._get_candidates(sx);
                    return this._find_strips(candidates, (sx0, sx1) => sx0 <= sx && sx <= sx1);
                }
            })();
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const indices = (() => {
                const { sx0: gsx0, sx1: gsx1 } = geometry;
                const candidates = this._get_candidates(gsx0, gsx1);
                return this._find_strips(candidates, (sx0, sx1) => {
                    return gsx0 <= sx0 && sx0 <= gsx1 && gsx0 <= sx1 && sx1 <= gsx1;
                });
            })();
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.VStripView = VStripView;
    class VStrip extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = VStripView;
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
            this.define(() => ({
                x0: [p.XCoordinateSpec, { field: "x0" }],
                x1: [p.XCoordinateSpec, { field: "x1" }],
            }));
        }
    }
    exports.VStrip = VStrip;
},
/* models/glyphs/wedge.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(305) /* ./xy_glyph */;
    const glyph_1 = require(306) /* ./glyph */;
    const utils_1 = require(310) /* ./utils */;
    const property_mixins_1 = require(95) /* ../../core/property_mixins */;
    const types_1 = require(25) /* ../../core/types */;
    const enums_1 = require(21) /* ../../core/enums */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const math_1 = require(12) /* ../../core/util/math */;
    const selection_1 = require(144) /* ../selections/selection */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    class WedgeView extends xy_glyph_1.XYGlyphView {
        async load_glglyph() {
            const { WedgeGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(680) /* ./webgl/wedge */));
            return WedgeGL;
        }
        _index_data(index) {
            const { x, y, radius, data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const x_i = x[i];
                const y_i = y[i];
                const r_i = radius.get(i);
                index.add_rect(x_i - r_i, y_i - r_i, x_i + r_i, y_i + r_i);
            }
        }
        _map_data() {
            this._define_or_inherit_attr("sradius", () => {
                if (this.model.properties.radius.units == "data") {
                    if (this.inherited_x && this.inherited_radius) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.xscale, this.x, this.radius);
                    }
                }
                else {
                    return this.inherited_radius ? glyph_1.inherit : (0, types_1.to_screen)(this.radius);
                }
            });
            this._define_or_inherit_attr("max_sradius", () => (0, arrayable_1.max)(this.sradius));
        }
        _paint(ctx, indices, data) {
            const { sx, sy, sradius, start_angle, end_angle } = { ...this, ...data };
            const anticlock = this.model.direction == "anticlock";
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const sradius_i = sradius[i];
                const start_angle_i = start_angle.get(i);
                const end_angle_i = end_angle.get(i);
                if (!isFinite(sx_i + sy_i + sradius_i + start_angle_i + end_angle_i)) {
                    continue;
                }
                ctx.beginPath();
                ctx.arc(sx_i, sy_i, sradius_i, start_angle_i, end_angle_i, anticlock);
                ctx.lineTo(sx_i, sy_i);
                ctx.closePath();
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _hit_point(geometry) {
            let dist, sx0, sx1, sy0, sy1;
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            // check diameter first
            sx0 = sx - this.max_sradius;
            sx1 = sx + this.max_sradius;
            const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
            sy0 = sy - this.max_sradius;
            sy1 = sy + this.max_sradius;
            const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            const candidates = [];
            for (const i of this.index.indices({ x0, x1, y0, y1 })) {
                const r2 = this.sradius[i] ** 2;
                [sx0, sx1] = this.renderer.xscale.r_compute(x, this.x[i]);
                [sy0, sy1] = this.renderer.yscale.r_compute(y, this.y[i]);
                dist = (sx0 - sx1) ** 2 + (sy0 - sy1) ** 2;
                if (dist <= r2) {
                    candidates.push(i);
                }
            }
            const anticlock = this.model.direction == "anticlock";
            const indices = [];
            for (const i of candidates) {
                // NOTE: minus the angle because JS uses non-mathy convention for angles
                const angle = Math.atan2(sy - this.sy[i], sx - this.sx[i]);
                const is_full_circle = Math.abs(this.start_angle.get(i) - this.end_angle.get(i)) >= 2 * Math.PI;
                if (is_full_circle || (0, math_1.angle_between)(-angle, -this.start_angle.get(i), -this.end_angle.get(i), anticlock)) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
        scenterxy(i) {
            const r = this.sradius[i] / 2;
            const a = (this.start_angle.get(i) + this.end_angle.get(i)) / 2;
            const scx = this.sx[i] + r * Math.cos(a);
            const scy = this.sy[i] + r * Math.sin(a);
            return [scx, scy];
        }
    }
    exports.WedgeView = WedgeView;
    class Wedge extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = WedgeView;
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
            this.define(({}) => ({
                direction: [enums_1.Direction, "anticlock"],
                radius: [p.DistanceSpec, { field: "radius" }],
                start_angle: [p.AngleSpec, { field: "start_angle" }],
                end_angle: [p.AngleSpec, { field: "end_angle" }],
            }));
        }
    }
    exports.Wedge = Wedge;
},
/* models/graphics/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var decoration_1 = require(309) /* ./decoration */;
    __esExport("Decoration", decoration_1.Decoration);
    var marking_1 = require(253) /* ./marking */;
    __esExport("Marking", marking_1.Marking);
},
/* models/graphs/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(499) /* ./graph_hit_test_policy */, exports);
    tslib_1.__exportStar(require(500) /* ./layout_provider */, exports);
    tslib_1.__exportStar(require(501) /* ./static_layout_provider */, exports);
},
/* models/graphs/graph_hit_test_policy.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const array_1 = require(10) /* ../../core/util/array */;
    const object_1 = require(9) /* ../../core/util/object */;
    const selection_1 = require(144) /* ../selections/selection */;
    class GraphHitTestPolicy extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        _hit_test(geometry, graph_view, renderer_view) {
            if (!graph_view.model.visible) {
                return null;
            }
            const hit_test_result = renderer_view.glyph.hit_test(geometry);
            if (hit_test_result == null) {
                return null;
            }
            else {
                return renderer_view.model.view.convert_selection_from_subset(hit_test_result);
            }
        }
    }
    exports.GraphHitTestPolicy = GraphHitTestPolicy;
    class EdgesOnly extends GraphHitTestPolicy {
        constructor(attrs) {
            super(attrs);
        }
        hit_test(geometry, graph_view) {
            return this._hit_test(geometry, graph_view, graph_view.edge_view);
        }
        do_selection(hit_test_result, graph, final, mode) {
            if (hit_test_result == null) {
                return false;
            }
            const edge_selection = graph.edge_renderer.data_source.selected;
            edge_selection.update(hit_test_result, final, mode);
            graph.edge_renderer.data_source._select.emit();
            return !edge_selection.is_empty();
        }
        do_inspection(hit_test_result, geometry, graph_view, final, mode) {
            if (hit_test_result == null) {
                return false;
            }
            const { edge_renderer } = graph_view.model;
            const edge_inspection = edge_renderer.get_selection_manager().get_or_create_inspector(graph_view.edge_view.model);
            edge_inspection.update(hit_test_result, final, mode);
            // silently set inspected attr to avoid triggering data_source.change event and rerender
            graph_view.edge_view.model.data_source.setv({ inspected: edge_inspection }, { silent: true });
            graph_view.edge_view.model.data_source.inspect.emit([graph_view.edge_view.model, { geometry }]);
            return !edge_inspection.is_empty();
        }
    }
    exports.EdgesOnly = EdgesOnly;
    class NodesOnly extends GraphHitTestPolicy {
        constructor(attrs) {
            super(attrs);
        }
        hit_test(geometry, graph_view) {
            return this._hit_test(geometry, graph_view, graph_view.node_view);
        }
        do_selection(hit_test_result, graph, final, mode) {
            if (hit_test_result == null) {
                return false;
            }
            const node_selection = graph.node_renderer.data_source.selected;
            node_selection.update(hit_test_result, final, mode);
            graph.node_renderer.data_source._select.emit();
            return !node_selection.is_empty();
        }
        do_inspection(hit_test_result, geometry, graph_view, final, mode) {
            if (hit_test_result == null) {
                return false;
            }
            const { node_renderer } = graph_view.model;
            const node_inspection = node_renderer.get_selection_manager().get_or_create_inspector(graph_view.node_view.model);
            node_inspection.update(hit_test_result, final, mode);
            // silently set inspected attr to avoid triggering data_source.change event and rerender
            graph_view.node_view.model.data_source.setv({ inspected: node_inspection }, { silent: true });
            graph_view.node_view.model.data_source.inspect.emit([graph_view.node_view.model, { geometry }]);
            return !node_inspection.is_empty();
        }
    }
    exports.NodesOnly = NodesOnly;
    class NodesAndLinkedEdges extends GraphHitTestPolicy {
        constructor(attrs) {
            super(attrs);
        }
        hit_test(geometry, graph_view) {
            return this._hit_test(geometry, graph_view, graph_view.node_view);
        }
        get_linked_edges(node_source, edge_source, mode) {
            const node_data = (0, object_1.dict)(node_source.data);
            const index = node_data.get("index") ?? [];
            const node_indices = (() => {
                switch (mode) {
                    case "selection": return (0, arrayable_1.map)(node_source.selected.indices, (i) => index[i]);
                    case "inspection": return (0, arrayable_1.map)(node_source.inspected.indices, (i) => index[i]);
                }
            })();
            const edge_data = (0, object_1.dict)(edge_source.data);
            const start = edge_data.get("start") ?? [];
            const end = edge_data.get("end") ?? [];
            const edge_indices = [];
            const n = start.length;
            for (let i = 0; i < n; i++) {
                if ((0, array_1.contains)(node_indices, start[i]) || (0, array_1.contains)(node_indices, end[i])) {
                    edge_indices.push(i);
                }
            }
            const linked_edges = new selection_1.Selection();
            for (const i of edge_indices) {
                linked_edges.multiline_indices.set(i, [0]); //currently only supports 2-element multilines, so this is all of it
            }
            linked_edges.indices = edge_indices;
            return linked_edges;
        }
        do_selection(hit_test_result, graph, final, mode) {
            if (hit_test_result == null) {
                return false;
            }
            const node_selection = graph.node_renderer.data_source.selected;
            node_selection.update(hit_test_result, final, mode);
            const edge_selection = graph.edge_renderer.data_source.selected;
            const linked_edges_selection = this.get_linked_edges(graph.node_renderer.data_source, graph.edge_renderer.data_source, "selection");
            edge_selection.update(linked_edges_selection, final, mode);
            graph.node_renderer.data_source._select.emit();
            return !node_selection.is_empty();
        }
        do_inspection(hit_test_result, geometry, graph_view, final, mode) {
            if (hit_test_result == null) {
                return false;
            }
            const node_inspection = graph_view.node_view.model.data_source.selection_manager.get_or_create_inspector(graph_view.node_view.model);
            node_inspection.update(hit_test_result, final, mode);
            graph_view.node_view.model.data_source.setv({ inspected: node_inspection }, { silent: true });
            const edge_inspection = graph_view.edge_view.model.data_source.selection_manager.get_or_create_inspector(graph_view.edge_view.model);
            const linked_edges = this.get_linked_edges(graph_view.node_view.model.data_source, graph_view.edge_view.model.data_source, "inspection");
            edge_inspection.update(linked_edges, final, mode);
            //silently set inspected attr to avoid triggering data_source.change event and rerender
            graph_view.edge_view.model.data_source.setv({ inspected: edge_inspection }, { silent: true });
            graph_view.node_view.model.data_source.inspect.emit([graph_view.node_view.model, { geometry }]);
            return !node_inspection.is_empty();
        }
    }
    exports.NodesAndLinkedEdges = NodesAndLinkedEdges;
    class EdgesAndLinkedNodes extends GraphHitTestPolicy {
        constructor(attrs) {
            super(attrs);
        }
        hit_test(geometry, graph_view) {
            return this._hit_test(geometry, graph_view, graph_view.edge_view);
        }
        get_linked_nodes(node_source, edge_source, mode) {
            const edge_indices = (() => {
                switch (mode) {
                    case "selection": return edge_source.selected.indices;
                    case "inspection": return edge_source.inspected.indices;
                }
            })();
            const edge_data = (0, object_1.dict)(edge_source.data);
            const start = edge_data.get("start") ?? [];
            const end = edge_data.get("end") ?? [];
            const nodes = [];
            for (const i of edge_indices) {
                nodes.push(start[i], end[i]);
            }
            const node_data = (0, object_1.dict)(node_source.data);
            const index = node_data.get("index") ?? [];
            const node_indices = (0, array_1.uniq)(nodes).map((i) => (0, arrayable_1.index_of)(index, i));
            return new selection_1.Selection({ indices: node_indices });
        }
        do_selection(hit_test_result, graph, final, mode) {
            if (hit_test_result == null) {
                return false;
            }
            const edge_selection = graph.edge_renderer.data_source.selected;
            edge_selection.update(hit_test_result, final, mode);
            const node_selection = graph.node_renderer.data_source.selected;
            const linked_nodes = this.get_linked_nodes(graph.node_renderer.data_source, graph.edge_renderer.data_source, "selection");
            node_selection.update(linked_nodes, final, mode);
            graph.edge_renderer.data_source._select.emit();
            return !edge_selection.is_empty();
        }
        do_inspection(hit_test_result, geometry, graph_view, final, mode) {
            if (hit_test_result == null) {
                return false;
            }
            const edge_inspection = graph_view.edge_view.model.data_source.selection_manager.get_or_create_inspector(graph_view.edge_view.model);
            edge_inspection.update(hit_test_result, final, mode);
            graph_view.edge_view.model.data_source.setv({ inspected: edge_inspection }, { silent: true });
            const node_inspection = graph_view.node_view.model.data_source.selection_manager.get_or_create_inspector(graph_view.node_view.model);
            const linked_nodes = this.get_linked_nodes(graph_view.node_view.model.data_source, graph_view.edge_view.model.data_source, "inspection");
            node_inspection.update(linked_nodes, final, mode);
            // silently set inspected attr to avoid triggering data_source.change event and rerender
            graph_view.node_view.model.data_source.setv({ inspected: node_inspection }, { silent: true });
            graph_view.edge_view.model.data_source.inspect.emit([graph_view.edge_view.model, { geometry }]);
            return !edge_inspection.is_empty();
        }
    }
    exports.EdgesAndLinkedNodes = EdgesAndLinkedNodes;
    class NodesAndAdjacentNodes extends GraphHitTestPolicy {
        constructor(attrs) {
            super(attrs);
        }
        hit_test(geometry, graph_view) {
            return this._hit_test(geometry, graph_view, graph_view.node_view);
        }
        get_adjacent_nodes(node_source, edge_source, mode) {
            const node_data = (0, object_1.dict)(node_source.data);
            const index = node_data.get("index") ?? [];
            const selected_node_indices = (() => {
                switch (mode) {
                    case "selection": return (0, arrayable_1.map)(node_source.selected.indices, (i) => index[i]);
                    case "inspection": return (0, arrayable_1.map)(node_source.inspected.indices, (i) => index[i]);
                }
            })();
            const edge_data = (0, object_1.dict)(edge_source.data);
            const start = edge_data.get("start") ?? [];
            const end = edge_data.get("end") ?? [];
            const adjacent_nodes = [];
            const selected_nodes = [];
            for (let i = 0; i < start.length; i++) {
                if ((0, array_1.contains)(selected_node_indices, start[i])) {
                    adjacent_nodes.push(end[i]);
                    selected_nodes.push(start[i]);
                }
                if ((0, array_1.contains)(selected_node_indices, end[i])) {
                    adjacent_nodes.push(start[i]);
                    selected_nodes.push(end[i]);
                }
            }
            for (let i = 0; i < selected_nodes.length; i++) {
                adjacent_nodes.push(selected_nodes[i]);
            }
            const adjacent_node_indices = (0, array_1.uniq)(adjacent_nodes).map((i) => (0, arrayable_1.index_of)(index, i));
            return new selection_1.Selection({ indices: adjacent_node_indices });
        }
        do_selection(hit_test_result, graph, final, mode) {
            if (hit_test_result == null) {
                return false;
            }
            const node_selection = graph.node_renderer.data_source.selected;
            node_selection.update(hit_test_result, final, mode);
            const adjacent_nodes_selection = this.get_adjacent_nodes(graph.node_renderer.data_source, graph.edge_renderer.data_source, "selection");
            if (!adjacent_nodes_selection.is_empty()) {
                node_selection.update(adjacent_nodes_selection, final, mode);
            }
            graph.node_renderer.data_source._select.emit();
            return !node_selection.is_empty();
        }
        do_inspection(hit_test_result, geometry, graph_view, final, mode) {
            if (hit_test_result == null) {
                return false;
            }
            const node_inspection = graph_view.node_view.model.data_source.selection_manager.get_or_create_inspector(graph_view.node_view.model);
            node_inspection.update(hit_test_result, final, mode);
            graph_view.node_view.model.data_source.setv({ inspected: node_inspection }, { silent: true });
            const adjacent_nodes_inspection = this.get_adjacent_nodes(graph_view.node_view.model.data_source, graph_view.edge_view.model.data_source, "inspection");
            if (!adjacent_nodes_inspection.is_empty()) {
                node_inspection.update(adjacent_nodes_inspection, final, mode);
                graph_view.node_view.model.data_source.setv({ inspected: node_inspection }, { silent: true });
            }
            graph_view.node_view.model.data_source.inspect.emit([graph_view.node_view.model, { geometry }]);
            return !node_inspection.is_empty();
        }
    }
    exports.NodesAndAdjacentNodes = NodesAndAdjacentNodes;
},
/* models/graphs/layout_provider.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    const coordinate_transform_1 = require(445) /* ../expressions/coordinate_transform */;
    class LayoutProvider extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        get node_coordinates() {
            return new NodeCoordinates({ layout: this });
        }
        get edge_coordinates() {
            return new EdgeCoordinates({ layout: this });
        }
    }
    exports.LayoutProvider = LayoutProvider;
    class GraphCoordinates extends coordinate_transform_1.CoordinateTransform {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Ref }) => ({
                layout: [Ref(LayoutProvider)],
            }));
        }
    }
    exports.GraphCoordinates = GraphCoordinates;
    class NodeCoordinates extends GraphCoordinates {
        constructor(attrs) {
            super(attrs);
        }
        _v_compute(source) {
            const [x, y] = this.layout.get_node_coordinates(source);
            return { x, y };
        }
    }
    exports.NodeCoordinates = NodeCoordinates;
    class EdgeCoordinates extends GraphCoordinates {
        constructor(attrs) {
            super(attrs);
        }
        _v_compute(source) {
            const [x, y] = this.layout.get_edge_coordinates(source);
            return { x, y };
        }
    }
    exports.EdgeCoordinates = EdgeCoordinates;
},
/* models/graphs/static_layout_provider.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const layout_provider_1 = require(500) /* ./layout_provider */;
    const object_1 = require(9) /* ../../core/util/object */;
    const kinds_1 = require(22) /* ../../core/kinds */;
    exports.GraphLayout = (0, kinds_1.Or)((0, kinds_1.Dict)((0, kinds_1.Arrayable)(kinds_1.Float)), (0, kinds_1.Mapping)((0, kinds_1.Or)(kinds_1.Int, kinds_1.Str), (0, kinds_1.Arrayable)(kinds_1.Float)));
    class StaticLayoutProvider extends layout_provider_1.LayoutProvider {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(() => ({
                graph_layout: [exports.GraphLayout, new Map()], // TODO: length == 2
            }));
        }
        get_node_coordinates(node_source) {
            const data = (0, object_1.dict)(node_source.data);
            const index = data.get("index") ?? [];
            const n = index.length;
            const xs = new Float64Array(n);
            const ys = new Float64Array(n);
            const graph_layout = (0, object_1.dict)(this.graph_layout);
            for (let i = 0; i < n; i++) {
                const j = index[i];
                const [x, y] = graph_layout.get(j) ?? [NaN, NaN];
                xs[i] = x;
                ys[i] = y;
            }
            return [xs, ys];
        }
        get_edge_coordinates(edge_source) {
            const data = (0, object_1.dict)(edge_source.data);
            const starts = (data.get("start") ?? []);
            const ends = (data.get("end") ?? []);
            const n = Math.min(starts.length, ends.length);
            const xs = [];
            const ys = [];
            const edge_xs = data.get("xs");
            const edge_ys = data.get("ys");
            const has_paths = edge_xs != null && edge_ys != null;
            const graph_layout = (0, object_1.dict)(this.graph_layout);
            for (let i = 0; i < n; i++) {
                const in_layout = graph_layout.has(starts[i]) && graph_layout.has(ends[i]);
                if (has_paths && in_layout) {
                    xs.push(edge_xs[i]);
                    ys.push(edge_ys[i]);
                }
                else {
                    const start = graph_layout.get(starts[i]) ?? [NaN, NaN];
                    const end = graph_layout.get(ends[i]) ?? [NaN, NaN];
                    xs.push([start[0], end[0]]);
                    ys.push([start[1], end[1]]);
                }
            }
            return [xs, ys];
        }
    }
    exports.StaticLayoutProvider = StaticLayoutProvider;
},
/* models/grids/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var grid_1 = require(377) /* ./grid */;
    __esExport("Grid", grid_1.Grid);
},
/* models/layouts/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var column_1 = require(504) /* ./column */;
    __esExport("Column", column_1.Column);
    var flex_box_1 = require(505) /* ./flex_box */;
    __esExport("FlexBox", flex_box_1.FlexBox);
    var grid_box_1 = require(507) /* ./grid_box */;
    __esExport("GridBox", grid_box_1.GridBox);
    var group_box_1 = require(509) /* ./group_box */;
    __esExport("GroupBox", group_box_1.GroupBox);
    var hbox_1 = require(511) /* ./hbox */;
    __esExport("HBox", hbox_1.HBox);
    var layout_dom_1 = require(131) /* ./layout_dom */;
    __esExport("LayoutDOM", layout_dom_1.LayoutDOM);
    var row_1 = require(512) /* ./row */;
    __esExport("Row", row_1.Row);
    var scroll_box_1 = require(513) /* ./scroll_box */;
    __esExport("ScrollBox", scroll_box_1.ScrollBox);
    var spacer_1 = require(514) /* ./spacer */;
    __esExport("Spacer", spacer_1.Spacer);
    var tab_panel_1 = require(515) /* ./tab_panel */;
    __esExport("TabPanel", tab_panel_1.TabPanel);
    var tabs_1 = require(519) /* ./tabs */;
    __esExport("Tabs", tabs_1.Tabs);
    var vbox_1 = require(521) /* ./vbox */;
    __esExport("VBox", vbox_1.VBox);
},
/* models/layouts/column.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const flex_box_1 = require(505) /* ./flex_box */;
    class ColumnView extends flex_box_1.FlexBoxView {
        _direction = "column";
    }
    exports.ColumnView = ColumnView;
    class Column extends flex_box_1.FlexBox {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ColumnView;
        }
    }
    exports.Column = Column;
},
/* models/layouts/flex_box.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const layout_dom_1 = require(131) /* ./layout_dom */;
    const alignments_1 = require(506) /* ./alignments */;
    const grid_1 = require(139) /* ../../core/layout/grid */;
    const ui_element_1 = require(55) /* ../ui/ui_element */;
    const dom_1 = require(61) /* ../../core/dom */;
    class FlexBoxView extends layout_dom_1.LayoutDOMView {
        connect_signals() {
            super.connect_signals();
            const { children, spacing } = this.model.properties;
            this.on_change(children, () => this.update_children());
            this.on_change(spacing, () => this.invalidate_layout());
        }
        get child_models() {
            return this.model.children;
        }
        _intrinsic_display() {
            return { inner: this.model.flow_mode, outer: "flex" };
        }
        _update_layout() {
            super._update_layout();
            this.style.append(":host", {
                flex_direction: this._direction,
                gap: (0, dom_1.px)(this.model.spacing),
            });
            const layoutable = new grid_1.Container();
            let r0 = 0;
            let c0 = 0;
            for (const view of this.child_views) {
                if (!(view instanceof layout_dom_1.LayoutDOMView)) {
                    continue;
                }
                const sizing = view.box_sizing();
                const flex = (() => {
                    const policy = this._direction == "row" ? sizing.width_policy : sizing.height_policy;
                    const size = this._direction == "row" ? sizing.width : sizing.height;
                    const basis = size != null ? (0, dom_1.px)(size) : "auto";
                    switch (policy) {
                        case "auto":
                        case "fixed": return `0 0 ${basis}`;
                        case "fit": return "1 1 auto";
                        case "min": return "0 1 auto";
                        case "max": return "1 0 0px";
                    }
                })();
                const align_self = (() => {
                    const policy = this._direction == "row" ? sizing.height_policy : sizing.width_policy;
                    switch (policy) {
                        case "auto":
                        case "fixed":
                        case "fit":
                        case "min": return this._direction == "row" ? sizing.valign : sizing.halign;
                        case "max": return "stretch";
                    }
                })();
                function min_size(size) {
                    return size != null ? (0, dom_1.px)(size) : "0";
                }
                const min_width = min_size(view.model.min_width);
                const min_height = min_size(view.model.min_height);
                view.parent_style.append(":host", { flex, align_self, min_width, min_height });
                // undo `width/height: 100%` and let `align-self: stretch` do the work
                if (this._direction == "row") {
                    if (sizing.height_policy == "max") {
                        view.parent_style.append(":host", { height: "auto" });
                    }
                }
                else {
                    if (sizing.width_policy == "max") {
                        view.parent_style.append(":host", { width: "auto" });
                    }
                }
                if (view.layout != null) {
                    layoutable.add({ r0, c0, r1: r0 + 1, c1: c0 + 1 }, view);
                    if (this._direction == "row") {
                        c0 += 1;
                    }
                    else {
                        r0 += 1;
                    }
                }
            }
            if (layoutable.size != 0) {
                this.layout = new alignments_1.GridAlignmentLayout(layoutable);
                this.layout.set_sizing();
            }
            else {
                delete this.layout;
            }
        }
    }
    exports.FlexBoxView = FlexBoxView;
    class FlexBox extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Float, List, Ref }) => ({
                children: [List(Ref(ui_element_1.UIElement)), []],
                spacing: [Float, 0],
            }));
        }
    }
    exports.FlexBox = FlexBox;
},
/* models/layouts/alignments.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const layoutable_1 = require(137) /* ../../core/layout/layoutable */;
    const bbox_1 = require(62) /* ../../core/util/bbox */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    const { max } = Math;
    class GridAlignmentLayout extends layoutable_1.Layoutable {
        children;
        constructor(children) {
            super();
            this.children = children;
        }
        _measure(_viewport) {
            return { width: 0, height: 0 };
        }
        compute(viewport = {}) {
            const { width, height } = viewport;
            (0, assert_1.assert)(width != null && height != null);
            const size_hint = { width, height };
            const outer = new bbox_1.BBox({ left: 0, top: 0, width, height });
            let inner = undefined;
            if (size_hint.inner != null) {
                const { left, top, right, bottom } = size_hint.inner;
                inner = new bbox_1.BBox({ left, top, right: width - right, bottom: height - bottom });
            }
            this.set_geometry(outer, inner);
        }
        _set_geometry(outer, inner) {
            super._set_geometry(outer, inner);
            const items = this.children.map((_, child) => {
                const { layout, bbox } = child;
                (0, assert_1.assert)(layout != null);
                const size_hint = layout.measure(bbox);
                return { child, layout, bbox, size_hint };
            });
            const row_extents = Array(items.nrows).fill(null).map(() => ({ top: 0, bottom: 0 }));
            const col_extents = Array(items.ncols).fill(null).map(() => ({ left: 0, right: 0 }));
            items.foreach(({ r0, c0, r1, c1 }, { size_hint }) => {
                const { inner } = size_hint;
                if (inner != null) {
                    col_extents[c0].left = max(col_extents[c0].left, inner.left);
                    col_extents[c1].right = max(col_extents[c1].right, inner.right);
                    row_extents[r0].top = max(row_extents[r0].top, inner.top);
                    row_extents[r1].bottom = max(row_extents[r1].bottom, inner.bottom);
                }
            });
            items.foreach(({ r0, c0, r1, c1 }, { layout, size_hint, bbox }) => {
                const outer_bbox = bbox;
                const inner_bbox = size_hint.inner == null ? undefined : (() => {
                    const { inner, align } = size_hint;
                    const align_left = align?.left ?? true;
                    const align_right = align?.right ?? true;
                    const align_top = align?.top ?? true;
                    const align_bottom = align?.bottom ?? true;
                    const fixed_width = align?.fixed_width ?? false;
                    const fixed_height = align?.fixed_height ?? false;
                    const { left, right } = (() => {
                        if (fixed_width) {
                            const inner_width = outer_bbox.width - inner.right - inner.left;
                            if (align_left) {
                                const left = col_extents[c0].left;
                                const right = outer_bbox.width - (left + inner_width);
                                return { left, right };
                            }
                            else if (align_right) {
                                const right = col_extents[c1].right;
                                const left = outer_bbox.width - (right + inner_width);
                                return { left, right };
                            }
                            else {
                                const left = inner.left;
                                const right = inner.right;
                                return { left, right };
                            }
                        }
                        else {
                            const left = align_left ? col_extents[c0].left : inner.left;
                            const right = align_right ? col_extents[c1].right : inner.right;
                            return { left, right };
                        }
                    })();
                    const { top, bottom } = (() => {
                        if (fixed_height) {
                            const inner_height = outer_bbox.height - inner.bottom - inner.top;
                            if (align_top) {
                                const top = row_extents[r0].top;
                                const bottom = outer_bbox.height - (top + inner_height);
                                return { top, bottom };
                            }
                            else if (align_bottom) {
                                const bottom = row_extents[r1].bottom;
                                const top = outer_bbox.height - (bottom + inner_height);
                                return { top, bottom };
                            }
                            else {
                                const top = inner.top;
                                const bottom = inner.bottom;
                                return { top, bottom };
                            }
                        }
                        else {
                            const top = align_top ? row_extents[r0].top : inner.top;
                            const bottom = align_bottom ? row_extents[r1].bottom : inner.bottom;
                            return { top, bottom };
                        }
                    })();
                    const { width, height } = outer_bbox;
                    return bbox_1.BBox.from_lrtb({ left, top, right: width - right, bottom: height - bottom });
                })();
                layout.set_geometry(outer_bbox, inner_bbox);
            });
        }
    }
    exports.GridAlignmentLayout = GridAlignmentLayout;
},
/* models/layouts/grid_box.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const css_grid_box_1 = require(508) /* ./css_grid_box */;
    const kinds_1 = require(124) /* ../common/kinds */;
    const ui_element_1 = require(55) /* ../ui/ui_element */;
    class GridBoxView extends css_grid_box_1.CSSGridBoxView {
        connect_signals() {
            super.connect_signals();
            const { children, rows, cols } = this.model.properties;
            this.on_change(children, () => this.update_children());
            this.on_change([rows, cols], () => this.invalidate_layout());
        }
        get _children() {
            return this.model.children;
        }
        get _rows() {
            return this.model.rows;
        }
        get _cols() {
            return this.model.cols;
        }
    }
    exports.GridBoxView = GridBoxView;
    class GridBox extends css_grid_box_1.CSSGridBox {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = GridBoxView;
            this.define(({ List, Nullable }) => {
                return {
                    children: [List((0, kinds_1.GridChild)(ui_element_1.UIElement)), []],
                    rows: [Nullable(kinds_1.TracksSizing), null],
                    cols: [Nullable(kinds_1.TracksSizing), null],
                };
            });
        }
    }
    exports.GridBox = GridBox;
},
/* models/layouts/css_grid_box.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const layout_dom_1 = require(131) /* ./layout_dom */;
    const alignments_1 = require(506) /* ./alignments */;
    const kinds_1 = require(124) /* ../common/kinds */;
    const dom_1 = require(61) /* ../../core/dom */;
    const grid_1 = require(139) /* ../../core/layout/grid */;
    const iterator_1 = require(15) /* ../../core/util/iterator */;
    const types_1 = require(8) /* ../../core/util/types */;
    const { max } = Math;
    class CSSGridBoxView extends layout_dom_1.LayoutDOMView {
        connect_signals() {
            super.connect_signals();
            const { spacing } = this.model.properties;
            this.on_change(spacing, () => this.invalidate_layout());
        }
        get child_models() {
            return this._children.map(([child]) => child);
        }
        _intrinsic_display() {
            return { inner: this.model.flow_mode, outer: "grid" };
        }
        _update_layout() {
            super._update_layout();
            const styles = {};
            const [row_gap, column_gap] = (() => {
                const { spacing } = this.model;
                return (0, types_1.isNumber)(spacing) ? [spacing, spacing] : spacing;
            })();
            styles.row_gap = (0, dom_1.px)(row_gap);
            styles.column_gap = (0, dom_1.px)(column_gap);
            let nrows = 0;
            let ncols = 0;
            const layoutable = new grid_1.Container();
            for (const [[, row, col, row_span = 1, col_span = 1], i] of (0, iterator_1.enumerate)(this._children)) {
                const view = this.child_views[i];
                nrows = max(nrows, row + row_span);
                ncols = max(ncols, col + col_span);
                // CSS grid is 1-based, but layout is 0-based
                const styles = {};
                styles.grid_row_start = `${row + 1}`;
                styles.grid_row_end = `span ${row_span}`;
                styles.grid_column_start = `${col + 1}`;
                styles.grid_column_end = `span ${col_span}`;
                view.parent_style.append(":host", styles);
                if (view instanceof layout_dom_1.LayoutDOMView && view.layout != null) {
                    const r0 = row;
                    const c0 = col;
                    const r1 = row + row_span - 1;
                    const c1 = col + col_span - 1;
                    layoutable.add({ r0, c0, r1, c1 }, view);
                }
            }
            const { _rows: rows, _cols: cols } = this;
            if (rows instanceof Map) {
                nrows = max(nrows, ...rows.keys());
            }
            else if ((0, types_1.isArray)(rows)) {
                nrows = max(nrows, rows.length);
            }
            if (cols instanceof Map) {
                ncols = max(ncols, ...cols.keys());
            }
            else if ((0, types_1.isArray)(cols)) {
                ncols = max(ncols, cols.length);
            }
            function parse_sizing(tracks, template) {
                if (tracks instanceof Map) {
                    for (const [i, spec] of tracks.entries()) {
                        if ((0, types_1.isString)(spec)) {
                            template[i].size = spec;
                        }
                        else {
                            template[i] = spec;
                        }
                    }
                }
                else if ((0, types_1.isArray)(tracks)) {
                    for (const [spec, i] of (0, iterator_1.enumerate)(tracks)) {
                        if ((0, types_1.isString)(spec)) {
                            template[i].size = spec;
                        }
                        else {
                            template[i] = spec;
                        }
                    }
                }
                else if (tracks != null) {
                    for (const row of template) {
                        if ((0, types_1.isString)(tracks)) {
                            row.size = tracks;
                        }
                        else {
                            row.size = tracks.size;
                            row.align = tracks.align;
                        }
                    }
                }
            }
            const rows_template = Array(nrows).fill(null).map(() => ({}));
            const cols_template = Array(ncols).fill(null).map(() => ({}));
            parse_sizing(rows, rows_template);
            parse_sizing(cols, cols_template);
            for (const [[, row, col], i] of (0, iterator_1.enumerate)(this._children)) {
                const view = this.child_views[i];
                const { halign, valign } = view.box_sizing();
                view.parent_style.append(":host", {
                    justify_self: halign ?? cols_template[col].align,
                    align_self: valign ?? rows_template[row].align,
                });
            }
            const default_size = "auto";
            styles.grid_template_rows = rows_template.map(({ size }) => size ?? default_size).join(" ");
            styles.grid_template_columns = cols_template.map(({ size }) => size ?? default_size).join(" ");
            this.style.append(":host", styles);
            if (layoutable.size != 0) {
                this.layout = new alignments_1.GridAlignmentLayout(layoutable);
                this.layout.set_sizing();
            }
            else {
                delete this.layout;
            }
        }
    }
    exports.CSSGridBoxView = CSSGridBoxView;
    class CSSGridBox extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(() => ({
                spacing: [kinds_1.GridSpacing, 0],
            }));
        }
    }
    exports.CSSGridBox = CSSGridBox;
},
/* models/layouts/group_box.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const layout_dom_1 = require(131) /* ./layout_dom */;
    const ui_element_1 = require(55) /* ../ui/ui_element */;
    const dom_1 = require(61) /* ../../core/dom */;
    const group_box_css_1 = tslib_1.__importDefault(require(510) /* ../../styles/group_box.css */);
    class GroupBoxView extends layout_dom_1.LayoutDOMView {
        checkbox_el;
        fieldset_el;
        stylesheets() {
            return [...super.stylesheets(), group_box_css_1.default];
        }
        connect_signals() {
            super.connect_signals();
            const { child } = this.model.properties;
            this.on_change(child, () => this.update_children());
            const { checkable, disabled } = this.model.properties;
            this.on_change(checkable, () => {
                (0, dom_1.display)(this.checkbox_el, this.model.checkable);
            });
            this.on_change(disabled, () => {
                this.checkbox_el.checked = !this.model.disabled;
            });
        }
        get child_models() {
            return [this.model.child];
        }
        render() {
            super.render();
            const { checkable, disabled, title } = this.model;
            this.checkbox_el = (0, dom_1.input)({ type: "checkbox", checked: !disabled });
            this.checkbox_el.addEventListener("change", () => {
                this.model.disabled = !this.checkbox_el.checked;
            });
            (0, dom_1.display)(this.checkbox_el, checkable);
            const title_el = (0, dom_1.legend)({}, this.checkbox_el, title);
            const child_els = this.child_views.map((child) => child.el);
            this.fieldset_el = (0, dom_1.fieldset)({}, title_el, ...child_els);
            this.shadow_el.appendChild(this.fieldset_el);
        }
        _update_children() {
            const child_els = this.child_views.map((child) => child.el);
            this.fieldset_el.append(...child_els);
        }
    }
    exports.GroupBoxView = GroupBoxView;
    class GroupBox extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = GroupBoxView;
            this.define(({ Bool, Str, Nullable, Ref }) => ({
                title: [Nullable(Str), null],
                child: [Ref(ui_element_1.UIElement)],
                checkable: [Bool, false],
            }));
        }
    }
    exports.GroupBox = GroupBox;
},
/* styles/group_box.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = `legend{display:flex;gap:0.5em;padding:0 calc(var(--padding-horizontal) / 2);}fieldset{border:var(--border);}`;
},
/* models/layouts/hbox.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const css_grid_box_1 = require(508) /* ./css_grid_box */;
    const kinds_1 = require(124) /* ../common/kinds */;
    const ui_element_1 = require(55) /* ../ui/ui_element */;
    const kinds_2 = require(22) /* ../../core/kinds */;
    const HBoxChild = (0, kinds_2.Struct)({ child: (0, kinds_2.Ref)(ui_element_1.UIElement), col: (0, kinds_2.Opt)(kinds_1.Index), span: (0, kinds_2.Opt)(kinds_1.Span) });
    class HBoxView extends css_grid_box_1.CSSGridBoxView {
        connect_signals() {
            super.connect_signals();
            const { children, cols } = this.model.properties;
            this.on_change(children, () => this.update_children());
            this.on_change(cols, () => this.invalidate_layout());
        }
        get _children() {
            return this.model.children.map(({ child, col, span }, i) => [child, 0, col ?? i, 1, span ?? 1]);
        }
        get _rows() {
            return null;
        }
        get _cols() {
            return this.model.cols;
        }
    }
    exports.HBoxView = HBoxView;
    class HBox extends css_grid_box_1.CSSGridBox {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = HBoxView;
            this.define(({ List, Nullable }) => ({
                children: [List(HBoxChild), []],
                cols: [Nullable(kinds_1.TracksSizing), null],
            }));
        }
    }
    exports.HBox = HBox;
},
/* models/layouts/row.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const flex_box_1 = require(505) /* ./flex_box */;
    class RowView extends flex_box_1.FlexBoxView {
        _direction = "row";
    }
    exports.RowView = RowView;
    class Row extends flex_box_1.FlexBox {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = RowView;
        }
    }
    exports.Row = Row;
},
/* models/layouts/scroll_box.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const layout_dom_1 = require(131) /* ./layout_dom */;
    const ui_element_1 = require(55) /* ../ui/ui_element */;
    const enums_1 = require(21) /* ../../core/enums */;
    class ScrollBoxView extends layout_dom_1.LayoutDOMView {
        stylesheets() {
            return [...super.stylesheets()];
        }
        connect_signals() {
            super.connect_signals();
            const { child, horizontal_scrollbar, vertical_scrollbar } = this.model.properties;
            this.on_change(child, () => this.update_children());
            this.on_change([horizontal_scrollbar, vertical_scrollbar], () => this.invalidate_layout());
        }
        get child_models() {
            return [this.model.child];
        }
        _update_layout() {
            super._update_layout();
            function to_overflow(policy) {
                switch (policy) {
                    case "auto": return "auto";
                    case "visible": return "scroll";
                    case "hidden": return "hidden";
                }
            }
            const { horizontal_scrollbar, vertical_scrollbar } = this.model;
            this.style.append(":host", {
                overflow_x: to_overflow(horizontal_scrollbar),
                overflow_y: to_overflow(vertical_scrollbar),
            });
        }
    }
    exports.ScrollBoxView = ScrollBoxView;
    class ScrollBox extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ScrollBoxView;
            this.define(({ Ref }) => ({
                child: [Ref(ui_element_1.UIElement)],
                horizontal_scrollbar: [enums_1.ScrollbarPolicy, "auto"],
                vertical_scrollbar: [enums_1.ScrollbarPolicy, "auto"],
            }));
        }
    }
    exports.ScrollBox = ScrollBox;
},
/* models/layouts/spacer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const layout_dom_1 = require(131) /* ./layout_dom */;
    class SpacerView extends layout_dom_1.LayoutDOMView {
        get child_models() {
            return [];
        }
        _auto_width = "auto";
        _auto_height = "auto";
    }
    exports.SpacerView = SpacerView;
    class Spacer extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = SpacerView;
        }
    }
    exports.Spacer = Spacer;
},
/* models/layouts/tab_panel.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tooltip_1 = require(516) /* ../ui/tooltip */;
    const model_1 = require(52) /* ../../model */;
    const ui_element_1 = require(55) /* ../ui/ui_element */;
    class TabPanel extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Bool, Str, Ref, Nullable }) => ({
                title: [Str, ""],
                tooltip: [Nullable(Ref(tooltip_1.Tooltip)), null],
                child: [Ref(ui_element_1.UIElement)],
                closable: [Bool, false],
                disabled: [Bool, false],
            }));
        }
    }
    exports.TabPanel = TabPanel;
},
/* models/ui/tooltip.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const ui_element_1 = require(55) /* ./ui_element */;
    const dom_node_1 = require(130) /* ../dom/dom_node */;
    const coordinate_1 = require(58) /* ../coordinates/coordinate */;
    const selector_1 = require(517) /* ../selectors/selector */;
    const enums_1 = require(21) /* ../../core/enums */;
    const dom_1 = require(61) /* ../../core/dom */;
    const dom_view_1 = require(64) /* ../../core/dom_view */;
    const types_1 = require(8) /* ../../core/util/types */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    const bbox_1 = require(62) /* ../../core/util/bbox */;
    const logging_1 = require(11) /* ../../core/logging */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const model_1 = require(52) /* ../../model */;
    const NativeNode = globalThis.Node;
    const tooltips_css_1 = tslib_1.__importStar(require(518) /* ../../styles/tooltips.css */), tooltips = tooltips_css_1;
    const icons_css_1 = tslib_1.__importDefault(require(76) /* ../../styles/icons.css */);
    class TooltipView extends ui_element_1.UIElementView {
        arrow_el;
        content_el;
        _observer;
        _target;
        get target() {
            return this._target;
        }
        set target(el) {
            this._target = el;
        }
        _init_target() {
            const { target } = this.model;
            const el = (() => {
                if (target instanceof ui_element_1.UIElement) {
                    return this.owner.find_one(target)?.el ?? null;
                }
                else if (target instanceof selector_1.Selector) {
                    return target.find_one(document);
                }
                else if (target instanceof NativeNode) {
                    return target;
                }
                else {
                    const { parent } = this;
                    return parent instanceof dom_view_1.DOMElementView ? parent.el : null;
                }
            })();
            if (el instanceof Element) {
                this._target = el;
            }
            else {
                logging_1.logger.warn(`unable to resolve target '${target}' for '${this}'`);
                this._target = document.body;
            }
        }
        initialize() {
            super.initialize();
            this._init_target();
        }
        _element_view = null;
        children_views() {
            return [...super.children_views(), this._element_view];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._build_content();
        }
        async _build_content() {
            if (this._element_view != null) {
                this._element_view.remove();
                this._element_view = null;
            }
            const { content } = this.model;
            if (content instanceof model_1.Model) {
                this._element_view = await (0, build_views_1.build_view)(content, { parent: this });
            }
        }
        _scroll_listener;
        connect_signals() {
            super.connect_signals();
            this._observer = new ResizeObserver(() => {
                this._reposition();
            });
            this._observer.observe(this.target);
            let throttle = false;
            document.addEventListener("scroll", this._scroll_listener = () => {
                if (!throttle) {
                    requestAnimationFrame(() => {
                        this._reposition();
                        throttle = false;
                    });
                    throttle = true;
                }
            }, { capture: true });
            const { target, content, closable, interactive, position, attachment, visible } = this.model.properties;
            this.on_change(target, () => {
                this._init_target();
                this._observer.disconnect();
                this._observer.observe(this.target);
                this.render();
                this.after_render();
            });
            this.on_change(content, async () => {
                await this._build_content();
                this.render();
                this.after_render();
            });
            this.on_change([closable, interactive], () => {
                this.render();
                this.after_render();
            });
            this.on_change([position, attachment, visible], () => {
                this._reposition();
            });
        }
        disconnect_signals() {
            if (this._scroll_listener != null) {
                document.removeEventListener("scroll", this._scroll_listener, { capture: true });
                delete this._scroll_listener;
            }
            super.disconnect_signals();
        }
        remove() {
            this._observer.disconnect();
            super.remove();
        }
        stylesheets() {
            return [...super.stylesheets(), tooltips_css_1.default, icons_css_1.default];
        }
        get content() {
            const { content } = this.model;
            if ((0, types_1.isString)(content)) {
                return document.createTextNode(content);
            }
            else if (content instanceof model_1.Model) {
                (0, assert_1.assert)(this._element_view != null);
                return this._element_view.el;
            }
            else {
                return content;
            }
        }
        _has_rendered = false;
        render() {
            super.render();
            const { _element_view } = this;
            if (_element_view != null) {
                _element_view.render();
                _element_view.r_after_render();
            }
            this.arrow_el = (0, dom_1.div)({ class: tooltips.arrow }, (0, dom_1.div)({ class: tooltips.arrow_inner }));
            this.content_el = (0, dom_1.div)({ class: tooltips.tooltip_content }, this.content);
            this.shadow_el.append(this.arrow_el, this.content_el);
            this.class_list.toggle(tooltips.closable, this.model.closable);
            const close_el = (0, dom_1.div)({ class: tooltips.close });
            this.shadow_el.append(close_el);
            close_el.addEventListener("click", () => {
                this.model.visible = false;
            });
            this.el.setAttribute("popover", "manual"); // allows multiple simultaneous popover elements
            this.el.classList.toggle(tooltips.show_arrow, this.model.show_arrow);
            this.el.classList.toggle(tooltips.non_interactive, !this.model.interactive);
            this._has_rendered = true;
        }
        _after_render() {
            super._after_render();
            this._reposition();
        }
        _after_resize() {
            super._after_resize();
            this._reposition();
        }
        _anchor_to_align(anchor) {
            anchor = (() => {
                switch (anchor) {
                    case "top": return "top_center";
                    case "bottom": return "bottom_center";
                    case "left": return "center_left";
                    case "right": return "center_right";
                    default: return anchor;
                }
            })();
            const [v, h] = anchor.split("_");
            return { v, h };
        }
        _reposition() {
            // Append to `body` to deal with CSS' `contain` interaction
            // with `position: fixed`. We assume initial containment
            // block in this function, but `contain` can introduce a
            // new containment block and offset tooltip's position.
            const target = document.body.shadowRoot ?? document.body;
            if (!this._has_rendered) {
                this.render_to(target);
                this.after_render();
                return; // render() calls _reposition()
            }
            const { position, visible } = this.model;
            if (position == null || !visible) {
                this.el.remove();
                return;
            }
            target.append(this.el);
            // If popover API isn't available, then tooltip will still show in most
            // situations, but not in fullscreen or may be partially obscured by
            // other elements or components.
            if (typeof this.el.showPopover !== "undefined") {
                this.el.showPopover();
            }
            const bbox = (0, dom_1.bounding_box)(this.target);
            const [sx, sy] = (() => {
                if ((0, types_1.isString)(position)) {
                    const { v: v_align, h: h_align } = this._anchor_to_align(position);
                    const sx = (() => {
                        switch (h_align) {
                            case "left": return bbox.left;
                            case "center": return bbox.hcenter;
                            case "right": return bbox.right;
                        }
                    })();
                    const sy = (() => {
                        switch (v_align) {
                            case "top": return bbox.top;
                            case "center": return bbox.vcenter;
                            case "bottom": return bbox.bottom;
                        }
                    })();
                    return [sx, sy];
                }
                else if ((0, types_1.isArray)(position)) {
                    const [x, y] = position;
                    return [bbox.left + x, bbox.top + y];
                }
                else {
                    // XXX this assumes position is resolved relative to this.target
                    const { x, y } = this.resolve_as_xy(position);
                    return [bbox.left + x, bbox.top + y];
                }
            })();
            const viewport = new bbox_1.BBox({
                x: 0,
                y: 0,
                width: window.innerWidth,
                height: window.innerHeight,
            });
            // TODO box_size(this.arrow_el), but currently doesn't work reliably
            const el_style = getComputedStyle(this.el);
            const arrow_size = {
                width: parseFloat(el_style.getPropertyValue("--tooltip-arrow-width")),
                height: parseFloat(el_style.getPropertyValue("--tooltip-arrow-height")),
            };
            const side = (() => {
                const attachment = (() => {
                    const { attachment } = this.model;
                    if (attachment == "auto") {
                        if ((0, types_1.isString)(position)) {
                            const { v: v_align, h: h_align } = this._anchor_to_align(position);
                            if (h_align != "center") {
                                return h_align == "left" ? "left" : "right";
                            }
                            if (v_align != "center") {
                                return v_align == "top" ? "above" : "below";
                            }
                        }
                        return "horizontal";
                    }
                    else {
                        return attachment;
                    }
                })();
                const el_size = (0, dom_1.box_size)(this.el);
                const width = el_size.width + arrow_size.width;
                const height = el_size.height + arrow_size.height;
                switch (attachment) {
                    case "horizontal": {
                        if (sx < bbox.hcenter) {
                            return sx + width <= viewport.right ? "right" : "left";
                        }
                        else {
                            return sx - width >= viewport.left ? "left" : "right";
                        }
                    }
                    case "vertical": {
                        if (sy < bbox.vcenter) {
                            return sy + height <= viewport.bottom ? "below" : "above";
                        }
                        else {
                            return sy - height >= viewport.top ? "above" : "below";
                        }
                    }
                    default:
                        return attachment;
                }
            })();
            // slightly confusing: side "left" (for example) is relative to point that
            // is being annotated but CS class ".bk-left" is relative to the tooltip itself
            this.class_list.remove(tooltips.right, tooltips.left, tooltips.above, tooltips.below);
            this.class_list.add((() => {
                switch (side) {
                    case "left": return tooltips.right;
                    case "right": return tooltips.left;
                    case "above": return tooltips.below;
                    case "below": return tooltips.above;
                }
            })());
            this.arrow_el.style.left = `${sx}px`;
            this.arrow_el.style.top = `${sy}px`;
            const { left, top } = (() => {
                const { width, height } = (0, dom_1.box_size)(this.el);
                function adjust_top(top) {
                    if (top < viewport.top) {
                        return viewport.top;
                    }
                    else if (top + height > viewport.bottom) {
                        return viewport.bottom - height;
                    }
                    else {
                        return top;
                    }
                }
                function adjust_left(left) {
                    if (left < viewport.left) {
                        return viewport.left;
                    }
                    else if (left + width > viewport.right) {
                        return viewport.right - width;
                    }
                    else {
                        return left;
                    }
                }
                switch (side) {
                    case "left": {
                        return {
                            left: sx - width - arrow_size.width,
                            top: adjust_top(sy - height / 2),
                        };
                    }
                    case "right": {
                        return {
                            left: sx + arrow_size.width,
                            top: adjust_top(sy - height / 2),
                        };
                    }
                    case "above": {
                        return {
                            left: adjust_left(sx - width / 2),
                            top: sy - height - arrow_size.height,
                        };
                    }
                    case "below": {
                        return {
                            left: adjust_left(sx - width / 2),
                            top: sy + arrow_size.height,
                        };
                    }
                }
            })();
            this.el.style.top = `${top}px`;
            this.el.style.left = `${left}px`;
            this.update_bbox();
        }
    }
    exports.TooltipView = TooltipView;
    class Tooltip extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = TooltipView;
            this.define(({ Bool, Float, Str, Tuple, Or, Ref, Nullable, Auto }) => ({
                target: [Or(Ref(ui_element_1.UIElement), Ref(selector_1.Selector), Ref(NativeNode), Auto), "auto"],
                position: [Nullable(Or(enums_1.Anchor, Tuple(Float, Float), Ref(coordinate_1.Coordinate))), null],
                content: [Or(Str, Ref(dom_node_1.DOMNode), Ref(ui_element_1.UIElement), Ref(NativeNode))],
                attachment: [Or(enums_1.TooltipAttachment, Auto), "auto"],
                show_arrow: [Bool, true],
                closable: [Bool, false],
                interactive: [Bool, true],
            }));
            this.override({
                visible: false,
            });
        }
        show({ x, y }) {
            this.setv({ position: [x, y], visible: true }, { check_eq: false }); // XXX: force update
        }
        clear() {
            this.position = null;
        }
    }
    exports.Tooltip = Tooltip;
},
/* models/selectors/selector.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    class Selector extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Str }) => ({
                query: [Str],
            }));
        }
    }
    exports.Selector = Selector;
},
/* styles/tooltips.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.non_interactive = "bk-non-interactive";
    exports.arrow = "bk-arrow";
    exports.left = "bk-left";
    exports.right = "bk-right";
    exports.above = "bk-above";
    exports.below = "bk-below";
    exports.arrow_inner = "bk-arrow-inner";
    exports.show_arrow = "bk-show-arrow";
    exports.tooltip_content = "bk-tooltip-content";
    exports.tooltip_row_label = "bk-tooltip-row-label";
    exports.tooltip_row_value = "bk-tooltip-row-value";
    exports.tooltip_color_block = "bk-tooltip-color-block";
    exports.closable = "bk-closable";
    exports.close = "bk-close";
    exports.default = `:host{--tooltip-border:var(--divider-color);--tooltip-color:var(--background-color);--tooltip-text:var(--color);--tooltip-arrow-color:white;--tooltip-arrow-width:10px;--tooltip-arrow-height:10px;--tooltip-arrow-half-width:7px;--tooltip-arrow-half-height:7px;--tooltip-arrow-border:2px;--tooltip-arrow-inner-color:var(--icon-color);--tooltip-arrow-inner-width:calc(var(--tooltip-arrow-width) - var(--tooltip-arrow-border));--tooltip-arrow-inner-height:calc(var(--tooltip-arrow-height) - var(--tooltip-arrow-border));--tooltip-arrow-inner-half-width:calc(var(--tooltip-arrow-half-width) - var(--tooltip-arrow-border));--tooltip-arrow-inner-half-height:calc(var(--tooltip-arrow-half-height) - var(--tooltip-arrow-border));}:host{width:max-content;font-size:var(--font-size);position:fixed;padding:5px;border:1px solid var(--tooltip-border);color:var(--tooltip-text);background-color:var(--tooltip-color);opacity:0.95;z-index:var(--bokeh-top-level);margin:0;}:host(.bk-non-interactive){pointer-events:none;}.bk-arrow{pointer-events:none;position:fixed;width:0;height:0;content:" ";border-style:solid;border-color:transparent;}:host(.bk-left) .bk-arrow,:host(.bk-right) .bk-arrow{border-width:var(--tooltip-arrow-half-height) 0 var(--tooltip-arrow-half-height) 0;}:host(.bk-above) .bk-arrow,:host(.bk-below) .bk-arrow{border-width:0 var(--tooltip-arrow-half-width) 0 var(--tooltip-arrow-half-width);}:host(.bk-left) .bk-arrow{transform:translate(0%, -50%);border-right-width:var(--tooltip-arrow-width);border-right-color:var(--tooltip-arrow-color);}:host(.bk-right) .bk-arrow{transform:translate(-100%, -50%);border-left-width:var(--tooltip-arrow-width);border-left-color:var(--tooltip-arrow-color);}:host(.bk-above) .bk-arrow{transform:translate(-50%, 0%);border-bottom-width:var(--tooltip-arrow-height);border-bottom-color:var(--tooltip-arrow-color);}:host(.bk-below) .bk-arrow{transform:translate(-50%, -100%);border-top-width:var(--tooltip-arrow-height);border-top-color:var(--tooltip-arrow-color);}.bk-arrow-inner{pointer-events:none;position:fixed;width:0;height:0;content:" ";border-style:solid;border-color:transparent;}:host(.bk-left) .bk-arrow-inner,:host(.bk-right) .bk-arrow-inner{border-width:var(--tooltip-arrow-inner-half-height) 0 var(--tooltip-arrow-inner-half-height) 0;}:host(.bk-above) .bk-arrow-inner,:host(.bk-below) .bk-arrow-inner{border-width:0 var(--tooltip-arrow-inner-half-width) 0 var(--tooltip-arrow-inner-half-width);}:host(.bk-left) .bk-arrow-inner{left:calc(1 * var(--tooltip-arrow-border));transform:translate(0%, -50%);border-right-width:var(--tooltip-arrow-inner-width);border-right-color:var(--tooltip-arrow-inner-color);}:host(.bk-right) .bk-arrow-inner{left:calc(-1 * var(--tooltip-arrow-border));transform:translate(-100%, -50%);border-left-width:var(--tooltip-arrow-inner-width);border-left-color:var(--tooltip-arrow-inner-color);}:host(.bk-above) .bk-arrow-inner{top:calc(1 * var(--tooltip-arrow-border));transform:translate(-50%, 0%);border-bottom-width:var(--tooltip-arrow-inner-height);border-bottom-color:var(--tooltip-arrow-inner-color);}:host(.bk-below) .bk-arrow-inner{top:calc(-1 * var(--tooltip-arrow-border));transform:translate(-50%, -100%);border-top-width:var(--tooltip-arrow-inner-height);border-top-color:var(--tooltip-arrow-inner-color);}:host(:not(.bk-show-arrow)) .bk-arrow{display:none;}.bk-tooltip-content > div:not(:first-child){margin-top:5px;border-top:var(--tooltip-border) 1px dashed;}.bk-tooltip-row-label{text-align:right;color:#26aae1;}.bk-tooltip-row-value{color:none;}.bk-tooltip-color-block{width:12px;height:12px;margin-left:5px;margin-right:5px;outline:#dddddd solid 1px;display:inline-block;}:host(.bk-closable){padding-right:17px;}:host(:not(.bk-closable)) .bk-close{display:none;}.bk-close{position:absolute;top:2px;right:2px;width:12px;height:12px;cursor:pointer;background-color:gray;mask-image:var(--bokeh-icon-x);mask-size:contain;mask-repeat:no-repeat;-webkit-mask-image:var(--bokeh-icon-x);-webkit-mask-size:contain;-webkit-mask-repeat:no-repeat;}.bk-close:hover{background-color:red;}`;
},
/* models/layouts/tabs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const dom_1 = require(61) /* ../../core/dom */;
    const array_1 = require(10) /* ../../core/util/array */;
    const grid_1 = require(139) /* ../../core/layout/grid */;
    const enums_1 = require(21) /* ../../core/enums */;
    const layout_dom_1 = require(131) /* ./layout_dom */;
    const tab_panel_1 = require(515) /* ./tab_panel */;
    const alignments_1 = require(506) /* ./alignments */;
    const tabs_css_1 = tslib_1.__importStar(require(520) /* ../../styles/tabs.css */), tabs = tabs_css_1;
    const icons_css_1 = tslib_1.__importDefault(require(76) /* ../../styles/icons.css */);
    class TabsView extends layout_dom_1.LayoutDOMView {
        tooltip_views = new Map();
        _materialized_tabs = new Set();
        header_el;
        headers_wrapper_el;
        header_els;
        connect_signals() {
            super.connect_signals();
            const { tabs, active, link_layouts } = this.model.properties;
            this.on_change(tabs, async () => {
                this._update_headers();
                await this.update_children();
                this.update_active();
            });
            this.on_change([active, link_layouts], async () => {
                await this.update_children();
                this.update_active();
            });
            this.on_transitive_change(tabs, async () => {
                await this.update_children();
                this.update_active();
            }, { signal: (tab) => tab.properties.child.change });
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const { tabs } = this.model;
            const tooltips = tabs.map((tab) => tab.tooltip).filter((tt) => tt != null);
            await (0, build_views_1.build_views)(this.tooltip_views, tooltips, { parent: this });
        }
        stylesheets() {
            return [...super.stylesheets(), tabs_css_1.default, icons_css_1.default];
        }
        get child_models() {
            const { link_layouts, tabs } = this.model;
            if (link_layouts) {
                return tabs.map((tab) => tab.child);
            }
            else if (tabs.length == 0) {
                this._materialized_tabs.clear();
                return [];
            }
            else {
                const children = tabs.map((tab) => tab.child);
                const current = new Set(children);
                for (const child of this._materialized_tabs) {
                    if (!current.has(child)) {
                        this._materialized_tabs.delete(child);
                    }
                }
                this._materialized_tabs.add(tabs[this.normalized_active].child);
                return children.filter((child) => this._materialized_tabs.has(child));
            }
        }
        get normalized_active() {
            return Math.max(0, Math.min(this.model.active, this.model.tabs.length - 1));
        }
        _intrinsic_display() {
            return { inner: this.model.flow_mode, outer: "grid" };
        }
        _update_layout() {
            super._update_layout();
            const loc = this.model.tabs_location;
            this.class_list.remove([...enums_1.Location].map((loc) => tabs[loc]));
            this.class_list.add(tabs[loc]);
            for (const view of this.child_views) {
                view.parent_style.append(":host", { grid_area: "stack" });
            }
            if (this.model.link_layouts) {
                const layoutable = new grid_1.Container();
                for (const view of this.child_views) {
                    view.parent_style.append(":host", { grid_area: "stack" });
                    if (view instanceof layout_dom_1.LayoutDOMView && view.layout != null) {
                        layoutable.add({ r0: 0, c0: 0, r1: 1, c1: 1 }, view);
                    }
                }
                if (layoutable.size != 0) {
                    this.layout = new alignments_1.GridAlignmentLayout(layoutable);
                    this.layout.set_sizing();
                }
                else {
                    delete this.layout;
                }
            }
        }
        _after_layout() {
            super._after_layout();
            this.update_active();
        }
        render() {
            super.render();
            this.header_el = (0, dom_1.div)({ class: tabs.header });
            this.headers_wrapper_el = (0, dom_1.div)({ class: tabs.headers_wrapper });
            this.header_el.append(this.headers_wrapper_el);
            this.shadow_el.append(this.header_el);
            this._update_headers();
        }
        _update_headers() {
            const { active } = this.model;
            const headers = this.model.tabs.map((tab, i) => {
                const tab_el = (0, dom_1.div)({ class: [tabs.tab, i == active ? tabs.active : null], tabIndex: 0 }, tab.title);
                tab_el.addEventListener("click", (event) => {
                    if (this.model.disabled) {
                        return;
                    }
                    if (event.target == event.currentTarget) {
                        this.change_active(i);
                    }
                });
                const tooltip_view = tab.tooltip != null ? this.tooltip_views.get(tab.tooltip) : null;
                if (tooltip_view != null) {
                    tooltip_view.model.target = tab_el;
                    const toggle_tooltip = (visible) => {
                        tooltip_view.model.visible = visible;
                    };
                    tab_el.addEventListener("mouseenter", () => {
                        toggle_tooltip(true);
                    });
                    tab_el.addEventListener("mouseleave", () => {
                        toggle_tooltip(false);
                    });
                }
                if (tab.closable) {
                    const close_el = (0, dom_1.div)({ class: tabs.close });
                    close_el.addEventListener("click", (event) => {
                        if (event.target == event.currentTarget) {
                            this.model.tabs = (0, array_1.remove_at)(this.model.tabs, i);
                            const ntabs = this.model.tabs.length;
                            if (this.model.active > ntabs - 1) {
                                this.model.active = ntabs - 1;
                            }
                        }
                    });
                    tab_el.appendChild(close_el);
                }
                if (this.model.disabled || tab.disabled) {
                    tab_el.classList.add(tabs.disabled);
                }
                return tab_el;
            });
            this.header_els = headers;
            (0, dom_1.empty)(this.headers_wrapper_el);
            this.headers_wrapper_el.append(...headers);
        }
        change_active(i) {
            if (i != this.model.active) {
                this.model.active = i;
            }
        }
        update_active() {
            const i = this.normalized_active;
            const { header_els } = this;
            for (const el of header_els) {
                el.classList.remove(tabs.active);
            }
            if (i in header_els) {
                header_els[i].classList.add(tabs.active);
            }
            const { child_views } = this;
            for (const child_view of child_views) {
                (0, dom_1.hide)(child_view.el);
            }
            const active_child = this.model.tabs[i]?.child;
            const active_view = child_views.find((view) => view.model == active_child);
            if (active_view != null) {
                (0, dom_1.show)(active_view.el);
            }
        }
    }
    exports.TabsView = TabsView;
    class Tabs extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = TabsView;
            this.define(({ Int, List, Ref, Bool }) => ({
                tabs: [List(Ref(tab_panel_1.TabPanel)), []],
                tabs_location: [enums_1.Location, "above"],
                active: [Int, 0],
                link_layouts: [Bool, false],
            }));
        }
    }
    exports.Tabs = Tabs;
},
/* styles/tabs.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.above = "bk-above";
    exports.below = "bk-below";
    exports.left = "bk-left";
    exports.right = "bk-right";
    exports.header = "bk-header";
    exports.headers_wrapper = "bk-headers-wrapper";
    exports.tab = "bk-tab";
    exports.active = "bk-active";
    exports.close = "bk-close";
    exports.disabled = "bk-disabled";
    exports.icon = "bk-icon";
    exports.default = `:host{--block-start-border-width:3px;--close-icon-hover-background-color:var(--error);--close-icon-width:14px;--close-icon-height:14px;--close-icon-color:var(--icon-color);--close-icon-space-away-from-tab-text:10px;--padding-vertical:4px;--padding-horizontal:8px;--outline-offset:-5px;--disabled-opacity:0.65;}:host{display:grid;}:host(.bk-above){grid-template:"header" max-content "stack" 1fr / 1fr;}:host(.bk-below){grid-template:"stack" 1fr "header" max-content / 1fr;}:host(.bk-left){grid-template:"header stack" 1fr / max-content 1fr;}:host(.bk-right){grid-template:"stack header" 1fr / 1fr max-content;}.bk-header{grid-area:header;display:flex;overflow:hidden;user-select:none;-webkit-user-select:none;}.bk-headers-wrapper{display:flex;flex-wrap:nowrap;align-items:stretch;}:host(.bk-above) .bk-header,:host(.bk-below) .bk-header{flex-direction:row;}:host(.bk-above) .bk-headers-wrapper,:host(.bk-below) .bk-headers-wrapper{flex-direction:row;overflow-x:auto;overflow-y:hidden;}:host(.bk-left) .bk-header,:host(.bk-right) .bk-header{flex-direction:column;}:host(.bk-left) .bk-headers-wrapper,:host(.bk-right) .bk-headers-wrapper{flex-direction:column;overflow-x:hidden;overflow-y:auto;}:host(.bk-above) .bk-header{border-bottom:var(--divider);}:host(.bk-right) .bk-header{border-left:var(--divider);}:host(.bk-below) .bk-header{border-top:var(--divider);}:host(.bk-left) .bk-header{border-right:var(--divider);}.bk-tab{padding:var(--padding-vertical) var(--padding-horizontal);border:var(--border-style) transparent;outline:0;outline-offset:var(--outline-offset);white-space:nowrap;cursor:pointer;text-align:center;}.bk-tab:hover{background-color:var(--hover-color);}.bk-tab:focus,.bk-tab:active{outline:var(--outline);}.bk-tab.bk-active{color:var(--color);background-color:var(--background-color);border-color:var(--border-color);}.bk-tab .bk-close{margin-left:var(--close-icon-space-away-from-tab-text);}.bk-tab[disabled],.bk-tab.bk-disabled{background-color:inherit;color:inherit;cursor:not-allowed;pointer-events:none;opacity:var(--disabled-opacity);}.bk-tab[disabled] .bk-icon,.bk-tab.bk-disabled .bk-icon{color:inherit;}:host(.bk-above) .bk-tab{border-width:var(--block-start-border-width) var(--divider-width) 0 var(--divider-width);border-radius:var(--border-radius) var(--border-radius) 0 0;}:host(.bk-right) .bk-tab{border-width:var(--divider-width) var(--block-start-border-width) var(--divider-width) 0;border-radius:0 var(--border-radius) var(--border-radius) 0;}:host(.bk-below) .bk-tab{border-width:0 var(--divider-width) var(--block-start-border-width) var(--divider-width);border-radius:0 0 var(--border-radius) var(--border-radius);}:host(.bk-left) .bk-tab{border-width:var(--divider-width) 0 var(--divider-width) var(--block-start-border-width);border-radius:var(--border-radius) 0 0 var(--border-radius);}.bk-close{display:inline-block;vertical-align:middle;width:var(--close-icon-width);height:var(--close-icon-height);cursor:pointer;background-color:var(--close-icon-color);mask-image:var(--bokeh-icon-x);mask-size:contain;mask-repeat:no-repeat;-webkit-mask-image:var(--bokeh-icon-x);-webkit-mask-size:contain;-webkit-mask-repeat:no-repeat;}.bk-close:hover{background-color:var(--close-icon-hover-background-color);}`;
},
/* models/layouts/vbox.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const css_grid_box_1 = require(508) /* ./css_grid_box */;
    const kinds_1 = require(124) /* ../common/kinds */;
    const ui_element_1 = require(55) /* ../ui/ui_element */;
    const kinds_2 = require(22) /* ../../core/kinds */;
    const VBoxChild = (0, kinds_2.Struct)({ child: (0, kinds_2.Ref)(ui_element_1.UIElement), row: (0, kinds_2.Opt)(kinds_1.Index), span: (0, kinds_2.Opt)(kinds_1.Span) });
    class VBoxView extends css_grid_box_1.CSSGridBoxView {
        connect_signals() {
            super.connect_signals();
            const { children, rows } = this.model.properties;
            this.on_change(children, () => this.update_children());
            this.on_change(rows, () => this.invalidate_layout());
        }
        get _children() {
            return this.model.children.map(({ child, row, span }, i) => [child, row ?? i, 0, span ?? 1, 1]);
        }
        get _rows() {
            return this.model.rows;
        }
        get _cols() {
            return null;
        }
    }
    exports.VBoxView = VBoxView;
    class VBox extends css_grid_box_1.CSSGridBox {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = VBoxView;
            this.define(({ List, Nullable }) => ({
                children: [List(VBoxChild), []],
                rows: [Nullable(kinds_1.TracksSizing), null],
            }));
        }
    }
    exports.VBox = VBox;
},
/* models/misc/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var group_by_1 = require(523) /* ./group_by */;
    __esExport("GroupByModels", group_by_1.GroupByModels);
    __esExport("GroupByName", group_by_1.GroupByName);
},
/* models/misc/group_by.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    const kinds_1 = require(22) /* ../../core/kinds */;
    class GroupBy extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.GroupBy = GroupBy;
    class GroupByModels extends GroupBy {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define({
                groups: [(0, kinds_1.List)((0, kinds_1.List)((0, kinds_1.Ref)(model_1.Model)))],
            });
        }
        *query_groups(models, _pool) {
            for (const model of models) {
                for (const group of this.groups) {
                    if (group.includes(model)) {
                        yield group;
                    }
                }
            }
        }
    }
    exports.GroupByModels = GroupByModels;
    class GroupByName extends GroupBy {
        constructor(attrs) {
            super(attrs);
        }
        *query_groups(models, pool) {
            const groups = new Map();
            for (const model of pool) {
                const { name } = model;
                if (name != null) {
                    let group = groups.get(name);
                    if (group === undefined) {
                        group = new Set();
                        groups.set(name, group);
                    }
                    group.add(model);
                }
            }
            for (const model of models) {
                for (const group of groups.values()) {
                    if (model.name != null && group.has(model)) {
                        yield [...group];
                    }
                }
            }
        }
    }
    exports.GroupByName = GroupByName;
},
/* models/text/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var math_text_1 = require(260) /* ./math_text */;
    __esExport("MathText", math_text_1.MathText);
    __esExport("Ascii", math_text_1.Ascii);
    __esExport("MathML", math_text_1.MathML);
    __esExport("TeX", math_text_1.TeX);
    var plain_text_1 = require(266) /* ./plain_text */;
    __esExport("PlainText", plain_text_1.PlainText);
},
/* models/transforms/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var customjs_transform_1 = require(526) /* ./customjs_transform */;
    __esExport("CustomJSTransform", customjs_transform_1.CustomJSTransform);
    var dodge_1 = require(527) /* ./dodge */;
    __esExport("Dodge", dodge_1.Dodge);
    var interpolator_1 = require(529) /* ./interpolator */;
    __esExport("Interpolator", interpolator_1.Interpolator);
    var jitter_1 = require(530) /* ./jitter */;
    __esExport("Jitter", jitter_1.Jitter);
    var linear_interpolator_1 = require(532) /* ./linear_interpolator */;
    __esExport("LinearInterpolator", linear_interpolator_1.LinearInterpolator);
    var step_interpolator_1 = require(533) /* ./step_interpolator */;
    __esExport("StepInterpolator", step_interpolator_1.StepInterpolator);
    var transform_1 = require(109) /* ./transform */;
    __esExport("Transform", transform_1.Transform);
},
/* models/transforms/customjs_transform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const transform_1 = require(109) /* ./transform */;
    const object_1 = require(9) /* ../../core/util/object */;
    const string_1 = require(41) /* ../../core/util/string */;
    class CustomJSTransform extends transform_1.Transform {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Unknown, Str, Dict }) => ({
                args: [Dict(Unknown), {}],
                func: [Str, ""],
                v_func: [Str, ""],
            }));
        }
        get names() {
            return (0, object_1.keys)(this.args);
        }
        get values() {
            return (0, object_1.values)(this.args);
        }
        _make_transform(name, func) {
            return new Function(...this.names, name, (0, string_1.use_strict)(func));
        }
        get scalar_transform() {
            return this._make_transform("x", this.func);
        }
        get vector_transform() {
            return this._make_transform("xs", this.v_func);
        }
        compute(x) {
            return this.scalar_transform(...this.values, x);
        }
        v_compute(xs) {
            return this.vector_transform(...this.values, xs);
        }
    }
    exports.CustomJSTransform = CustomJSTransform;
},
/* models/transforms/dodge.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const range_transform_1 = require(528) /* ./range_transform */;
    class Dodge extends range_transform_1.RangeTransform {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Float }) => ({
                value: [Float, 0],
            }));
        }
        _compute(x) {
            return x + this.value;
        }
    }
    exports.Dodge = Dodge;
},
/* models/transforms/range_transform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const transform_1 = require(109) /* ./transform */;
    const range_1 = require(110) /* ../ranges/range */;
    const factor_range_1 = require(121) /* ../ranges/factor_range */;
    const types_1 = require(25) /* ../../core/types */;
    const types_2 = require(8) /* ../../core/util/types */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    class RangeTransform extends transform_1.Transform {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Ref, Nullable }) => ({
                range: [Nullable(Ref(range_1.Range)), null],
            }));
        }
        v_compute(xs0) {
            let xs;
            if (this.range instanceof factor_range_1.FactorRange) {
                xs = this.range.v_synthetic(xs0);
            }
            else if ((0, types_2.isArrayableOf)(xs0, types_2.isNumber)) {
                xs = xs0;
            }
            else {
                (0, assert_1.unreachable)();
            }
            const result = new ((0, types_1.infer_type)(xs))(xs.length);
            for (let i = 0; i < xs.length; i++) {
                const x = xs[i];
                result[i] = this._compute(x);
            }
            return result;
        }
        compute(x) {
            if (this.range instanceof factor_range_1.FactorRange) {
                return this._compute(this.range.synthetic(x));
            }
            else if ((0, types_2.isNumber)(x)) {
                return this._compute(x);
            }
            else {
                (0, assert_1.unreachable)();
            }
        }
    }
    exports.RangeTransform = RangeTransform;
},
/* models/transforms/interpolator.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const transform_1 = require(109) /* ./transform */;
    const columnar_data_source_1 = require(142) /* ../sources/columnar_data_source */;
    const types_1 = require(25) /* ../../core/types */;
    const array_1 = require(10) /* ../../core/util/array */;
    const types_2 = require(8) /* ../../core/util/types */;
    class Interpolator extends transform_1.Transform {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Bool, Float, Str, Ref, List, Or, Nullable }) => ({
                x: [Or(Str, List(Float))],
                y: [Or(Str, List(Float))],
                data: [Nullable(Ref(columnar_data_source_1.ColumnarDataSource)), null],
                clip: [Bool, true],
            }));
        }
        _x_sorted;
        _y_sorted;
        _sorted_dirty = true;
        connect_signals() {
            super.connect_signals();
            this.connect(this.change, () => this._sorted_dirty = true);
        }
        v_compute(xs) {
            const ArrayType = (0, types_1.infer_type)(xs);
            const result = new ArrayType(xs.length);
            for (let i = 0; i < xs.length; i++) {
                const x = xs[i];
                result[i] = this.compute(x);
            }
            return result;
        }
        sort(descending = false) {
            if (!this._sorted_dirty) {
                return;
            }
            let tsx;
            let tsy;
            if ((0, types_2.isString)(this.x) && (0, types_2.isString)(this.y) && this.data != null) {
                const column_names = this.data.columns();
                if (!(0, array_1.includes)(column_names, this.x)) {
                    throw new Error("The x parameter does not correspond to a valid column name defined in the data parameter");
                }
                if (!(0, array_1.includes)(column_names, this.y)) {
                    throw new Error("The y parameter does not correspond to a valid column name defined in the data parameter");
                }
                tsx = this.data.get_column(this.x);
                tsy = this.data.get_column(this.y);
            }
            else if ((0, types_2.isArray)(this.x) && (0, types_2.isArray)(this.y)) {
                tsx = this.x;
                tsy = this.y;
            }
            else {
                throw new Error("parameters 'x' and 'y' must be both either string fields or arrays");
            }
            if (tsx.length !== tsy.length) {
                throw new Error("The length for x and y do not match");
            }
            if (tsx.length < 2) {
                throw new Error("x and y must have at least two elements to support interpolation");
            }
            const n = tsx.length;
            const index = new Uint32Array(n);
            for (let i = 0; i < n; i++) {
                index[i] = i;
            }
            const sign = descending ? -1 : 1;
            index.sort((i, j) => sign * (tsx[i] - tsx[j]));
            this._x_sorted = new ((0, types_1.infer_type)(tsx))(n);
            this._y_sorted = new ((0, types_1.infer_type)(tsy))(n);
            for (let i = 0; i < n; i++) {
                this._x_sorted[i] = tsx[index[i]];
                this._y_sorted[i] = tsy[index[i]];
            }
            this._sorted_dirty = false;
        }
    }
    exports.Interpolator = Interpolator;
},
/* models/transforms/jitter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const range_transform_1 = require(528) /* ./range_transform */;
    const factor_range_1 = require(121) /* ../ranges/factor_range */;
    const random_generator_1 = require(531) /* ../random/random_generator */;
    const enums_1 = require(21) /* ../../core/enums */;
    const arrayable_1 = require(14) /* ../../core/util/arrayable */;
    const random_1 = require(74) /* ../../core/util/random */;
    class Jitter extends range_transform_1.RangeTransform {
        _previous_offsets = null;
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Float }) => ({
                mean: [Float, 0],
                width: [Float, 1],
                distribution: [enums_1.Distribution, "uniform"],
            }));
            this.internal(({ Nullable, Ref, AnyRef }) => ({
                _generator: [AnyRef()], // TODO computed property
                random_generator: [Nullable(Ref(random_generator_1.RandomGenerator)), null, {
                        on_update(value, obj) {
                            obj._generator = value?.generator() ?? new random_1.SystemRandom();
                        },
                    }],
            }));
        }
        v_compute(xs0) {
            const xs = (() => {
                if (this.range instanceof factor_range_1.FactorRange) {
                    return this.range.v_synthetic(xs0);
                }
                else {
                    return xs0;
                }
            })();
            const offsets = (() => {
                const xs_length = xs.length;
                if (this._previous_offsets?.length != xs_length) {
                    this._previous_offsets = this._v_compute(xs_length);
                }
                return this._previous_offsets;
            })();
            return (0, arrayable_1.map)(offsets, (offset, i) => offset + xs[i]);
        }
        _compute() {
            const { mean, width } = this;
            switch (this.distribution) {
                case "uniform": return this._generator.uniform(mean, width);
                case "normal": return this._generator.normal(mean, width);
            }
        }
        _v_compute(n) {
            const { mean, width } = this;
            switch (this.distribution) {
                case "uniform": return this._generator.uniforms(mean, width, n);
                case "normal": return this._generator.normals(mean, width, n);
            }
        }
    }
    exports.Jitter = Jitter;
},
/* models/random/random_generator.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    class RandomGenerator extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.RandomGenerator = RandomGenerator;
},
/* models/transforms/linear_interpolator.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const array_1 = require(10) /* ../../core/util/array */;
    const interpolator_1 = require(529) /* ./interpolator */;
    class LinearInterpolator extends interpolator_1.Interpolator {
        constructor(attrs) {
            super(attrs);
        }
        compute(x) {
            this.sort(false);
            if (this.clip) {
                if (x < this._x_sorted[0] || x > this._x_sorted[this._x_sorted.length - 1]) {
                    return NaN;
                }
            }
            else {
                if (x < this._x_sorted[0]) {
                    return this._y_sorted[0];
                }
                if (x > this._x_sorted[this._x_sorted.length - 1]) {
                    return this._y_sorted[this._y_sorted.length - 1];
                }
            }
            if (x == this._x_sorted[0]) {
                return this._y_sorted[0];
            }
            const ind = (0, array_1.find_last_index)(this._x_sorted, num => num < x);
            const x1 = this._x_sorted[ind];
            const x2 = this._x_sorted[ind + 1];
            const y1 = this._y_sorted[ind];
            const y2 = this._y_sorted[ind + 1];
            return y1 + (((x - x1) / (x2 - x1)) * (y2 - y1));
        }
    }
    exports.LinearInterpolator = LinearInterpolator;
},
/* models/transforms/step_interpolator.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const interpolator_1 = require(529) /* ./interpolator */;
    const enums_1 = require(21) /* ../../core/enums */;
    const array_1 = require(10) /* ../../core/util/array */;
    class StepInterpolator extends interpolator_1.Interpolator {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(() => ({
                mode: [enums_1.StepMode, "after"],
            }));
        }
        compute(x) {
            this.sort(false);
            if (this.clip) {
                if (x < this._x_sorted[0] || x > this._x_sorted[this._x_sorted.length - 1]) {
                    return NaN;
                }
            }
            else {
                if (x < this._x_sorted[0]) {
                    return this._y_sorted[0];
                }
                if (x > this._x_sorted[this._x_sorted.length - 1]) {
                    return this._y_sorted[this._y_sorted.length - 1];
                }
            }
            let ind;
            switch (this.mode) {
                case "after": {
                    ind = (0, array_1.find_last_index)(this._x_sorted, num => x >= num);
                    break;
                }
                case "before": {
                    ind = (0, array_1.find_index)(this._x_sorted, num => x <= num);
                    break;
                }
                case "center": {
                    const diffs = (0, array_1.map)(this._x_sorted, (tx) => Math.abs(tx - x));
                    const mdiff = (0, array_1.min)(diffs);
                    ind = (0, array_1.find_index)(diffs, num => mdiff === num);
                    break;
                }
                default:
                    throw new Error(`unknown mode: ${this.mode}`);
            }
            return ind != -1 ? this._y_sorted[ind] : NaN;
        }
    }
    exports.StepInterpolator = StepInterpolator;
},
/* models/plots/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var gmap_plot_1 = require(535) /* ./gmap_plot */;
    __esExport("MapOptions", gmap_plot_1.MapOptions);
    var gmap_plot_2 = require(535) /* ./gmap_plot */;
    __esExport("GMapOptions", gmap_plot_2.GMapOptions);
    var gmap_plot_3 = require(535) /* ./gmap_plot */;
    __esExport("GMapPlot", gmap_plot_3.GMapPlot);
    var gmap_1 = require(537) /* ./gmap */;
    __esExport("GMap", gmap_1.GMap);
    var plot_1 = require(376) /* ./plot */;
    __esExport("Plot", plot_1.Plot);
    var grid_plot_1 = require(538) /* ./grid_plot */;
    __esExport("GridPlot", grid_plot_1.GridPlot);
    var figure_1 = require(539) /* ./figure */;
    __esExport("Figure", figure_1.Figure);
},
/* models/plots/gmap_plot.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const plot_1 = require(376) /* ./plot */;
    const enums_1 = require(21) /* ../../core/enums */;
    const model_1 = require(52) /* ../../model */;
    const range1d_1 = require(111) /* ../ranges/range1d */;
    const gmap_plot_canvas_1 = require(536) /* ./gmap_plot_canvas */;
    __esExport("GMapPlotView", gmap_plot_canvas_1.GMapPlotView);
    class MapOptions extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Int, Float }) => ({
                lat: [Float],
                lng: [Float],
                zoom: [Int, 12],
            }));
        }
    }
    exports.MapOptions = MapOptions;
    class GMapOptions extends MapOptions {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Bool, Int, Str, Nullable }) => ({
                map_type: [enums_1.MapType, "roadmap"],
                scale_control: [Bool, false],
                styles: [Nullable(Str), null],
                tilt: [Int, 45],
            }));
        }
    }
    exports.GMapOptions = GMapOptions;
    class GMapPlot extends plot_1.Plot {
        use_map = true;
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = gmap_plot_canvas_1.GMapPlotView;
            this.define(({ Str, Bytes, Ref }) => ({
                map_options: [Ref(GMapOptions)],
                api_key: [Bytes],
                api_version: [Str, "weekly"],
            }));
            this.override({
                x_range: () => new range1d_1.Range1d(),
                y_range: () => new range1d_1.Range1d(),
                background_fill_alpha: 0.0,
            });
        }
    }
    exports.GMapPlot = GMapPlot;
},
/* models/plots/gmap_plot_canvas.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const logging_1 = require(11) /* ../../core/logging */;
    const signaling_1 = require(17) /* ../../core/signaling */;
    const dom_1 = require(61) /* ../../core/dom */;
    const projections_1 = require(148) /* ../../core/util/projections */;
    const plot_canvas_1 = require(398) /* ./plot_canvas */;
    function has_maps_API() {
        return typeof google != "undefined" && typeof google.maps != "undefined";
    }
    const gmaps_ready = new signaling_1.Signal0({}, "gmaps_ready");
    const load_google_api = function (api_key, api_version) {
        window._bokeh_gmaps_callback = () => gmaps_ready.emit();
        const enc = encodeURIComponent;
        const script = document.createElement("script");
        script.src = `https://maps.googleapis.com/maps/api/js?v=${enc(api_version)}&key=${enc(api_key)}&callback=_bokeh_gmaps_callback&loading=async`;
        document.body.appendChild(script);
    };
    class GMapPlotView extends plot_canvas_1.PlotView {
        _tiles_loaded;
        zoom_count;
        initial_zoom;
        initial_lat;
        initial_lng;
        map_el;
        map;
        map_types;
        _api_key;
        initialize() {
            super.initialize();
            this._tiles_loaded = false;
            this.zoom_count = 0;
            const { zoom, lat, lng } = this.model.map_options;
            this.initial_zoom = zoom;
            this.initial_lat = lat;
            this.initial_lng = lng;
            const decoder = new TextDecoder("utf-8");
            this._api_key = decoder.decode(this.model.api_key);
            if (this._api_key == "") {
                const url = "https://developers.google.com/maps/documentation/javascript/get-api-key";
                logging_1.logger.error(`api_key is required. See ${url} for more information on how to obtain your own.`);
            }
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            this.map_el = (0, dom_1.div)({ style: { position: "absolute" } });
            this.canvas_view.underlays_el.append(this.map_el);
            if (!has_maps_API()) {
                if (typeof window._bokeh_gmaps_callback === "undefined") {
                    const { api_version } = this.model;
                    load_google_api(this._api_key, api_version);
                }
                gmaps_ready.connect(() => {
                    this._build_map();
                    this.request_repaint();
                });
            }
            else {
                this._build_map();
            }
        }
        remove() {
            this.map_el.remove();
            super.remove();
        }
        update_range(range_info, options) {
            // RESET -------------------------
            if (range_info == null) {
                this.map.setCenter({ lat: this.initial_lat, lng: this.initial_lng });
                this.map.setOptions({ zoom: this.initial_zoom });
                super.reset_range();
                // PAN ----------------------------
            }
            else if (range_info.sdx != null || range_info.sdy != null) {
                this.map.panBy(range_info.sdx ?? 0, range_info.sdy ?? 0);
                super.update_range(range_info, options);
                // ZOOM ---------------------------
            }
            else if (range_info.factor != null) {
                // The zoom count decreases the sensitivity of the zoom. (We could make this user configurable)
                if (this.zoom_count !== 10) {
                    this.zoom_count += 1;
                    return;
                }
                this.zoom_count = 0;
                this.pause();
                super.update_range(range_info, options);
                const zoom_change = range_info.factor < 0 ? -1 : 1;
                const old_map_zoom = this.map.getZoom();
                const bounds = this.map.getBounds();
                if (old_map_zoom != null && bounds != null) {
                    const new_map_zoom = old_map_zoom + zoom_change;
                    // Zooming out too far causes problems
                    if (new_map_zoom >= 2) {
                        this.map.setZoom(new_map_zoom);
                        // Check we haven't gone out of bounds, and if we have undo the zoom
                        const [proj_xstart, proj_xend] = this._get_projected_bounds(bounds);
                        if (proj_xend - proj_xstart < 0) {
                            this.map.setZoom(old_map_zoom);
                        }
                    }
                }
                this.unpause();
            }
            // Finally re-center
            this._set_bokeh_ranges();
        }
        _build_map() {
            const { maps } = google;
            this.map_types = {
                satellite: maps.MapTypeId.SATELLITE,
                terrain: maps.MapTypeId.TERRAIN,
                roadmap: maps.MapTypeId.ROADMAP,
                hybrid: maps.MapTypeId.HYBRID,
            };
            const mo = this.model.map_options;
            const map_options = {
                center: new maps.LatLng(mo.lat, mo.lng),
                zoom: mo.zoom,
                disableDefaultUI: true,
                mapTypeId: this.map_types[mo.map_type],
                scaleControl: mo.scale_control,
                tilt: mo.tilt,
            };
            if (mo.styles != null) {
                map_options.styles = JSON.parse(mo.styles);
            }
            // create the map with above options in div
            this.map = new maps.Map(this.map_el, map_options);
            // update bokeh ranges whenever the map idles, which should be after most UI action
            maps.event.addListener(this.map, "idle", () => this._set_bokeh_ranges());
            // also need an event when bounds change so that map resizes trigger renders too
            maps.event.addListener(this.map, "bounds_changed", () => this._set_bokeh_ranges());
            maps.event.addListenerOnce(this.map, "tilesloaded", () => this._render_finished());
            // wire up listeners so that changes to properties are reflected
            this.connect(this.model.properties.map_options.change, () => this._update_options());
            this.connect(this.model.map_options.properties.styles.change, () => this._update_styling());
            this.connect(this.model.map_options.properties.lat.change, () => this._update_center("lat"));
            this.connect(this.model.map_options.properties.lng.change, () => this._update_center("lng"));
            this.connect(this.model.map_options.properties.zoom.change, () => this._update_zoom());
            this.connect(this.model.map_options.properties.map_type.change, () => this._update_map_type());
            this.connect(this.model.map_options.properties.scale_control.change, () => this._update_scale_control());
            this.connect(this.model.map_options.properties.tilt.change, () => this._update_tilt());
        }
        _render_finished() {
            this._tiles_loaded = true;
            this.notify_finished();
        }
        has_finished() {
            return super.has_finished() && this._tiles_loaded === true;
        }
        _get_latlon_bounds(bounds) {
            const top_right = bounds.getNorthEast();
            const bottom_left = bounds.getSouthWest();
            const xstart = bottom_left.lng();
            const xend = top_right.lng();
            const ystart = bottom_left.lat();
            const yend = top_right.lat();
            return [xstart, xend, ystart, yend];
        }
        _get_projected_bounds(bounds) {
            const [xstart, xend, ystart, yend] = this._get_latlon_bounds(bounds);
            const [proj_xstart, proj_ystart] = projections_1.wgs84_mercator.compute(xstart, ystart);
            const [proj_xend, proj_yend] = projections_1.wgs84_mercator.compute(xend, yend);
            return [proj_xstart, proj_xend, proj_ystart, proj_yend];
        }
        _set_bokeh_ranges() {
            const bounds = this.map.getBounds();
            if (bounds != null) {
                const [proj_xstart, proj_xend, proj_ystart, proj_yend] = this._get_projected_bounds(bounds);
                this.frame.x_range.setv({ start: proj_xstart, end: proj_xend });
                this.frame.y_range.setv({ start: proj_ystart, end: proj_yend });
            }
        }
        _update_center(fld) {
            const center = this.map.getCenter()?.toJSON();
            if (center != null) {
                center[fld] = this.model.map_options[fld];
                this.map.setCenter(center);
                this._set_bokeh_ranges();
            }
        }
        _update_map_type() {
            this.map.setOptions({ mapTypeId: this.map_types[this.model.map_options.map_type] });
        }
        _update_scale_control() {
            this.map.setOptions({ scaleControl: this.model.map_options.scale_control });
        }
        _update_tilt() {
            this.map.setOptions({ tilt: this.model.map_options.tilt });
        }
        _update_options() {
            this._update_styling();
            this._update_center("lat");
            this._update_center("lng");
            this._update_zoom();
            this._update_map_type();
        }
        _update_styling() {
            const { styles } = this.model.map_options;
            this.map.setOptions({ styles: styles != null ? JSON.parse(styles) : null });
        }
        _update_zoom() {
            this.map.setOptions({ zoom: this.model.map_options.zoom });
            this._set_bokeh_ranges();
        }
        _after_layout() {
            super._after_layout();
            const { left, top, width, height } = this.frame.bbox;
            this.map_el.style.top = `${top}px`;
            this.map_el.style.left = `${left}px`;
            this.map_el.style.width = `${width}px`;
            this.map_el.style.height = `${height}px`;
        }
    }
    exports.GMapPlotView = GMapPlotView;
},
/* models/plots/gmap.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const gmap_plot_1 = require(535) /* ./gmap_plot */;
    class GMapView extends gmap_plot_1.GMapPlotView {
    }
    exports.GMapView = GMapView;
    class GMap extends gmap_plot_1.GMapPlot {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = GMapView;
        }
    }
    exports.GMap = GMap;
},
/* models/plots/grid_plot.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const layout_dom_1 = require(131) /* ../layouts/layout_dom */;
    const ui_element_1 = require(55) /* ../ui/ui_element */;
    const grid_box_1 = require(507) /* ../layouts/grid_box */;
    const kinds_1 = require(124) /* ../common/kinds */;
    const toolbar_1 = require(378) /* ../tools/toolbar */;
    const action_tool_1 = require(393) /* ../tools/actions/action_tool */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const enums_1 = require(21) /* ../../core/enums */;
    class GridPlotView extends layout_dom_1.LayoutDOMView {
        _grid_box;
        get toolbar_view() {
            return this.child_views.find((v) => v.model == this.model.toolbar);
        }
        get grid_box_view() {
            return this.child_views.find((v) => v.model == this._grid_box);
        }
        _update_location() {
            const location = this.model.toolbar_location;
            if (location == null) {
                this.model.toolbar.visible = false;
            }
            else {
                this.model.toolbar.setv({ visible: true, location });
            }
        }
        initialize() {
            super.initialize();
            this._update_location();
            const { children, rows, cols, spacing } = this.model;
            this._grid_box = new grid_box_1.GridBox({ children, rows, cols, spacing, sizing_mode: "inherit" });
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this.build_tool_views();
        }
        connect_signals() {
            super.connect_signals();
            const { toolbar, toolbar_location, children, rows, cols, spacing } = this.model.properties;
            this.on_change(toolbar_location, async () => {
                this._update_location();
                this.invalidate_layout();
            });
            this.on_change(toolbar, async () => {
                await this.update_children();
            });
            this.on_change([children, rows, cols, spacing], async () => {
                const { children, rows, cols, spacing } = this.model;
                this._grid_box.setv({ children, rows, cols, spacing });
                await this.grid_box_view.ready;
            });
            this.on_change(this.model.toolbar.properties.tools, async () => {
                await this.build_tool_views();
            });
            this.mouseenter.connect(() => {
                this.toolbar_view.set_visibility(true);
            });
            this.mouseleave.connect(() => {
                this.toolbar_view.set_visibility(false);
            });
        }
        _tool_views = new Map();
        async build_tool_views() {
            const tools = this.model.toolbar.tools.filter((tool) => tool instanceof action_tool_1.ActionTool);
            await (0, build_views_1.build_views)(this._tool_views, tools, { parent: this });
        }
        children_views() {
            return [...super.children_views(), ...this._tool_views.values()];
        }
        get child_models() {
            return [this.model.toolbar, this._grid_box];
        }
        _intrinsic_display() {
            return { inner: this.model.flow_mode, outer: "flex" };
        }
        _update_layout() {
            super._update_layout();
            const { location } = this.model.toolbar;
            const flex_direction = (() => {
                switch (location) {
                    case "above": return "column";
                    case "below": return "column-reverse";
                    case "left": return "row";
                    case "right": return "row-reverse";
                }
            })();
            this.style.append(":host", { flex_direction });
        }
    }
    exports.GridPlotView = GridPlotView;
    class GridPlot extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = GridPlotView;
            this.define(({ List, Ref, Nullable }) => ({
                toolbar: [Ref(toolbar_1.Toolbar), () => new toolbar_1.Toolbar()],
                toolbar_location: [Nullable(enums_1.Location), "above"],
                children: [List((0, kinds_1.GridChild)(ui_element_1.UIElement)), []],
                rows: [Nullable(kinds_1.TracksSizing), null],
                cols: [Nullable(kinds_1.TracksSizing), null],
                spacing: [kinds_1.GridSpacing, 0],
            }));
        }
    }
    exports.GridPlot = GridPlot;
},
/* models/plots/figure.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const plot_1 = require(376) /* ./plot */;
    class FigureView extends plot_1.PlotView {
    }
    exports.FigureView = FigureView;
    class Figure extends plot_1.Plot {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = FigureView;
        }
    }
    exports.Figure = Figure;
},
/* models/policies/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(276) /* ./labeling */, exports);
},
/* models/random/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var park_miller_lcg_1 = require(542) /* ./park_miller_lcg */;
    __esExport("ParkMillerLCG", park_miller_lcg_1.ParkMillerLCG);
},
/* models/random/park_miller_lcg.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const random_generator_1 = require(531) /* ./random_generator */;
    const random_1 = require(74) /* ../../core/util/random */;
    class ParkMillerLCG extends random_generator_1.RandomGenerator {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Int, Nullable }) => ({
                seed: [Nullable(Int), null],
            }));
        }
        generator() {
            return new random_1.LCGRandom(this.seed ?? Date.now());
        }
    }
    exports.ParkMillerLCG = ParkMillerLCG;
},
/* models/renderers/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var contour_renderer_1 = require(544) /* ./contour_renderer */;
    __esExport("ContourRenderer", contour_renderer_1.ContourRenderer);
    var glyph_renderer_1 = require(302) /* ./glyph_renderer */;
    __esExport("GlyphRenderer", glyph_renderer_1.GlyphRenderer);
    var graph_renderer_1 = require(545) /* ./graph_renderer */;
    __esExport("GraphRenderer", graph_renderer_1.GraphRenderer);
    var guide_renderer_1 = require(273) /* ./guide_renderer */;
    __esExport("GuideRenderer", guide_renderer_1.GuideRenderer);
    var renderer_1 = require(98) /* ./renderer */;
    __esExport("Renderer", renderer_1.Renderer);
    var renderer_group_1 = require(129) /* ./renderer_group */;
    __esExport("RendererGroup", renderer_group_1.RendererGroup);
},
/* models/renderers/contour_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const data_renderer_1 = require(303) /* ./data_renderer */;
    const glyph_renderer_1 = require(302) /* ./glyph_renderer */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    class ContourRendererView extends data_renderer_1.DataRendererView {
        fill_view;
        line_view;
        children_views() {
            return [...super.children_views(), this.fill_view, this.line_view];
        }
        get glyph_view() {
            if (this.fill_view.glyph.data_size > 0) {
                return this.fill_view.glyph;
            }
            else {
                return this.line_view.glyph;
            }
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const { parent } = this;
            const { fill_renderer, line_renderer } = this.model;
            this.fill_view = await (0, build_views_1.build_view)(fill_renderer, { parent });
            this.line_view = await (0, build_views_1.build_view)(line_renderer, { parent });
        }
        _paint(ctx) {
            this.fill_view.paint(ctx);
            this.line_view.paint(ctx);
        }
        hit_test(geometry) {
            return this.fill_view.hit_test(geometry);
        }
    }
    exports.ContourRendererView = ContourRendererView;
    class ContourRenderer extends data_renderer_1.DataRenderer {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ContourRendererView;
            this.define(({ List, Float, Ref }) => ({
                fill_renderer: [Ref(glyph_renderer_1.GlyphRenderer)],
                line_renderer: [Ref(glyph_renderer_1.GlyphRenderer)],
                levels: [List(Float), []],
            }));
        }
        get_selection_manager() {
            return this.fill_renderer.data_source.selection_manager;
        }
    }
    exports.ContourRenderer = ContourRenderer;
},
/* models/renderers/graph_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const data_renderer_1 = require(303) /* ./data_renderer */;
    const glyph_renderer_1 = require(302) /* ./glyph_renderer */;
    const layout_provider_1 = require(500) /* ../graphs/layout_provider */;
    const graph_hit_test_policy_1 = require(499) /* ../graphs/graph_hit_test_policy */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    const logging_1 = require(11) /* ../../core/logging */;
    const xy_glyph_1 = require(305) /* ../glyphs/xy_glyph */;
    const multi_line_1 = require(478) /* ../glyphs/multi_line */;
    const patches_1 = require(481) /* ../glyphs/patches */;
    class GraphRendererView extends data_renderer_1.DataRendererView {
        edge_view;
        node_view;
        get glyph_view() {
            return this.node_view.glyph;
        }
        children_views() {
            return [...super.children_views(), this.edge_view, this.node_view];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            this.apply_coordinates();
            const { parent } = this;
            const { edge_renderer, node_renderer } = this.model;
            this.edge_view = await (0, build_views_1.build_view)(edge_renderer, { parent });
            this.node_view = await (0, build_views_1.build_view)(node_renderer, { parent });
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.layout_provider.change, async () => {
                this.apply_coordinates();
                await this.edge_view.set_data();
                await this.node_view.set_data();
                this.request_paint();
            });
        }
        apply_coordinates() {
            const { edge_renderer, node_renderer } = this.model;
            const edge_coords = this.model.layout_provider.edge_coordinates;
            const node_coords = this.model.layout_provider.node_coordinates;
            const xs = { expr: edge_coords.x };
            const ys = { expr: edge_coords.y };
            const x = { expr: node_coords.x };
            const y = { expr: node_coords.y };
            const edge_glyphs = [
                edge_renderer.glyph,
                edge_renderer.hover_glyph,
                edge_renderer.muted_glyph,
                edge_renderer.selection_glyph,
                edge_renderer.nonselection_glyph,
            ];
            const node_glyphs = [
                node_renderer.glyph,
                node_renderer.hover_glyph,
                node_renderer.muted_glyph,
                node_renderer.selection_glyph,
                node_renderer.nonselection_glyph,
            ];
            for (const glyph of edge_glyphs) {
                if (glyph == null || glyph == "auto") {
                    continue;
                }
                if (!(glyph instanceof multi_line_1.MultiLine || glyph instanceof patches_1.Patches)) {
                    logging_1.logger.warn(`${this}.edge_renderer only supports MultiLine and Patches glyphs`);
                    continue;
                }
                glyph.properties.xs.internal = true;
                glyph.properties.ys.internal = true;
                glyph.xs = xs;
                glyph.ys = ys;
            }
            for (const glyph of node_glyphs) {
                if (glyph == null || glyph == "auto") {
                    continue;
                }
                if (!(glyph instanceof xy_glyph_1.XYGlyph)) {
                    logging_1.logger.warn(`${this}.node_renderer only supports XY glyphs`);
                    continue;
                }
                glyph.properties.x.internal = true;
                glyph.properties.y.internal = true;
                glyph.x = x;
                glyph.y = y;
            }
        }
        _paint(ctx) {
            this.edge_view.paint(ctx);
            this.node_view.paint(ctx);
        }
        get has_webgl() {
            return this.edge_view.has_webgl || this.node_view.has_webgl;
        }
        hit_test(geometry) {
            return this.model.inspection_policy.hit_test(geometry, this);
        }
    }
    exports.GraphRendererView = GraphRendererView;
    class GraphRenderer extends data_renderer_1.DataRenderer {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = GraphRendererView;
            this.define(({ Ref }) => ({
                layout_provider: [Ref(layout_provider_1.LayoutProvider)],
                node_renderer: [Ref(glyph_renderer_1.GlyphRenderer)],
                edge_renderer: [Ref(glyph_renderer_1.GlyphRenderer)],
                selection_policy: [Ref(graph_hit_test_policy_1.GraphHitTestPolicy), () => new graph_hit_test_policy_1.NodesOnly()],
                inspection_policy: [Ref(graph_hit_test_policy_1.GraphHitTestPolicy), () => new graph_hit_test_policy_1.NodesOnly()],
            }));
        }
        get_selection_manager() {
            return this.node_renderer.data_source.selection_manager;
        }
    }
    exports.GraphRenderer = GraphRenderer;
},
/* models/selections/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(145) /* ./interaction_policy */, exports);
    var selection_1 = require(144) /* ./selection */;
    __esExport("Selection", selection_1.Selection);
},
/* models/selectors/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var by_id_1 = require(548) /* ./by_id */;
    __esExport("ByID", by_id_1.ByID);
    var by_class_1 = require(549) /* ./by_class */;
    __esExport("ByClass", by_class_1.ByClass);
    var by_css_1 = require(550) /* ./by_css */;
    __esExport("ByCSS", by_css_1.ByCSS);
    var by_xpath_1 = require(551) /* ./by_xpath */;
    __esExport("ByXPath", by_xpath_1.ByXPath);
},
/* models/selectors/by_id.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const selector_1 = require(517) /* ./selector */;
    class ByID extends selector_1.Selector {
        constructor(attrs) {
            super(attrs);
        }
        find_one(target) {
            return target.querySelector(`#${this.query}`);
        }
    }
    exports.ByID = ByID;
},
/* models/selectors/by_class.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const selector_1 = require(517) /* ./selector */;
    class ByClass extends selector_1.Selector {
        constructor(attrs) {
            super(attrs);
        }
        find_one(target) {
            return target.querySelector(`.${this.query}`);
        }
    }
    exports.ByClass = ByClass;
},
/* models/selectors/by_css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const selector_1 = require(517) /* ./selector */;
    class ByCSS extends selector_1.Selector {
        constructor(attrs) {
            super(attrs);
        }
        find_one(target) {
            return target.querySelector(this.query);
        }
    }
    exports.ByCSS = ByCSS;
},
/* models/selectors/by_xpath.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const selector_1 = require(517) /* ./selector */;
    class ByXPath extends selector_1.Selector {
        constructor(attrs) {
            super(attrs);
        }
        find_one(target) {
            return document.evaluate(this.query, target).iterateNext();
        }
    }
    exports.ByXPath = ByXPath;
},
/* models/sources/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var server_sent_data_source_1 = require(553) /* ./server_sent_data_source */;
    __esExport("ServerSentDataSource", server_sent_data_source_1.ServerSentDataSource);
    var ajax_data_source_1 = require(555) /* ./ajax_data_source */;
    __esExport("AjaxDataSource", ajax_data_source_1.AjaxDataSource);
    var column_data_source_1 = require(147) /* ./column_data_source */;
    __esExport("ColumnDataSource", column_data_source_1.ColumnDataSource);
    var columnar_data_source_1 = require(142) /* ./columnar_data_source */;
    __esExport("ColumnarDataSource", columnar_data_source_1.ColumnarDataSource);
    var cds_view_1 = require(320) /* ./cds_view */;
    __esExport("CDSView", cds_view_1.CDSView);
    var data_source_1 = require(146) /* ./data_source */;
    __esExport("DataSource", data_source_1.DataSource);
    var geojson_data_source_1 = require(556) /* ./geojson_data_source */;
    __esExport("GeoJSONDataSource", geojson_data_source_1.GeoJSONDataSource);
    var web_data_source_1 = require(554) /* ./web_data_source */;
    __esExport("WebDataSource", web_data_source_1.WebDataSource);
},
/* models/sources/server_sent_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const web_data_source_1 = require(554) /* ./web_data_source */;
    class ServerSentDataSource extends web_data_source_1.WebDataSource {
        constructor(attrs) {
            super(attrs);
        }
        initialized = false;
        setup() {
            if (!this.initialized) {
                this.initialized = true;
                const source = new EventSource(this.data_url);
                source.onmessage = async (event) => {
                    await this.load_data(JSON.parse(event.data), this.mode, this.max_size ?? undefined);
                };
            }
        }
    }
    exports.ServerSentDataSource = ServerSentDataSource;
},
/* models/sources/web_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const column_data_source_1 = require(147) /* ./column_data_source */;
    const enums_1 = require(21) /* ../../core/enums */;
    const callbacks_1 = require(51) /* ../../core/util/callbacks */;
    const object_1 = require(9) /* ../../core/util/object */;
    class WebDataSource extends column_data_source_1.ColumnDataSource {
        constructor(attrs) {
            super(attrs);
        }
        get_column(name) {
            const data = (0, object_1.dict)(this.data);
            return data.get(name) ?? [];
        }
        get_length() {
            return super.get_length() ?? 0;
        }
        initialize() {
            super.initialize();
            this.setup();
        }
        async load_data(raw_data, mode, max_size) {
            const { adapter } = this;
            let data;
            if (adapter != null) {
                data = await (0, callbacks_1.execute)(adapter, this, { response: raw_data });
            }
            else {
                data = raw_data;
            }
            switch (mode) {
                case "replace": {
                    break;
                }
                case "append": {
                    const old_data = (0, object_1.dict)(this.data);
                    const new_data = (0, object_1.dict)(data);
                    for (const column of this.columns()) {
                        // XXX: support typed arrays
                        const old_col = Array.from(old_data.get(column) ?? []);
                        const new_col = Array.from(new_data.get(column) ?? []);
                        const array = old_col.concat(new_col);
                        new_data.set(column, max_size != null ? array.slice(-max_size) : array);
                    }
                    break;
                }
            }
            this.data = data;
        }
        static {
            this.define(({ Any, Int, Str, Nullable }) => ({
                max_size: [Nullable(Int), null],
                mode: [enums_1.UpdateMode, "replace"],
                adapter: [Nullable(Any /*TODO*/), null],
                data_url: [Str],
            }));
        }
    }
    exports.WebDataSource = WebDataSource;
},
/* models/sources/ajax_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const web_data_source_1 = require(554) /* ./web_data_source */;
    const enums_1 = require(21) /* ../../core/enums */;
    const logging_1 = require(11) /* ../../core/logging */;
    const object_1 = require(9) /* ../../core/util/object */;
    class AjaxDataSource extends web_data_source_1.WebDataSource {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Bool, Int, Str, Dict, Nullable }) => ({
                polling_interval: [Nullable(Int), null],
                content_type: [Str, "application/json"],
                http_headers: [Dict(Str), {}],
                method: [enums_1.HTTPMethod, "POST"],
                if_modified: [Bool, false],
            }));
        }
        // TODO don't use initializers until https://github.com/bokeh/bokeh/issues/13732 is fixed
        interval;
        initialized;
        last_fetch_time;
        destroy() {
            if (this.interval != null) {
                clearInterval(this.interval);
            }
            super.destroy();
        }
        setup() {
            if (this.initialized !== true) {
                this.initialized = true;
                this.get_data(this.mode);
                if (this.polling_interval != null) {
                    const callback = () => this.get_data(this.mode, this.max_size, this.if_modified);
                    this.interval = setInterval(callback, this.polling_interval);
                }
            }
        }
        get_data(mode, max_size = null, if_modified = false) {
            const xhr = this.prepare_request();
            xhr.addEventListener("load", () => this.do_load(xhr, mode, max_size ?? undefined));
            xhr.addEventListener("error", () => this.do_error(xhr));
            if (if_modified && this.last_fetch_time != null) {
                xhr.setRequestHeader("If-Modified-Since", this.last_fetch_time.toUTCString());
            }
            xhr.send();
        }
        prepare_request() {
            const xhr = new XMLHttpRequest();
            xhr.open(this.method, this.data_url, true);
            xhr.withCredentials = false;
            xhr.setRequestHeader("Content-Type", this.content_type);
            for (const [name, value] of (0, object_1.entries)(this.http_headers)) {
                xhr.setRequestHeader(name, value);
            }
            return xhr;
        }
        async do_load(xhr, mode, max_size) {
            if (xhr.status == 200) {
                const raw_data = JSON.parse(xhr.responseText);
                this.last_fetch_time = new Date();
                await this.load_data(raw_data, mode, max_size);
            }
        }
        do_error(xhr) {
            logging_1.logger.error(`Failed to fetch JSON from ${this.data_url} with code ${xhr.status}`);
        }
    }
    exports.AjaxDataSource = AjaxDataSource;
},
/* models/sources/geojson_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const columnar_data_source_1 = require(142) /* ./columnar_data_source */;
    const logging_1 = require(11) /* ../../core/logging */;
    const types_1 = require(8) /* ../../core/util/types */;
    const array_1 = require(10) /* ../../core/util/array */;
    const object_1 = require(9) /* ../../core/util/object */;
    function orNaN(v) {
        return v != null ? v : NaN;
    }
    class GeoJSONDataSource extends columnar_data_source_1.ColumnarDataSource {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Str }) => ({
                geojson: [Str],
            }));
            this.internal(({ Unknown, Dict, Arrayable }) => ({
                data: [Dict(Arrayable(Unknown)), {}], // TODO computed property geojson
            }));
        }
        initialize() {
            super.initialize();
            this._update_data();
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.properties.geojson.change, () => this._update_data());
        }
        _update_data() {
            this.data = this.geojson_to_column_data();
        }
        _get_new_list_array(length) {
            return (0, array_1.range)(0, length).map((_i) => []);
        }
        _get_new_nan_array(length) {
            return (0, array_1.range)(0, length).map((_i) => NaN);
        }
        _add_properties(item, data, i, item_count) {
            const properties = item.properties ?? {};
            const data_proxy = (0, object_1.dict)(data);
            for (const [property, value] of (0, object_1.dict)(properties)) {
                if (!data_proxy.has(property)) {
                    data[property] = this._get_new_nan_array(item_count);
                }
                // orNaN necessary here to prevent null values from ending up in the column
                data[property][i] = orNaN(value);
            }
        }
        _add_geometry(geometry, data, i) {
            function flatten(acc, item) {
                return acc.concat([[NaN, NaN, NaN]]).concat(item);
            }
            switch (geometry.type) {
                case "Point": {
                    const [x, y, z] = geometry.coordinates;
                    data.x[i] = x;
                    data.y[i] = y;
                    data.z[i] = orNaN(z);
                    break;
                }
                case "LineString": {
                    const { coordinates } = geometry;
                    for (let j = 0; j < coordinates.length; j++) {
                        const [x, y, z] = coordinates[j];
                        data.xs[i][j] = x;
                        data.ys[i][j] = y;
                        data.zs[i][j] = orNaN(z);
                    }
                    break;
                }
                case "Polygon": {
                    if (geometry.coordinates.length > 1) {
                        logging_1.logger.warn("Bokeh does not support Polygons with holes in, only exterior ring used.");
                    }
                    const exterior_ring = geometry.coordinates[0];
                    for (let j = 0; j < exterior_ring.length; j++) {
                        const [x, y, z] = exterior_ring[j];
                        data.xs[i][j] = x;
                        data.ys[i][j] = y;
                        data.zs[i][j] = orNaN(z);
                    }
                    break;
                }
                case "MultiPoint": {
                    logging_1.logger.warn("MultiPoint not supported in Bokeh");
                    break;
                }
                case "MultiLineString": {
                    const coordinates = geometry.coordinates.reduce(flatten);
                    for (let j = 0; j < coordinates.length; j++) {
                        const [x, y, z] = coordinates[j];
                        data.xs[i][j] = x;
                        data.ys[i][j] = y;
                        data.zs[i][j] = orNaN(z);
                    }
                    break;
                }
                case "MultiPolygon": {
                    const exterior_rings = [];
                    for (const polygon of geometry.coordinates) {
                        if (polygon.length > 1) {
                            logging_1.logger.warn("Bokeh does not support Polygons with holes in, only exterior ring used.");
                        }
                        exterior_rings.push(polygon[0]);
                    }
                    const coordinates = exterior_rings.reduce(flatten);
                    for (let j = 0; j < coordinates.length; j++) {
                        const [x, y, z] = coordinates[j];
                        data.xs[i][j] = x;
                        data.ys[i][j] = y;
                        data.zs[i][j] = orNaN(z);
                    }
                    break;
                }
                default:
                    throw new Error(`Invalid GeoJSON geometry type: ${geometry.type}`);
            }
        }
        geojson_to_column_data() {
            const geojson = JSON.parse(this.geojson);
            let items;
            switch (geojson.type) {
                case "GeometryCollection": {
                    if ((0, types_1.is_undefined)(geojson.geometries)) {
                        throw new Error("No geometries found in GeometryCollection");
                    }
                    if (geojson.geometries.length === 0) {
                        throw new Error("geojson.geometries must have one or more items");
                    }
                    items = geojson.geometries;
                    break;
                }
                case "FeatureCollection": {
                    if ((0, types_1.is_undefined)(geojson.features)) {
                        throw new Error("No features found in FeaturesCollection");
                    }
                    if (geojson.features.length == 0) {
                        throw new Error("geojson.features must have one or more items");
                    }
                    items = geojson.features;
                    break;
                }
                default:
                    throw new Error("Bokeh only supports type GeometryCollection and FeatureCollection at top level");
            }
            let item_count = 0;
            for (const item of items) {
                const geometry = item.type === "Feature" ? item.geometry : item;
                if (geometry.type == "GeometryCollection") {
                    item_count += geometry.geometries.length;
                }
                else {
                    item_count += 1;
                }
            }
            const data = {
                x: this._get_new_nan_array(item_count),
                y: this._get_new_nan_array(item_count),
                z: this._get_new_nan_array(item_count),
                xs: this._get_new_list_array(item_count),
                ys: this._get_new_list_array(item_count),
                zs: this._get_new_list_array(item_count),
            };
            let arr_index = 0;
            for (const item of items) {
                const geometry = item.type == "Feature" ? item.geometry : item;
                if (geometry.type == "GeometryCollection") {
                    for (const g of geometry.geometries) {
                        this._add_geometry(g, data, arr_index);
                        if (item.type === "Feature") {
                            this._add_properties(item, data, arr_index, item_count);
                        }
                        arr_index += 1;
                    }
                }
                else {
                    this._add_geometry(geometry, data, arr_index);
                    if (item.type === "Feature") {
                        this._add_properties(item, data, arr_index, item_count);
                    }
                    arr_index += 1;
                }
            }
            return data;
        }
    }
    exports.GeoJSONDataSource = GeoJSONDataSource;
},
/* models/tiles/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var bbox_tile_source_1 = require(558) /* ./bbox_tile_source */;
    __esExport("BBoxTileSource", bbox_tile_source_1.BBoxTileSource);
    var mercator_tile_source_1 = require(559) /* ./mercator_tile_source */;
    __esExport("MercatorTileSource", mercator_tile_source_1.MercatorTileSource);
    var quadkey_tile_source_1 = require(562) /* ./quadkey_tile_source */;
    __esExport("QUADKEYTileSource", quadkey_tile_source_1.QUADKEYTileSource);
    var tile_renderer_1 = require(563) /* ./tile_renderer */;
    __esExport("TileRenderer", tile_renderer_1.TileRenderer);
    var tile_source_1 = require(560) /* ./tile_source */;
    __esExport("TileSource", tile_source_1.TileSource);
    var tms_tile_source_1 = require(565) /* ./tms_tile_source */;
    __esExport("TMSTileSource", tms_tile_source_1.TMSTileSource);
    var wmts_tile_source_1 = require(564) /* ./wmts_tile_source */;
    __esExport("WMTSTileSource", wmts_tile_source_1.WMTSTileSource);
},
/* models/tiles/bbox_tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const mercator_tile_source_1 = require(559) /* ./mercator_tile_source */;
    class BBoxTileSource extends mercator_tile_source_1.MercatorTileSource {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Bool }) => ({
                use_latlon: [Bool, false],
            }));
        }
        get_image_url(x, y, z) {
            const image_url = this.string_lookup_replace(this.url, this.extra_url_vars);
            let xmax, xmin, ymax, ymin;
            if (this.use_latlon) {
                [xmin, ymin, xmax, ymax] = this.get_tile_geographic_bounds(x, y, z);
            }
            else {
                [xmin, ymin, xmax, ymax] = this.get_tile_meter_bounds(x, y, z);
            }
            return image_url
                .replace("{XMIN}", xmin.toString())
                .replace("{YMIN}", ymin.toString())
                .replace("{XMAX}", xmax.toString())
                .replace("{YMAX}", ymax.toString());
        }
    }
    exports.BBoxTileSource = BBoxTileSource;
},
/* models/tiles/mercator_tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tile_source_1 = require(560) /* ./tile_source */;
    const logging_1 = require(11) /* ../../core/logging */;
    const tile_utils_1 = require(561) /* ./tile_utils */;
    const array_1 = require(10) /* ../../core/util/array */;
    class MercatorTileSource extends tile_source_1.TileSource {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Bool }) => ({
                snap_to_zoom: [Bool, false],
                wrap_around: [Bool, true],
            }));
            this.internal(({ Float, List }) => ({
                _resolutions: [List(Float), (obj) => {
                        return (0, array_1.range)(obj.min_zoom, obj.max_zoom + 1).map((z) => obj.get_resolution(z));
                    }],
            }));
            this.override({
                x_origin_offset: 20037508.34,
                y_origin_offset: 20037508.34,
                initial_resolution: 156543.03392804097,
            });
        }
        /**
         * The coarsest zoom level provided by this source.
         */
        get min_level() {
            return Math.max(0, Math.floor(this.min_zoom));
        }
        /**
         * The finest zoom level provided by this source.
         */
        get max_level() {
            return Math.max(this.min_level, Math.floor(this.max_zoom));
        }
        _computed_initial_resolution() {
            if (this.initial_resolution != null) {
                return this.initial_resolution;
            }
            else {
                // TODO testing 2015-11-17, if this codepath is used it seems
                // to use 100% cpu and wedge Chrome
                return (2 * Math.PI * 6378137) / this.tile_size;
            }
        }
        is_valid_tile(x, y, z) {
            if (z < this.min_level || z > this.max_level) {
                return false;
            }
            if (!this.wrap_around) {
                if (x < 0 || x >= 2 ** z) {
                    return false;
                }
            }
            if (y < 0 || y >= 2 ** z) {
                return false;
            }
            return true;
        }
        get_resolution(level) {
            return this._computed_initial_resolution() / 2 ** level;
        }
        get_resolution_by_extent(extent, height, width) {
            const x_rs = (extent[2] - extent[0]) / width;
            const y_rs = (extent[3] - extent[1]) / height;
            return [x_rs, y_rs];
        }
        /**
         * The resolution needed to fit `extent` into `width` x `height` pixels.
         */
        _required_resolution(extent, height, width) {
            const [x_rs, y_rs] = this.get_resolution_by_extent(extent, height, width);
            return Math.max(x_rs, y_rs);
        }
        /**
         * The finest level whose tiles still cover `extent`, i.e. the extent is
         * never cropped, at the cost of drawing tiles magnified up to 2x.
         */
        get_level_by_extent(extent, height, width) {
            const resolution = this._required_resolution(extent, height, width);
            const { min_level, max_level } = this;
            if (!isFinite(resolution)) {
                return min_level;
            }
            for (let level = min_level; level <= max_level; level++) {
                if (resolution > this.get_resolution(level)) {
                    return Math.max(min_level, level - 1);
                }
            }
            return max_level;
        }
        /**
         * The level whose resolution is closest to the one `extent` requires, which
         * keeps tiles within a factor of sqrt(2) of their native size.
         */
        get_closest_level_by_extent(extent, height, width) {
            const resolution = this._required_resolution(extent, height, width);
            const { min_level, max_level } = this;
            if (!isFinite(resolution) || resolution <= 0) {
                return min_level;
            }
            // resolutions form a geometric series, so proximity is measured as a ratio,
            // not as an absolute difference
            let closest = min_level;
            let closest_distance = Infinity;
            for (let level = min_level; level <= max_level; level++) {
                const distance = Math.abs(Math.log2(this.get_resolution(level) / resolution));
                if (distance >= closest_distance) {
                    break;
                }
                closest = level;
                closest_distance = distance;
            }
            return closest;
        }
        /**
         * `extent` grown or shrunk around its center to `resolution` in both axes.
         */
        _extent_at_resolution(extent, height, width, resolution) {
            const [xmin, ymin, xmax, ymax] = extent;
            const x_adjust = ((width * resolution) - (xmax - xmin)) / 2;
            const y_adjust = ((height * resolution) - (ymax - ymin)) / 2;
            return [xmin - x_adjust, ymin - y_adjust, xmax + x_adjust, ymax + y_adjust];
        }
        snap_to_zoom_level(extent, height, width, level) {
            const resolution = this.snap_to_zoom ? this.get_resolution(level) : this._required_resolution(extent, height, width);
            return this._extent_at_resolution(extent, height, width, resolution);
        }
        /**
         * `extent` adjusted so that both axes resolve to the same number of meters
         * per pixel, by growing the axis that has room to spare. Tiles are square, so
         * an extent that scales the axes independently (as a box zoom, a single
         * dimension wheel zoom, or an auto-ranged range does) draws them distorted.
         */
        constrain_extent(extent, height, width) {
            if (!extent.every(isFinite) || !(width > 0) || !(height > 0)) {
                return extent;
            }
            if (this.snap_to_zoom) {
                const level = this.get_level_by_extent(extent, height, width);
                return this.snap_to_zoom_level(extent, height, width, level);
            }
            const [xmin, ymin, xmax, ymax] = extent;
            const [x_rs, y_rs] = this.get_resolution_by_extent(extent, height, width);
            // only the axis that has to grow is touched, so that constraining an extent
            // that already is consistent doesn't perturb it
            if (x_rs > y_rs) {
                const y_adjust = ((height * x_rs) - (ymax - ymin)) / 2;
                return [xmin, ymin - y_adjust, xmax, ymax + y_adjust];
            }
            else {
                const x_adjust = ((width * y_rs) - (xmax - xmin)) / 2;
                return [xmin - x_adjust, ymin, xmax + x_adjust, ymax];
            }
        }
        rescale(extent, height, width, last_height, last_width) {
            if (!(last_width > 0) || !(last_height > 0)) {
                return extent;
            }
            const [xmin, ymin, xmax, ymax] = extent;
            const x_delta = xmax - xmin;
            const y_delta = ymax - ymin;
            const x_scale = width / last_width;
            const y_scale = height / last_height;
            const desired_x_delta = x_delta * x_scale;
            const desired_y_delta = y_delta * y_scale;
            const x_adjust = desired_x_delta - x_delta;
            const y_adjust = desired_y_delta - y_delta;
            return [xmin - x_adjust / 2, ymin - y_adjust / 2, xmax + x_adjust / 2, ymax + y_adjust / 2];
        }
        tms_to_wmts(x, y, z) {
            // Note this works both ways
            return [x, 2 ** z - 1 - y, z];
        }
        wmts_to_tms(x, y, z) {
            // Note this works both ways
            return [x, 2 ** z - 1 - y, z];
        }
        pixels_to_meters(px, py, level) {
            const res = this.get_resolution(level);
            const mx = (px * res) - this.x_origin_offset;
            const my = (py * res) - this.y_origin_offset;
            return [mx, my];
        }
        meters_to_pixels(mx, my, level) {
            const res = this.get_resolution(level);
            const px = (mx + this.x_origin_offset) / res;
            const py = (my + this.y_origin_offset) / res;
            return [px, py];
        }
        pixels_to_tile(px, py) {
            const { tile_size } = this;
            return [Math.floor(px / tile_size), Math.floor(py / tile_size)];
        }
        meters_to_tile(mx, my, level) {
            const [px, py] = this.meters_to_pixels(mx, my, level);
            return this.pixels_to_tile(px, py);
        }
        get_tile_meter_bounds(tx, ty, level) {
            // expects tms styles coordinates (bottom-left origin)
            const [xmin, ymin] = this.pixels_to_meters(tx * this.tile_size, ty * this.tile_size, level);
            const [xmax, ymax] = this.pixels_to_meters((tx + 1) * this.tile_size, (ty + 1) * this.tile_size, level);
            return [xmin, ymin, xmax, ymax];
        }
        get_tile_geographic_bounds(tx, ty, level) {
            const bounds = this.get_tile_meter_bounds(tx, ty, level);
            const [minLon, minLat, maxLon, maxLat] = (0, tile_utils_1.meters_extent_to_geographic)(bounds);
            return [minLon, minLat, maxLon, maxLat];
        }
        get_tiles_by_extent(extent, level, tile_border = 1) {
            // skip calculation if any axis has undefined extent
            if (extent.some(value => !isFinite(value))) {
                return [];
            }
            // unpack extent and convert to tile coordinates
            const [xmin, ymin, xmax, ymax] = extent;
            let [txmin, tymin] = this.meters_to_tile(xmin, ymin, level);
            let [txmax, tymax] = this.meters_to_tile(xmax, ymax, level);
            // add tiles which border
            txmin -= tile_border;
            tymin -= tile_border;
            txmax += tile_border;
            tymax += tile_border;
            // An extent that doesn't correspond to `level` (e.g. one that was never
            // constrained to the levels this source provides) can ask for an unbounded
            // number of tiles, so fall back to the tiles closest to the center.
            const nx = txmax - txmin + 1;
            const ny = tymax - tymin + 1;
            const { max_tiles } = this;
            if (nx * ny > max_tiles) {
                logging_1.logger.warn(`${this}: extent requires ${nx * ny} tiles at zoom level ${level}, limiting to ${max_tiles}`);
                const scale = Math.sqrt(max_tiles / (nx * ny));
                const cx = Math.max(1, Math.floor(nx * scale));
                const cy = Math.max(1, Math.floor(ny * scale));
                txmin += Math.floor((nx - cx) / 2);
                txmax = txmin + cx - 1;
                tymin += Math.floor((ny - cy) / 2);
                tymax = tymin + cy - 1;
            }
            const tiles = [];
            for (let ty = tymax; ty >= tymin; ty--) {
                for (let tx = txmin; tx <= txmax; tx++) {
                    if (this.is_valid_tile(tx, ty, level)) {
                        tiles.push([tx, ty, level, this.get_tile_meter_bounds(tx, ty, level)]);
                    }
                }
            }
            this.sort_tiles_from_center(tiles, [txmin, tymin, txmax, tymax]);
            return tiles;
        }
        quadkey_to_tile_xyz(quadKey) {
            /**
             * Computes tile x, y and z values based on quadKey.
             */
            let tileX = 0;
            let tileY = 0;
            const tileZ = quadKey.length;
            for (let i = tileZ; i > 0; i--) {
                const value = quadKey.charAt(tileZ - i);
                const mask = 1 << (i - 1);
                switch (value) {
                    case "0":
                        continue;
                    case "1":
                        tileX |= mask;
                        break;
                    case "2":
                        tileY |= mask;
                        break;
                    case "3":
                        tileX |= mask;
                        tileY |= mask;
                        break;
                    default:
                        throw new TypeError(`Invalid Quadkey: ${quadKey}`);
                }
            }
            return [tileX, tileY, tileZ];
        }
        tile_xyz_to_quadkey(x, y, z) {
            /*
             * Computes quadkey value based on tile x, y and z values.
             */
            let quadkey = "";
            for (let i = z; i > 0; i--) {
                const mask = 1 << (i - 1);
                let digit = 0;
                if ((x & mask) !== 0) {
                    digit += 1;
                }
                if ((y & mask) !== 0) {
                    digit += 2;
                }
                quadkey += digit.toString();
            }
            return quadkey;
        }
        children_by_tile_xyz(x, y, z) {
            const quadkey = this.tile_xyz_to_quadkey(x, y, z);
            const child_tile_xyz = [];
            for (let i = 0; i <= 3; i++) {
                const [cx, cy, cz] = this.quadkey_to_tile_xyz(quadkey + i.toString());
                if (this.is_valid_tile(cx, cy, cz)) {
                    child_tile_xyz.push([cx, cy, cz, this.get_tile_meter_bounds(cx, cy, cz)]);
                }
            }
            return child_tile_xyz;
        }
        get_closest_parent_by_tile_xyz(x, y, z) {
            const world_x = this.calculate_world_x_by_tile_xyz(x, y, z);
            [x, y, z] = this.normalize_xyz(x, y, z);
            let quadkey = this.tile_xyz_to_quadkey(x, y, z);
            while (quadkey.length > 0) {
                quadkey = quadkey.substring(0, quadkey.length - 1);
                const [px, py, pz] = this.denormalize_xyz(...this.quadkey_to_tile_xyz(quadkey), world_x);
                if (this.has_tile(this.tile_xyz_to_key(px, py, pz))) {
                    return [px, py, pz];
                }
            }
            return null;
        }
        normalize_xyz(x, y, z) {
            if (this.wrap_around) {
                const tile_count = 2 ** z;
                return [((x % tile_count) + tile_count) % tile_count, y, z];
            }
            else {
                return [x, y, z];
            }
        }
        denormalize_xyz(x, y, z, world_x) {
            return [x + (world_x * 2 ** z), y, z];
        }
        calculate_world_x_by_tile_xyz(x, _y, z) {
            return Math.floor(x / 2 ** z);
        }
    }
    exports.MercatorTileSource = MercatorTileSource;
},
/* models/tiles/tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    const object_1 = require(9) /* ../../core/util/object */;
    class TileSource extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Float, Str, Dict, Nullable /*, Null, Or, Ref*/ }) => ({
                url: [Str, "", { convert: (url) => TileSource._normalize_case(url) }],
                tile_size: [Float, 256],
                pixel_ratio: [Float, 1],
                max_zoom: [Float, 30],
                min_zoom: [Float, 0],
                extra_url_vars: [Dict(Str), {}],
                attribution: [Str, ""], // Or(Str, Ref(DOMElement), Null), null ],
                x_origin_offset: [Float],
                y_origin_offset: [Float],
                initial_resolution: [Nullable(Float), null],
            }));
        }
        tiles = new Map();
        connect_signals() {
            super.connect_signals();
            this.connect(this.change, () => this._clear_cache());
        }
        /**
         * The number of tiles retained in the cache. Least recently used tiles are
         * evicted first, so this needs to comfortably exceed the number of tiles a
         * single viewport can show.
         */
        get max_cache_size() {
            return 512;
        }
        /**
         * An upper bound on the number of tiles requested for a single extent, as a
         * safeguard against extents that don't correspond to the requested level.
         */
        get max_tiles() {
            return 4096;
        }
        string_lookup_replace(str, lookup) {
            let result_str = str;
            for (const [key, value] of (0, object_1.entries)(lookup)) {
                result_str = result_str.replace(`{${key}}`, value);
            }
            return result_str;
        }
        static _normalize_case(url) {
            return url
                .replace("{x}", "{X}")
                .replace("{y}", "{Y}")
                .replace("{z}", "{Z}")
                .replace("{q}", "{Q}")
                .replace("{xmin}", "{XMIN}")
                .replace("{ymin}", "{YMIN}")
                .replace("{xmax}", "{XMAX}")
                .replace("{ymax}", "{YMAX}");
        }
        _clear_cache() {
            this.tiles.clear();
        }
        has_tile(key) {
            return this.tiles.has(key);
        }
        /**
         * Looks up a cached tile, marking it as the most recently used.
         */
        get_tile(key) {
            const tile = this.tiles.get(key);
            if (tile != null) {
                this.tiles.delete(key);
                this.tiles.set(key, tile);
            }
            return tile;
        }
        /**
         * Caches a tile, evicting least recently used tiles beyond `max_cache_size`.
         * Keys in `preserve` are never evicted, so that a viewport needing more tiles
         * than the cache nominally holds doesn't discard tiles it is about to draw and
         * request them again on the next paint.
         */
        set_tile(key, tile, preserve) {
            this.tiles.delete(key);
            this.tiles.set(key, tile);
            const { max_cache_size } = this;
            let excess = this.tiles.size - max_cache_size;
            if (excess > 0) {
                // relies on maps iterating in insertion order, which `get_tile()` maintains
                for (const key of this.tiles.keys()) {
                    if (preserve?.has(key) ?? false) {
                        continue;
                    }
                    this.tiles.delete(key);
                    if (--excess == 0) {
                        break;
                    }
                }
            }
        }
        delete_tile(key) {
            this.tiles.delete(key);
        }
        tile_xyz_to_key(x, y, z) {
            return `${x}:${y}:${z}`;
        }
        key_to_tile_xyz(key) {
            const [x, y, z] = key.split(":").map((c) => parseInt(c));
            return [x, y, z];
        }
        sort_tiles_from_center(tiles, tile_extent) {
            const [txmin, tymin, txmax, tymax] = tile_extent;
            const center_x = ((txmax - txmin) / 2) + txmin;
            const center_y = ((tymax - tymin) / 2) + tymin;
            tiles.sort(function (a, b) {
                const a_distance = Math.sqrt((center_x - a[0]) ** 2 + (center_y - a[1]) ** 2);
                const b_distance = Math.sqrt((center_x - b[0]) ** 2 + (center_y - b[1]) ** 2);
                return a_distance - b_distance;
            });
        }
        get_image_url(x, y, z) {
            const image_url = this.string_lookup_replace(this.url, this.extra_url_vars);
            return image_url
                .replace("{X}", x.toString())
                .replace("{Y}", y.toString())
                .replace("{Z}", z.toString());
        }
    }
    exports.TileSource = TileSource;
},
/* models/tiles/tile_utils.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.geographic_to_meters = geographic_to_meters;
    exports.meters_to_geographic = meters_to_geographic;
    exports.geographic_extent_to_meters = geographic_extent_to_meters;
    exports.meters_extent_to_geographic = meters_extent_to_geographic;
    const projections_1 = require(148) /* ../../core/util/projections */;
    function geographic_to_meters(x_lon, y_lat) {
        return projections_1.wgs84_mercator.compute(x_lon, y_lat);
    }
    function meters_to_geographic(mx, my) {
        return projections_1.wgs84_mercator.invert(mx, my);
    }
    function geographic_extent_to_meters(extent) {
        const [g_xmin, g_ymin, g_xmax, g_ymax] = extent;
        const [m_xmin, m_ymin] = geographic_to_meters(g_xmin, g_ymin);
        const [m_xmax, m_ymax] = geographic_to_meters(g_xmax, g_ymax);
        return [m_xmin, m_ymin, m_xmax, m_ymax];
    }
    function meters_extent_to_geographic(extent) {
        const [m_xmin, m_ymin, m_xmax, m_ymax] = extent;
        const [g_xmin, g_ymin] = meters_to_geographic(m_xmin, m_ymin);
        const [g_xmax, g_ymax] = meters_to_geographic(m_xmax, m_ymax);
        return [g_xmin, g_ymin, g_xmax, g_ymax];
    }
},
/* models/tiles/quadkey_tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const mercator_tile_source_1 = require(559) /* ./mercator_tile_source */;
    class QUADKEYTileSource extends mercator_tile_source_1.MercatorTileSource {
        constructor(attrs) {
            super(attrs);
        }
        get_image_url(x, y, z) {
            const image_url = this.string_lookup_replace(this.url, this.extra_url_vars);
            const [wx, wy, wz] = this.tms_to_wmts(x, y, z);
            const quadKey = this.tile_xyz_to_quadkey(wx, wy, wz);
            return image_url.replace("{Q}", quadKey);
        }
    }
    exports.QUADKEYTileSource = QUADKEYTileSource;
},
/* models/tiles/tile_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tile_source_1 = require(560) /* ./tile_source */;
    const wmts_tile_source_1 = require(564) /* ./wmts_tile_source */;
    const renderer_1 = require(98) /* ../renderers/renderer */;
    const range1d_1 = require(111) /* ../ranges/range1d */;
    const data_range1d_1 = require(118) /* ../ranges/data_range1d */;
    const html_1 = require(133) /* ../dom/html */;
    const image_1 = require(261) /* ../../core/util/image */;
    const logging_1 = require(11) /* ../../core/logging */;
    /** Number of times a tile that failed to load is requested again. */
    const MAX_ATTEMPTS = 2;
    /** Number of tiles of the next zoom level fetched ahead of time. */
    const MAX_PREFETCH = 40;
    const FETCH_DELAY = 65;
    const PREFETCH_DELAY = 500;
    /**
     * Whether `target` differs from `current` by more than rounding error. Extents
     * are compared with a tolerance so that constraining the ranges can't turn into
     * an endless sequence of repaints.
     */
    function extent_changed(current, target) {
        const tolerance = 1e-6 * Math.max(target[2] - target[0], target[3] - target[1]);
        return current.some((value, i) => Math.abs(value - target[i]) > tolerance);
    }
    class TileRendererView extends renderer_1.RendererView {
        extent;
        map_initialized = false;
        /** Frame size, in CSS pixels, the extent was last adjusted to. */
        _last_size = null;
        /** Zoom level the last update drew, if any. */
        _last_level = null;
        /** Whether at least one update completed, i.e. whether tiles are known. */
        _updated = false;
        /** Tiles the last update asked for, not requested yet. */
        _to_fetch = [];
        /** Keys of tiles with an image request in flight. */
        _loading = new Set();
        /**
         * Tiles with an image request in flight, held outside the bounded cache so
         * that they can't be evicted before they arrive, which would lose track of
         * the request and of how many attempts were already made.
         */
        _pending = new Map();
        /** Keys of the tiles the current extent needs, which are never evicted. */
        _current = new Set();
        _fetch_timer = null;
        _prefetch_timer = null;
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.request_paint());
            this.on_transitive_change(this.model.properties.tile_source, () => {
                // the source dropped its cache, so requests in flight belong to a tile
                // set that no longer applies; they can't be cancelled, but forgetting
                // them here keeps their images from repopulating the cache
                this._clear_timers();
                this._to_fetch = [];
                this._pending.clear();
                this._loading.clear();
                this.request_paint();
            });
        }
        remove() {
            this._clear_timers();
            this._pending.clear();
            this.force_finished();
            super.remove();
        }
        _clear_timers() {
            if (this._fetch_timer != null) {
                clearTimeout(this._fetch_timer);
                this._fetch_timer = null;
            }
            if (this._prefetch_timer != null) {
                clearTimeout(this._prefetch_timer);
                this._prefetch_timer = null;
            }
        }
        force_finished() {
            super.force_finished();
            this._updated = true;
            this._to_fetch = [];
            this._loading.clear();
        }
        has_finished() {
            if (!super.has_finished()) {
                return false;
            }
            return this._updated && this._to_fetch.length == 0 && this._loading.size == 0;
        }
        get attribution() {
            return new html_1.HTML({ html: [this.model.tile_source.attribution] });
        }
        get x_range() {
            return this.coordinates.x_source;
        }
        get y_range() {
            return this.coordinates.y_source;
        }
        get_extent() {
            const { x_range, y_range } = this;
            const { start: x_start, end: x_end } = x_range;
            const { start: y_start, end: y_end } = y_range;
            // tile geometry is orientation agnostic; reversed ranges are dealt with when drawing
            return [
                Math.min(x_start, x_end), Math.min(y_start, y_end),
                Math.max(x_start, x_end), Math.max(y_start, y_end),
            ];
        }
        /**
         * Assigns an extent's interval to a range, preserving its orientation and
         * optionally making it the range's reset state.
         */
        _set_range(range, min, max, reset = false) {
            const [start, end] = range.start <= range.end ? [min, max] : [max, min];
            range.setv({ start, end });
            if (range instanceof data_range1d_1.DataRange1d) {
                // An auto-ranged range re-fits to the data bounds on every paint, which
                // would undo the constraint and leave the tiles distorted. Marking the
                // range as updated interactively, which is what pan and zoom tools do,
                // stops that at the cost of the range no longer following the data.
                // Tiles and auto-ranging are fundamentally incompatible, and a distorted
                // map is never what's wanted, so the constraint wins.
                range.have_updated_interactively = true;
            }
            if (reset && range instanceof range1d_1.Range1d) {
                range.reset_start = start;
                range.reset_end = end;
            }
        }
        /**
         * The size of the frame in tile image pixels, which is the unit zoom levels
         * are expressed in. The display may have more device pixels than CSS pixels,
         * and a source may serve more image pixels than tile pixels ("@2x" tiles).
         */
        _tile_pixel_size() {
            const { width, height } = this.plot_view.frame.bbox;
            const { pixel_ratio } = this.model.tile_source;
            const scale = this.canvas.pixel_ratio / (pixel_ratio > 0 ? pixel_ratio : 1);
            return { width: width * scale, height: height * scale };
        }
        _init_map({ width, height }) {
            const { tile_source } = this.model;
            const { x_range, y_range } = this;
            const extent = tile_source.constrain_extent(this.get_extent(), height, width);
            if (extent.every(isFinite)) {
                this._set_range(x_range, extent[0], extent[2], true);
                this._set_range(y_range, extent[1], extent[3], true);
            }
            else {
                logging_1.logger.warn(`${this}: tile extent is not fully defined, no tiles will be rendered`);
            }
            this.extent = extent;
            this._last_size = { width, height };
        }
        /**
         * Adjusts the ranges so that both axes resolve to the same number of meters
         * per pixel, within the range of zoom levels the source provides. Without
         * this, anything that scales the axes independently (a box zoom, a single
         * dimension wheel zoom, an auto-ranged range) leaves the tiles distorted.
         */
        _enforce_extent({ width, height }) {
            const { tile_source } = this.model;
            const extent = this.get_extent();
            const rescaled = (() => {
                const { _last_size } = this;
                // a resize preserves the current resolution, so that resizing the plot
                // reveals more of the map instead of zooming it
                if (_last_size != null && (_last_size.width != width || _last_size.height != height)) {
                    return tile_source.rescale(extent, height, width, _last_size.height, _last_size.width);
                }
                return extent;
            })();
            const target = tile_source.constrain_extent(rescaled, height, width);
            this._last_size = { width, height };
            this.extent = target;
            if (extent_changed(extent, target)) {
                this._set_range(this.x_range, target[0], target[2]);
                this._set_range(this.y_range, target[1], target[3]);
            }
        }
        _paint(ctx) {
            const size = this.plot_view.frame.bbox;
            // a collapsed frame (e.g. a plot in a hidden tab) can't be measured, and
            // recording its size would break the next resize
            if (!(size.width > 0) || !(size.height > 0)) {
                return;
            }
            if (!this.map_initialized) {
                this._init_map(size);
                this.map_initialized = true;
            }
            else {
                this._enforce_extent(size);
            }
            this._update(ctx);
            this._schedule_prefetch();
            if (this.has_finished()) {
                this.notify_finished();
            }
        }
        _update(ctx) {
            const { tile_source, render_parents } = this.model;
            const { extent } = this;
            const { width, height } = this._tile_pixel_size();
            const level = tile_source.get_closest_level_by_extent(extent, height, width);
            const zooming_out = this._last_level != null && level < this._last_level;
            const cached = [];
            const parents = new Set();
            const children = new Set();
            const current = new Set();
            const loading = new Set();
            const need_load = [];
            for (const [x, y, z, bounds] of tile_source.get_tiles_by_extent(extent, level)) {
                const key = tile_source.tile_xyz_to_key(x, y, z);
                current.add(key);
                const tile = this._get_tile(key);
                if (tile != null && tile.loaded) {
                    cached.push(tile.cache_key);
                    continue;
                }
                if (this._needs_load(tile)) {
                    need_load.push([x, y, z, bounds]);
                }
                else if (tile != null && !tile.finished) {
                    loading.add(key);
                }
                if (render_parents) {
                    const parent = tile_source.get_closest_parent_by_tile_xyz(x, y, z);
                    if (parent != null) {
                        const parent_key = tile_source.tile_xyz_to_key(...parent);
                        if (this._is_loaded(parent_key)) {
                            parents.add(parent_key);
                        }
                    }
                    if (zooming_out) {
                        for (const [cx, cy, cz] of tile_source.children_by_tile_xyz(x, y, z)) {
                            const child_key = tile_source.tile_xyz_to_key(cx, cy, cz);
                            if (this._is_loaded(child_key)) {
                                children.add(child_key);
                            }
                        }
                    }
                }
            }
            // stand-ins for tiles that haven't arrived yet are drawn first, so that the
            // tiles of the current level paint over them
            this._render_tiles(ctx, [...parents, ...children, ...cached]);
            this._to_fetch = need_load;
            this._current = current;
            this._loading = loading;
            this._last_level = level;
            this._updated = true;
            if (this._fetch_timer != null) {
                clearTimeout(this._fetch_timer);
                this._fetch_timer = null;
            }
            if (need_load.length != 0) {
                this._fetch_timer = setTimeout(() => this._fetch_tiles(), FETCH_DELAY);
            }
        }
        _get_tile(key) {
            return this._pending.get(key) ?? this.model.tile_source.get_tile(key);
        }
        _is_loaded(key) {
            return this._get_tile(key)?.loaded ?? false;
        }
        /**
         * Whether a tile has to be requested. Tiles that failed are retried, but only
         * a bounded number of times, so that a broken source isn't requested forever.
         */
        _needs_load(tile) {
            if (tile == null) {
                return true;
            }
            return !tile.loaded && tile.finished && tile.attempts < MAX_ATTEMPTS;
        }
        _fetch_tiles() {
            this._fetch_timer = null;
            const tiles = this._to_fetch;
            this._to_fetch = [];
            if (this.is_destroyed) {
                return;
            }
            for (const [x, y, z, bounds] of tiles) {
                this._create_tile(x, y, z, bounds);
            }
        }
        _schedule_prefetch() {
            if (this._prefetch_timer != null) {
                clearTimeout(this._prefetch_timer);
            }
            this._prefetch_timer = setTimeout(() => this._prefetch_tiles(), PREFETCH_DELAY);
        }
        _prefetch_tiles() {
            this._prefetch_timer = null;
            if (this.is_destroyed) {
                return;
            }
            const { tile_source } = this.model;
            const { extent } = this;
            const { width, height } = this._tile_pixel_size();
            const level = tile_source.get_closest_level_by_extent(extent, height, width);
            let prefetched = 0;
            for (const [x, y, z] of tile_source.get_tiles_by_extent(extent, level)) {
                for (const [cx, cy, cz, cbounds] of tile_source.children_by_tile_xyz(x, y, z)) {
                    if (prefetched == MAX_PREFETCH) {
                        return;
                    }
                    const child_key = tile_source.tile_xyz_to_key(cx, cy, cz);
                    if (!tile_source.has_tile(child_key) && !this._pending.has(child_key)) {
                        this._create_tile(cx, cy, cz, cbounds, true);
                        prefetched++;
                    }
                }
            }
        }
        _create_tile(x, y, z, bounds, cache_only = false) {
            const { tile_source } = this.model;
            const cache_key = tile_source.tile_xyz_to_key(x, y, z);
            if (this._pending.has(cache_key)) {
                // already requested, possibly as a prefetch that is now on display
                if (!cache_only) {
                    this._loading.add(cache_key);
                }
                return;
            }
            const cached = this._get_tile(cache_key);
            if (!this._needs_load(cached)) {
                return;
            }
            const tile = {
                img: undefined,
                tile_coords: [x, y, z],
                quadkey: tile_source.tile_xyz_to_quadkey(x, y, z),
                cache_key,
                bounds,
                loaded: false,
                finished: false,
                attempts: (cached?.attempts ?? 0) + 1,
            };
            tile_source.delete_tile(cache_key);
            this._pending.set(cache_key, tile);
            if (!cache_only) {
                this._loading.add(cache_key);
            }
            const settled = () => {
                if (this._pending.get(cache_key) !== tile) {
                    // superseded, e.g. because the source changed while loading
                    return;
                }
                tile.finished = true;
                this._pending.delete(cache_key);
                tile_source.set_tile(cache_key, tile, this._current);
                const was_loading = this._loading.delete(cache_key);
                if (!this.is_destroyed && (was_loading || !cache_only)) {
                    // the paint reports completion, and draws the tile if it loaded
                    this.request_paint();
                }
            };
            const [nx, ny, nz] = tile_source.normalize_xyz(x, y, z);
            new image_1.ImageLoader(tile_source.get_image_url(nx, ny, nz), {
                loaded: (img) => {
                    Object.assign(tile, { img, loaded: true });
                    settled();
                },
                failed: settled,
            });
        }
        _render_tiles(ctx, tile_keys) {
            ctx.save();
            this._set_rect(ctx);
            ctx.globalAlpha = this.model.alpha;
            for (const tile_key of tile_keys) {
                this._draw_tile(ctx, tile_key);
            }
            ctx.restore();
        }
        _draw_tile(ctx, tile_key) {
            const tile = this._get_tile(tile_key);
            if (tile == null || !tile.loaded) {
                return;
            }
            const { bounds } = tile;
            const [[sx_min], [sy_min]] = this.coordinates.map_to_screen([bounds[0]], [bounds[3]]);
            const [[sx_max], [sy_max]] = this.coordinates.map_to_screen([bounds[2]], [bounds[1]]);
            // rounding to whole device pixels keeps seams from showing between tiles
            const { pixel_ratio } = ctx.layer;
            const snap = (value) => Math.round(value * pixel_ratio) / pixel_ratio;
            const sx = snap(sx_min);
            const sy = snap(sy_min);
            const sw = snap(sx_max) - sx;
            const sh = snap(sy_max) - sy;
            if (!isFinite(sw) || !isFinite(sh) || sw == 0 || sh == 0) {
                return;
            }
            const old_smoothing = ctx.imageSmoothingEnabled;
            ctx.imageSmoothingEnabled = this.model.smoothing;
            if (sw > 0 && sh > 0) {
                ctx.drawImage(tile.img, sx, sy, sw, sh);
            }
            else {
                // a reversed range mirrors the image, which drawImage() can't express
                ctx.save();
                ctx.translate(sx, sy);
                ctx.scale(Math.sign(sw), Math.sign(sh));
                ctx.drawImage(tile.img, 0, 0, Math.abs(sw), Math.abs(sh));
                ctx.restore();
            }
            ctx.imageSmoothingEnabled = old_smoothing;
        }
        _set_rect(ctx) {
            const outline_width = this.plot_model.outline_line_width;
            const l = this.plot_view.frame.bbox.left + (outline_width / 2);
            const t = this.plot_view.frame.bbox.top + (outline_width / 2);
            const w = this.plot_view.frame.bbox.width - outline_width;
            const h = this.plot_view.frame.bbox.height - outline_width;
            ctx.rect(l, t, w, h);
            ctx.clip();
        }
    }
    exports.TileRendererView = TileRendererView;
    class TileRenderer extends renderer_1.Renderer {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = TileRendererView;
            this.define(({ Bool, Float, Ref }) => ({
                alpha: [Float, 1.0],
                smoothing: [Bool, true],
                tile_source: [Ref(tile_source_1.TileSource), () => new wmts_tile_source_1.WMTSTileSource()],
                render_parents: [Bool, true],
            }));
            this.override({
                level: "image",
            });
        }
    }
    exports.TileRenderer = TileRenderer;
},
/* models/tiles/wmts_tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const mercator_tile_source_1 = require(559) /* ./mercator_tile_source */;
    class WMTSTileSource extends mercator_tile_source_1.MercatorTileSource {
        constructor(attrs) {
            super(attrs);
        }
        get_image_url(x, y, z) {
            const image_url = this.string_lookup_replace(this.url, this.extra_url_vars);
            const [wx, wy, wz] = this.tms_to_wmts(x, y, z);
            return image_url
                .replace("{X}", wx.toString())
                .replace("{Y}", wy.toString())
                .replace("{Z}", wz.toString());
        }
    }
    exports.WMTSTileSource = WMTSTileSource;
},
/* models/tiles/tms_tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const mercator_tile_source_1 = require(559) /* ./mercator_tile_source */;
    class TMSTileSource extends mercator_tile_source_1.MercatorTileSource {
        constructor(attrs) {
            super(attrs);
        }
        get_image_url(x, y, z) {
            const image_url = this.string_lookup_replace(this.url, this.extra_url_vars);
            return image_url
                .replace("{X}", x.toString())
                .replace("{Y}", y.toString())
                .replace("{Z}", z.toString());
        }
    }
    exports.TMSTileSource = TMSTileSource;
},
/* models/textures/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var canvas_texture_1 = require(567) /* ./canvas_texture */;
    __esExport("CanvasTexture", canvas_texture_1.CanvasTexture);
    var image_url_texture_1 = require(569) /* ./image_url_texture */;
    __esExport("ImageURLTexture", image_url_texture_1.ImageURLTexture);
    var texture_1 = require(568) /* ./texture */;
    __esExport("Texture", texture_1.Texture);
},
/* models/textures/canvas_texture.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const texture_1 = require(568) /* ./texture */;
    const string_1 = require(41) /* ../../core/util/string */;
    class CanvasTexture extends texture_1.Texture {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Str }) => ({
                code: [Str],
            }));
        }
        get func() {
            const code = (0, string_1.use_strict)(this.code);
            return new Function("ctx", "color", "scale", "weight", code);
        }
        get_pattern(color, scale, weight) {
            const canvas = document.createElement("canvas");
            canvas.width = scale;
            canvas.height = scale;
            const pattern_ctx = canvas.getContext("2d");
            this.func.call(this, pattern_ctx, color, scale, weight);
            return canvas;
        }
    }
    exports.CanvasTexture = CanvasTexture;
},
/* models/textures/texture.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    const enums_1 = require(21) /* ../../core/enums */;
    class Texture extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(() => ({
                repetition: [enums_1.TextureRepetition, "repeat"],
            }));
        }
    }
    exports.Texture = Texture;
},
/* models/textures/image_url_texture.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const texture_1 = require(568) /* ./texture */;
    const image_1 = require(261) /* ../../core/util/image */;
    class ImageURLTexture extends texture_1.Texture {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Str }) => ({
                url: [Str],
            }));
            this.internal(({ Ref }) => ({
                _loader: [Ref(image_1.ImageLoader), (obj) => new image_1.ImageLoader(obj.url), { readonly: true }], // TODO computed property of url
            }));
        }
        get_pattern(_color, _scale, _weight) {
            const { _loader } = this;
            return this._loader.finished ? _loader.image : _loader.promise;
        }
    }
    exports.ImageURLTexture = ImageURLTexture;
},
/* models/ui/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(571) /* ./icons */, exports);
    tslib_1.__exportStar(require(380) /* ./menus */, exports);
    var dialog_1 = require(428) /* ./dialog */;
    __esExport("Dialog", dialog_1.Dialog);
    var drawer_1 = require(576) /* ./drawer */;
    __esExport("Drawer", drawer_1.Drawer);
    var examiner_1 = require(578) /* ./examiner */;
    __esExport("Examiner", examiner_1.Examiner);
    var notifications_1 = require(54) /* ./notifications */;
    __esExport("Notifications", notifications_1.Notifications);
    var panel_1 = require(405) /* ./panel */;
    __esExport("Panel", panel_1.Panel);
    var pane_1 = require(132) /* ./pane */;
    __esExport("Pane", pane_1.Pane);
    var tooltip_1 = require(516) /* ./tooltip */;
    __esExport("Tooltip", tooltip_1.Tooltip);
    var ui_element_1 = require(55) /* ./ui_element */;
    __esExport("UIElement", ui_element_1.UIElement);
},
/* models/ui/icons/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var builtin_icon_1 = require(572) /* ./builtin_icon */;
    __esExport("BuiltinIcon", builtin_icon_1.BuiltinIcon);
    var svg_icon_1 = require(574) /* ./svg_icon */;
    __esExport("SVGIcon", svg_icon_1.SVGIcon);
    var tabler_icon_1 = require(575) /* ./tabler_icon */;
    __esExport("TablerIcon", tabler_icon_1.TablerIcon);
},
/* models/ui/icons/builtin_icon.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const icon_1 = require(573) /* ./icon */;
    const dom_1 = require(61) /* ../../../core/dom */;
    const color_1 = require(23) /* ../../../core/util/color */;
    const types_1 = require(8) /* ../../../core/util/types */;
    const icons_css_1 = tslib_1.__importDefault(require(76) /* ../../../styles/icons.css */);
    class BuiltinIconView extends icon_1.IconView {
        _style = new dom_1.InlineStyleSheet("", "icon");
        stylesheets() {
            return [...super.stylesheets(), icons_css_1.default, this._style];
        }
        render() {
            super.render();
            const icon = `var(--bokeh-icon-${this.model.icon_name})`;
            const color = (0, color_1.color2css)(this.model.color);
            const size = (() => {
                const { size } = this.model;
                return (0, types_1.isNumber)(size) ? `${size}px` : size;
            })();
            this._style.replace(`
      :host {
        display: inline-block;
        vertical-align: middle;
        width: ${size};
        height: ${size};
        background-color: ${color};
        mask-image: ${icon};
        mask-size: contain;
        mask-repeat: no-repeat;
        -webkit-mask-image: ${icon};
        -webkit-mask-size: contain;
        -webkit-mask-repeat: no-repeat;
      }
    `);
        }
    }
    exports.BuiltinIconView = BuiltinIconView;
    class BuiltinIcon extends icon_1.Icon {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = BuiltinIconView;
            this.define(({ Str, Color }) => ({
                icon_name: [Str],
                color: [Color, "gray"],
            }));
        }
    }
    exports.BuiltinIcon = BuiltinIcon;
},
/* models/ui/icons/icon.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const ui_element_1 = require(55) /* ../ui_element */;
    class IconView extends ui_element_1.UIElementView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.render());
        }
    }
    exports.IconView = IconView;
    class Icon extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Float, Or, CSSLength }) => ({
                size: [Or(Float, CSSLength), "1em"],
            }));
        }
    }
    exports.Icon = Icon;
},
/* models/ui/icons/svg_icon.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const icon_1 = require(573) /* ./icon */;
    const dom_1 = require(61) /* ../../../core/dom */;
    const types_1 = require(8) /* ../../../core/util/types */;
    class SVGIconView extends icon_1.IconView {
        _style = new dom_1.InlineStyleSheet("", "icon");
        stylesheets() {
            return [...super.stylesheets(), this._style];
        }
        render() {
            super.render();
            const size = (() => {
                const { size } = this.model;
                return (0, types_1.isNumber)(size) ? `${size}px` : size;
            })();
            this._style.replace(`
      :host {
        display: inline-block;
        vertical-align: middle;
      }
      :host svg {
        width: ${size};
        height: ${size};
      }
    `);
            const parser = new DOMParser();
            const doc = parser.parseFromString(this.model.svg, "image/svg+xml");
            this.shadow_el.append(doc.documentElement);
        }
    }
    exports.SVGIconView = SVGIconView;
    class SVGIcon extends icon_1.Icon {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = SVGIconView;
            this.define(({ Str }) => ({
                svg: [Str],
            }));
        }
    }
    exports.SVGIcon = SVGIcon;
},
/* models/ui/icons/tabler_icon.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const icon_1 = require(573) /* ./icon */;
    const dom_1 = require(61) /* ../../../core/dom */;
    const types_1 = require(8) /* ../../../core/util/types */;
    class TablerIconView extends icon_1.IconView {
        static _url = "https://cdn.jsdelivr.net/npm/@tabler/icons-webfont@latest";
        static _fonts = new dom_1.GlobalInlineStyleSheet(`\
    /*!
    * Tabler Icons 1.68.0 by tabler - https://tabler.io
    * License - https://github.com/tabler/tabler-icons/blob/master/LICENSE
    */
  @font-face {
    font-family: "tabler-icons";
    font-style: normal;
    font-weight: 400;
    src: url("${this._url}/fonts/tabler-icons.eot");
    src: url("${this._url}/fonts/tabler-icons.eot?#iefix") format("embedded-opentype"),
         url("${this._url}/fonts/tabler-icons.woff2") format("woff2"),
         url("${this._url}/fonts/tabler-icons.woff") format("woff"),
         url("${this._url}/fonts/tabler-icons.ttf") format("truetype"),
         url("${this._url}/fonts/tabler-icons.svg#tabler-icons") format("svg");
  }

  @media screen and (-webkit-min-device-pixel-ratio: 0) {
    @font-face {
      font-family: "tabler-icons";
      src: url("${this._url}/fonts/tabler-icons.svg#tabler-icons") format("svg");
    }
  }
`);
        _tabler = new dom_1.ImportedStyleSheet(`${TablerIconView._url}/tabler-icons.min.css`);
        _style = new dom_1.InlineStyleSheet("", "icon");
        stylesheets() {
            return [...super.stylesheets(), TablerIconView._fonts, this._tabler, this._style];
        }
        render() {
            super.render();
            const size = (() => {
                const { size } = this.model;
                return (0, types_1.isNumber)(size) ? `${size}px` : size;
            })();
            this._style.replace(`
      :host {
        display: inline-block;
        vertical-align: middle;
        font-size: ${size};
      }
    `);
            const icon = (0, dom_1.span)({ class: ["ti", `ti-${this.model.icon_name}`] });
            this.shadow_el.appendChild(icon);
        }
    }
    exports.TablerIconView = TablerIconView;
    class TablerIcon extends icon_1.Icon {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = TablerIconView;
            this.define(({ Str }) => ({
                icon_name: [Str],
            }));
        }
    }
    exports.TablerIcon = TablerIcon;
},
/* models/ui/drawer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const pane_1 = require(132) /* ../ui/pane */;
    const dom_1 = require(61) /* ../../core/dom */;
    const enums_1 = require(21) /* ../../core/enums */;
    const ui_gestures_1 = require(386) /* ../../core/ui_gestures */;
    const kinds_1 = require(22) /* ../../core/kinds */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    const types_1 = require(8) /* ../../core/util/types */;
    const drawers_css = tslib_1.__importStar(require(577) /* ../../styles/drawers.css */);
    const icons_css = tslib_1.__importStar(require(76) /* ../../styles/icons.css */);
    const { max } = Math;
    const CSSSize = (0, kinds_1.Or)(kinds_1.Float, kinds_1.CSSLength);
    class DrawerView extends pane_1.PaneView {
        constructor(options) {
            super(options);
            this.on_pan_start = this.on_pan_start.bind(this);
            this.on_pan = this.on_pan.bind(this);
            this.on_pan_end = this.on_pan_end.bind(this);
        }
        sizing = new dom_1.InlineStyleSheet("", "sizing");
        stylesheets() {
            return [...super.stylesheets(), icons_css.default, drawers_css.default, this.sizing];
        }
        handle_el = (0, dom_1.div)({ class: drawers_css.handle });
        contents_el = (0, dom_1.div)({ class: drawers_css.contents });
        toggle_el;
        ui_gestures = new ui_gestures_1.UIGestures(this.handle_el, this);
        connect_signals() {
            super.connect_signals();
            this.ui_gestures.connect_signals();
            const { location, open, resizable } = this.model.properties;
            this.on_change(open, () => {
                this.toggle(this.model.open);
            });
            this.on_change(location, () => {
                this.class_list.remove(drawers_css.left, drawers_css.right, drawers_css.above, drawers_css.below);
                this.class_list.add(drawers_css[this.model.location]);
            });
            this.on_change(resizable, () => {
                this.class_list.toggle(drawers_css.resizable, this.model.resizable);
            });
        }
        get self_target() {
            return this.contents_el;
        }
        title(open) {
            return open ? "Collapse" : "Expand";
        }
        render() {
            super.render();
            const { location, open, size, resizable } = this.model;
            this.class_list.add(drawers_css[location]);
            this.class_list.toggle(drawers_css.open, open);
            this.class_list.toggle(drawers_css.resizable, resizable);
            const icon_el = (0, dom_1.div)({ class: drawers_css.chevron });
            const title = this.title(open);
            this.toggle_el = (0, dom_1.div)({ class: drawers_css.toggle, title }, icon_el);
            this.toggle_el.addEventListener("click", () => this.toggle());
            this.shadow_el.append(this.contents_el, this.toggle_el, this.handle_el);
            this.sizing.replace(`
      :host {
        --drawer-size: ${(0, types_1.isNumber)(size) ? (0, dom_1.px)(size) : size};
      }
    `);
        }
        toggle(open) {
            open = this.class_list.toggle(drawers_css.open, open);
            this.toggle_el.title = this.title(open);
            this.model.open = open;
        }
        state = null;
        on_pan_start(_event) {
            (0, assert_1.assert)(this.state == null);
            const styles = getComputedStyle(this.el);
            this.state = {
                width: parseFloat(styles.width),
                height: parseFloat(styles.height),
            };
            this.class_list.add(drawers_css.resizing);
        }
        on_pan(event) {
            (0, assert_1.assert)(this.state != null);
            const size = (() => {
                const { width, height } = this.state;
                const { dx, dy } = event;
                switch (this.model.location) {
                    case "left": return max(width + dx, 0);
                    case "right": return max(width - dx, 0);
                    case "above": return max(height + dy, 0);
                    case "below": return max(height - dy, 0);
                }
            })();
            this.sizing.replace(`
      :host {
        --drawer-size: ${size}px;
      }
    `);
        }
        on_pan_end(_event) {
            (0, assert_1.assert)(this.state != null);
            this.state = null;
            this.class_list.remove(drawers_css.resizing);
        }
    }
    exports.DrawerView = DrawerView;
    class Drawer extends pane_1.Pane {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = DrawerView;
            this.define(({ Bool }) => ({
                location: [enums_1.Location],
                open: [Bool, false],
                size: [CSSSize, 300],
                resizable: [Bool, false],
            }));
        }
    }
    exports.Drawer = Drawer;
},
/* styles/drawers.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.left = "bk-left";
    exports.right = "bk-right";
    exports.above = "bk-above";
    exports.below = "bk-below";
    exports.open = "bk-open";
    exports.handle = "bk-handle";
    exports.contents = "bk-contents";
    exports.resizing = "bk-resizing";
    exports.toggle = "bk-toggle";
    exports.chevron = "bk-chevron";
    exports.resizable = "bk-resizable";
    exports.default = `:host{--drawer-size:300px;}:host{position:absolute;background-color:var(--background-color);}:host(.bk-left),:host(.bk-right){--toggle-width:20px;--toggle-height:50px;max-width:calc(100% - var(--toggle-width));}:host(.bk-above),:host(.bk-below){--toggle-width:50px;--toggle-height:20px;max-height:calc(100% - var(--toggle-height));}:host(:not(.bk-open)) .bk-handle{display:none;}:host(.bk-left){left:0;top:0;bottom:0;width:0;}:host(.bk-right){right:0;top:0;bottom:0;width:0;}:host(.bk-above){left:0;right:0;top:0;height:0;}:host(.bk-below){left:0;right:0;bottom:0;height:0;}.bk-contents{position:relative;width:100%;height:100%;overflow:hidden;}:host(:not(.bk-resizing)){transition:width 200ms,
              height 200ms;}:host(.bk-left.bk-open){width:var(--drawer-size);border-right:var(--border);}:host(.bk-right.bk-open){width:var(--drawer-size);border-left:var(--border);}:host(.bk-above.bk-open){height:var(--drawer-size);border-bottom:var(--border);}:host(.bk-below.bk-open){height:var(--drawer-size);border-top:var(--border);}.bk-toggle{position:absolute;display:flex;align-items:center;width:var(--toggle-width);height:var(--toggle-height);cursor:pointer;background-color:white;border:var(--border);}:host(.bk-left) .bk-toggle{flex-direction:row;transform:translate(0, -50%);top:50%;left:100%;border-top-right-radius:15px;border-bottom-right-radius:15px;box-shadow:inset 1px 0px 5px 0px var(--box-shadow-color);}:host(.bk-right) .bk-toggle{flex-direction:row;transform:translate(0, -50%);top:50%;right:100%;border-top-left-radius:15px;border-bottom-left-radius:15px;box-shadow:inset -1px 0px 5px 0px var(--box-shadow-color);}:host(.bk-above) .bk-toggle{flex-direction:column;transform:translate(-50%, 0);left:50%;top:100%;border-bottom-left-radius:15px;border-bottom-right-radius:15px;box-shadow:inset 0px 1px 5px 0px var(--box-shadow-color);}:host(.bk-below) .bk-toggle{flex-direction:column;transform:translate(-50%, 0);left:50%;bottom:100%;border-top-left-radius:15px;border-top-right-radius:15px;box-shadow:inset 0px -1px 5px 0px var(--box-shadow-color);}.bk-chevron{width:1.5em;height:1.5em;background-color:var(--icon-color);mask-image:var(--bokeh-icon-chevron-left);-webkit-mask-image:var(--bokeh-icon-chevron-left);mask-size:100% 100%;-webkit-mask-size:100% 100%;mask-position:center center;-webkit-mask-position:center center;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat;}:host(.bk-left) .bk-chevron{rotate:0.5turn;}:host(.bk-left.bk-open) .bk-chevron{rotate:0turn;}:host(.bk-right) .bk-chevron{rotate:0turn;}:host(.bk-right.bk-open) .bk-chevron{rotate:0.5turn;}:host(.bk-above) .bk-chevron{rotate:-0.25turn;}:host(.bk-above.bk-open) .bk-chevron{rotate:0.25turn;}:host(.bk-below) .bk-chevron{rotate:0.25turn;}:host(.bk-below.bk-open) .bk-chevron{rotate:-0.25turn;}.bk-handle{position:absolute;--handle-depth:6px;}:host(:not(.bk-resizable)) .bk-handle{display:none;}:host(.bk-left) .bk-handle{right:0;top:0;bottom:0;width:var(--handle-depth);transform:translate(50%, 0);cursor:ew-resize;}:host(.bk-right) .bk-handle{left:0;top:0;bottom:0;width:var(--handle-depth);transform:translate(-50%, 0);cursor:ew-resize;}:host(.bk-above) .bk-handle{left:0;right:0;bottom:0;height:var(--handle-depth);transform:translate(0, 50%);cursor:ns-resize;}:host(.bk-below) .bk-handle{left:0;right:0;top:0;height:var(--handle-depth);transform:translate(0, -50%);cursor:ns-resize;}`;
},
/* models/ui/examiner.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const jsx_runtime_1 = require(579) /* preact/jsx-runtime */;
    const ui_element_1 = require(55) /* ./ui_element */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const has_props_1 = require(16) /* ../../core/has_props */;
    const types_1 = require(8) /* ../../core/util/types */;
    const object_1 = require(9) /* ../../core/util/object */;
    const iterator_1 = require(15) /* ../../core/util/iterator */;
    const signaling_1 = require(17) /* ../../core/signaling */;
    const diagnostics_1 = require(39) /* ../../core/diagnostics */;
    const assert_1 = require(13) /* ../../core/util/assert */;
    const printers_1 = require(581) /* ./printers */;
    const examiner_css_1 = tslib_1.__importDefault(require(583) /* ../../styles/examiner.css */);
    const pretty_css_1 = tslib_1.__importDefault(require(582) /* ../../styles/pretty.css */);
    const icons_css_1 = tslib_1.__importDefault(require(76) /* ../../styles/icons.css */);
    const preact_1 = require(580) /* preact */;
    const signals_1 = require(584) /* @preact/signals */;
    const serializer_1 = require(34) /* ../../core/serialization/serializer */;
    const deserializer_1 = require(48) /* ../../core/serialization/deserializer */;
    function highlight(el) {
        for (const animation of el.getAnimations()) {
            animation.cancel();
        }
        el.animate([
            { backgroundColor: "#def189" },
            { backgroundColor: "initial" },
        ], { duration: 2000 });
    }
    function emphasize(text, pattern) {
        const i = text.indexOf(pattern);
        if (i == -1) {
            return (0, jsx_runtime_1.jsx)("span", { children: text });
        }
        else {
            const j = i + pattern.length;
            const prefix = text.substring(0, i);
            const infix = text.substring(i, j);
            const suffix = text.substring(j);
            return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [
                    (0, jsx_runtime_1.jsx)("span", { children: prefix }), (0, jsx_runtime_1.jsx)("span", { class: "underline", children: infix }), (0, jsx_runtime_1.jsx)("span", { children: suffix })
                ] }));
        }
    }
    function compute_attrs(model) {
        const bases = [];
        let proto = Object.getPrototypeOf(model);
        do {
            bases.push([proto.constructor, (0, object_1.keys)(proto._props)]);
            proto = Object.getPrototypeOf(proto);
        } while (proto.constructor != has_props_1.HasProps);
        bases.reverse();
        const cumulative = [];
        for (const [, attrs] of bases) {
            attrs.splice(0, cumulative.length);
            cumulative.push(...attrs);
        }
        return bases.map(([base, attrs]) => [base, attrs.map((attr) => model.property(attr))]);
    }
    class ExaminerView extends ui_element_1.UIElementView {
        stylesheets() {
            return [...super.stylesheets(), pretty_css_1.default, examiner_css_1.default, icons_css_1.default];
        }
        render() {
            super.render();
            const models_filter = (0, signals_1.signal)("");
            const props_filter = (0, signals_1.signal)("");
            const watches_filter = (0, signals_1.signal)("");
            const group_props = (0, signals_1.signal)(true);
            const show_initial = (0, signals_1.signal)(true);
            const show_internal = (0, signals_1.signal)(true);
            const opaque_types = (0, signals_1.signal)(false);
            const watched_props = (0, signals_1.signal)(new Set());
            function cls(...classes) {
                const transformed = classes
                    .flatMap((cls) => (0, types_1.isArray)(cls) ? cls : [cls])
                    .filter((cls) => cls != null)
                    .map((cls) => cls.trim())
                    .filter((cls) => cls.length != 0);
                return [...new Set(transformed)].join(" ");
            }
            function click(obj) {
                if (obj instanceof has_props_1.HasProps) {
                    current_model.value = obj;
                }
            }
            function to_html(obj) {
                const printer = new printers_1.ValuePrinter(click);
                return printer.to_html(obj);
            }
            class ModelItem extends preact_1.Component {
                constructor(props) {
                    super(props);
                    this.state = {
                        value_changed: new Date(),
                    };
                }
                _model_el = null;
                listener = ((obj) => {
                    if (!(obj instanceof p.Property && this._model_el != null)) {
                        return;
                    }
                    const { model } = this.props;
                    for (const prop of model) {
                        if (prop == obj) {
                            this.setState({ value_changed: new Date() });
                            highlight(this._model_el);
                        }
                    }
                }).bind(this);
                componentDidMount() {
                    diagnostics_1.diagnostics.connect(this.listener);
                }
                componentWillUnmount() {
                    diagnostics_1.diagnostics.disconnect(this.listener);
                }
                render() {
                    const { model } = this.props;
                    const root = model.is_root ? (0, jsx_runtime_1.jsx)("span", { class: "tag", children: "root" }) : null;
                    const key_down = (event) => {
                        if (event.key == "Enter") {
                            click(model);
                        }
                    };
                    const active = current_model.value == model ? "active" : null;
                    return ((0, jsx_runtime_1.jsxs)("span", { class: cls("model-ref", active), tabIndex: 0, onKeyDown: key_down, ref: (el) => { this._model_el = el; }, children: [to_html(model), root] }));
                }
            }
            class ModelsToolbar extends preact_1.Component {
                render() {
                    const key_up = (event) => {
                        if (event.currentTarget instanceof HTMLInputElement) {
                            models_filter.value = event.currentTarget.value;
                        }
                    };
                    return ((0, jsx_runtime_1.jsx)("div", { class: "toolbar", children: (0, jsx_runtime_1.jsx)("input", { class: "filter", type: "text", placeholder: "Filter", onKeyUp: key_up }) }));
                }
            }
            class PropsToolbar extends preact_1.Component {
                render() {
                    const key_up = (event) => {
                        if (event.currentTarget instanceof HTMLInputElement) {
                            props_filter.value = event.currentTarget.value;
                        }
                    };
                    return ((0, jsx_runtime_1.jsxs)("div", { class: "toolbar", children: [
                            (0, jsx_runtime_1.jsx)("input", { class: "filter", type: "text", placeholder: "Filter", onKeyUp: key_up }), (0, jsx_runtime_1.jsxs)("span", { class: "checkbox", children: [
                                    (0, jsx_runtime_1.jsx)("input", { type: "checkbox", checked: group_props.value, onChange: (event) => group_props.value = event.currentTarget.checked }), (0, jsx_runtime_1.jsx)("span", { children: "Group" })
                                ] }), (0, jsx_runtime_1.jsxs)("span", { class: "checkbox", children: [
                                    (0, jsx_runtime_1.jsx)("input", { type: "checkbox", checked: show_initial.value, onChange: (event) => show_initial.value = event.currentTarget.checked }), (0, jsx_runtime_1.jsx)("span", { children: "Show initial" })
                                ] }), (0, jsx_runtime_1.jsxs)("span", { class: "checkbox", children: [
                                    (0, jsx_runtime_1.jsx)("input", { type: "checkbox", checked: show_internal.value, onChange: (event) => show_internal.value = event.currentTarget.checked }), (0, jsx_runtime_1.jsx)("span", { children: "Show internal" })
                                ] }), (0, jsx_runtime_1.jsxs)("span", { class: "checkbox", children: [
                                    (0, jsx_runtime_1.jsx)("input", { type: "checkbox", checked: opaque_types.value, onChange: (event) => opaque_types.value = event.currentTarget.checked }), (0, jsx_runtime_1.jsx)("span", { children: "Opaque types" })
                                ] })
                        ] }));
                }
            }
            class ModelsList extends preact_1.Component {
                constructor(props) {
                    super(props);
                }
                models_list = (0, signals_1.computed)(() => {
                    const pattern = models_filter.value;
                    return this.props.models.filter((model) => model.constructor.__qualified__.includes(pattern));
                });
                render() {
                    return ((0, jsx_runtime_1.jsxs)("div", { class: "models-panel", children: [
                            (0, jsx_runtime_1.jsx)(ModelsToolbar, {}), (0, jsx_runtime_1.jsx)("div", { class: "models-list", children: this.models_list.value.map((model) => (0, jsx_runtime_1.jsx)(ModelItem, { model: model })) })
                        ] }));
                }
            }
            class PropEditor extends preact_1.Component {
                constructor(props) {
                    super(props);
                }
                get serializer() {
                    const doc = this.props.prop.obj.document;
                    (0, assert_1.assert)(doc != null);
                    const all_refs = new Map((0, iterator_1.map)(doc.all_models, (model) => [model, model.ref()]));
                    return new serializer_1.Serializer({ binary: false, include_defaults: false, references: all_refs });
                }
                get deserializer() {
                    const doc = this.props.prop.obj.document;
                    (0, assert_1.assert)(doc != null);
                    const all_models = new Map((0, iterator_1.map)(doc.all_models, (model) => [model.id, model]));
                    return new deserializer_1.Deserializer(doc.resolver, all_models, (obj) => obj.attach_document(doc));
                }
                commit(value) {
                    const parsed = JSON.parse(value);
                    const decoded = this.deserializer.decode(parsed);
                    const { prop } = this.props;
                    prop.obj.setv({ [prop.attr]: decoded });
                }
                input_el = null;
                render() {
                    const { prop } = this.props;
                    const value = this.serializer.encode(prop.get_value());
                    return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [
                            (0, jsx_runtime_1.jsx)("input", { type: "text", ref: (el) => { this.input_el = el; }, onKeyUp: (event) => this.on_key_up(event), value: JSON.stringify(value) }), (0, jsx_runtime_1.jsx)("div", { class: "btn btn-accept", onClick: () => this.accept_edit() }), (0, jsx_runtime_1.jsx)("div", { class: "btn btn-cancel", onClick: () => this.cancel_edit() }), (0, jsx_runtime_1.jsx)("div", { class: "btn btn-delete", onClick: () => this.delete_value() })
                        ] }));
                }
                accept_edit() {
                    (0, assert_1.assert)(this.input_el != null);
                    this.commit(this.input_el.value);
                    this.finalize();
                }
                cancel_edit() {
                    this.finalize();
                }
                delete_value() {
                    const { prop } = this.props;
                    const value = prop.default_value(prop.obj);
                    prop.obj.setv({ [prop.attr]: value });
                    this.finalize();
                }
                finalize() {
                    this.props.close();
                }
                on_key_up(event) {
                    switch (event.key) {
                        case "Enter": {
                            this.commit(event.currentTarget.value);
                            break;
                        }
                        case "Escape": {
                            this.cancel_edit();
                            break;
                        }
                        default:
                    }
                }
                componentDidMount() {
                    this.input_el?.focus();
                }
            }
            class PropValue extends preact_1.Component {
                constructor(props) {
                    super(props);
                    this.state = {
                        value_changed: new Date(),
                    };
                }
                _value_el = null;
                listener = ((obj) => {
                    if (obj === this.props.prop && this._value_el != null) {
                        this.setState({ value_changed: new Date() });
                        highlight(this._value_el);
                    }
                }).bind(this);
                componentDidMount() {
                    diagnostics_1.diagnostics.connect(this.listener);
                }
                componentWillUnmount() {
                    diagnostics_1.diagnostics.disconnect(this.listener);
                }
                render() {
                    const { prop } = this.props;
                    return ((0, jsx_runtime_1.jsx)("span", { class: "value", ref: (el) => { this._value_el = el; }, children: prop.is_unset ? (0, jsx_runtime_1.jsx)("span", { children: "unset" }) : to_html(prop.get_value()) }));
                }
            }
            class PropItem extends preact_1.Component {
                constructor(props) {
                    super(props);
                    this.state = { editing: false };
                }
                toggle_edit() {
                    const { editing } = this.state;
                    this.setState({ editing: !editing });
                }
                render() {
                    const { prop } = this.props;
                    const connections = signaling_1.receivers_for_sender.get(prop.obj) ?? [];
                    const listeners = connections.filter((connection) => connection.signal == prop.change).length;
                    const watched = watched_props.value.has(prop);
                    const watch_el = (0, jsx_runtime_1.jsx)("input", { type: "checkbox", checked: watched, onChange: (event) => {
                            const { checked } = event.currentTarget;
                            const watched = watched_props.value;
                            watched[checked ? "add" : "delete"](prop);
                            watched_props.value = new Set(watched);
                        } });
                    const dirty = prop.dirty ? "dirty" : null;
                    const internal = prop.internal ? "internal" : null;
                    const hidden = !prop.dirty && !show_initial.value || prop.internal && !show_internal.value ? "hidden" : null;
                    const pattern = props_filter.value;
                    const { attr } = prop;
                    const kind_printer = opaque_types.value ? new printers_1.OpaqueKindPrinter() : new printers_1.KindPrinter();
                    const { editing } = this.state;
                    return ((0, jsx_runtime_1.jsxs)("div", { class: cls("prop", dirty, internal, hidden), children: [
                            (0, jsx_runtime_1.jsxs)("div", { class: "prop-attr", tabIndex: 0, children: [watch_el, emphasize(attr, pattern), prop.internal ? (0, jsx_runtime_1.jsx)("span", { class: "tag", children: "internal" }) : null] }), (0, jsx_runtime_1.jsx)("div", { class: "prop-conns", children: listeners != 0 ? (0, jsx_runtime_1.jsx)("span", { class: "tag", children: `${listeners}` }) : null }), (0, jsx_runtime_1.jsx)("div", { class: "prop-kind", children: kind_printer.to_html(prop.kind) }), (0, jsx_runtime_1.jsx)("div", { class: cls("prop-value", editing ? "editing" : null), children: !editing ?
                                    (0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [
                                            (0, jsx_runtime_1.jsx)(PropValue, { prop: prop }), (0, jsx_runtime_1.jsx)("div", { class: "btn btn-edit", onClick: () => this.toggle_edit() })
                                        ] })
                                    :
                                        (0, jsx_runtime_1.jsx)(PropEditor, { prop: prop, close: () => this.toggle_edit() }) })
                        ] }));
                }
            }
            class BaseItem extends preact_1.Component {
                collapsed = (0, signals_1.signal)(false);
                render() {
                    const toggle = () => {
                        this.collapsed.value = !this.collapsed.value;
                    };
                    const { base, props } = this.props;
                    const items = props.map((prop) => (0, jsx_runtime_1.jsx)(PropItem, { prop: prop }));
                    if (group_props.value) {
                        return ((0, jsx_runtime_1.jsxs)("div", { class: cls("branch", this.collapsed.value ? "collapsed" : null), children: [
                                (0, jsx_runtime_1.jsxs)("div", { class: "base", onClick: toggle, children: [
                                        (0, jsx_runtime_1.jsx)("span", { class: "expander" }),
                                        "inherited from ",
                                        (0, jsx_runtime_1.jsx)("span", { class: "monospace", children: base.__qualified__ })
                                    ] }), items
                            ] }));
                    }
                    else {
                        return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: items });
                    }
                }
            }
            class PropsList extends preact_1.Component {
                model_props = (0, signals_1.computed)(() => {
                    const model = current_model.value;
                    return model != null ? compute_attrs(model) : [];
                });
                props_list = (0, signals_1.computed)(() => {
                    const text = props_filter.value;
                    return this.model_props.value.map(([base, props]) => [base, props.filter((prop) => prop.attr.includes(text))]);
                });
                render() {
                    return ((0, jsx_runtime_1.jsx)("div", { class: "props-list", children: this.props_list.value.map(([base, props]) => (0, jsx_runtime_1.jsx)(BaseItem, { base: base, props: props })) }));
                }
            }
            class PropsPanel extends preact_1.Component {
                render() {
                    return ((0, jsx_runtime_1.jsxs)("div", { class: "props-panel", children: [
                            (0, jsx_runtime_1.jsx)(PropsToolbar, {}), (0, jsx_runtime_1.jsx)(PropsList, {})
                        ] }));
                }
            }
            class WatchesToolbar extends preact_1.Component {
                render() {
                    const key_up = (event) => {
                        if (event.currentTarget instanceof HTMLInputElement) {
                            watches_filter.value = event.currentTarget.value;
                        }
                    };
                    return ((0, jsx_runtime_1.jsx)("div", { class: "toolbar", children: (0, jsx_runtime_1.jsx)("input", { class: "filter", type: "text", placeholder: "Filter", onKeyUp: key_up }) }));
                }
            }
            class WatchesList extends preact_1.Component {
                remove_watch(prop) {
                    const watched = watched_props.value;
                    watched.delete(prop);
                    watched_props.value = new Set(watched);
                }
                render() {
                    const props = [...watched_props.value];
                    const entries = (() => {
                        if (props.length == 0) {
                            return (0, jsx_runtime_1.jsx)("div", { class: "nothing", children: "No watched properties" });
                        }
                        else {
                            return props.map((prop) => ((0, jsx_runtime_1.jsxs)("div", { class: cls("prop", prop.dirty ? "dirty" : null), children: [
                                    (0, jsx_runtime_1.jsx)("div", { children: to_html(prop) }), (0, jsx_runtime_1.jsx)("div", { children: (0, jsx_runtime_1.jsx)(PropValue, { prop: prop }) }), (0, jsx_runtime_1.jsx)("div", { class: "btn btn-delete", onClick: () => this.remove_watch(prop) })
                                ] })));
                        }
                    })();
                    return (0, jsx_runtime_1.jsx)("div", { class: "watches-list", children: entries });
                }
            }
            class WatchesPanel extends preact_1.Component {
                render() {
                    return ((0, jsx_runtime_1.jsxs)("div", { class: "watches-panel", children: [
                            (0, jsx_runtime_1.jsx)(WatchesToolbar, {}), (0, jsx_runtime_1.jsx)(WatchesList, {})
                        ] }));
                }
            }
            class ExaminerPanel extends preact_1.Component {
                render() {
                    return ((0, jsx_runtime_1.jsxs)("div", { class: "examiner", children: [
                            (0, jsx_runtime_1.jsx)(ModelsList, { models: [...models] }), (0, jsx_runtime_1.jsxs)("div", { class: "col", style: { width: "100%" }, children: [
                                    (0, jsx_runtime_1.jsx)(WatchesPanel, {}), (0, jsx_runtime_1.jsx)(PropsPanel, {})
                                ] })
                        ] }));
                }
            }
            const { target } = this.model;
            const models = (() => {
                if (target != null) {
                    return target.references();
                }
                else {
                    return this.model.document?.all_models ?? new Set();
                }
            })();
            const current_model = (0, signals_1.signal)([...models][0]);
            const examiner = (0, jsx_runtime_1.jsx)(ExaminerPanel, {});
            (0, preact_1.render)(examiner, this.shadow_el);
        }
    }
    exports.ExaminerView = ExaminerView;
    class Examiner extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ExaminerView;
            this.define(({ Ref, Nullable }) => ({
                target: [Nullable(Ref(has_props_1.HasProps)), null],
            }));
        }
    }
    exports.Examiner = Examiner;
},
/* preact/jsx-runtime/dist/jsxRuntime.module.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.jsx = u;
    exports.jsxDEV = u;
    exports.jsxs = u;
    exports.jsxAttr = l;
    exports.jsxEscape = s;
    exports.jsxTemplate = a;
    const preact_1 = require(580) /* preact */;
    var preact_2 = require(580) /* preact */;
    __esExport("Fragment", preact_2.Fragment);
    var t = /["&<]/;
    function n(r) {
        if (0 === r.length || !1 === t.test(r))
            return r;
        for (var e = 0, n = 0, o = "", f = ""; n < r.length; n++) {
            switch (r.charCodeAt(n)) {
                case 34:
                    f = "&quot;";
                    break;
                case 38:
                    f = "&amp;";
                    break;
                case 60:
                    f = "&lt;";
                    break;
                default: continue;
            }
            n !== e && (o += r.slice(e, n)), o += f, e = n + 1;
        }
        return n !== e && (o += r.slice(e, n)), o;
    }
    var o = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i, f = 0, i = Array.isArray;
    function u(e, t, n, o, i, u) {
        t || (t = {});
        var a, c, p = t;
        if ("ref" in p)
            for (c in p = {}, t)
                "ref" == c ? a = t[c] : p[c] = t[c];
        var l = { type: e, props: p, key: n, ref: a, __k: null, __: null, __b: 0, __e: null, __c: null, constructor: void 0, __v: --f, __i: -1, __u: 0, __source: i, __self: u };
        if ("function" == typeof e && (a = e.defaultProps))
            for (c in a)
                void 0 === p[c] && (p[c] = a[c]);
        return preact_1.options.vnode && preact_1.options.vnode(l), l;
    }
    function a(r) { var t = u(preact_1.Fragment, { tpl: r, exprs: [].slice.call(arguments, 1) }); return t.key = t.__v, t; }
    var c = {}, p = /[A-Z]/g;
    function l(e, t) {
        if (preact_1.options.attr) {
            var f = preact_1.options.attr(e, t);
            if ("string" == typeof f)
                return f;
        }
        if (t = function (r) { return null !== r && "object" == typeof r && "function" == typeof r.valueOf ? r.valueOf() : r; }(t), "ref" === e || "key" === e)
            return "";
        if ("style" === e && "object" == typeof t) {
            var i = "";
            for (var u in t) {
                var a = t[u];
                if (null != a && "" !== a) {
                    var l = "-" == u[0] ? u : c[u] || (c[u] = u.replace(p, "-$&").toLowerCase()), s = ";";
                    "number" != typeof a || l.startsWith("--") || o.test(l) || (s = "px;"), i = i + l + ":" + a + s;
                }
            }
            return e + '="' + n(i) + '"';
        }
        return null == t || !1 === t || "function" == typeof t || "object" == typeof t ? "" : !0 === t ? e : e + '="' + n("" + t) + '"';
    }
    function s(r) {
        if (null == r || "boolean" == typeof r || "function" == typeof r)
            return null;
        if ("object" == typeof r) {
            if (void 0 === r.constructor)
                return r;
            if (i(r)) {
                for (var e = 0; e < r.length; e++)
                    r[e] = s(r[e]);
                return r;
            }
        }
        return n("" + r);
    }
},
/* preact/dist/preact.module.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.Component = x;
    exports.Fragment = k;
    exports.cloneElement = K;
    exports.createContext = Q;
    exports.createElement = _;
    exports.h = _;
    exports.createRef = b;
    exports.hydrate = J;
    exports.render = G;
    exports.toChildArray = H;
    var n, l, u, t, i, o, r, e, f, c, s, a, h, p = {}, v = [], y = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i, d = Array.isArray;
    function w(n, l) {
        for (var u in l)
            n[u] = l[u];
        return n;
    }
    function g(n) { n && n.parentNode && n.parentNode.removeChild(n); }
    function _(l, u, t) {
        var i, o, r, e = {};
        for (r in u)
            "key" == r ? i = u[r] : "ref" == r ? o = u[r] : e[r] = u[r];
        if (arguments.length > 2 && (e.children = arguments.length > 3 ? n.call(arguments, 2) : t), "function" == typeof l && null != l.defaultProps)
            for (r in l.defaultProps)
                void 0 === e[r] && (e[r] = l.defaultProps[r]);
        return m(l, e, i, o, null);
    }
    function m(n, t, i, o, r) { var e = { type: n, props: t, key: i, ref: o, __k: null, __: null, __b: 0, __e: null, __c: null, constructor: void 0, __v: null == r ? ++u : r, __i: -1, __u: 0 }; return null == r && null != l.vnode && l.vnode(e), e; }
    function b() { return { current: null }; }
    function k(n) { return n.children; }
    function x(n, l) { this.props = n, this.context = l; }
    function S(n, l) {
        if (null == l)
            return n.__ ? S(n.__, n.__i + 1) : null;
        for (var u; l < n.__k.length; l++)
            if (null != (u = n.__k[l]) && null != u.__e)
                return u.__e;
        return "function" == typeof n.type ? S(n) : null;
    }
    function C(n) {
        var l, u;
        if (null != (n = n.__) && null != n.__c) {
            for (n.__e = n.__c.base = null, l = 0; l < n.__k.length; l++)
                if (null != (u = n.__k[l]) && null != u.__e) {
                    n.__e = n.__c.base = u.__e;
                    break;
                }
            return C(n);
        }
    }
    function M(n) { (!n.__d && (n.__d = !0) && i.push(n) && !$.__r++ || o != l.debounceRendering) && ((o = l.debounceRendering) || r)($); }
    function $() {
        for (var n, u, t, o, r, f, c, s = 1; i.length;)
            i.length > s && i.sort(e), n = i.shift(), s = i.length, n.__d && (t = void 0, o = void 0, r = (o = (u = n).__v).__e, f = [], c = [], u.__P && ((t = w({}, o)).__v = o.__v + 1, l.vnode && l.vnode(t), O(u.__P, t, o, u.__n, u.__P.namespaceURI, 32 & o.__u ? [r] : null, f, null == r ? S(o) : r, !!(32 & o.__u), c), t.__v = o.__v, t.__.__k[t.__i] = t, N(f, t, c), o.__e = o.__ = null, t.__e != r && C(t)));
        $.__r = 0;
    }
    function I(n, l, u, t, i, o, r, e, f, c, s) {
        var a, h, y, d, w, g, _, m = t && t.__k || v, b = l.length;
        for (f = P(u, l, m, f, b), a = 0; a < b; a++)
            null != (y = u.__k[a]) && (h = -1 == y.__i ? p : m[y.__i] || p, y.__i = a, g = O(n, y, h, i, o, r, e, f, c, s), d = y.__e, y.ref && h.ref != y.ref && (h.ref && B(h.ref, null, y), s.push(y.ref, y.__c || d, y)), null == w && null != d && (w = d), (_ = !!(4 & y.__u)) || h.__k === y.__k ? f = A(y, f, n, _) : "function" == typeof y.type && void 0 !== g ? f = g : d && (f = d.nextSibling), y.__u &= -7);
        return u.__e = w, f;
    }
    function P(n, l, u, t, i) {
        var o, r, e, f, c, s = u.length, a = s, h = 0;
        for (n.__k = new Array(i), o = 0; o < i; o++)
            null != (r = l[o]) && "boolean" != typeof r && "function" != typeof r ? ("string" == typeof r || "number" == typeof r || "bigint" == typeof r || r.constructor == String ? r = n.__k[o] = m(null, r, null, null, null) : d(r) ? r = n.__k[o] = m(k, { children: r }, null, null, null) : void 0 === r.constructor && r.__b > 0 ? r = n.__k[o] = m(r.type, r.props, r.key, r.ref ? r.ref : null, r.__v) : n.__k[o] = r, f = o + h, r.__ = n, r.__b = n.__b + 1, e = null, -1 != (c = r.__i = L(r, u, f, a)) && (a--, (e = u[c]) && (e.__u |= 2)), null == e || null == e.__v ? (-1 == c && (i > s ? h-- : i < s && h++), "function" != typeof r.type && (r.__u |= 4)) : c != f && (c == f - 1 ? h-- : c == f + 1 ? h++ : (c > f ? h-- : h++, r.__u |= 4))) : n.__k[o] = null;
        if (a)
            for (o = 0; o < s; o++)
                null != (e = u[o]) && 0 == (2 & e.__u) && (e.__e == t && (t = S(e)), D(e, e));
        return t;
    }
    function A(n, l, u, t) {
        var i, o;
        if ("function" == typeof n.type) {
            for (i = n.__k, o = 0; i && o < i.length; o++)
                i[o] && (i[o].__ = n, l = A(i[o], l, u, t));
            return l;
        }
        n.__e != l && (t && (l && n.type && !l.parentNode && (l = S(n)), u.insertBefore(n.__e, l || null)), l = n.__e);
        do {
            l = l && l.nextSibling;
        } while (null != l && 8 == l.nodeType);
        return l;
    }
    function H(n, l) { return l = l || [], null == n || "boolean" == typeof n || (d(n) ? n.some(function (n) { H(n, l); }) : l.push(n)), l; }
    function L(n, l, u, t) {
        var i, o, r, e = n.key, f = n.type, c = l[u], s = null != c && 0 == (2 & c.__u);
        if (null === c && null == e || s && e == c.key && f == c.type)
            return u;
        if (t > (s ? 1 : 0))
            for (i = u - 1, o = u + 1; i >= 0 || o < l.length;)
                if (null != (c = l[r = i >= 0 ? i-- : o++]) && 0 == (2 & c.__u) && e == c.key && f == c.type)
                    return r;
        return -1;
    }
    function T(n, l, u) { "-" == l[0] ? n.setProperty(l, null == u ? "" : u) : n[l] = null == u ? "" : "number" != typeof u || y.test(l) ? u : u + "px"; }
    function j(n, l, u, t, i) {
        var o, r;
        n: if ("style" == l)
            if ("string" == typeof u)
                n.style.cssText = u;
            else {
                if ("string" == typeof t && (n.style.cssText = t = ""), t)
                    for (l in t)
                        u && l in u || T(n.style, l, "");
                if (u)
                    for (l in u)
                        t && u[l] == t[l] || T(n.style, l, u[l]);
            }
        else if ("o" == l[0] && "n" == l[1])
            o = l != (l = l.replace(f, "$1")), r = l.toLowerCase(), l = r in n || "onFocusOut" == l || "onFocusIn" == l ? r.slice(2) : l.slice(2), n.l || (n.l = {}), n.l[l + o] = u, u ? t ? u.u = t.u : (u.u = c, n.addEventListener(l, o ? a : s, o)) : n.removeEventListener(l, o ? a : s, o);
        else {
            if ("http://www.w3.org/2000/svg" == i)
                l = l.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s");
            else if ("width" != l && "height" != l && "href" != l && "list" != l && "form" != l && "tabIndex" != l && "download" != l && "rowSpan" != l && "colSpan" != l && "role" != l && "popover" != l && l in n)
                try {
                    n[l] = null == u ? "" : u;
                    break n;
                }
                catch (n) { }
            "function" == typeof u || (null == u || !1 === u && "-" != l[4] ? n.removeAttribute(l) : n.setAttribute(l, "popover" == l && 1 == u ? "" : u));
        }
    }
    function F(n) {
        return function (u) {
            if (this.l) {
                var t = this.l[u.type + n];
                if (null == u.t)
                    u.t = c++;
                else if (u.t < t.u)
                    return;
                return t(l.event ? l.event(u) : u);
            }
        };
    }
    function O(n, u, t, i, o, r, e, f, c, s) {
        var a, h, p, v, y, _, m, b, S, C, M, $, P, A, H, L, T, j = u.type;
        if (void 0 !== u.constructor)
            return null;
        128 & t.__u && (c = !!(32 & t.__u), r = [f = u.__e = t.__e]), (a = l.__b) && a(u);
        n: if ("function" == typeof j)
            try {
                if (b = u.props, S = "prototype" in j && j.prototype.render, C = (a = j.contextType) && i[a.__c], M = a ? C ? C.props.value : a.__ : i, t.__c ? m = (h = u.__c = t.__c).__ = h.__E : (S ? u.__c = h = new j(b, M) : (u.__c = h = new x(b, M), h.constructor = j, h.render = E), C && C.sub(h), h.state || (h.state = {}), h.__n = i, p = h.__d = !0, h.__h = [], h._sb = []), S && null == h.__s && (h.__s = h.state), S && null != j.getDerivedStateFromProps && (h.__s == h.state && (h.__s = w({}, h.__s)), w(h.__s, j.getDerivedStateFromProps(b, h.__s))), v = h.props, y = h.state, h.__v = u, p)
                    S && null == j.getDerivedStateFromProps && null != h.componentWillMount && h.componentWillMount(), S && null != h.componentDidMount && h.__h.push(h.componentDidMount);
                else {
                    if (S && null == j.getDerivedStateFromProps && b !== v && null != h.componentWillReceiveProps && h.componentWillReceiveProps(b, M), u.__v == t.__v || !h.__e && null != h.shouldComponentUpdate && !1 === h.shouldComponentUpdate(b, h.__s, M)) {
                        for (u.__v != t.__v && (h.props = b, h.state = h.__s, h.__d = !1), u.__e = t.__e, u.__k = t.__k, u.__k.some(function (n) { n && (n.__ = u); }), $ = 0; $ < h._sb.length; $++)
                            h.__h.push(h._sb[$]);
                        h._sb = [], h.__h.length && e.push(h);
                        break n;
                    }
                    null != h.componentWillUpdate && h.componentWillUpdate(b, h.__s, M), S && null != h.componentDidUpdate && h.__h.push(function () { h.componentDidUpdate(v, y, _); });
                }
                if (h.context = M, h.props = b, h.__P = n, h.__e = !1, P = l.__r, A = 0, S) {
                    for (h.state = h.__s, h.__d = !1, P && P(u), a = h.render(h.props, h.state, h.context), H = 0; H < h._sb.length; H++)
                        h.__h.push(h._sb[H]);
                    h._sb = [];
                }
                else
                    do {
                        h.__d = !1, P && P(u), a = h.render(h.props, h.state, h.context), h.state = h.__s;
                    } while (h.__d && ++A < 25);
                h.state = h.__s, null != h.getChildContext && (i = w(w({}, i), h.getChildContext())), S && !p && null != h.getSnapshotBeforeUpdate && (_ = h.getSnapshotBeforeUpdate(v, y)), L = a, null != a && a.type === k && null == a.key && (L = V(a.props.children)), f = I(n, d(L) ? L : [L], u, t, i, o, r, e, f, c, s), h.base = u.__e, u.__u &= -161, h.__h.length && e.push(h), m && (h.__E = h.__ = null);
            }
            catch (n) {
                if (u.__v = null, c || null != r)
                    if (n.then) {
                        for (u.__u |= c ? 160 : 128; f && 8 == f.nodeType && f.nextSibling;)
                            f = f.nextSibling;
                        r[r.indexOf(f)] = null, u.__e = f;
                    }
                    else {
                        for (T = r.length; T--;)
                            g(r[T]);
                        z(u);
                    }
                else
                    u.__e = t.__e, u.__k = t.__k, n.then || z(u);
                l.__e(n, u, t);
            }
        else
            null == r && u.__v == t.__v ? (u.__k = t.__k, u.__e = t.__e) : f = u.__e = q(t.__e, u, t, i, o, r, e, c, s);
        return (a = l.diffed) && a(u), 128 & u.__u ? void 0 : f;
    }
    function z(n) { n && n.__c && (n.__c.__e = !0), n && n.__k && n.__k.forEach(z); }
    function N(n, u, t) {
        for (var i = 0; i < t.length; i++)
            B(t[i], t[++i], t[++i]);
        l.__c && l.__c(u, n), n.some(function (u) {
            try {
                n = u.__h, u.__h = [], n.some(function (n) { n.call(u); });
            }
            catch (n) {
                l.__e(n, u.__v);
            }
        });
    }
    function V(n) { return "object" != typeof n || null == n || n.__b && n.__b > 0 ? n : d(n) ? n.map(V) : w({}, n); }
    function q(u, t, i, o, r, e, f, c, s) {
        var a, h, v, y, w, _, m, b = i.props || p, k = t.props, x = t.type;
        if ("svg" == x ? r = "http://www.w3.org/2000/svg" : "math" == x ? r = "http://www.w3.org/1998/Math/MathML" : r || (r = "http://www.w3.org/1999/xhtml"), null != e)
            for (a = 0; a < e.length; a++)
                if ((w = e[a]) && "setAttribute" in w == !!x && (x ? w.localName == x : 3 == w.nodeType)) {
                    u = w, e[a] = null;
                    break;
                }
        if (null == u) {
            if (null == x)
                return document.createTextNode(k);
            u = document.createElementNS(r, x, k.is && k), c && (l.__m && l.__m(t, e), c = !1), e = null;
        }
        if (null == x)
            b === k || c && u.data == k || (u.data = k);
        else {
            if (e = e && n.call(u.childNodes), !c && null != e)
                for (b = {}, a = 0; a < u.attributes.length; a++)
                    b[(w = u.attributes[a]).name] = w.value;
            for (a in b)
                if (w = b[a], "children" == a)
                    ;
                else if ("dangerouslySetInnerHTML" == a)
                    v = w;
                else if (!(a in k)) {
                    if ("value" == a && "defaultValue" in k || "checked" == a && "defaultChecked" in k)
                        continue;
                    j(u, a, null, w, r);
                }
            for (a in k)
                w = k[a], "children" == a ? y = w : "dangerouslySetInnerHTML" == a ? h = w : "value" == a ? _ = w : "checked" == a ? m = w : c && "function" != typeof w || b[a] === w || j(u, a, w, b[a], r);
            if (h)
                c || v && (h.__html == v.__html || h.__html == u.innerHTML) || (u.innerHTML = h.__html), t.__k = [];
            else if (v && (u.innerHTML = ""), I("template" == t.type ? u.content : u, d(y) ? y : [y], t, i, o, "foreignObject" == x ? "http://www.w3.org/1999/xhtml" : r, e, f, e ? e[0] : i.__k && S(i, 0), c, s), null != e)
                for (a = e.length; a--;)
                    g(e[a]);
            c || (a = "value", "progress" == x && null == _ ? u.removeAttribute("value") : null != _ && (_ !== u[a] || "progress" == x && !_ || "option" == x && _ != b[a]) && j(u, a, _, b[a], r), a = "checked", null != m && m != u[a] && j(u, a, m, b[a], r));
        }
        return u;
    }
    function B(n, u, t) {
        try {
            if ("function" == typeof n) {
                var i = "function" == typeof n.__u;
                i && n.__u(), i && null == u || (n.__u = n(u));
            }
            else
                n.current = u;
        }
        catch (n) {
            l.__e(n, t);
        }
    }
    function D(n, u, t) {
        var i, o;
        if (l.unmount && l.unmount(n), (i = n.ref) && (i.current && i.current != n.__e || B(i, null, u)), null != (i = n.__c)) {
            if (i.componentWillUnmount)
                try {
                    i.componentWillUnmount();
                }
                catch (n) {
                    l.__e(n, u);
                }
            i.base = i.__P = null;
        }
        if (i = n.__k)
            for (o = 0; o < i.length; o++)
                i[o] && D(i[o], u, t || "function" != typeof n.type);
        t || g(n.__e), n.__c = n.__ = n.__e = void 0;
    }
    function E(n, l, u) { return this.constructor(n, u); }
    function G(u, t, i) { var o, r, e, f; t == document && (t = document.documentElement), l.__ && l.__(u, t), r = (o = "function" == typeof i) ? null : i && i.__k || t.__k, e = [], f = [], O(t, u = (!o && i || t).__k = _(k, null, [u]), r || p, p, t.namespaceURI, !o && i ? [i] : r ? null : t.firstChild ? n.call(t.childNodes) : null, e, !o && i ? i : r ? r.__e : t.firstChild, o, f), N(e, u, f); }
    function J(n, l) { G(n, l, J); }
    function K(l, u, t) {
        var i, o, r, e, f = w({}, l.props);
        for (r in l.type && l.type.defaultProps && (e = l.type.defaultProps), u)
            "key" == r ? i = u[r] : "ref" == r ? o = u[r] : f[r] = void 0 === u[r] && null != e ? e[r] : u[r];
        return arguments.length > 2 && (f.children = arguments.length > 3 ? n.call(arguments, 2) : t), m(l.type, f, i || l.key, o || l.ref, null);
    }
    function Q(n) { function l(n) { var u, t; return this.getChildContext || (u = new Set, (t = {})[l.__c] = this, this.getChildContext = function () { return t; }, this.componentWillUnmount = function () { u = null; }, this.shouldComponentUpdate = function (n) { this.props.value != n.value && u.forEach(function (n) { n.__e = !0, M(n); }); }, this.sub = function (n) { u.add(n); var l = n.componentWillUnmount; n.componentWillUnmount = function () { u && u.delete(n), l && l.call(n); }; }), n.children; } return l.__c = "__cC" + h++, l.__ = n, l.Provider = l.__l = (l.Consumer = function (n, l) { return n.children(l); }).contextType = l, l; }
    n = v.slice, exports.options = l = { __e: function (n, l, u, t) {
            for (var i, o, r; l = l.__;)
                if ((i = l.__c) && !i.__)
                    try {
                        if ((o = i.constructor) && null != o.getDerivedStateFromError && (i.setState(o.getDerivedStateFromError(n)), r = i.__d), null != i.componentDidCatch && (i.componentDidCatch(n, t || {}), r = i.__d), r)
                            return i.__E = i;
                    }
                    catch (l) {
                        n = l;
                    }
            throw n;
        } }, u = 0, exports.isValidElement = t = function (n) { return null != n && void 0 === n.constructor; }, x.prototype.setState = function (n, l) { var u; u = null != this.__s && this.__s != this.state ? this.__s : this.__s = w({}, this.state), "function" == typeof n && (n = n(w({}, u), this.props)), n && w(u, n), null != n && this.__v && (l && this._sb.push(l), M(this)); }, x.prototype.forceUpdate = function (n) { this.__v && (this.__e = !0, n && this.__h.push(n), M(this)); }, x.prototype.render = k, i = [], r = "function" == typeof Promise ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, e = function (n, l) { return n.__v.__b - l.__v.__b; }, $.__r = 0, f = /(PointerCapture)$|Capture$/i, c = 0, s = F(!1), a = F(!0), h = 0;
},
/* models/ui/printers.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const jsx_runtime_1 = require(579) /* preact/jsx-runtime */;
    const pretty_1 = require(43) /* ../../core/util/pretty */;
    const has_props_1 = require(16) /* ../../core/has_props */;
    const types_1 = require(8) /* ../../core/util/types */;
    const object_1 = require(9) /* ../../core/util/object */;
    const array_1 = require(10) /* ../../core/util/array */;
    const color_1 = require(23) /* ../../core/util/color */;
    const kinds_1 = require(22) /* ../../core/kinds */;
    const p = tslib_1.__importStar(require(20) /* ../../core/properties */);
    const pretty = tslib_1.__importStar(require(582) /* ../../styles/pretty.css */);
    class BasePrinter {
        null() {
            return (0, jsx_runtime_1.jsx)("span", { class: pretty.nullish, children: "null" });
        }
        token(val) {
            return (0, jsx_runtime_1.jsx)("span", { class: pretty.token, children: val });
        }
        boolean(val) {
            return (0, jsx_runtime_1.jsx)("span", { class: pretty.boolean, children: `${val}` });
        }
        number(val) {
            return (0, jsx_runtime_1.jsx)("span", { class: pretty.number, children: `${val}` });
        }
        string(val) {
            const sq = val.includes("'");
            const dq = val.includes('"');
            const str = (() => {
                if (sq && dq) {
                    return `\`${val.replace(/`/g, "\\`")}\``;
                }
                else if (dq) {
                    return `'${val}'`;
                }
                else {
                    return `"${val}"`;
                }
            })();
            const rep = (0, jsx_runtime_1.jsx)("span", { class: pretty.string, children: str });
            const color = (0, color_1.css4_parse)(val);
            if (color == null) {
                return rep;
            }
            else {
                return ((0, jsx_runtime_1.jsxs)("span", { class: pretty.color, children: [
                        (0, jsx_runtime_1.jsx)("span", { class: pretty.swatch, style: { backgroundColor: val } }), rep
                    ] }));
            }
        }
        symbol(val) {
            return (0, jsx_runtime_1.jsx)("span", { class: pretty.symbol, children: val.toString() });
        }
    }
    exports.BasePrinter = BasePrinter;
    class OpaqueKindPrinter extends BasePrinter {
        to_html(obj) {
            if (obj == null) {
                return this.null();
            }
            else if ((0, types_1.isBoolean)(obj)) {
                return this.boolean(obj);
            }
            else if ((0, types_1.isNumber)(obj)) {
                return this.number(obj);
            }
            else if ((0, types_1.isString)(obj)) {
                return this.string(obj);
            }
            else if ((0, types_1.isSymbol)(obj)) {
                return this.symbol(obj);
            }
            else if (obj instanceof kinds_1.Kinds.Ref) {
                return this.ref(obj);
            }
            else if (obj instanceof kinds_1.Kinds.Struct) {
                return this.struct(obj);
            }
            else if (obj instanceof kinds_1.Kinds.PartialStruct) {
                return this.partial_struct(obj);
            }
            else if (obj instanceof kinds_1.Kinds.Func) {
                return this.func(obj);
            }
            else if (obj instanceof kinds_1.Kind) {
                return this.kind(obj);
            }
            else {
                return (0, jsx_runtime_1.jsx)("span", { children: obj.toString() });
            }
        }
        ref(obj) {
            const T = this.token;
            return (0, jsx_runtime_1.jsxs)("span", { children: [obj.kind_name, T("("), (0, jsx_runtime_1.jsx)("span", { class: pretty.type, children: obj.type_name }), T(")")] });
        }
        struct(obj) {
            const T = this.token;
            const args = (0, object_1.entries)(obj.struct_type).map(([key, val]) => (0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [this.to_html(key), T(": "), this.to_html(val)] }));
            return (0, jsx_runtime_1.jsxs)("span", { children: [obj.kind_name, T("({"), args, T("})")] });
        }
        partial_struct(obj) {
            const T = this.token;
            const args = (0, object_1.entries)(obj.struct_type).map(([key, val]) => (0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [this.to_html(key), T("?: "), this.to_html(val)] }));
            return (0, jsx_runtime_1.jsxs)("span", { children: [obj.kind_name, T("({"), args, T("})")] });
        }
        func(obj) {
            const T = this.token;
            const args = obj.args_types?.map((arg) => this.to_html(arg)) ?? [];
            const ret = obj.ret_type === undefined ? (0, jsx_runtime_1.jsx)("span", { children: "Void" }) : this.to_html(obj.ret_type);
            return (0, jsx_runtime_1.jsxs)("span", { children: [obj.kind_name, T("("), T("("), (0, array_1.interleave)(args, () => T(", ")), T(")"), T(", "), ret, T(")")] });
        }
        kind(obj) {
            const T = this.token;
            const { kind_name, kind_args } = obj;
            if (kind_args.length == 0) {
                return (0, jsx_runtime_1.jsx)("span", { children: kind_name });
            }
            else {
                const args = kind_args.map((arg) => this.to_html(arg));
                return (0, jsx_runtime_1.jsxs)("span", { children: [kind_name, T("("), (0, array_1.interleave)(args, () => T(", ")), T(")")] });
            }
        }
    }
    exports.OpaqueKindPrinter = OpaqueKindPrinter;
    class KindPrinter extends BasePrinter {
        _precedence_queue = [];
        to_html(obj) {
            const p_prev = this._precedence_queue.at(-1);
            const p = this.precedence(obj);
            this._precedence_queue.push(p);
            try {
                const rep = this._to_html(obj);
                if (p_prev === undefined || p >= p_prev) {
                    return rep;
                }
                else {
                    const T = this.token;
                    return (0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [T("("), rep, T(")")] });
                }
            }
            finally {
                this._precedence_queue.pop();
            }
        }
        _to_html(obj) {
            if (obj == null) {
                return this.null();
            }
            else if ((0, types_1.isBoolean)(obj)) {
                return this.boolean(obj);
            }
            else if ((0, types_1.isNumber)(obj)) {
                return this.number(obj);
            }
            else if ((0, types_1.isString)(obj)) {
                return this.string(obj);
            }
            else if ((0, types_1.isSymbol)(obj)) {
                return this.symbol(obj);
            }
            else if (obj instanceof kinds_1.Kinds.Ref) {
                return this.ref(obj);
            }
            else if (obj instanceof kinds_1.Kinds.Nullable) {
                return this.nullable(obj);
            }
            else if (obj instanceof kinds_1.Kinds.Opt) {
                return this.opt(obj);
            }
            else if (obj instanceof kinds_1.Kinds.List) {
                return this.list(obj);
            }
            else if (obj instanceof kinds_1.Kinds.Set) {
                return this.set(obj);
            }
            else if (obj instanceof kinds_1.Kinds.Dict) {
                return this.dict(obj);
            }
            else if (obj instanceof kinds_1.Kinds.Mapping) {
                return this.mapping(obj);
            }
            else if (obj instanceof kinds_1.Kinds.Tuple) {
                return this.tuple(obj);
            }
            else if (obj instanceof kinds_1.Kinds.Or) {
                return this.or(obj);
            }
            else if (obj instanceof kinds_1.Kinds.And) {
                return this.and(obj);
            }
            else if (obj instanceof kinds_1.Kinds.Enum) {
                return this.enum(obj);
            }
            else if (obj instanceof kinds_1.Kinds.Struct) {
                return this.struct(obj);
            }
            else if (obj instanceof kinds_1.Kinds.PartialStruct) {
                return this.partial_struct(obj);
            }
            else if (obj instanceof kinds_1.Kinds.Func) {
                return this.func(obj);
            }
            else if (obj instanceof kinds_1.Kinds.Regex) {
                return this.regex(obj);
            }
            else if (obj instanceof kinds_1.Kinds.PrefixedStr) {
                return this.prefixed_str(obj);
            }
            else if (obj instanceof kinds_1.Kinds.Primitive) {
                return this.primitive(obj.toString().toLocaleLowerCase());
            }
            else {
                return (0, jsx_runtime_1.jsx)("span", { children: obj.toString() });
            }
        }
        precedence(kind) {
            if (kind instanceof kinds_1.Kinds.Or || kind instanceof kinds_1.Kinds.Enum || kind instanceof kinds_1.Kinds.Tuple) {
                return 0;
            }
            else if (kind instanceof kinds_1.Kinds.And) {
                return 1;
            }
            else {
                return 2;
            }
        }
        primitive(obj) {
            return (0, jsx_runtime_1.jsx)("span", { class: pretty.primitive, children: obj });
        }
        ref(obj) {
            return (0, jsx_runtime_1.jsx)("span", { class: pretty.type, children: obj.type_name });
        }
        nullable(obj) {
            const T = this.token;
            return (0, jsx_runtime_1.jsxs)("span", { children: [this.to_html(obj.base_type), T("?")] });
        }
        opt(obj) {
            return this.nullable(obj);
        }
        list(obj) {
            const T = this.token;
            return (0, jsx_runtime_1.jsxs)("span", { children: [this.to_html(obj.item_type), T("["), T("]")] });
        }
        set(obj) {
            const T = this.token;
            return (0, jsx_runtime_1.jsxs)("span", { children: [T("{"), this.to_html(obj.item_type), T("}")] });
        }
        dict(obj) {
            const T = this.token;
            return (0, jsx_runtime_1.jsxs)("span", { children: [T("{"), this.primitive("str"), T(": "), this.to_html(obj.item_type), T("}")] });
        }
        mapping(obj) {
            const T = this.token;
            return (0, jsx_runtime_1.jsxs)("span", { children: [T("{"), this.to_html(obj.key_type), T(" => "), this.to_html(obj.item_type), T("}")] });
        }
        tuple(obj) {
            const T = this.token;
            const types = obj.types.map((tp) => this.to_html(tp));
            return (0, jsx_runtime_1.jsxs)("span", { children: [T("["), (0, array_1.interleave)(types, () => T(", ")), T("]")] });
        }
        or(obj) {
            const T = this.token;
            const types = obj.types.map((tp) => this.to_html(tp));
            return (0, jsx_runtime_1.jsx)("span", { children: (0, array_1.interleave)(types, () => T(" | ")) });
        }
        and(obj) {
            const T = this.token;
            const types = obj.types.map((tp) => this.to_html(tp));
            return (0, jsx_runtime_1.jsx)("span", { children: (0, array_1.interleave)(types, () => T(" & ")) });
        }
        enum(obj) {
            const T = this.token;
            const types = [...obj.values].map((val) => this.to_html(val));
            return (0, jsx_runtime_1.jsx)("span", { children: (0, array_1.interleave)(types, () => T(" | ")) });
        }
        struct(obj) {
            const T = this.token;
            const fields = (0, object_1.entries)(obj.struct_type).map(([name, kind]) => {
                return (0, jsx_runtime_1.jsxs)("span", { children: [name, T(": "), this.to_html(kind)] });
            });
            return (0, jsx_runtime_1.jsxs)("span", { children: [T("{"), (0, array_1.interleave)(fields, () => T(", ")), T("}")] });
        }
        partial_struct(obj) {
            const T = this.token;
            const fields = (0, object_1.entries)(obj.struct_type).map(([name, kind]) => {
                return (0, jsx_runtime_1.jsxs)("span", { children: [name, T("?: "), this.to_html(kind)] });
            });
            return (0, jsx_runtime_1.jsxs)("span", { children: [T("{"), (0, array_1.interleave)(fields, () => T(", ")), T("}")] });
        }
        func(obj) {
            const T = this.token;
            const args = obj.args_types?.map((arg) => this.to_html(arg)) ?? [];
            const ret = obj.ret_type === undefined ? this.primitive("void") : this.to_html(obj.ret_type);
            return (0, jsx_runtime_1.jsxs)("span", { children: [T("("), (0, array_1.interleave)(args, () => T(", ")), T(")"), T(" => "), ret] });
        }
        regex(obj) {
            const T = this.token;
            const { source, flags } = obj.regex;
            return (0, jsx_runtime_1.jsxs)("span", { children: [T("/"), source, T("/"), flags] });
        }
        prefixed_str(obj) {
            const T = this.token;
            return (0, jsx_runtime_1.jsxs)("span", { children: ["PrefixedStr", T("("), this.to_html(obj.prefix), T(")")] });
        }
    }
    exports.KindPrinter = KindPrinter;
    class ValuePrinter extends BasePrinter {
        click;
        max_items;
        max_depth;
        visited = new WeakSet();
        depth = 0;
        constructor(click, max_items = 5, max_depth = 3) {
            super();
            this.click = click;
            this.max_items = max_items;
            this.max_depth = max_depth;
        }
        to_html(obj) {
            if ((0, types_1.isObject)(obj)) {
                if (this.visited.has(obj)) {
                    return (0, jsx_runtime_1.jsx)("span", { children: "circular" });
                }
                else {
                    this.visited.add(obj);
                }
            }
            if (obj == null) {
                return this.null();
            }
            else if ((0, types_1.isBoolean)(obj)) {
                return this.boolean(obj);
            }
            else if ((0, types_1.isNumber)(obj)) {
                return this.number(obj);
            }
            else if ((0, types_1.isString)(obj)) {
                return this.string(obj);
            }
            else if ((0, types_1.isSymbol)(obj)) {
                return this.symbol(obj);
            }
            else if (obj instanceof has_props_1.HasProps) {
                return this.model(obj);
            }
            else if (obj instanceof p.Property) {
                return this.property(obj);
            }
            else if ((0, types_1.isPlainObject)(obj)) {
                return this.object(obj);
            }
            else if ((0, types_1.isArray)(obj)) {
                return this.array(obj);
            }
            else if ((0, types_1.isIterable)(obj)) {
                return this.iterable(obj);
            }
            else {
                return (0, jsx_runtime_1.jsx)("span", { children: (0, pretty_1.to_string)(obj) });
            }
        }
        array(obj) {
            const T = this.token;
            const items = [];
            let i = 0;
            for (const entry of obj) {
                items.push(this.to_html(entry));
                if (i++ > this.max_items) {
                    items.push((0, jsx_runtime_1.jsx)("span", { children: "\\u2026" }));
                    break;
                }
            }
            return (0, jsx_runtime_1.jsxs)("span", { class: pretty.array, children: [T("["), (0, array_1.interleave)(items, () => T(", ")), T("]")] });
        }
        iterable(obj) {
            const T = this.token;
            const tag = Object(obj)[Symbol.toStringTag] ?? "Object";
            const items = this.array([...obj]);
            return (0, jsx_runtime_1.jsxs)("span", { class: pretty.iterable, children: [`${tag}`, T("("), items, T(")")] });
        }
        object(obj) {
            const T = this.token;
            const items = [];
            let i = 0;
            for (const [key, val] of (0, object_1.entries)(obj)) {
                items.push((0, jsx_runtime_1.jsxs)("span", { children: ["$", `${key}`, T(": "), this.to_html(val)] }));
                if (i++ > this.max_items) {
                    items.push((0, jsx_runtime_1.jsx)("span", { children: "\\u2026" }));
                    break;
                }
            }
            return (0, jsx_runtime_1.jsxs)("span", { class: pretty.object, children: [T("{"), (0, array_1.interleave)(items, () => T(", ")), T("}")] });
        }
        model(obj) {
            const T = this.token;
            const { click } = this;
            return ((0, jsx_runtime_1.jsxs)("span", { class: `${pretty.model} ${click != null ? "ref" : ""}`, onClick: () => click?.(obj), children: [obj.constructor.__qualified__, T("("), this.to_html(obj.id), T(")")] }));
        }
        property(obj) {
            const model = this.model(obj.obj);
            const attr = (0, jsx_runtime_1.jsx)("span", { class: pretty.attr, children: obj.attr });
            return (0, jsx_runtime_1.jsxs)("span", { children: [model, this.token("."), attr] });
        }
    }
    exports.ValuePrinter = ValuePrinter;
},
/* styles/pretty.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.nullish = "bk-nullish";
    exports.token = "bk-token";
    exports.boolean = "bk-boolean";
    exports.number = "bk-number";
    exports.string = "bk-string";
    exports.symbol = "bk-symbol";
    exports.model = "bk-model";
    exports.attr = "bk-attr";
    exports.array = "bk-array";
    exports.object = "bk-object";
    exports.iterable = "bk-iterable";
    exports.primitive = "bk-primitive";
    exports.type = "bk-type";
    exports.color = "bk-color";
    exports.swatch = "bk-swatch";
    exports.default = `.bk-nullish{color:#7724c1;}.bk-token{color:#881280;}.bk-boolean{color:#007500;}.bk-number{color:#1a1aa6;}.bk-string{color:#994500;}.bk-symbol{color:#c80000;}.bk-model{color:initial;}.bk-attr{color:#c80000;}.bk-array{color:initial;}.bk-object{color:initial;}.bk-iterable{color:initial;}.bk-primitive{color:#007500;}.bk-type{color:#1a1aa6;}.bk-color{display:flex;flex-direction:row;flex-wrap:nowrap;align-items:center;gap:0.25em;}.bk-color .bk-swatch{display:inline-block;width:1em;height:1em;border:1px solid black;}`;
},
/* styles/examiner.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = `:host{--common-padding:3px;--common-outline:#1a73e8 solid 1px;--panel-bg-color:#f1f3f4;--panel-border-color:var(--border-color);--muted-bg-color:#f1f3f4;--muted-color:#5f6368;--btn-size:16px;--btn-color:var(--shortcut-color);}.ref{cursor:pointer;}.monospace{font-family:var(--mono-font);}.hidden{display:none !important;}.col{display:flex;flex-direction:column;}.row{display:flex;flex-direction:row;}.toolbar{display:flex;flex-direction:row;gap:1em;background-color:var(--panel-bg-color);border-bottom:1px solid var(--panel-border-color);padding:var(--common-padding);}.checkbox{display:flex;flex-direction:row;align-items:center;gap:0.25em;}.filter:focus{outline:var(--common-outline);}.examiner{height:100%;display:flex;border:1px solid var(--panel-border-color);}.models-panel{display:flex;flex-direction:column;border-right:1px solid var(--panel-border-color);}.props-panel{display:flex;flex-direction:column;height:100%;overflow:auto;}.watches-panel{display:flex;flex-direction:column;border-bottom:1px solid var(--panel-border-color);}.models-list{display:flex;flex-direction:column;height:min-content;padding:var(--common-padding);overflow-x:hidden;overflow-y:auto;}.props-list{display:grid;grid-template-columns:min-content min-content 1fr 1fr;column-gap:1em;padding:var(--common-padding);}.watches-list{display:grid;grid-template-columns:1fr 1fr max-content;column-gap:1em;padding:var(--common-padding);}.nothing{grid-column:1 / span 3;font-style:italic;text-align:center;}.prop{display:contents;}.prop.closed{display:none;}.prop > *{opacity:0.6;}.prop.dirty > *{opacity:1;}.model-ref{display:flex;align-items:center;flex-direction:row;font-family:var(--mono-font);}.model-ref:focus-visible{outline:var(--common-outline);}.model-ref:hover{background-color:var(--hover-color);}.model-ref.active{background-color:var(--active-bg);}.tag{margin-left:1em;padding:0 4px;font-size:60%;border-width:1px;border-style:solid;border-radius:4px;color:var(--color);background-color:var(--surface-background-color);border-color:var(--border-color);}.expander{margin:0 2px;display:inline-block;vertical-align:middle;background-color:var(--muted-color);--open-image:url('data:image/svg+xml;utf8,\
    <svg xmlns="http://www.w3.org/2000/svg" width="6" height="6">\
      <path d="M 0 1 L 6 1 3 5 Z"/>\
    </svg>');--closed-image:url('data:image/svg+xml;utf8,\
    <svg xmlns="http://www.w3.org/2000/svg" width="6" height="6">\
      <path d="M 1 0 L 5 3 1 6 Z"/>\
    </svg>');}.expander{width:6px;height:6px;mask-image:var(--open-image);-webkit-mask-image:var(--open-image);}.branch{display:contents;}.branch.collapsed > .prop{display:none;}.branch.collapsed .expander{mask-image:var(--closed-image);-webkit-mask-image:var(--closed-image);}.base{grid-column:1 / span 4;color:var(--muted-color);cursor:pointer;}.prop-attr,.prop-conns,.prop-kind,.prop-value{display:flex;flex-direction:row;align-items:center;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;font-family:var(--mono-font);}.prop-attr > input[type="checkbox"]{visibility:hidden;margin-right:0.25em;}.prop-attr > input[type="checkbox"]:checked,.prop-attr:hover > input{visibility:visible;}.prop-attr:focus-visible{outline:var(--common-outline);}.prop-value{gap:0.5em;}.underline{text-decoration:underline;}.value.animated{animation-name:highlight;animation-duration:2s;animation-iteration-count:1;animation-timing-function:ease;}@keyframes highlight{0%{background-color:#def189;}100%{background-color:initial;}}.btn{width:var(--btn-size);height:var(--btn-size);cursor:pointer;background-color:var(--btn-color);}.btn:hover{background-color:red;}.btn-edit{background-color:var(--icon-color);mask-image:var(--bokeh-icon-pencil);-webkit-mask-image:var(--bokeh-icon-pencil);mask-size:100% 100%;-webkit-mask-size:100% 100%;mask-position:center center;-webkit-mask-position:center center;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat;}.btn-accept{background-color:var(--icon-color);mask-image:var(--bokeh-icon-check);-webkit-mask-image:var(--bokeh-icon-check);mask-size:100% 100%;-webkit-mask-size:100% 100%;mask-position:center center;-webkit-mask-position:center center;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat;}.btn-cancel{background-color:var(--icon-color);mask-image:var(--bokeh-icon-x);-webkit-mask-image:var(--bokeh-icon-x);mask-size:100% 100%;-webkit-mask-size:100% 100%;mask-position:center center;-webkit-mask-position:center center;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat;}.btn-delete{background-color:var(--icon-color);mask-image:var(--bokeh-icon-trash);-webkit-mask-image:var(--bokeh-icon-trash);mask-size:100% 100%;-webkit-mask-size:100% 100%;mask-position:center center;-webkit-mask-position:center center;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat;}.prop-value .btn-edit{visibility:hidden;}.prop-value:hover .btn-edit{visibility:visible;}.prop-value .btn-accept:hover{background-color:green;}`;
},
/* @preact/signals/dist/signals.module.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.useComputed = useComputed;
    exports.useSignal = useSignal;
    exports.useSignalEffect = useSignalEffect;
    const preact_1 = require(580) /* preact */;
    const hooks_1 = require(585) /* preact/hooks */;
    const signals_core_1 = require(586) /* @preact/signals-core */;
    var signals_core_2 = require(586) /* @preact/signals-core */;
    __esExport("Signal", signals_core_2.Signal);
    __esExport("batch", signals_core_2.batch);
    __esExport("computed", signals_core_2.computed);
    __esExport("effect", signals_core_2.effect);
    __esExport("signal", signals_core_2.signal);
    __esExport("untracked", signals_core_2.untracked);
    var h, l, p, m = "undefined" != typeof window && !!window.__PREACT_SIGNALS_DEVTOOLS__, w = [], _ = [];
    (0, signals_core_1.effect)(function () { h = this.N; })();
    function g(i, t) { preact_1.options[i] = t.bind(null, preact_1.options[i] || function () { }); }
    function y(i) {
        if (p)
            p();
        p = i && i.S();
    }
    function b(i) {
        var n = this, r = i.data, o = useSignal(r);
        o.value = r;
        var e = (0, hooks_1.useMemo)(function () {
            var i = n, r = n.__v;
            while (r = r.__)
                if (r.__c) {
                    r.__c.__$f |= 4;
                    break;
                }
            var f = (0, signals_core_1.computed)(function () { var i = o.value.value; return 0 === i ? 0 : !0 === i ? "" : i || ""; }), e = (0, signals_core_1.computed)(function () { return !Array.isArray(f.value) && !(0, preact_1.isValidElement)(f.value); }), u = (0, signals_core_1.effect)(function () {
                this.N = M;
                if (e.value) {
                    var n = f.value;
                    if (i.__v && i.__v.__e && 3 === i.__v.__e.nodeType)
                        i.__v.__e.data = n;
                }
            }), c = n.__$u.d;
            n.__$u.d = function () { u(); c.call(this); };
            return [e, f];
        }, []), u = e[0], c = e[1];
        return u.value ? c.peek() : c.value;
    }
    b.displayName = "ReactiveTextNode";
    Object.defineProperties(signals_core_1.Signal.prototype, { constructor: { configurable: !0, value: void 0 }, type: { configurable: !0, value: b }, props: { configurable: !0, get: function () { return { data: this }; } }, __b: { configurable: !0, value: 1 } });
    g("__b", function (i, n) {
        if (m && "function" == typeof n.type)
            window.__PREACT_SIGNALS_DEVTOOLS__.exitComponent();
        if ("string" == typeof n.type) {
            var t, r = n.props;
            for (var f in r)
                if ("children" !== f) {
                    var o = r[f];
                    if (o instanceof signals_core_1.Signal) {
                        if (!t)
                            n.__np = t = {};
                        t[f] = o;
                        r[f] = o.peek();
                    }
                }
        }
        i(n);
    });
    g("__r", function (i, n) {
        if (m && "function" == typeof n.type)
            window.__PREACT_SIGNALS_DEVTOOLS__.enterComponent(n);
        if (n.type !== preact_1.Fragment) {
            y();
            var t, f = n.__c;
            if (f) {
                f.__$f &= -2;
                if (void 0 === (t = f.__$u))
                    f.__$u = t = function (i) { var n; (0, signals_core_1.effect)(function () { n = this; }); n.c = function () { f.__$f |= 1; f.setState({}); }; return n; }();
            }
            l = f;
            y(t);
        }
        i(n);
    });
    g("__e", function (i, n, t, r) {
        if (m)
            window.__PREACT_SIGNALS_DEVTOOLS__.exitComponent();
        y();
        l = void 0;
        i(n, t, r);
    });
    g("diffed", function (i, n) {
        if (m && "function" == typeof n.type)
            window.__PREACT_SIGNALS_DEVTOOLS__.exitComponent();
        y();
        l = void 0;
        var t;
        if ("string" == typeof n.type && (t = n.__e)) {
            var r = n.__np, f = n.props;
            if (r) {
                var o = t.U;
                if (o)
                    for (var e in o) {
                        var u = o[e];
                        if (void 0 !== u && !(e in r)) {
                            u.d();
                            o[e] = void 0;
                        }
                    }
                else {
                    o = {};
                    t.U = o;
                }
                for (var a in r) {
                    var c = o[a], v = r[a];
                    if (void 0 === c) {
                        c = k(t, a, v, f);
                        o[a] = c;
                    }
                    else
                        c.o(v, f);
                }
            }
        }
        i(n);
    });
    function k(i, n, t, r) {
        var f = n in i && void 0 === i.ownerSVGElement, o = (0, signals_core_1.signal)(t);
        return { o: function (i, n) { o.value = i; r = n; }, d: (0, signals_core_1.effect)(function () {
                this.N = M;
                var t = o.value.value;
                if (r[n] !== t) {
                    r[n] = t;
                    if (f)
                        i[n] = t;
                    else if (null != t && (!1 !== t || "-" === n[4]))
                        i.setAttribute(n, t);
                    else
                        i.removeAttribute(n);
                }
            }) };
    }
    g("unmount", function (i, n) {
        if ("string" == typeof n.type) {
            var t = n.__e;
            if (t) {
                var r = t.U;
                if (r) {
                    t.U = void 0;
                    for (var f in r) {
                        var o = r[f];
                        if (o)
                            o.d();
                    }
                }
            }
        }
        else {
            var e = n.__c;
            if (e) {
                var u = e.__$u;
                if (u) {
                    e.__$u = void 0;
                    u.d();
                }
            }
        }
        i(n);
    });
    g("__h", function (i, n, t, r) {
        if (r < 3 || 9 === r)
            n.__$f |= 2;
        i(n, t, r);
    });
    preact_1.Component.prototype.shouldComponentUpdate = function (i, n) {
        var t = this.__$u, r = t && void 0 !== t.s;
        for (var f in n)
            return !0;
        if (this.__f || "boolean" == typeof this.u && !0 === this.u) {
            var o = 2 & this.__$f;
            if (!(r || o || 4 & this.__$f))
                return !0;
            if (1 & this.__$f)
                return !0;
        }
        else {
            if (!(r || 4 & this.__$f))
                return !0;
            if (3 & this.__$f)
                return !0;
        }
        for (var e in i)
            if ("__source" !== e && i[e] !== this.props[e])
                return !0;
        for (var u in this.props)
            if (!(u in i))
                return !0;
        return !1;
    };
    function useSignal(i, n) { return (0, hooks_1.useState)(function () { return (0, signals_core_1.signal)(i, n); })[0]; }
    function useComputed(i, n) { var t = (0, hooks_1.useRef)(i); t.current = i; l.__$f |= 4; return (0, hooks_1.useMemo)(function () { return (0, signals_core_1.computed)(function () { return t.current(); }, n); }, []); }
    var q = "undefined" == typeof requestAnimationFrame ? setTimeout : function (i) { var n = function () { clearTimeout(t); cancelAnimationFrame(r); i(); }, t = setTimeout(n, 35), r = requestAnimationFrame(n); }, A = function (i) { queueMicrotask(function () { queueMicrotask(i); }); };
    function T() {
        (0, signals_core_1.batch)(function () {
            var i;
            while (i = w.shift())
                h.call(i);
        });
    }
    function x() {
        if (1 === w.push(this))
            (preact_1.options.requestAnimationFrame || q)(T);
    }
    function F() {
        (0, signals_core_1.batch)(function () {
            var i;
            while (i = _.shift())
                h.call(i);
        });
    }
    function M() {
        if (1 === _.push(this))
            (preact_1.options.requestAnimationFrame || A)(F);
    }
    function useSignalEffect(i, n) { var t = (0, hooks_1.useRef)(i); t.current = i; (0, hooks_1.useEffect)(function () { return (0, signals_core_1.effect)(function () { this.N = x; return t.current(); }, n); }, []); }
},
/* preact/hooks/dist/hooks.module.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.useCallback = q;
    exports.useContext = x;
    exports.useDebugValue = P;
    exports.useEffect = y;
    exports.useErrorBoundary = b;
    exports.useId = g;
    exports.useImperativeHandle = F;
    exports.useLayoutEffect = _;
    exports.useMemo = T;
    exports.useReducer = h;
    exports.useRef = A;
    exports.useState = d;
    const preact_1 = require(580) /* preact */;
    var t, r, u, i, o = 0, f = [], c = preact_1.options, e = c.__b, a = c.__r, v = c.diffed, l = c.__c, m = c.unmount, s = c.__;
    function p(n, t) { c.__h && c.__h(r, n, o || t), o = 0; var u = r.__H || (r.__H = { __: [], __h: [] }); return n >= u.__.length && u.__.push({}), u.__[n]; }
    function d(n) { return o = 1, h(D, n); }
    function h(n, u, i) {
        var o = p(t++, 2);
        if (o.t = n, !o.__c && (o.__ = [i ? i(u) : D(void 0, u), function (n) { var t = o.__N ? o.__N[0] : o.__[0], r = o.t(t, n); t !== r && (o.__N = [r, o.__[1]], o.__c.setState({})); }], o.__c = r, !r.__f)) {
            var f = function (n, t, r) {
                if (!o.__c.__H)
                    return !0;
                var u = o.__c.__H.__.filter(function (n) { return !!n.__c; });
                if (u.every(function (n) { return !n.__N; }))
                    return !c || c.call(this, n, t, r);
                var i = o.__c.props !== n;
                return u.forEach(function (n) {
                    if (n.__N) {
                        var t = n.__[0];
                        n.__ = n.__N, n.__N = void 0, t !== n.__[0] && (i = !0);
                    }
                }), c && c.call(this, n, t, r) || i;
            };
            r.__f = !0;
            var c = r.shouldComponentUpdate, e = r.componentWillUpdate;
            r.componentWillUpdate = function (n, t, r) {
                if (this.__e) {
                    var u = c;
                    c = void 0, f(n, t, r), c = u;
                }
                e && e.call(this, n, t, r);
            }, r.shouldComponentUpdate = f;
        }
        return o.__N || o.__;
    }
    function y(n, u) { var i = p(t++, 3); !c.__s && C(i.__H, u) && (i.__ = n, i.u = u, r.__H.__h.push(i)); }
    function _(n, u) { var i = p(t++, 4); !c.__s && C(i.__H, u) && (i.__ = n, i.u = u, r.__h.push(i)); }
    function A(n) { return o = 5, T(function () { return { current: n }; }, []); }
    function F(n, t, r) {
        o = 6, _(function () {
            if ("function" == typeof n) {
                var r = n(t());
                return function () { n(null), r && "function" == typeof r && r(); };
            }
            if (n)
                return n.current = t(), function () { return n.current = null; };
        }, null == r ? r : r.concat(n));
    }
    function T(n, r) { var u = p(t++, 7); return C(u.__H, r) && (u.__ = n(), u.__H = r, u.__h = n), u.__; }
    function q(n, t) { return o = 8, T(function () { return n; }, t); }
    function x(n) { var u = r.context[n.__c], i = p(t++, 9); return i.c = n, u ? (null == i.__ && (i.__ = !0, u.sub(r)), u.props.value) : n.__; }
    function P(n, t) { c.useDebugValue && c.useDebugValue(t ? t(n) : n); }
    function b(n) { var u = p(t++, 10), i = d(); return u.__ = n, r.componentDidCatch || (r.componentDidCatch = function (n, t) { u.__ && u.__(n, t), i[1](n); }), [i[0], function () { i[1](void 0); }]; }
    function g() {
        var n = p(t++, 11);
        if (!n.__) {
            for (var u = r.__v; null !== u && !u.__m && null !== u.__;)
                u = u.__;
            var i = u.__m || (u.__m = [0, 0]);
            n.__ = "P" + i[0] + "-" + i[1]++;
        }
        return n.__;
    }
    function j() {
        for (var n; n = f.shift();)
            if (n.__P && n.__H)
                try {
                    n.__H.__h.forEach(z), n.__H.__h.forEach(B), n.__H.__h = [];
                }
                catch (t) {
                    n.__H.__h = [], c.__e(t, n.__v);
                }
    }
    c.__b = function (n) { r = null, e && e(n); }, c.__ = function (n, t) { n && t.__k && t.__k.__m && (n.__m = t.__k.__m), s && s(n, t); }, c.__r = function (n) { a && a(n), t = 0; var i = (r = n.__c).__H; i && (u === r ? (i.__h = [], r.__h = [], i.__.forEach(function (n) { n.__N && (n.__ = n.__N), n.u = n.__N = void 0; })) : (i.__h.forEach(z), i.__h.forEach(B), i.__h = [], t = 0)), u = r; }, c.diffed = function (n) { v && v(n); var t = n.__c; t && t.__H && (t.__H.__h.length && (1 !== f.push(t) && i === c.requestAnimationFrame || ((i = c.requestAnimationFrame) || w)(j)), t.__H.__.forEach(function (n) { n.u && (n.__H = n.u), n.u = void 0; })), u = r = null; }, c.__c = function (n, t) {
        t.some(function (n) {
            try {
                n.__h.forEach(z), n.__h = n.__h.filter(function (n) { return !n.__ || B(n); });
            }
            catch (r) {
                t.some(function (n) { n.__h && (n.__h = []); }), t = [], c.__e(r, n.__v);
            }
        }), l && l(n, t);
    }, c.unmount = function (n) {
        m && m(n);
        var t, r = n.__c;
        r && r.__H && (r.__H.__.forEach(function (n) {
            try {
                z(n);
            }
            catch (n) {
                t = n;
            }
        }), r.__H = void 0, t && c.__e(t, r.__v));
    };
    var k = "function" == typeof requestAnimationFrame;
    function w(n) { var t, r = function () { clearTimeout(u), k && cancelAnimationFrame(t), setTimeout(n); }, u = setTimeout(r, 35); k && (t = requestAnimationFrame(r)); }
    function z(n) { var t = r, u = n.__c; "function" == typeof u && (n.__c = void 0, u()), r = t; }
    function B(n) { var t = r; n.__c = n.__(), r = t; }
    function C(n, t) { return !n || n.length !== t.length || t.some(function (t, r) { return t !== n[r]; }); }
    function D(n, t) { return "function" == typeof t ? t(n) : t; }
},
/* @preact/signals-core/dist/signals-core.module.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.Computed = y;
    exports.Effect = p;
    exports.Signal = u;
    exports.batch = r;
    exports.computed = w;
    exports.effect = E;
    exports.signal = d;
    exports.untracked = n;
    var i = Symbol.for("preact-signals");
    function t() {
        if (!(s > 1)) {
            var i, t = !1;
            while (void 0 !== h) {
                var r = h;
                h = void 0;
                f++;
                while (void 0 !== r) {
                    var o = r.o;
                    r.o = void 0;
                    r.f &= -3;
                    if (!(8 & r.f) && c(r))
                        try {
                            r.c();
                        }
                        catch (r) {
                            if (!t) {
                                i = r;
                                t = !0;
                            }
                        }
                    r = o;
                }
            }
            f = 0;
            s--;
            if (t)
                throw i;
        }
        else
            s--;
    }
    function r(i) {
        if (s > 0)
            return i();
        s++;
        try {
            return i();
        }
        finally {
            t();
        }
    }
    var o = void 0;
    function n(i) {
        var t = o;
        o = void 0;
        try {
            return i();
        }
        finally {
            o = t;
        }
    }
    var h = void 0, s = 0, f = 0, v = 0;
    function e(i) {
        if (void 0 !== o) {
            var t = i.n;
            if (void 0 === t || t.t !== o) {
                t = { i: 0, S: i, p: o.s, n: void 0, t: o, e: void 0, x: void 0, r: t };
                if (void 0 !== o.s)
                    o.s.n = t;
                o.s = t;
                i.n = t;
                if (32 & o.f)
                    i.S(t);
                return t;
            }
            else if (-1 === t.i) {
                t.i = 0;
                if (void 0 !== t.n) {
                    t.n.p = t.p;
                    if (void 0 !== t.p)
                        t.p.n = t.n;
                    t.p = o.s;
                    t.n = void 0;
                    o.s.n = t;
                    o.s = t;
                }
                return t;
            }
        }
    }
    function u(i, t) { this.v = i; this.i = 0; this.n = void 0; this.t = void 0; this.W = null == t ? void 0 : t.watched; this.Z = null == t ? void 0 : t.unwatched; this.name = null == t ? void 0 : t.name; }
    u.prototype.brand = i;
    u.prototype.h = function () { return !0; };
    u.prototype.S = function (i) {
        var t = this, r = this.t;
        if (r !== i && void 0 === i.e) {
            i.x = r;
            this.t = i;
            if (void 0 !== r)
                r.e = i;
            else
                n(function () { var i; null == (i = t.W) || i.call(t); });
        }
    };
    u.prototype.U = function (i) {
        var t = this;
        if (void 0 !== this.t) {
            var r = i.e, o = i.x;
            if (void 0 !== r) {
                r.x = o;
                i.e = void 0;
            }
            if (void 0 !== o) {
                o.e = r;
                i.x = void 0;
            }
            if (i === this.t) {
                this.t = o;
                if (void 0 === o)
                    n(function () { var i; null == (i = t.Z) || i.call(t); });
            }
        }
    };
    u.prototype.subscribe = function (i) {
        var t = this;
        return E(function () {
            var r = t.value, n = o;
            o = void 0;
            try {
                i(r);
            }
            finally {
                o = n;
            }
        }, { name: "sub" });
    };
    u.prototype.valueOf = function () { return this.value; };
    u.prototype.toString = function () { return this.value + ""; };
    u.prototype.toJSON = function () { return this.value; };
    u.prototype.peek = function () {
        var i = o;
        o = void 0;
        try {
            return this.value;
        }
        finally {
            o = i;
        }
    };
    Object.defineProperty(u.prototype, "value", { get: function () {
            var i = e(this);
            if (void 0 !== i)
                i.i = this.i;
            return this.v;
        }, set: function (i) {
            if (i !== this.v) {
                if (f > 100)
                    throw new Error("Cycle detected");
                this.v = i;
                this.i++;
                v++;
                s++;
                try {
                    for (var r = this.t; void 0 !== r; r = r.x)
                        r.t.N();
                }
                finally {
                    t();
                }
            }
        } });
    function d(i, t) { return new u(i, t); }
    function c(i) {
        for (var t = i.s; void 0 !== t; t = t.n)
            if (t.S.i !== t.i || !t.S.h() || t.S.i !== t.i)
                return !0;
        return !1;
    }
    function a(i) {
        for (var t = i.s; void 0 !== t; t = t.n) {
            var r = t.S.n;
            if (void 0 !== r)
                t.r = r;
            t.S.n = t;
            t.i = -1;
            if (void 0 === t.n) {
                i.s = t;
                break;
            }
        }
    }
    function l(i) {
        var t = i.s, r = void 0;
        while (void 0 !== t) {
            var o = t.p;
            if (-1 === t.i) {
                t.S.U(t);
                if (void 0 !== o)
                    o.n = t.n;
                if (void 0 !== t.n)
                    t.n.p = o;
            }
            else
                r = t;
            t.S.n = t.r;
            if (void 0 !== t.r)
                t.r = void 0;
            t = o;
        }
        i.s = r;
    }
    function y(i, t) { u.call(this, void 0); this.x = i; this.s = void 0; this.g = v - 1; this.f = 4; this.W = null == t ? void 0 : t.watched; this.Z = null == t ? void 0 : t.unwatched; this.name = null == t ? void 0 : t.name; }
    y.prototype = new u;
    y.prototype.h = function () {
        this.f &= -3;
        if (1 & this.f)
            return !1;
        if (32 == (36 & this.f))
            return !0;
        this.f &= -5;
        if (this.g === v)
            return !0;
        this.g = v;
        this.f |= 1;
        if (this.i > 0 && !c(this)) {
            this.f &= -2;
            return !0;
        }
        var i = o;
        try {
            a(this);
            o = this;
            var t = this.x();
            if (16 & this.f || this.v !== t || 0 === this.i) {
                this.v = t;
                this.f &= -17;
                this.i++;
            }
        }
        catch (i) {
            this.v = i;
            this.f |= 16;
            this.i++;
        }
        o = i;
        l(this);
        this.f &= -2;
        return !0;
    };
    y.prototype.S = function (i) {
        if (void 0 === this.t) {
            this.f |= 36;
            for (var t = this.s; void 0 !== t; t = t.n)
                t.S.S(t);
        }
        u.prototype.S.call(this, i);
    };
    y.prototype.U = function (i) {
        if (void 0 !== this.t) {
            u.prototype.U.call(this, i);
            if (void 0 === this.t) {
                this.f &= -33;
                for (var t = this.s; void 0 !== t; t = t.n)
                    t.S.U(t);
            }
        }
    };
    y.prototype.N = function () {
        if (!(2 & this.f)) {
            this.f |= 6;
            for (var i = this.t; void 0 !== i; i = i.x)
                i.t.N();
        }
    };
    Object.defineProperty(y.prototype, "value", { get: function () {
            if (1 & this.f)
                throw new Error("Cycle detected");
            var i = e(this);
            this.h();
            if (void 0 !== i)
                i.i = this.i;
            if (16 & this.f)
                throw this.v;
            return this.v;
        } });
    function w(i, t) { return new y(i, t); }
    function _(i) {
        var r = i.u;
        i.u = void 0;
        if ("function" == typeof r) {
            s++;
            var n = o;
            o = void 0;
            try {
                r();
            }
            catch (t) {
                i.f &= -2;
                i.f |= 8;
                b(i);
                throw t;
            }
            finally {
                o = n;
                t();
            }
        }
    }
    function b(i) {
        for (var t = i.s; void 0 !== t; t = t.n)
            t.S.U(t);
        i.x = void 0;
        i.s = void 0;
        _(i);
    }
    function g(i) {
        if (o !== this)
            throw new Error("Out-of-order effect");
        l(this);
        o = i;
        this.f &= -2;
        if (8 & this.f)
            b(this);
        t();
    }
    function p(i, t) { this.x = i; this.u = void 0; this.s = void 0; this.o = void 0; this.f = 32; this.name = null == t ? void 0 : t.name; }
    p.prototype.c = function () {
        var i = this.S();
        try {
            if (8 & this.f)
                return;
            if (void 0 === this.x)
                return;
            var t = this.x();
            if ("function" == typeof t)
                this.u = t;
        }
        finally {
            i();
        }
    };
    p.prototype.S = function () {
        if (1 & this.f)
            throw new Error("Cycle detected");
        this.f |= 1;
        this.f &= -9;
        _(this);
        a(this);
        s++;
        var i = o;
        o = this;
        return g.bind(this, i);
    };
    p.prototype.N = function () {
        if (!(2 & this.f)) {
            this.f |= 2;
            this.o = h;
            h = this;
        }
    };
    p.prototype.d = function () {
        this.f |= 8;
        if (!(1 & this.f))
            b(this);
    };
    p.prototype.dispose = function () { this.d(); };
    function E(i, t) {
        var r = new p(i, t);
        try {
            r.c();
        }
        catch (i) {
            r.d();
            throw i;
        }
        var o = r.d.bind(r);
        o[Symbol.dispose] = o;
        return o;
    }
},
/* models/tools/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(588) /* ./actions */, exports);
    tslib_1.__exportStar(require(604) /* ./edit */, exports);
    tslib_1.__exportStar(require(614) /* ./gestures */, exports);
    tslib_1.__exportStar(require(626) /* ./inspectors */, exports);
    var tool_1 = require(379) /* ./tool */;
    __esExport("Tool", tool_1.Tool);
    var tool_proxy_1 = require(383) /* ./tool_proxy */;
    __esExport("ToolProxy", tool_proxy_1.ToolProxy);
    var tool_menu_1 = require(403) /* ./tool_menu */;
    __esExport("ToolMenu", tool_menu_1.ToolMenu);
    var toolbar_1 = require(378) /* ./toolbar */;
    __esExport("Toolbar", toolbar_1.Toolbar);
    var tool_button_1 = require(385) /* ./tool_button */;
    __esExport("ToolButton", tool_button_1.ToolButton);
    var on_off_button_1 = require(391) /* ./on_off_button */;
    __esExport("OnOffButton", on_off_button_1.OnOffButton);
    var click_button_1 = require(394) /* ./click_button */;
    __esExport("ClickButton", click_button_1.ClickButton);
},
/* models/tools/actions/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var action_tool_1 = require(393) /* ./action_tool */;
    __esExport("ActionTool", action_tool_1.ActionTool);
    var copy_tool_1 = require(589) /* ./copy_tool */;
    __esExport("CopyTool", copy_tool_1.CopyTool);
    var custom_action_1 = require(590) /* ./custom_action */;
    __esExport("CustomAction", custom_action_1.CustomAction);
    var fullscreen_tool_1 = require(591) /* ./fullscreen_tool */;
    __esExport("FullscreenTool", fullscreen_tool_1.FullscreenTool);
    var help_tool_1 = require(395) /* ./help_tool */;
    __esExport("HelpTool", help_tool_1.HelpTool);
    var examine_tool_1 = require(592) /* ./examine_tool */;
    __esExport("ExamineTool", examine_tool_1.ExamineTool);
    var click_pan_tool_1 = require(593) /* ./click_pan_tool */;
    __esExport("ClickPanTool", click_pan_tool_1.ClickPanTool);
    var redo_tool_1 = require(596) /* ./redo_tool */;
    __esExport("RedoTool", redo_tool_1.RedoTool);
    var reset_tool_1 = require(597) /* ./reset_tool */;
    __esExport("ResetTool", reset_tool_1.ResetTool);
    var save_tool_1 = require(598) /* ./save_tool */;
    __esExport("SaveTool", save_tool_1.SaveTool);
    var undo_tool_1 = require(599) /* ./undo_tool */;
    __esExport("UndoTool", undo_tool_1.UndoTool);
    var zoom_in_tool_1 = require(600) /* ./zoom_in_tool */;
    __esExport("ZoomInTool", zoom_in_tool_1.ZoomInTool);
    var zoom_out_tool_1 = require(603) /* ./zoom_out_tool */;
    __esExport("ZoomOutTool", zoom_out_tool_1.ZoomOutTool);
},
/* models/tools/actions/copy_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const action_tool_1 = require(393) /* ./action_tool */;
    const icons_css_1 = require(76) /* ../../../styles/icons.css */;
    class CopyToolView extends action_tool_1.ActionToolView {
        async copy() {
            const blob = await this.parent.export().to_blob();
            const item = new ClipboardItem({ [blob.type]: blob });
            await navigator.clipboard.write([item]);
        }
        doit() {
            void this.copy();
        }
    }
    exports.CopyToolView = CopyToolView;
    class CopyTool extends action_tool_1.ActionTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = CopyToolView;
            this.register_alias("copy", () => new CopyTool());
        }
        tool_name = "Copy";
        tool_icon = icons_css_1.tool_icon_copy;
    }
    exports.CopyTool = CopyTool;
},
/* models/tools/actions/custom_action.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const action_tool_1 = require(393) /* ./action_tool */;
    const customjs_1 = require(423) /* ../../callbacks/customjs */;
    const callbacks_1 = require(51) /* ../../../core/util/callbacks */;
    const types_1 = require(8) /* ../../../core/util/types */;
    const icons = tslib_1.__importStar(require(76) /* ../../../styles/icons.css */);
    const logging_1 = require(11) /* ../../../core/logging */;
    class CustomActionView extends action_tool_1.ActionToolView {
        async _update_active() {
            const { active_callback } = this.model;
            if (active_callback == "auto") {
                this.model.active = !this.model.active;
            }
            else if (active_callback != null) {
                const active = await (0, callbacks_1.execute)(active_callback, this.model);
                if ((0, types_1.isBoolean)(active)) {
                    this.model.active = active;
                }
                else {
                    logging_1.logger.warn(`${this.model}.active_callback (${active_callback}) must return a boolean value, got ${typeof active}`);
                }
            }
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const { active_callback } = this.model;
            if (!(active_callback == "auto" || active_callback == null)) {
                await this._update_active();
            }
        }
        async _execute() {
            const { callback, active_callback } = this.model;
            if (callback != null) {
                const result = await (0, callbacks_1.execute)(callback, this.model);
                if (active_callback != null) {
                    await this._update_active();
                }
                else if ((0, types_1.isBoolean)(result)) {
                    this.model.active = result;
                }
                else if (result !== undefined) {
                    logging_1.logger.warn(`${this.model}.callback (${callback}) must return a boolean value or void, got ${typeof result}`);
                }
            }
        }
        doit() {
            this._await_ready(this._execute());
        }
    }
    exports.CustomActionView = CustomActionView;
    class CustomAction extends action_tool_1.ActionTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = CustomActionView;
            this.define(({ Func, Nullable, Ref, Or, Auto }) => ({
                callback: [Nullable(Or(Ref(customjs_1.CustomJS), Func())), null],
                active_callback: [Nullable(Or(Ref(customjs_1.CustomJS), Func(), Auto)), null],
            }));
            this.override({
                description: "Perform a Custom Action",
            });
            // `active` and `disabled` are defined in `Tool` model as internal properties
            this.override_options({
                active: { internal: false },
                disabled: { internal: false },
            });
        }
        tool_name = "Custom Action";
        tool_icon = icons.tool_icon_unknown;
    }
    exports.CustomAction = CustomAction;
},
/* models/tools/actions/fullscreen_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const action_tool_1 = require(393) /* ./action_tool */;
    const icons = tslib_1.__importStar(require(76) /* ../../../styles/icons.css */);
    const request_fullscreen = (() => {
        if (typeof Element.prototype.webkitRequestFullscreen !== "undefined") {
            return (el, options) => el.webkitRequestFullscreen(options);
        }
        else {
            return (el, options) => el.requestFullscreen(options);
        }
    })();
    class FullscreenToolView extends action_tool_1.ActionToolView {
        initialize() {
            super.initialize();
            const handler = () => {
                const active = document.fullscreenElement == this.parent.el;
                this.model.active = active;
            };
            document.addEventListener("fullscreenchange", handler, { signal: this.abort_signal });
            document.addEventListener("webkitfullscreenchange", handler, { signal: this.abort_signal });
        }
        async fullscreen() {
            if (document.fullscreenElement != null) {
                await document.exitFullscreen();
            }
            else {
                await request_fullscreen(this.parent.el);
            }
        }
        doit() {
            void this.fullscreen();
        }
    }
    exports.FullscreenToolView = FullscreenToolView;
    class FullscreenTool extends action_tool_1.ActionTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = FullscreenToolView;
            this.register_alias("fullscreen", () => new FullscreenTool());
        }
        tool_name = "Fullscreen";
        tool_icon = icons.tool_icon_fullscreen;
    }
    exports.FullscreenTool = FullscreenTool;
},
/* models/tools/actions/examine_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const action_tool_1 = require(393) /* ./action_tool */;
    const icons = tslib_1.__importStar(require(76) /* ../../../styles/icons.css */);
    const dialog_1 = require(428) /* ../../ui/dialog */;
    const examiner_1 = require(578) /* ../../ui/examiner */;
    const printers_1 = require(581) /* ../../ui/printers */;
    const html_1 = require(133) /* ../../dom/html */;
    const build_views_1 = require(69) /* ../../../core/build_views */;
    const dom_1 = require(61) /* ../../../core/dom */;
    const pretty_css_1 = tslib_1.__importDefault(require(582) /* ../../../styles/pretty.css */);
    const preact_1 = require(580) /* preact */;
    class ExamineToolView extends action_tool_1.ActionToolView {
        dialog;
        children_views() {
            return [...super.children_views(), this.dialog];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const target = this.parent.model;
            const printer = new printers_1.ValuePrinter();
            const title_el = (0, dom_1.div)();
            (0, preact_1.render)(printer.to_html(target), title_el);
            // NOTE because preact prepends during render
            // TODO add support for VNode to HTML model
            title_el.prepend("Examine ");
            const dialog = new dialog_1.Dialog({
                stylesheets: [pretty_css_1.default],
                title: new html_1.HTML({ html: title_el }),
                content: new examiner_1.Examiner({ target, stylesheets: [":host { width: 100%; height: 100%; }"] }),
                visible: false,
                close_action: "hide",
            });
            this.dialog = await (0, build_views_1.build_view)(dialog, { parent: this.parent });
        }
        connect_signals() {
            super.connect_signals();
            this.dialog.displayed.connect((visible) => this.model.active = visible);
        }
        doit() {
            this.dialog.toggle();
        }
    }
    exports.ExamineToolView = ExamineToolView;
    class ExamineTool extends action_tool_1.ActionTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ExamineToolView;
            this.register_alias("examine", () => new ExamineTool());
        }
        tool_name = "Examine";
        tool_icon = icons.tool_icon_settings; // TODO: better icon
    }
    exports.ExamineTool = ExamineTool;
},
/* models/tools/actions/click_pan_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const plot_action_tool_1 = require(594) /* ./plot_action_tool */;
    const pan_tool_1 = require(595) /* ../gestures/pan_tool */;
    const kinds_1 = require(22) /* ../../../core/kinds */;
    const enums_1 = require(21) /* ../../../core/enums */;
    const icons = tslib_1.__importStar(require(76) /* ../../../styles/icons.css */);
    class ClickPanToolView extends plot_action_tool_1.PlotActionToolView {
        doit() {
            const direction = (() => {
                switch (this.model.direction) {
                    case "left":
                    case "west":
                        return { x: -1, y: 0 };
                    case "right":
                    case "east":
                        return { x: +1, y: 0 };
                    case "up":
                    case "north":
                        return { x: 0, y: -1 };
                    case "down":
                    case "south":
                        return { x: 0, y: +1 };
                }
            })();
            const { frame } = this.plot_view;
            const { factor } = this.model;
            const x_offset = direction.x * factor * frame.bbox.width;
            const y_offset = direction.y * factor * frame.bbox.height;
            const bbox = frame.bbox.translate(x_offset, y_offset);
            const xrs = (0, pan_tool_1.update_ranges)(frame.x_scales, bbox.x0, bbox.x1);
            const yrs = (0, pan_tool_1.update_ranges)(frame.y_scales, bbox.y0, bbox.y1);
            this.plot_view.update_range({ xrs, yrs }, { panning: true });
        }
    }
    exports.ClickPanToolView = ClickPanToolView;
    class ClickPanTool extends plot_action_tool_1.PlotActionTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ClickPanToolView;
            this.define(() => ({
                direction: [enums_1.PanDirection],
                factor: [kinds_1.Float, 0.1],
            }));
            this.register_alias("pan_left", () => new ClickPanTool({ direction: "left" }));
            this.register_alias("pan_right", () => new ClickPanTool({ direction: "right" }));
            this.register_alias("pan_up", () => new ClickPanTool({ direction: "up" }));
            this.register_alias("pan_down", () => new ClickPanTool({ direction: "down" }));
            this.register_alias("pan_west", () => new ClickPanTool({ direction: "west" }));
            this.register_alias("pan_east", () => new ClickPanTool({ direction: "east" }));
            this.register_alias("pan_north", () => new ClickPanTool({ direction: "north" }));
            this.register_alias("pan_south", () => new ClickPanTool({ direction: "south" }));
        }
        tool_name = "Click Pan";
        get tooltip() {
            return `Pan ${this.direction}`;
        }
        get computed_icon() {
            const icon = super.computed_icon;
            if (icon != null) {
                return icon;
            }
            else {
                switch (this.direction) {
                    case "left":
                    case "west":
                        return `.${icons.tool_icon_pan_left}`;
                    case "right":
                    case "east":
                        return `.${icons.tool_icon_pan_right}`;
                    case "up":
                    case "north":
                        return `.${icons.tool_icon_pan_up}`;
                    case "down":
                    case "south":
                        return `.${icons.tool_icon_pan_down}`;
                }
            }
        }
    }
    exports.ClickPanTool = ClickPanTool;
},
/* models/tools/actions/plot_action_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const action_tool_1 = require(393) /* ./action_tool */;
    class PlotActionToolView extends action_tool_1.ActionToolView {
        get plot_view() {
            return this.parent;
        }
    }
    exports.PlotActionToolView = PlotActionToolView;
    class PlotActionTool extends action_tool_1.ActionTool {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.PlotActionTool = PlotActionTool;
},
/* models/tools/gestures/pan_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.update_ranges = update_ranges;
    const tslib_1 = require(1) /* tslib */;
    const gesture_tool_1 = require(390) /* ./gesture_tool */;
    const menus_1 = require(380) /* ../../ui/menus */;
    const assert_1 = require(13) /* ../../../core/util/assert */;
    const enums_1 = require(21) /* ../../../core/enums */;
    const icons = tslib_1.__importStar(require(76) /* ../../../styles/icons.css */);
    function update_ranges(scales, p0, p1) {
        const r = new Map();
        for (const [, scale] of scales) {
            const [start, end] = scale.r_invert(p0, p1);
            r.set(scale.source_range, { start, end });
        }
        return r;
    }
    class PanToolView extends gesture_tool_1.GestureToolView {
        pan_info;
        state = null;
        cursor(sx, sy) {
            if (this.state != null) {
                const { dims } = this.state;
                switch (dims == "both" ? this.model.dimensions : dims) {
                    case "both": return "move";
                    case "width": return "ew-resize";
                    case "height": return "ns-resize";
                }
            }
            return super.cursor(sx, sy);
        }
        _interactive_dims({ sx, sy }) {
            const { dimensions } = this.model;
            const { plot_view } = this;
            const axis_view = plot_view.axis_views.find((view) => view.bbox.contains(sx, sy));
            if (axis_view != null) {
                switch (axis_view.dimension) {
                    case 0: {
                        if (dimensions == "width" || dimensions == "both") {
                            return "width";
                        }
                        break;
                    }
                    case 1: {
                        if (dimensions == "height" || dimensions == "both") {
                            return "height";
                        }
                        break;
                    }
                }
            }
            else if (plot_view.frame.bbox.contains(sx, sy)) {
                return "both";
            }
            return null;
        }
        _pan_start(ev) {
            (0, assert_1.assert)(this.state == null);
            const { sx, sy } = ev;
            const dims = this._interactive_dims({ sx, sy });
            if (dims != null) {
                this.state = { last_dx: 0, last_dy: 0, dims };
                this.model.document?.interactive_start(this.plot_view.model);
            }
        }
        _pan(ev) {
            if (this.state != null) {
                this._update(ev.dx, ev.dy);
                this.model.document?.interactive_start(this.plot_view.model);
            }
        }
        _pan_end(_e) {
            if (this.state != null) {
                this.state = null;
                if (this.pan_info != null) {
                    this.plot_view.state.push("pan", { range: this.pan_info });
                }
                this.plot_view.trigger_ranges_update_event();
            }
        }
        _update(dx, dy) {
            const { state } = this;
            (0, assert_1.assert)(state != null);
            const frame = this.plot_view.frame;
            const new_dx = dx - state.last_dx;
            const new_dy = dy - state.last_dy;
            const hr = frame.bbox.h_range;
            const sx_low = hr.start - new_dx;
            const sx_high = hr.end - new_dx;
            const vr = frame.bbox.v_range;
            const sy_low = vr.start - new_dy;
            const sy_high = vr.end - new_dy;
            const dims = this.model.dimensions;
            const { x_scales, y_scales } = frame;
            const x_axis_only = state.dims == "width";
            const y_axis_only = state.dims == "height";
            // Here we are a bit careful to only update the range info for dimensions that
            // are "in play". This is to avoid superfluous noise updates to dataranges that
            // would cause windowed auto-ranging to turn off.
            let sdx;
            let xrs;
            if ((dims == "width" || dims == "both") && !y_axis_only) {
                sdx = -new_dx;
                xrs = update_ranges(x_scales, sx_low, sx_high);
            }
            else {
                sdx = 0;
                xrs = new Map();
            }
            let sdy;
            let yrs;
            if ((dims == "height" || dims == "both") && !x_axis_only) {
                sdy = -new_dy;
                yrs = update_ranges(y_scales, sy_low, sy_high);
            }
            else {
                sdy = 0;
                yrs = new Map();
            }
            state.last_dx = dx;
            state.last_dy = dy;
            this.pan_info = { xrs, yrs, sdx, sdy };
            this.plot_view.update_range(this.pan_info, { panning: true });
        }
    }
    exports.PanToolView = PanToolView;
    class PanTool extends gesture_tool_1.GestureTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = PanToolView;
            this.define(() => ({
                dimensions: [enums_1.Dimensions, "both"],
            }));
            this.register_alias("pan", () => new PanTool({ dimensions: "both" }));
            this.register_alias("xpan", () => new PanTool({ dimensions: "width" }));
            this.register_alias("ypan", () => new PanTool({ dimensions: "height" }));
        }
        tool_name = "Pan";
        event_type = "pan";
        default_order = 10;
        get tooltip() {
            return this._get_dim_tooltip(this.dimensions);
        }
        get computed_icon() {
            const icon = super.computed_icon;
            if (icon != null) {
                return icon;
            }
            else {
                switch (this.dimensions) {
                    case "both": return `.${icons.tool_icon_pan}`;
                    case "width": return `.${icons.tool_icon_x_pan}`;
                    case "height": return `.${icons.tool_icon_y_pan}`;
                }
            }
        }
        get menu() {
            return [
                new menus_1.MenuItem({
                    icon: `.${icons.tool_icon_pan}`,
                    label: "XY mode",
                    tooltip: "Pan in both dimensions",
                    checked: () => this.dimensions == "both",
                    action: () => {
                        this.dimensions = "both";
                        this.active = true;
                    },
                }),
                new menus_1.MenuItem({
                    icon: `.${icons.tool_icon_x_pan}`,
                    label: "X-only",
                    tooltip: "Pan in x-dimension",
                    checked: () => this.dimensions == "width",
                    action: () => {
                        this.dimensions = "width";
                        this.active = true;
                    },
                }),
                new menus_1.MenuItem({
                    icon: `.${icons.tool_icon_y_pan}`,
                    label: "Y-only",
                    tooltip: "Pan in y-dimension",
                    checked: () => this.dimensions == "height",
                    action: () => {
                        this.dimensions = "height";
                        this.active = true;
                    },
                }),
            ];
        }
    }
    exports.PanTool = PanTool;
},
/* models/tools/actions/redo_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const plot_action_tool_1 = require(594) /* ./plot_action_tool */;
    const icons_css_1 = require(76) /* ../../../styles/icons.css */;
    class RedoToolView extends plot_action_tool_1.PlotActionToolView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.plot_view.state.changed, () => this.model.disabled = !this.plot_view.state.can_redo);
        }
        doit() {
            const state = this.plot_view.state.redo();
            if (state?.range != null) {
                this.plot_view.trigger_ranges_update_event();
            }
        }
    }
    exports.RedoToolView = RedoToolView;
    class RedoTool extends plot_action_tool_1.PlotActionTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = RedoToolView;
            this.override({
                disabled: true,
            });
            this.register_alias("redo", () => new RedoTool());
        }
        tool_name = "Redo";
        tool_icon = icons_css_1.tool_icon_redo;
    }
    exports.RedoTool = RedoTool;
},
/* models/tools/actions/reset_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const plot_action_tool_1 = require(594) /* ./plot_action_tool */;
    const icons_css_1 = require(76) /* ../../../styles/icons.css */;
    class ResetToolView extends plot_action_tool_1.PlotActionToolView {
        doit() {
            // reset() issues the RangesUpdate event
            this.plot_view.reset();
        }
    }
    exports.ResetToolView = ResetToolView;
    class ResetTool extends plot_action_tool_1.PlotActionTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ResetToolView;
            this.register_alias("reset", () => new ResetTool());
        }
        tool_name = "Reset";
        tool_icon = icons_css_1.tool_icon_reset;
    }
    exports.ResetTool = ResetTool;
},
/* models/tools/actions/save_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const action_tool_1 = require(393) /* ./action_tool */;
    const menus_1 = require(380) /* ../../ui/menus */;
    const icons = tslib_1.__importStar(require(76) /* ../../../styles/icons.css */);
    class SaveToolView extends action_tool_1.ActionToolView {
        async _export() {
            return this.parent.export().to_blob();
        }
        async copy() {
            const blob = await this._export();
            const item = new ClipboardItem({ [blob.type]: blob });
            await navigator.clipboard.write([item]);
        }
        async save(name) {
            const blob = await this._export();
            const link = document.createElement("a");
            link.href = URL.createObjectURL(blob);
            link.download = name; // + ".png" | "svg" (inferred from MIME type)
            link.target = "_blank";
            link.dispatchEvent(new MouseEvent("click"));
        }
        async open() {
            const blob = await this._export();
            const url = URL.createObjectURL(blob);
            open(url);
        }
        doit(action = "save") {
            switch (action) {
                case "save": {
                    const filename = this.model.filename ?? prompt("Enter filename", "bokeh_plot");
                    if (filename != null) {
                        void this.save(filename);
                    }
                    break;
                }
                case "copy": {
                    void this.copy();
                    break;
                }
                case "open": {
                    void this.open();
                    break;
                }
            }
        }
    }
    exports.SaveToolView = SaveToolView;
    class SaveTool extends action_tool_1.ActionTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = SaveToolView;
            this.define(({ Str, Nullable }) => ({
                filename: [Nullable(Str), null],
            }));
            this.register_alias("save", () => new SaveTool());
        }
        tool_name = "Save";
        tool_icon = icons.tool_icon_save;
        get menu() {
            return [
                new menus_1.MenuItem({
                    icon: `.${icons.tool_icon_save}`,
                    label: "Save",
                    tooltip: "Save image as a local file",
                    action: () => {
                        this.do.emit("save");
                    },
                }),
                new menus_1.MenuItem({
                    icon: `.${icons.tool_icon_copy}`,
                    label: "Copy",
                    tooltip: "Copy image to clipboard",
                    disabled: () => typeof ClipboardItem === "undefined",
                    action: () => {
                        this.do.emit("copy");
                    },
                }),
                new menus_1.MenuItem({
                    icon: `.${icons.tool_icon_open}`,
                    label: "Open",
                    tooltip: "Open image in a new tab",
                    action: () => {
                        this.do.emit("open");
                    },
                }),
            ];
        }
    }
    exports.SaveTool = SaveTool;
},
/* models/tools/actions/undo_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const plot_action_tool_1 = require(594) /* ./plot_action_tool */;
    const icons_css_1 = require(76) /* ../../../styles/icons.css */;
    class UndoToolView extends plot_action_tool_1.PlotActionToolView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.plot_view.state.changed, () => this.model.disabled = !this.plot_view.state.can_undo);
        }
        doit() {
            const state = this.plot_view.state.undo();
            if (state?.range != null) {
                this.plot_view.trigger_ranges_update_event();
            }
        }
    }
    exports.UndoToolView = UndoToolView;
    class UndoTool extends plot_action_tool_1.PlotActionTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = UndoToolView;
            this.override({
                disabled: true,
            });
            this.register_alias("undo", () => new UndoTool());
        }
        tool_name = "Undo";
        tool_icon = icons_css_1.tool_icon_undo;
    }
    exports.UndoTool = UndoTool;
},
/* models/tools/actions/zoom_in_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const zoom_base_tool_1 = require(601) /* ./zoom_base_tool */;
    const icons_css_1 = require(76) /* ../../../styles/icons.css */;
    class ZoomInToolView extends zoom_base_tool_1.ZoomBaseToolView {
        get factor() {
            return this.model.factor;
        }
    }
    exports.ZoomInToolView = ZoomInToolView;
    class ZoomInTool extends zoom_base_tool_1.ZoomBaseTool {
        maintain_focus = true;
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ZoomInToolView;
            this.register_alias("zoom_in", () => new ZoomInTool({ dimensions: "both" }));
            this.register_alias("xzoom_in", () => new ZoomInTool({ dimensions: "width" }));
            this.register_alias("yzoom_in", () => new ZoomInTool({ dimensions: "height" }));
        }
        tool_name = "Zoom In";
        tool_icon = icons_css_1.tool_icon_zoom_in;
    }
    exports.ZoomInTool = ZoomInTool;
},
/* models/tools/actions/zoom_base_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const plot_action_tool_1 = require(594) /* ./plot_action_tool */;
    const data_renderer_1 = require(303) /* ../../renderers/data_renderer */;
    const composite_scale_1 = require(117) /* ../../scales/composite_scale */;
    const enums_1 = require(21) /* ../../../core/enums */;
    const zoom_1 = require(602) /* ../../../core/util/zoom */;
    const logging_1 = require(11) /* ../../../core/logging */;
    class ZoomBaseToolView extends plot_action_tool_1.PlotActionToolView {
        doit() {
            // restrict to axis configured in tool's dimensions property
            const { dimensions } = this.model;
            const x_axis = dimensions == "width" || dimensions == "both";
            const y_axis = dimensions == "height" || dimensions == "both";
            const { frame } = this.plot_view;
            const { x_target, y_target } = frame;
            const x_frame_scales = new Map(frame.x_scales);
            const y_frame_scales = new Map(frame.y_scales);
            const { renderers } = this.model;
            if (renderers != "auto") {
                const x_range_names = new Set();
                const y_range_names = new Set();
                for (const renderer of renderers) {
                    if (renderer.coordinates == null) {
                        x_range_names.add(renderer.x_range_name);
                        y_range_names.add(renderer.y_range_name);
                    }
                }
                for (const name of x_frame_scales.keys()) {
                    if (!x_range_names.has(name)) {
                        x_frame_scales.delete(name);
                    }
                }
                for (const name of y_frame_scales.keys()) {
                    if (!y_range_names.has(name)) {
                        y_frame_scales.delete(name);
                    }
                }
            }
            const x_scales = [...x_frame_scales.values()];
            const y_scales = [...y_frame_scales.values()];
            const data_renderers = renderers != "auto" ? renderers : this.plot_view.model.data_renderers;
            for (const renderer of data_renderers) {
                if (renderer.coordinates == null) {
                    continue;
                }
                const rv = this.plot_view.views.get_one(renderer);
                const process = (scale, dim) => {
                    const { level } = this.model;
                    for (let i = 0; i < level; i++) {
                        if (scale instanceof composite_scale_1.CompositeScale) {
                            scale = scale.source_scale;
                        }
                        else {
                            logging_1.logger.warn(`can't reach sub-coordinate level ${level} for ${scale} in ${dim} dimension; stopped at ${i}`);
                            break;
                        }
                    }
                    if (scale instanceof composite_scale_1.CompositeScale) {
                        return scale.target_scale;
                    }
                    else {
                        return scale;
                    }
                };
                const { x_scale, y_scale } = rv.coordinates;
                x_scales.push(process(x_scale, "x"));
                y_scales.push(process(y_scale, "y"));
            }
            const zoom_info = (0, zoom_1.scale_range)(x_scales, y_scales, x_target, y_target, this.factor, x_axis, y_axis);
            this.plot_view.state.push("zoom_out", { range: zoom_info });
            this.plot_view.update_range(zoom_info, { scrolling: true, maintain_focus: this.model.maintain_focus });
            this.model.document?.interactive_start(this.plot_view.model);
            this.plot_view.trigger_ranges_update_event();
        }
    }
    exports.ZoomBaseToolView = ZoomBaseToolView;
    class ZoomBaseTool extends plot_action_tool_1.PlotActionTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Percent, Or, List, Ref, Auto, NonNegative, Int }) => ({
                factor: [Percent, 0.1],
                dimensions: [enums_1.Dimensions, "both"],
                renderers: [Or(List(Ref(data_renderer_1.DataRenderer)), Auto), "auto"],
                level: [NonNegative(Int), 0],
            }));
        }
        get tooltip() {
            return this._get_dim_tooltip(this.dimensions);
        }
    }
    exports.ZoomBaseTool = ZoomBaseTool;
},
/* core/util/zoom.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.scale_interval = scale_interval;
    exports.get_info = get_info;
    exports.rescale = rescale;
    exports.scale_range = scale_range;
    const assert_1 = require(13) /* ./assert */;
    const math_1 = require(12) /* ./math */;
    function scale_interval(range, factor, center) {
        (0, assert_1.assert)(Math.abs(factor) < 1);
        const [min, max] = (0, math_1.minmax)(range.start, range.end);
        const x = center ?? (max + min) / 2.0;
        const x0 = min - (min - x) * factor;
        const x1 = max - (max - x) * factor;
        return [x0, x1];
    }
    function get_info(scales, [sxy0, sxy1]) {
        const info = new Map();
        for (const scale of scales) {
            const [start, end] = scale.r_invert(sxy0, sxy1);
            info.set(scale.source_range, { start, end });
        }
        return info;
    }
    function rescale(scales, factor, center) {
        const output = new Map();
        for (const scale of scales) {
            const [v0, v1] = scale_interval(scale.target_range, factor, center);
            const [start, end] = scale.r_invert(v0, v1);
            output.set(scale.source_range, { start, end });
        }
        return output;
    }
    function scale_range(x_scales, y_scales, _x_target, _y_range, factor, x_axis = true, y_axis = true, center) {
        /*
         * Utility function for zoom tools to calculate/create the zoom_info object
         * of the form required by `PlotView.update_range`.
         */
        // Here we are a bit careful to only update the range info for dimensions that
        // are "in play". This is to avoid superfluous noise updates to dataranges that
        // would cause windowed auto-ranging to turn off.
        const xrs = x_axis ? rescale(x_scales, factor, center?.x) : new Map();
        const yrs = y_axis ? rescale(y_scales, factor, center?.y) : new Map();
        // OK this sucks we can't set factor independently in each direction. It is used
        // for GMap plots, and GMap plots always preserve aspect, so effective the value
        // of 'dimensions' is ignored.
        return { xrs, yrs, factor };
    }
},
/* models/tools/actions/zoom_out_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const zoom_base_tool_1 = require(601) /* ./zoom_base_tool */;
    const icons_css_1 = require(76) /* ../../../styles/icons.css */;
    class ZoomOutToolView extends zoom_base_tool_1.ZoomBaseToolView {
        get factor() {
            const { factor } = this.model;
            return -factor / (1 - factor);
        }
    }
    exports.ZoomOutToolView = ZoomOutToolView;
    class ZoomOutTool extends zoom_base_tool_1.ZoomBaseTool {
        maintain_focus;
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ZoomOutToolView;
            this.define(({ Bool }) => ({
                maintain_focus: [Bool, true],
            }));
            this.register_alias("zoom_out", () => new ZoomOutTool({ dimensions: "both" }));
            this.register_alias("xzoom_out", () => new ZoomOutTool({ dimensions: "width" }));
            this.register_alias("yzoom_out", () => new ZoomOutTool({ dimensions: "height" }));
        }
        tool_name = "Zoom Out";
        tool_icon = icons_css_1.tool_icon_zoom_out;
    }
    exports.ZoomOutTool = ZoomOutTool;
},
/* models/tools/edit/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var edit_tool_1 = require(605) /* ./edit_tool */;
    __esExport("EditTool", edit_tool_1.EditTool);
    var box_edit_tool_1 = require(606) /* ./box_edit_tool */;
    __esExport("BoxEditTool", box_edit_tool_1.BoxEditTool);
    var freehand_draw_tool_1 = require(607) /* ./freehand_draw_tool */;
    __esExport("FreehandDrawTool", freehand_draw_tool_1.FreehandDrawTool);
    var line_edit_tool_1 = require(608) /* ./line_edit_tool */;
    __esExport("LineEditTool", line_edit_tool_1.LineEditTool);
    var point_draw_tool_1 = require(610) /* ./point_draw_tool */;
    __esExport("PointDrawTool", point_draw_tool_1.PointDrawTool);
    var poly_draw_tool_1 = require(611) /* ./poly_draw_tool */;
    __esExport("PolyDrawTool", poly_draw_tool_1.PolyDrawTool);
    var poly_tool_1 = require(612) /* ./poly_tool */;
    __esExport("PolyTool", poly_tool_1.PolyTool);
    var poly_edit_tool_1 = require(613) /* ./poly_edit_tool */;
    __esExport("PolyEditTool", poly_edit_tool_1.PolyEditTool);
},
/* models/tools/edit/edit_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const vectorization_1 = require(29) /* ../../../core/vectorization */;
    const array_1 = require(10) /* ../../../core/util/array */;
    const object_1 = require(9) /* ../../../core/util/object */;
    const types_1 = require(8) /* ../../../core/util/types */;
    const assert_1 = require(13) /* ../../../core/util/assert */;
    const gesture_tool_1 = require(390) /* ../gestures/gesture_tool */;
    class EditToolView extends gesture_tool_1.GestureToolView {
        _basepoint;
        _mouse_in_frame = true;
        _select_mode(ev) {
            const { shift, ctrl } = ev.modifiers;
            if (!shift && !ctrl) {
                return "replace";
            }
            else if (shift && !ctrl) {
                return "append";
            }
            else if (!shift && ctrl) {
                return "intersect";
            }
            else if (shift && ctrl) {
                return "subtract";
            }
            else {
                (0, assert_1.unreachable)();
            }
        }
        _move_enter(_e) {
            this._mouse_in_frame = true;
        }
        _move_exit(_e) {
            this._mouse_in_frame = false;
        }
        _map_drag(sx, sy, renderer) {
            // Maps screen to data coordinates
            const frame = this.plot_view.frame;
            if (!frame.bbox.contains(sx, sy)) {
                return null;
            }
            const renderer_view = this.plot_view.views.find_one(renderer);
            if (renderer_view == null) {
                return null;
            }
            const x = renderer_view.coordinates.x_scale.invert(sx);
            const y = renderer_view.coordinates.y_scale.invert(sy);
            return [x, y];
        }
        _delete_selected(renderer) {
            // Deletes all selected rows in the ColumnDataSource
            const cds = renderer.data_source;
            const indices = cds.selected.indices;
            indices.sort();
            for (const column of cds.columns()) {
                const values = cds.get_array(column);
                for (let index = 0; index < indices.length; index++) {
                    const ind = indices[index];
                    values.splice(ind - index, 1);
                }
            }
            this._emit_cds_changes(cds);
        }
        _pop_glyphs(cds, num_objects) {
            // Pops rows in the CDS until only num_objects are left
            const columns = cds.columns();
            if (num_objects == 0 || columns.length == 0) {
                return;
            }
            const data = (0, object_1.dict)(cds.data);
            for (const column of columns) {
                let array = cds.get_array(column);
                const drop = array.length - num_objects + 1;
                if (drop < 1) {
                    continue;
                }
                if (!(0, types_1.isArray)(array)) {
                    array = Array.from(array);
                    data.set(column, array);
                }
                array.splice(0, drop);
            }
        }
        _emit_cds_changes(cds, redraw = true, clear = true, emit = true) {
            if (clear) {
                cds.selection_manager.clear();
            }
            if (redraw) {
                cds.change.emit();
            }
            if (emit) {
                const { data } = cds;
                cds.setv({ data }, { check_eq: false });
            }
        }
        _drag_points(ev, renderers, dim = "both") {
            if (this._basepoint == null) {
                return;
            }
            const [bx, by] = this._basepoint;
            for (const renderer of renderers) {
                const basepoint = this._map_drag(bx, by, renderer);
                const point = this._map_drag(ev.sx, ev.sy, renderer);
                if (point == null || basepoint == null) {
                    continue;
                }
                const [x, y] = point;
                const [px, py] = basepoint;
                const [dx, dy] = [x - px, y - py];
                // Type once dataspecs are typed
                const { glyph } = renderer;
                const cds = renderer.data_source;
                const data = (0, object_1.dict)(cds.data);
                const xkey = (0, vectorization_1.isField)(glyph.x) ? glyph.x.field : null;
                const ykey = (0, vectorization_1.isField)(glyph.y) ? glyph.y.field : null;
                for (const index of cds.selected.indices) {
                    if (xkey != null && (dim == "width" || dim == "both")) {
                        const column = (data.get(xkey) ?? []);
                        column[index] += dx;
                    }
                    if (ykey != null && (dim == "height" || dim == "both")) {
                        const column = (data.get(ykey) ?? []);
                        column[index] += dy;
                    }
                }
                cds.change.emit();
            }
            this._basepoint = [ev.sx, ev.sy];
        }
        _pad_empty_columns(cds, coord_columns) {
            // Pad ColumnDataSource non-coordinate columns with default values
            const { inferred_defaults } = cds;
            const default_values = (0, object_1.dict)(cds.default_values);
            const default_overrides = (0, object_1.dict)(this.model.default_overrides);
            for (const column of cds.columns()) {
                if (!(0, array_1.includes)(coord_columns, column)) {
                    const default_value = (() => {
                        if (default_overrides.has(column)) {
                            return default_overrides.get(column);
                        }
                        else if (default_values.has(column)) {
                            return default_values.get(column);
                        }
                        else if (inferred_defaults.has(column)) {
                            return inferred_defaults.get(column);
                        }
                        else {
                            return this.model.empty_value;
                        }
                    })();
                    cds.get_array(column).push(default_value);
                }
            }
        }
        _select_event(ev, mode, renderers) {
            // Process selection event on the supplied renderers and return selected renderers
            const frame = this.plot_view.frame;
            const { sx, sy } = ev;
            if (!frame.bbox.contains(sx, sy)) {
                return [];
            }
            const geometry = { type: "point", sx, sy };
            const selected = [];
            for (const renderer of renderers) {
                const sm = renderer.get_selection_manager();
                const cds = renderer.data_source;
                const view = this.plot_view.views.find_one(renderer);
                if (view != null) {
                    const did_hit = sm.select([view], geometry, true, mode);
                    if (did_hit) {
                        selected.push(renderer);
                    }
                    cds.properties.selected.change.emit();
                }
            }
            return selected;
        }
    }
    exports.EditToolView = EditToolView;
    class EditTool extends gesture_tool_1.GestureTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Unknown, Dict }) => ({
                default_overrides: [Dict(Unknown), {}],
                empty_value: [Unknown, 0],
            }));
        }
    }
    exports.EditTool = EditTool;
},
/* models/tools/edit/box_edit_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const enums_1 = require(21) /* ../../../core/enums */;
    const vectorization_1 = require(29) /* ../../../core/vectorization */;
    const xy_glyph_1 = require(305) /* ../../glyphs/xy_glyph */;
    const rect_1 = require(485) /* ../../glyphs/rect */;
    const block_1 = require(462) /* ../../glyphs/block */;
    const quad_1 = require(482) /* ../../glyphs/quad */;
    const hbar_1 = require(466) /* ../../glyphs/hbar */;
    const vbar_1 = require(493) /* ../../glyphs/vbar */;
    const hstrip_1 = require(469) /* ../../glyphs/hstrip */;
    const vstrip_1 = require(495) /* ../../glyphs/vstrip */;
    const glyph_renderer_1 = require(302) /* ../../renderers/glyph_renderer */;
    const edit_tool_1 = require(605) /* ./edit_tool */;
    const icons_css_1 = require(76) /* ../../../styles/icons.css */;
    const assert_1 = require(13) /* ../../../core/util/assert */;
    const object_1 = require(9) /* ../../../core/util/object */;
    class BoxEditToolView extends edit_tool_1.EditToolView {
        _draw_basepoint;
        _recent_renderers = [];
        _tap(ev) {
            if ((this._draw_basepoint != null) || (this._basepoint != null)) {
                return;
            }
            this._recent_renderers = this._select_event(ev, this._select_mode(ev), this.model.renderers);
        }
        _keyup(ev) {
            if (!this.model.active || !this._mouse_in_frame) {
                return;
            }
            for (const renderer of this.model.renderers) {
                if (ev.key == "Backspace") {
                    this._delete_selected(renderer);
                }
                else if (ev.key == "Escape") {
                    // Type properly once selection_manager is typed
                    const cds = renderer.data_source;
                    cds.selection_manager.clear();
                }
            }
        }
        _set_extent([sx0, sx1], [sy0, sy1], append, emit = false) {
            const renderer = this._recent_renderers[0] ?? this.model.renderers[0];
            const renderer_view = this.plot_view.views.find_one(renderer);
            if (renderer_view == null) {
                return;
            }
            const { glyph } = renderer;
            const cds = renderer.data_source;
            const data = (0, object_1.dict)(cds.data);
            const [dx0, dx1] = renderer_view.coordinates.x_scale.r_invert(sx0, sx1);
            const [dy0, dy1] = renderer_view.coordinates.y_scale.r_invert(sy0, sy1);
            const fields = (() => {
                if (glyph instanceof rect_1.Rect) {
                    const { x, y, width, height } = glyph;
                    if ((0, vectorization_1.isField)(x) && (0, vectorization_1.isField)(y) && (0, vectorization_1.isField)(width) && (0, vectorization_1.isField)(height)) {
                        return {
                            [x.field]: (dx0 + dx1) / 2,
                            [y.field]: (dy0 + dy1) / 2,
                            [width.field]: dx1 - dx0,
                            [height.field]: dy1 - dy0,
                        };
                    }
                }
                else if (glyph instanceof block_1.Block) {
                    const { x, y, width, height } = glyph;
                    if ((0, vectorization_1.isField)(x) && (0, vectorization_1.isField)(y) && (0, vectorization_1.isField)(width) && (0, vectorization_1.isField)(height)) {
                        return {
                            [x.field]: dx0,
                            [y.field]: dy0,
                            [width.field]: dx1 - dx0,
                            [height.field]: dy1 - dy0,
                        };
                    }
                }
                else if (glyph instanceof quad_1.Quad) {
                    const { right, bottom, left, top } = glyph;
                    if ((0, vectorization_1.isField)(right) && (0, vectorization_1.isField)(bottom) && (0, vectorization_1.isField)(left) && (0, vectorization_1.isField)(top)) {
                        return {
                            [right.field]: dx1,
                            [bottom.field]: dy0,
                            [left.field]: dx0,
                            [top.field]: dy1,
                        };
                    }
                }
                else if (glyph instanceof hbar_1.HBar) {
                    const { left, y, height, right } = glyph;
                    if ((0, vectorization_1.isField)(left) && (0, vectorization_1.isField)(y) && (0, vectorization_1.isField)(height) && (0, vectorization_1.isField)(right)) {
                        return {
                            [left.field]: dx0,
                            [y.field]: (dy0 + dy1) / 2.0,
                            [height.field]: dy1 - dy0,
                            [right.field]: dx1,
                        };
                    }
                }
                else if (glyph instanceof vbar_1.VBar) {
                    const { x, bottom, width, top } = glyph;
                    if ((0, vectorization_1.isField)(x) && (0, vectorization_1.isField)(bottom) && (0, vectorization_1.isField)(width) && (0, vectorization_1.isField)(top)) {
                        return {
                            [x.field]: (dx0 + dx1) / 2.0,
                            [bottom.field]: dy0,
                            [width.field]: dx1 - dx0,
                            [top.field]: dy1,
                        };
                    }
                }
                else if (glyph instanceof hstrip_1.HStrip) {
                    const { y0, y1 } = glyph;
                    if ((0, vectorization_1.isField)(y0) && (0, vectorization_1.isField)(y1)) {
                        return {
                            [y0.field]: dy0,
                            [y1.field]: dy1,
                        };
                    }
                }
                else if (glyph instanceof vstrip_1.VStrip) {
                    const { x0, x1 } = glyph;
                    if ((0, vectorization_1.isField)(x0) && (0, vectorization_1.isField)(x1)) {
                        return {
                            [x0.field]: dx0,
                            [x1.field]: dx1,
                        };
                    }
                }
                else {
                    (0, assert_1.unreachable)(`'${glyph.type}' is not supported"`);
                }
                return null;
            })();
            if (fields == null) {
                return;
            }
            if (append) {
                this._pop_glyphs(cds, this.model.num_objects);
                for (const [key, val] of (0, object_1.entries)(fields)) {
                    cds.get_array(key).push(val);
                }
                this._pad_empty_columns(cds, (0, object_1.keys)(fields));
            }
            else {
                const length = cds.get_length();
                if (length == null) {
                    return;
                }
                const index = length - 1;
                for (const [key, val] of (0, object_1.entries)(fields)) {
                    data.get(key)[index] = val;
                }
            }
            this._emit_cds_changes(cds, true, false, emit);
        }
        _update_box(ev, append = false, emit = false) {
            if (this._draw_basepoint == null) {
                return;
            }
            const curpoint = [ev.sx, ev.sy];
            const frame = this.plot_view.frame;
            const dims = this.model.dimensions;
            const [sxlim, sylim] = this.model._get_dim_limits(this._draw_basepoint, curpoint, frame, dims);
            this._set_extent(sxlim, sylim, append, emit);
        }
        _press(ev) {
            if (!this.model.active) {
                return;
            }
            if (this._draw_basepoint != null) {
                this._update_box(ev, false, true);
                this._draw_basepoint = null;
            }
            else {
                this._draw_basepoint = [ev.sx, ev.sy];
                this._select_event(ev, "append", this.model.renderers);
                this._update_box(ev, true, false);
            }
        }
        _move(ev) {
            this._update_box(ev, false, false);
        }
        _pan_start(ev) {
            if (ev.modifiers.shift) {
                if (this._draw_basepoint != null) {
                    return;
                }
                this._draw_basepoint = [ev.sx, ev.sy];
                this._update_box(ev, true, false);
            }
            else {
                if (this._basepoint != null) {
                    return;
                }
                this._recent_renderers = this._select_event(ev, "append", this.model.renderers);
                this._basepoint = [ev.sx, ev.sy];
            }
        }
        _pan(ev, append = false, emit = false) {
            if (ev.modifiers.shift) {
                if (this._draw_basepoint == null) {
                    return;
                }
                this._update_box(ev, append, emit);
            }
            else {
                if (this._basepoint == null) {
                    return;
                }
                this._drag_points(ev, this.model.renderers);
            }
        }
        _drag_points(ev, renderers, dim = "both") {
            if (this._basepoint == null) {
                return;
            }
            const [bx, by] = this._basepoint;
            for (const renderer of renderers) {
                const basepoint = this._map_drag(bx, by, renderer);
                const point = this._map_drag(ev.sx, ev.sy, renderer);
                if (point == null || basepoint == null) {
                    continue;
                }
                const [x, y] = point;
                const [px, py] = basepoint;
                const dx = dim == "width" || dim == "both" ? x - px : 0;
                const dy = dim == "height" || dim == "both" ? y - py : 0;
                const { glyph } = renderer;
                const cds = renderer.data_source;
                const data = (0, object_1.dict)(cds.data);
                const fields = {};
                if (glyph instanceof xy_glyph_1.XYGlyph) {
                    const { x, y } = glyph;
                    if ((0, vectorization_1.isField)(x)) {
                        fields[x.field] = dx;
                    }
                    if ((0, vectorization_1.isField)(y)) {
                        fields[y.field] = dy;
                    }
                }
                else if (glyph instanceof block_1.Block) {
                    const { x, y } = glyph;
                    if ((0, vectorization_1.isField)(x)) {
                        fields[x.field] = dx;
                    }
                    if ((0, vectorization_1.isField)(y)) {
                        fields[y.field] = dy;
                    }
                }
                else if (glyph instanceof quad_1.Quad) {
                    const { right, bottom, left, top } = glyph;
                    if ((0, vectorization_1.isField)(left) && (0, vectorization_1.isField)(right)) {
                        fields[left.field] = dx;
                        fields[right.field] = dx;
                    }
                    if ((0, vectorization_1.isField)(top) && (0, vectorization_1.isField)(bottom)) {
                        fields[top.field] = dy;
                        fields[bottom.field] = dy;
                    }
                }
                else if (glyph instanceof hbar_1.HBar) {
                    const { left, right, y } = glyph;
                    if ((0, vectorization_1.isField)(left) && (0, vectorization_1.isField)(right)) {
                        fields[left.field] = dx;
                        fields[right.field] = dx;
                    }
                    if ((0, vectorization_1.isField)(y)) {
                        fields[y.field] = dy;
                    }
                }
                else if (glyph instanceof vbar_1.VBar) {
                    const { x, top, bottom } = glyph;
                    if ((0, vectorization_1.isField)(x)) {
                        fields[x.field] = dx;
                    }
                    if ((0, vectorization_1.isField)(top) && (0, vectorization_1.isField)(bottom)) {
                        fields[top.field] = dy;
                        fields[bottom.field] = dy;
                    }
                }
                else if (glyph instanceof hstrip_1.HStrip) {
                    const { y0, y1 } = glyph;
                    if ((0, vectorization_1.isField)(y0) && (0, vectorization_1.isField)(y1)) {
                        fields[y0.field] = dy;
                        fields[y1.field] = dy;
                    }
                }
                else if (glyph instanceof vstrip_1.VStrip) {
                    const { x0, x1 } = glyph;
                    if ((0, vectorization_1.isField)(x0) && (0, vectorization_1.isField)(x1)) {
                        fields[x0.field] = dx;
                        fields[x1.field] = dx;
                    }
                }
                else {
                    (0, assert_1.unreachable)(`'${glyph.type}' is not supported"`);
                }
                for (const index of cds.selected.indices) {
                    for (const [key, val] of (0, object_1.entries)(fields)) {
                        const column = (data.get(key) ?? []);
                        column[index] += val;
                    }
                }
                cds.change.emit();
            }
            this._basepoint = [ev.sx, ev.sy];
        }
        _pan_end(ev) {
            this._pan(ev, false, true);
            if (ev.modifiers.shift) {
                this._draw_basepoint = null;
            }
            else {
                this._basepoint = null;
                for (const renderer of this.model.renderers) {
                    this._emit_cds_changes(renderer.data_source, false, true, true);
                }
            }
        }
    }
    exports.BoxEditToolView = BoxEditToolView;
    class BoxEditTool extends edit_tool_1.EditTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = BoxEditToolView;
            this.define(({ Int, List, Ref }) => ({
                dimensions: [enums_1.Dimensions, "both"],
                num_objects: [Int, 0],
                renderers: [List(Ref(glyph_renderer_1.GlyphRenderer)), []],
            }));
        }
        tool_name = "Box Edit Tool";
        tool_icon = icons_css_1.tool_icon_box_edit;
        event_type = ["tap", "press", "pan", "move"];
        default_order = 1;
    }
    exports.BoxEditTool = BoxEditTool;
},
/* models/tools/edit/freehand_draw_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const vectorization_1 = require(29) /* ../../../core/vectorization */;
    const object_1 = require(9) /* ../../../core/util/object */;
    const types_1 = require(8) /* ../../../core/util/types */;
    const edit_tool_1 = require(605) /* ./edit_tool */;
    const glyph_renderer_1 = require(302) /* ../../renderers/glyph_renderer */;
    const icons_css_1 = require(76) /* ../../../styles/icons.css */;
    class FreehandDrawToolView extends edit_tool_1.EditToolView {
        _draw(ev, mode, emit = false) {
            if (!this.model.active) {
                return;
            }
            const renderer = this.model.renderers[0];
            const point = this._map_drag(ev.sx, ev.sy, renderer);
            if (point == null) {
                return;
            }
            const [x, y] = point;
            const { glyph, data_source } = renderer;
            const xkey = (0, vectorization_1.isField)(glyph.xs) ? glyph.xs.field : null;
            const ykey = (0, vectorization_1.isField)(glyph.ys) ? glyph.ys.field : null;
            const data = (0, object_1.dict)(data_source.data);
            if (mode == "new") {
                this._pop_glyphs(data_source, this.model.num_objects);
                if (xkey != null) {
                    data_source.get_array(xkey).push([x]);
                }
                if (ykey != null) {
                    data_source.get_array(ykey).push([y]);
                }
                this._pad_empty_columns(data_source, [xkey, ykey]);
            }
            else if (mode == "add") {
                if (xkey != null) {
                    const column = data.get(xkey) ?? [];
                    const xidx = column.length - 1;
                    let xs = data_source.get_array(xkey)[xidx];
                    if (!(0, types_1.isArray)(xs)) {
                        xs = Array.from(xs);
                        column[xidx] = xs;
                    }
                    xs.push(x);
                }
                if (ykey != null) {
                    const column = data.get(ykey) ?? [];
                    const yidx = column.length - 1;
                    let ys = data_source.get_array(ykey)[yidx];
                    if (!(0, types_1.isArray)(ys)) {
                        ys = Array.from(ys);
                        column[yidx] = ys;
                    }
                    ys.push(y);
                }
            }
            this._emit_cds_changes(data_source, true, true, emit);
        }
        _pan_start(ev) {
            this._draw(ev, "new");
        }
        _pan(ev) {
            this._draw(ev, "add");
        }
        _pan_end(ev) {
            this._draw(ev, "add", true);
        }
        _tap(ev) {
            this._select_event(ev, this._select_mode(ev), this.model.renderers);
        }
        _keyup(ev) {
            if (!this.model.active || !this._mouse_in_frame) {
                return;
            }
            for (const renderer of this.model.renderers) {
                if (ev.key == "Escape") {
                    renderer.data_source.selection_manager.clear();
                }
                else if (ev.key == "Backspace") {
                    this._delete_selected(renderer);
                }
            }
        }
    }
    exports.FreehandDrawToolView = FreehandDrawToolView;
    class FreehandDrawTool extends edit_tool_1.EditTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = FreehandDrawToolView;
            this.define(({ Int, List, Ref }) => ({
                num_objects: [Int, 0],
                renderers: [List(Ref(glyph_renderer_1.GlyphRenderer)), []],
            }));
            this.register_alias("freehand_draw", () => new FreehandDrawTool());
        }
        tool_name = "Freehand Draw Tool";
        tool_icon = icons_css_1.tool_icon_freehand_draw;
        event_type = ["pan", "tap"];
        default_order = 3;
    }
    exports.FreehandDrawTool = FreehandDrawTool;
},
/* models/tools/edit/line_edit_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const vectorization_1 = require(29) /* ../../../core/vectorization */;
    const enums_1 = require(21) /* ../../../core/enums */;
    const object_1 = require(9) /* ../../../core/util/object */;
    const glyph_renderer_1 = require(302) /* ../../renderers/glyph_renderer */;
    const line_tool_1 = require(609) /* ./line_tool */;
    const icons_css_1 = require(76) /* ../../../styles/icons.css */;
    class LineEditToolView extends line_tool_1.LineToolView {
        _selected_renderer;
        _drawing = false;
        _press(ev) {
            if (!this.model.active) {
                return;
            }
            const renderers = this.model.renderers;
            for (const renderer of renderers) {
                const line_selected = this._select_event(ev, "replace", [renderer]);
                if (line_selected.length == 1) {
                    this._selected_renderer = renderer;
                }
            }
            this._show_intersections();
            this._update_line_cds();
        }
        _show_intersections() {
            if (!this.model.active) {
                return;
            }
            if (this._selected_renderer == null) {
                return;
            }
            const renderers = this.model.renderers;
            if (renderers.length == 0) {
                this._set_intersection([], []);
                this._selected_renderer = null;
                this._drawing = false;
                return;
            }
            const { glyph } = this._selected_renderer;
            if (!(0, vectorization_1.isField)(glyph.x) || !(0, vectorization_1.isField)(glyph.y)) {
                return;
            }
            const [xkey, ykey] = [glyph.x.field, glyph.y.field];
            const cds = this._selected_renderer.data_source;
            const x = cds.get_array(xkey);
            const y = cds.get_array(ykey);
            this._set_intersection(x, y);
        }
        _tap(ev) {
            const renderer = this.model.intersection_renderer;
            const point = this._map_drag(ev.sx, ev.sy, renderer);
            if (point == null) {
                return;
            }
            else if (this._drawing && this._selected_renderer != null) {
                const mode = this._select_mode(ev);
                const selected_points = this._select_event(ev, mode, [renderer]);
                if (selected_points.length == 0) {
                    return;
                }
            }
            const mode = this._select_mode(ev);
            this._select_event(ev, mode, [renderer]);
            this._select_event(ev, mode, this.model.renderers);
        }
        _update_line_cds() {
            if (this._selected_renderer == null) {
                return;
            }
            const point_glyph = this.model.intersection_renderer.glyph;
            const point_cds = this.model.intersection_renderer.data_source;
            const data = (0, object_1.dict)(point_cds.data);
            const pxkey = (0, vectorization_1.isField)(point_glyph.x) ? point_glyph.x.field : null;
            const pykey = (0, vectorization_1.isField)(point_glyph.y) ? point_glyph.y.field : null;
            if (pxkey != null && pykey != null) {
                const x = data.get(pxkey);
                const y = data.get(pykey);
                if (x != null) {
                    (0, object_1.dict)(this._selected_renderer.data_source.data).set(pxkey, x);
                }
                if (y != null) {
                    (0, object_1.dict)(this._selected_renderer.data_source.data).set(pykey, y);
                }
            }
            this._emit_cds_changes(this._selected_renderer.data_source, true, true, false);
        }
        _pan_start(ev) {
            this._select_event(ev, "append", [this.model.intersection_renderer]);
            this._basepoint = [ev.sx, ev.sy];
        }
        _pan(ev) {
            if (this._basepoint == null) {
                return;
            }
            this._drag_points(ev, [this.model.intersection_renderer], this.model.dimensions);
            if (this._selected_renderer != null) {
                this._selected_renderer.data_source.change.emit();
            }
        }
        _pan_end(ev) {
            if (this._basepoint == null) {
                return;
            }
            this._drag_points(ev, [this.model.intersection_renderer]);
            this._emit_cds_changes(this.model.intersection_renderer.data_source, false, true, true);
            if (this._selected_renderer != null) {
                this._emit_cds_changes(this._selected_renderer.data_source);
            }
            this._basepoint = null;
        }
        activate() {
            this._drawing = true;
        }
        deactivate() {
            if (this._selected_renderer == null) {
                return;
            }
            else if (this._drawing) {
                this._drawing = false;
            }
            this._hide_intersections();
        }
    }
    exports.LineEditToolView = LineEditToolView;
    class LineEditTool extends line_tool_1.LineTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = LineEditToolView;
            this.define(({ List, Ref }) => ({
                dimensions: [enums_1.Dimensions, "both"],
                renderers: [List(Ref(glyph_renderer_1.GlyphRenderer)), []],
            }));
        }
        tool_name = "Line Edit Tool";
        tool_icon = icons_css_1.tool_icon_line_edit;
        event_type = ["tap", "press", "pan", "move"];
        default_order = 4;
        get tooltip() {
            return this._get_dim_tooltip(this.dimensions);
        }
    }
    exports.LineEditTool = LineEditTool;
},
/* models/tools/edit/line_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const vectorization_1 = require(29) /* ../../../core/vectorization */;
    const object_1 = require(9) /* ../../../core/util/object */;
    const types_1 = require(8) /* ../../../core/util/types */;
    const glyph_renderer_1 = require(302) /* ../../renderers/glyph_renderer */;
    const edit_tool_1 = require(605) /* ./edit_tool */;
    class LineToolView extends edit_tool_1.EditToolView {
        _set_intersection(x, y) {
            const point_glyph = this.model.intersection_renderer.glyph;
            const point_cds = this.model.intersection_renderer.data_source;
            const data = (0, object_1.dict)(point_cds.data);
            const pxkey = (0, vectorization_1.isField)(point_glyph.x) ? point_glyph.x.field : null;
            const pykey = (0, vectorization_1.isField)(point_glyph.y) ? point_glyph.y.field : null;
            if (pxkey != null) {
                if ((0, types_1.isArray)(x)) {
                    data.set(pxkey, x);
                }
                else {
                    point_glyph.x = { value: x };
                }
            }
            if (pykey != null) {
                if ((0, types_1.isArray)(y)) {
                    data.set(pykey, y);
                }
                else {
                    point_glyph.y = { value: y };
                }
            }
            this._emit_cds_changes(point_cds, true, true, false);
        }
        _hide_intersections() {
            this._set_intersection([], []);
        }
    }
    exports.LineToolView = LineToolView;
    class LineTool extends edit_tool_1.EditTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Ref }) => ({
                intersection_renderer: [Ref(glyph_renderer_1.GlyphRenderer)],
            }));
        }
    }
    exports.LineTool = LineTool;
},
/* models/tools/edit/point_draw_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const vectorization_1 = require(29) /* ../../../core/vectorization */;
    const glyph_renderer_1 = require(302) /* ../../renderers/glyph_renderer */;
    const edit_tool_1 = require(605) /* ./edit_tool */;
    const icons_css_1 = require(76) /* ../../../styles/icons.css */;
    class PointDrawToolView extends edit_tool_1.EditToolView {
        _tap(ev) {
            const renderers = this._select_event(ev, this._select_mode(ev), this.model.renderers);
            if (renderers.length != 0 || !this.model.add) {
                return;
            }
            const renderer = this.model.renderers[0];
            const point = this._map_drag(ev.sx, ev.sy, renderer);
            if (point == null) {
                return;
            }
            const { glyph, data_source } = renderer;
            const xkey = (0, vectorization_1.isField)(glyph.x) ? glyph.x.field : null;
            const ykey = (0, vectorization_1.isField)(glyph.y) ? glyph.y.field : null;
            const [x, y] = point;
            this._pop_glyphs(data_source, this.model.num_objects);
            if (xkey != null) {
                data_source.get_array(xkey).push(x);
            }
            if (ykey != null) {
                data_source.get_array(ykey).push(y);
            }
            this._pad_empty_columns(data_source, [xkey, ykey]);
            const { data } = data_source;
            data_source.setv({ data }, { check_eq: false }); // XXX: inplace updates
        }
        _keyup(ev) {
            if (!this.model.active || !this._mouse_in_frame) {
                return;
            }
            for (const renderer of this.model.renderers) {
                if (ev.key == "Backspace") {
                    this._delete_selected(renderer);
                }
                else if (ev.key == "Escape") {
                    renderer.data_source.selection_manager.clear();
                }
            }
        }
        _pan_start(ev) {
            if (!this.model.drag) {
                return;
            }
            this._select_event(ev, "append", this.model.renderers);
            this._basepoint = [ev.sx, ev.sy];
        }
        _pan(ev) {
            if (!this.model.drag || this._basepoint == null) {
                return;
            }
            this._drag_points(ev, this.model.renderers);
        }
        _pan_end(ev) {
            if (!this.model.drag) {
                return;
            }
            this._pan(ev);
            for (const renderer of this.model.renderers) {
                this._emit_cds_changes(renderer.data_source, false, true, true);
            }
            this._basepoint = null;
        }
    }
    exports.PointDrawToolView = PointDrawToolView;
    class PointDrawTool extends edit_tool_1.EditTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = PointDrawToolView;
            this.define(({ Bool, Int, List, Ref }) => ({
                add: [Bool, true],
                drag: [Bool, true],
                num_objects: [Int, 0],
                renderers: [List(Ref(glyph_renderer_1.GlyphRenderer)), []],
            }));
        }
        tool_name = "Point Draw Tool";
        tool_icon = icons_css_1.tool_icon_point_draw;
        event_type = ["tap", "pan", "move"];
        default_order = 2;
    }
    exports.PointDrawTool = PointDrawTool;
},
/* models/tools/edit/poly_draw_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const vectorization_1 = require(29) /* ../../../core/vectorization */;
    const object_1 = require(9) /* ../../../core/util/object */;
    const types_1 = require(8) /* ../../../core/util/types */;
    const glyph_renderer_1 = require(302) /* ../../renderers/glyph_renderer */;
    const poly_tool_1 = require(612) /* ./poly_tool */;
    const icons_css_1 = require(76) /* ../../../styles/icons.css */;
    class PolyDrawToolView extends poly_tool_1.PolyToolView {
        _drawing = false;
        _initialized = false;
        _tap(ev) {
            if (this._drawing) {
                this._draw(ev, "add", true);
            }
            else {
                this._select_event(ev, this._select_mode(ev), this.model.renderers);
            }
        }
        _draw(ev, mode, emit = false) {
            const renderer = this.model.renderers[0];
            const point = this._map_drag(ev.sx, ev.sy, renderer);
            if (!this._initialized) {
                this.activate(); // Ensure that activate has been called
            }
            if (point == null) {
                return;
            }
            const [x, y] = this._snap_to_vertex(ev, ...point);
            const cds = renderer.data_source;
            const data = (0, object_1.dict)(cds.data);
            const glyph = renderer.glyph;
            const xkey = (0, vectorization_1.isField)(glyph.xs) ? glyph.xs.field : null;
            const ykey = (0, vectorization_1.isField)(glyph.ys) ? glyph.ys.field : null;
            if (mode == "new") {
                this._pop_glyphs(cds, this.model.num_objects);
                if (xkey != null) {
                    cds.get_array(xkey).push([x, x]);
                }
                if (ykey != null) {
                    cds.get_array(ykey).push([y, y]);
                }
                this._pad_empty_columns(cds, [xkey, ykey]);
            }
            else if (mode == "edit") {
                if (xkey != null) {
                    const column = data.get(xkey) ?? [];
                    const xs = column[column.length - 1];
                    xs[xs.length - 1] = x;
                }
                if (ykey != null) {
                    const column = data.get(ykey) ?? [];
                    const ys = column[column.length - 1];
                    ys[ys.length - 1] = y;
                }
            }
            else if (mode == "add") {
                if (xkey != null) {
                    const column = data.get(xkey) ?? [];
                    const xidx = column.length - 1;
                    let xs = cds.get_array(xkey)[xidx];
                    const nx = xs[xs.length - 1];
                    xs[xs.length - 1] = x;
                    if (!(0, types_1.isArray)(xs)) {
                        xs = Array.from(xs);
                        column[xidx] = xs;
                    }
                    xs.push(nx);
                }
                if (ykey != null) {
                    const column = data.get(ykey) ?? [];
                    const yidx = column.length - 1;
                    let ys = cds.get_array(ykey)[yidx];
                    const ny = ys[ys.length - 1];
                    ys[ys.length - 1] = y;
                    if (!(0, types_1.isArray)(ys)) {
                        ys = Array.from(ys);
                        column[yidx] = ys;
                    }
                    ys.push(ny);
                }
            }
            this._emit_cds_changes(cds, true, false, emit);
        }
        _show_vertices() {
            if (!this.model.active) {
                return;
            }
            const xs = [];
            const ys = [];
            for (let i = 0; i < this.model.renderers.length; i++) {
                const renderer = this.model.renderers[i];
                const { glyph, data_source } = renderer;
                const xkey = (0, vectorization_1.isField)(glyph.xs) ? glyph.xs.field : null;
                const ykey = (0, vectorization_1.isField)(glyph.ys) ? glyph.ys.field : null;
                if (xkey != null) {
                    for (const array of data_source.get_array(xkey)) {
                        xs.push(...array);
                    }
                }
                if (ykey != null) {
                    for (const array of data_source.get_array(ykey)) {
                        ys.push(...array);
                    }
                }
                if (this._drawing && (i == (this.model.renderers.length - 1))) {
                    // Skip currently drawn vertex
                    xs.splice(xs.length - 1, 1);
                    ys.splice(ys.length - 1, 1);
                }
            }
            this._set_vertices(xs, ys);
        }
        _press(ev) {
            if (!this.model.active) {
                return;
            }
            if (this._drawing) {
                this._drawing = false;
                this._draw(ev, "edit", true);
            }
            else {
                this._drawing = true;
                this._draw(ev, "new", true);
            }
        }
        _move(ev) {
            if (this._drawing) {
                this._draw(ev, "edit");
            }
        }
        _remove() {
            const renderer = this.model.renderers[0];
            const { glyph, data_source } = renderer;
            const xkey = (0, vectorization_1.isField)(glyph.xs) ? glyph.xs.field : null;
            const ykey = (0, vectorization_1.isField)(glyph.ys) ? glyph.ys.field : null;
            const data = (0, object_1.dict)(data_source.data);
            if (xkey != null) {
                const column = data.get(xkey) ?? [];
                const xidx = column.length - 1;
                const xs = data_source.get_array(xkey)[xidx];
                xs.splice(xs.length - 1, 1);
            }
            if (ykey != null) {
                const column = data.get(ykey) ?? [];
                const yidx = column.length - 1;
                const ys = data_source.get_array(ykey)[yidx];
                ys.splice(ys.length - 1, 1);
            }
            this._emit_cds_changes(data_source);
        }
        _keyup(ev) {
            if (!this.model.active || !this._mouse_in_frame) {
                return;
            }
            for (const renderer of this.model.renderers) {
                if (ev.key == "Backspace") {
                    this._delete_selected(renderer);
                }
                else if (ev.key == "Escape") {
                    if (this._drawing) {
                        this._remove();
                        this._drawing = false;
                    }
                    renderer.data_source.selection_manager.clear();
                }
            }
        }
        _pan_start(ev) {
            if (!this.model.drag) {
                return;
            }
            this._select_event(ev, "append", this.model.renderers);
            this._basepoint = [ev.sx, ev.sy];
        }
        _pan(ev) {
            if (this._basepoint == null || !this.model.drag) {
                return;
            }
            const [bx, by] = this._basepoint;
            // Process polygon/line dragging
            for (const renderer of this.model.renderers) {
                const basepoint = this._map_drag(bx, by, renderer);
                const point = this._map_drag(ev.sx, ev.sy, renderer);
                if (point == null || basepoint == null) {
                    continue;
                }
                const cds = renderer.data_source;
                const { glyph } = renderer;
                const xkey = (0, vectorization_1.isField)(glyph.xs) ? glyph.xs.field : null;
                const ykey = (0, vectorization_1.isField)(glyph.ys) ? glyph.ys.field : null;
                if (xkey == null && ykey == null) {
                    continue;
                }
                const [x, y] = point;
                const [px, py] = basepoint;
                const [dx, dy] = [x - px, y - py];
                const data = (0, object_1.dict)(cds.data);
                for (const index of cds.selected.indices) {
                    let length, xs, ys;
                    if (xkey != null) {
                        const column = data.get(xkey) ?? [];
                        xs = column[index];
                    }
                    if (ykey != null) {
                        const column = data.get(ykey) ?? [];
                        ys = column[index];
                        length = ys.length;
                    }
                    else {
                        length = xs.length;
                    }
                    for (let i = 0; i < length; i++) {
                        if (xs) {
                            xs[i] += dx;
                        }
                        if (ys) {
                            ys[i] += dy;
                        }
                    }
                }
                cds.change.emit();
            }
            this._basepoint = [ev.sx, ev.sy];
        }
        _pan_end(ev) {
            if (!this.model.drag) {
                return;
            }
            this._pan(ev);
            for (const renderer of this.model.renderers) {
                this._emit_cds_changes(renderer.data_source);
            }
            this._basepoint = null;
        }
        activate() {
            if (this.model.vertex_renderer == null || !this.model.active) {
                return;
            }
            this._show_vertices();
            if (!this._initialized) {
                for (const renderer of this.model.renderers) {
                    const cds = renderer.data_source;
                    cds.connect(cds.properties.data.change, () => this._show_vertices());
                }
            }
            this._initialized = true;
        }
        deactivate() {
            if (this._drawing) {
                this._remove();
                this._drawing = false;
            }
            if (this.model.vertex_renderer != null) {
                this._hide_vertices();
            }
        }
    }
    exports.PolyDrawToolView = PolyDrawToolView;
    class PolyDrawTool extends poly_tool_1.PolyTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = PolyDrawToolView;
            this.define(({ Bool, Int, List, Ref }) => ({
                drag: [Bool, true],
                num_objects: [Int, 0],
                renderers: [List(Ref(glyph_renderer_1.GlyphRenderer)), []],
            }));
        }
        tool_name = "Polygon Draw Tool";
        tool_icon = icons_css_1.tool_icon_poly_draw;
        event_type = ["pan", "tap", "press", "move"];
        default_order = 3;
    }
    exports.PolyDrawTool = PolyDrawTool;
},
/* models/tools/edit/poly_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const vectorization_1 = require(29) /* ../../../core/vectorization */;
    const object_1 = require(9) /* ../../../core/util/object */;
    const types_1 = require(8) /* ../../../core/util/types */;
    const assert_1 = require(13) /* ../../../core/util/assert */;
    const glyph_renderer_1 = require(302) /* ../../renderers/glyph_renderer */;
    const edit_tool_1 = require(605) /* ./edit_tool */;
    class PolyToolView extends edit_tool_1.EditToolView {
        _set_vertices(xs, ys) {
            const { vertex_renderer } = this.model;
            (0, assert_1.assert)(vertex_renderer != null);
            const point_glyph = vertex_renderer.glyph;
            const point_cds = vertex_renderer.data_source;
            const pxkey = (0, vectorization_1.isField)(point_glyph.x) ? point_glyph.x.field : null;
            const pykey = (0, vectorization_1.isField)(point_glyph.y) ? point_glyph.y.field : null;
            const data = (0, object_1.dict)(point_cds.data);
            if (pxkey != null) {
                if ((0, types_1.isArray)(xs)) {
                    data.set(pxkey, xs);
                }
                else {
                    point_glyph.x = { value: xs };
                }
            }
            if (pykey != null) {
                if ((0, types_1.isArray)(ys)) {
                    data.set(pykey, ys);
                }
                else {
                    point_glyph.y = { value: ys };
                }
            }
            this._emit_cds_changes(point_cds, true, true, false);
        }
        _hide_vertices() {
            this._set_vertices([], []);
        }
        _snap_to_vertex(ev, x, y) {
            if (this.model.vertex_renderer != null) {
                // If an existing vertex is hit snap to it
                const vertex_selected = this._select_event(ev, "replace", [this.model.vertex_renderer]);
                const point_ds = this.model.vertex_renderer.data_source;
                // Type once dataspecs are typed
                const point_glyph = this.model.vertex_renderer.glyph;
                const pxkey = (0, vectorization_1.isField)(point_glyph.x) ? point_glyph.x.field : null;
                const pykey = (0, vectorization_1.isField)(point_glyph.y) ? point_glyph.y.field : null;
                if (vertex_selected.length != 0) {
                    const index = point_ds.selected.indices[0];
                    const data = (0, object_1.dict)(point_ds.data);
                    if (pxkey != null) {
                        x = data.get(pxkey)[index];
                    }
                    if (pykey != null) {
                        y = data.get(pykey)[index];
                    }
                    point_ds.selection_manager.clear();
                }
            }
            return [x, y];
        }
    }
    exports.PolyToolView = PolyToolView;
    class PolyTool extends edit_tool_1.EditTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Ref, Nullable }) => ({
                vertex_renderer: [Nullable(Ref(glyph_renderer_1.GlyphRenderer)), null],
            }));
        }
    }
    exports.PolyTool = PolyTool;
},
/* models/tools/edit/poly_edit_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const vectorization_1 = require(29) /* ../../../core/vectorization */;
    const assert_1 = require(13) /* ../../../core/util/assert */;
    const types_1 = require(8) /* ../../../core/util/types */;
    const object_1 = require(9) /* ../../../core/util/object */;
    const glyph_renderer_1 = require(302) /* ../../renderers/glyph_renderer */;
    const poly_tool_1 = require(612) /* ./poly_tool */;
    const icons_css_1 = require(76) /* ../../../styles/icons.css */;
    class PolyEditToolView extends poly_tool_1.PolyToolView {
        _selected_renderer;
        _drawing = false;
        _cur_index = null;
        _press(ev) {
            if (this.model.vertex_renderer == null || !this.model.active) {
                return;
            }
            const point = this._map_drag(ev.sx, ev.sy, this.model.vertex_renderer);
            if (point == null) {
                return;
            }
            const [x, y] = point;
            // Perform hit testing
            const vertex_selected = this._select_event(ev, "replace", [this.model.vertex_renderer]);
            const point_cds = this.model.vertex_renderer.data_source;
            // Type once dataspecs are typed
            const point_glyph = this.model.vertex_renderer.glyph;
            const pxkey = (0, vectorization_1.isField)(point_glyph.x) ? point_glyph.x.field : null;
            const pykey = (0, vectorization_1.isField)(point_glyph.y) ? point_glyph.y.field : null;
            if (vertex_selected.length != 0 && this._selected_renderer != null) {
                // Insert a new point after the selected vertex and enter draw mode
                const index = point_cds.selected.indices[0];
                if (this._drawing) {
                    this._drawing = false;
                    point_cds.selection_manager.clear();
                }
                else {
                    point_cds.selected.indices = [index + 1];
                    if (pxkey != null) {
                        point_cds.get_array(pxkey).splice(index + 1, 0, x);
                    }
                    if (pykey != null) {
                        point_cds.get_array(pykey).splice(index + 1, 0, y);
                    }
                    this._drawing = true;
                }
                point_cds.change.emit();
                this._emit_cds_changes(this._selected_renderer.data_source);
            }
            else {
                this._show_vertices(ev);
            }
        }
        _show_vertices(ev) {
            if (!this.model.active) {
                return;
            }
            if (this.model.renderers.length == 0) {
                return;
            }
            const vsync_renderer = this.model.renderers[0];
            const vsync_updater = () => this._update_vertices(vsync_renderer);
            const vsync_ds = vsync_renderer.data_source;
            const renderers = this._select_event(ev, "replace", this.model.renderers);
            if (renderers.length == 0) {
                this._set_vertices([], []);
                this._selected_renderer = null;
                this._drawing = false;
                this._cur_index = null;
                vsync_ds.disconnect(vsync_ds.properties.data.change, vsync_updater);
                return;
            }
            vsync_ds.connect(vsync_ds.properties.data.change, vsync_updater);
            this._cur_index = renderers[0].data_source.selected.indices[0];
            this._update_vertices(renderers[0]);
        }
        _update_vertices(renderer) {
            const { glyph } = renderer;
            const xkey = (0, vectorization_1.isField)(glyph.xs) ? glyph.xs.field : null;
            const ykey = (0, vectorization_1.isField)(glyph.ys) ? glyph.ys.field : null;
            const data = (0, object_1.dict)(renderer.data_source.data);
            const index = this._cur_index;
            if (this._drawing) {
                return;
            }
            if (index == null && (xkey != null || ykey != null)) {
                return;
            }
            let xs;
            let ys;
            if (xkey != null && index != null) { // redundant xkey null check to satisfy build-time checks
                const column = data.get(xkey) ?? [];
                xs = column[index];
                if (!(0, types_1.isArray)(xs)) {
                    column[index] = xs = Array.from(xs);
                }
            }
            else {
                (0, assert_1.assert)((0, vectorization_1.isValue)(glyph.xs));
                xs = glyph.xs.value; // TODO this cast is wrong
            }
            if (ykey != null && index != null) {
                const column = data.get(ykey) ?? [];
                ys = column[index];
                if (!(0, types_1.isArray)(ys)) {
                    column[index] = ys = Array.from(ys);
                }
            }
            else {
                (0, assert_1.assert)((0, vectorization_1.isValue)(glyph.ys));
                ys = glyph.ys.value; // TODO this cast is wrong
            }
            this._selected_renderer = renderer;
            this._set_vertices(xs, ys);
        }
        _move(ev) {
            if (this._drawing && this._selected_renderer != null) {
                const renderer = this.model.vertex_renderer;
                if (renderer == null) {
                    return;
                }
                const cds = renderer.data_source;
                const data = (0, object_1.dict)(cds.data);
                const { glyph } = renderer;
                const point = this._map_drag(ev.sx, ev.sy, renderer);
                if (point == null) {
                    return;
                }
                let [x, y] = point;
                const indices = cds.selected.indices;
                [x, y] = this._snap_to_vertex(ev, x, y);
                cds.selected.indices = indices;
                const xkey = (0, vectorization_1.isField)(glyph.x) ? glyph.x.field : null;
                const ykey = (0, vectorization_1.isField)(glyph.y) ? glyph.y.field : null;
                const index = indices[0];
                if (xkey != null) {
                    data.get(xkey)[index] = x;
                }
                if (ykey != null) {
                    data.get(ykey)[index] = y;
                }
                cds.change.emit();
                this._selected_renderer.data_source.change.emit();
            }
        }
        _tap(ev) {
            const renderer = this.model.vertex_renderer;
            if (renderer == null) {
                return;
            }
            const point = this._map_drag(ev.sx, ev.sy, renderer);
            if (point == null) {
                return;
            }
            else if (this._drawing && this._selected_renderer != null) {
                let [x, y] = point;
                const cds = renderer.data_source;
                // Type once dataspecs are typed
                const { glyph } = renderer;
                const xkey = (0, vectorization_1.isField)(glyph.x) ? glyph.x.field : null;
                const ykey = (0, vectorization_1.isField)(glyph.y) ? glyph.y.field : null;
                const indices = cds.selected.indices;
                [x, y] = this._snap_to_vertex(ev, x, y);
                const index = indices[0];
                cds.selected.indices = [index + 1];
                if (xkey != null) {
                    const xs = cds.get_array(xkey);
                    const nx = xs[index];
                    xs[index] = x;
                    xs.splice(index + 1, 0, nx);
                }
                if (ykey != null) {
                    const ys = cds.get_array(ykey);
                    const ny = ys[index];
                    ys[index] = y;
                    ys.splice(index + 1, 0, ny);
                }
                cds.change.emit();
                this._emit_cds_changes(this._selected_renderer.data_source, true, false, true);
                return;
            }
            const mode = this._select_mode(ev);
            this._select_event(ev, mode, [renderer]);
            this._select_event(ev, mode, this.model.renderers);
        }
        _remove_vertex() {
            if (!this._drawing || this._selected_renderer == null) {
                return;
            }
            const renderer = this.model.vertex_renderer;
            if (renderer == null) {
                return;
            }
            const { glyph, data_source } = renderer;
            const index = data_source.selected.indices[0];
            const xkey = (0, vectorization_1.isField)(glyph.x) ? glyph.x.field : null;
            const ykey = (0, vectorization_1.isField)(glyph.y) ? glyph.y.field : null;
            if (xkey != null) {
                data_source.get_array(xkey).splice(index, 1);
            }
            if (ykey != null) {
                data_source.get_array(ykey).splice(index, 1);
            }
            data_source.change.emit();
            this._emit_cds_changes(this._selected_renderer.data_source);
        }
        _pan_start(ev) {
            if (this.model.vertex_renderer == null) {
                return;
            }
            this._select_event(ev, "append", [this.model.vertex_renderer]);
            this._basepoint = [ev.sx, ev.sy];
        }
        _pan(ev) {
            if (this._basepoint == null) {
                return;
            }
            if (this.model.vertex_renderer == null) {
                return;
            }
            this._drag_points(ev, [this.model.vertex_renderer]);
            if (this._selected_renderer != null) {
                this._selected_renderer.data_source.change.emit();
            }
        }
        _pan_end(ev) {
            if (this._basepoint == null) {
                return;
            }
            if (this.model.vertex_renderer == null) {
                return;
            }
            this._drag_points(ev, [this.model.vertex_renderer]);
            this._emit_cds_changes(this.model.vertex_renderer.data_source, false, true, true);
            if (this._selected_renderer != null) {
                this._emit_cds_changes(this._selected_renderer.data_source);
            }
            this._basepoint = null;
        }
        _keyup(ev) {
            if (!this.model.active || !this._mouse_in_frame) {
                return;
            }
            let renderers;
            if (this._selected_renderer != null) {
                const { vertex_renderer } = this.model;
                renderers = vertex_renderer != null ? [vertex_renderer] : [];
            }
            else {
                renderers = this.model.renderers;
            }
            for (const renderer of renderers) {
                if (ev.key == "Backspace") {
                    this._delete_selected(renderer);
                    if (this._selected_renderer != null) {
                        this._emit_cds_changes(this._selected_renderer.data_source);
                    }
                }
                else if (ev.key == "Escape") {
                    if (this._drawing) {
                        this._remove_vertex();
                        this._drawing = false;
                    }
                    else if (this._selected_renderer != null) {
                        this._hide_vertices();
                    }
                    renderer.data_source.selection_manager.clear();
                }
            }
        }
        deactivate() {
            if (this._selected_renderer == null) {
                return;
            }
            else if (this._drawing) {
                this._remove_vertex();
                this._drawing = false;
            }
            this._hide_vertices();
        }
    }
    exports.PolyEditToolView = PolyEditToolView;
    class PolyEditTool extends poly_tool_1.PolyTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = PolyEditToolView;
            this.define(({ List, Ref }) => ({
                renderers: [List(Ref(glyph_renderer_1.GlyphRenderer)), []],
            }));
        }
        tool_name = "Poly Edit Tool";
        tool_icon = icons_css_1.tool_icon_poly_edit;
        event_type = ["tap", "press", "pan", "move"];
        default_order = 4;
    }
    exports.PolyEditTool = PolyEditTool;
},
/* models/tools/gestures/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var box_select_tool_1 = require(615) /* ./box_select_tool */;
    __esExport("BoxSelectTool", box_select_tool_1.BoxSelectTool);
    var box_zoom_tool_1 = require(618) /* ./box_zoom_tool */;
    __esExport("BoxZoomTool", box_zoom_tool_1.BoxZoomTool);
    var gesture_tool_1 = require(390) /* ./gesture_tool */;
    __esExport("GestureTool", gesture_tool_1.GestureTool);
    var lasso_select_tool_1 = require(619) /* ./lasso_select_tool */;
    __esExport("LassoSelectTool", lasso_select_tool_1.LassoSelectTool);
    var pan_tool_1 = require(595) /* ./pan_tool */;
    __esExport("PanTool", pan_tool_1.PanTool);
    var poly_select_tool_1 = require(620) /* ./poly_select_tool */;
    __esExport("PolySelectTool", poly_select_tool_1.PolySelectTool);
    var range_tool_1 = require(621) /* ./range_tool */;
    __esExport("RangeTool", range_tool_1.RangeTool);
    var select_tool_1 = require(617) /* ./select_tool */;
    __esExport("SelectTool", select_tool_1.SelectTool);
    var tap_tool_1 = require(622) /* ./tap_tool */;
    __esExport("TapTool", tap_tool_1.TapTool);
    var wheel_pan_tool_1 = require(624) /* ./wheel_pan_tool */;
    __esExport("WheelPanTool", wheel_pan_tool_1.WheelPanTool);
    var wheel_zoom_tool_1 = require(625) /* ./wheel_zoom_tool */;
    __esExport("WheelZoomTool", wheel_zoom_tool_1.WheelZoomTool);
},
/* models/tools/gestures/box_select_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const region_select_tool_1 = require(616) /* ./region_select_tool */;
    const box_annotation_1 = require(345) /* ../../annotations/box_annotation */;
    const coordinate_1 = require(58) /* ../../coordinates/coordinate */;
    const enums_1 = require(21) /* ../../../core/enums */;
    const icons = tslib_1.__importStar(require(76) /* ../../../styles/icons.css */);
    class BoxSelectToolView extends region_select_tool_1.RegionSelectToolView {
        connect_signals() {
            super.connect_signals();
            const { pan } = this.model.overlay;
            this.connect(pan, ([phase, ev]) => {
                if ((phase == "pan" && this._is_continuous(ev)) || phase == "pan:end") {
                    const { left, top, right, bottom } = this.model.overlay;
                    if (!(left instanceof coordinate_1.Coordinate) && !(top instanceof coordinate_1.Coordinate) && !(right instanceof coordinate_1.Coordinate) && !(bottom instanceof coordinate_1.Coordinate)) {
                        const screen = this._compute_lrtb({ left, right, top, bottom });
                        this._do_select([screen.left, screen.right], [screen.top, screen.bottom], false, this._select_mode(ev));
                    }
                }
            });
            const { active } = this.model.properties;
            this.on_change(active, () => {
                if (!this.model.active && !this.model.persistent) {
                    this._clear_overlay();
                }
            });
        }
        _base_point;
        _compute_limits(curpoint) {
            const frame = this.plot_view.frame;
            const dims = this.model.dimensions;
            let base_point = this._base_point;
            if (this.model.origin == "center") {
                const [cx, cy] = base_point;
                const [dx, dy] = curpoint;
                base_point = [cx - (dx - cx), cy - (dy - cy)];
            }
            return this.model._get_dim_limits(base_point, curpoint, frame, dims);
        }
        _mappers() {
            const mapper = (units, scale, view, canvas) => {
                switch (units) {
                    case "canvas": return canvas;
                    case "screen": return view;
                    case "data": return scale;
                }
            };
            const { overlay } = this.model;
            const { frame, canvas } = this.plot_view;
            const { x_scale, y_scale } = frame;
            const { x_view, y_view } = frame.bbox;
            const { x_screen, y_screen } = canvas.bbox;
            return {
                left: mapper(overlay.left_units, x_scale, x_view, x_screen),
                right: mapper(overlay.right_units, x_scale, x_view, x_screen),
                top: mapper(overlay.top_units, y_scale, y_view, y_screen),
                bottom: mapper(overlay.bottom_units, y_scale, y_view, y_screen),
            };
        }
        _compute_lrtb({ left, right, top, bottom }) {
            const lrtb = this._mappers();
            return {
                left: lrtb.left.compute(left),
                right: lrtb.right.compute(right),
                top: lrtb.top.compute(top),
                bottom: lrtb.bottom.compute(bottom),
            };
        }
        _invert_lrtb({ left, right, top, bottom }) {
            const lrtb = this._mappers();
            return {
                left: lrtb.left.invert(left),
                right: lrtb.right.invert(right),
                top: lrtb.top.invert(top),
                bottom: lrtb.bottom.invert(bottom),
            };
        }
        _pan_start(ev) {
            const { sx, sy } = ev;
            const { frame } = this.plot_view;
            if (!frame.bbox.contains(sx, sy)) {
                return;
            }
            this._clear_other_overlays();
            this._base_point = [sx, sy];
        }
        _pan(ev) {
            if (this._base_point == null) {
                return;
            }
            const { sx, sy } = ev;
            const [sxlim, sylim] = this._compute_limits([sx, sy]);
            const [[left, right], [top, bottom]] = [sxlim, sylim];
            this.model.overlay.update(this._invert_lrtb({ left, right, top, bottom }));
            if (this._is_continuous(ev.modifiers)) {
                this._do_select(sxlim, sylim, false, this._select_mode(ev.modifiers));
            }
        }
        _pan_end(ev) {
            if (this._base_point == null) {
                return;
            }
            const { sx, sy } = ev;
            const [sxlim, sylim] = this._compute_limits([sx, sy]);
            this._do_select(sxlim, sylim, true, this._select_mode(ev.modifiers));
            if (!this.model.persistent) {
                this._clear_overlay();
            }
            this._base_point = null;
            this.plot_view.state.push("box_select", { selection: this.plot_view.get_selection() });
        }
        get _is_selecting() {
            return this._base_point != null;
        }
        _stop() {
            this._clear_overlay();
            this._base_point = null;
        }
        _keyup(ev) {
            if (!this.model.active) {
                return;
            }
            if (ev.key == "Escape") {
                if (this._is_selecting) {
                    this._stop();
                    return;
                }
                if (this.model.overlay.visible) {
                    this._clear_overlay();
                    return;
                }
            }
            super._keyup(ev);
        }
        _clear_selection() {
            if (this.model.overlay.visible) {
                this._clear_overlay();
            }
            else {
                super._clear_selection();
            }
        }
        _do_select([sx0, sx1], [sy0, sy1], final, mode = "replace") {
            const { greedy } = this.model;
            const geometry = { type: "rect", sx0, sx1, sy0, sy1, greedy };
            this._select(geometry, final, mode);
        }
    }
    exports.BoxSelectToolView = BoxSelectToolView;
    const DEFAULT_BOX_OVERLAY = () => {
        return new box_annotation_1.BoxAnnotation({
            syncable: false,
            level: "overlay",
            visible: false,
            editable: true,
            left: NaN,
            right: NaN,
            top: NaN,
            bottom: NaN,
            top_units: "data",
            left_units: "data",
            bottom_units: "data",
            right_units: "data",
            fill_color: "lightgrey",
            fill_alpha: 0.5,
            line_color: "black",
            line_alpha: 1.0,
            line_width: 2,
            line_dash: [4, 4],
        });
    };
    class BoxSelectTool extends region_select_tool_1.RegionSelectTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = BoxSelectToolView;
            this.define(({ Ref }) => ({
                dimensions: [enums_1.Dimensions, "both"],
                overlay: [Ref(box_annotation_1.BoxAnnotation), DEFAULT_BOX_OVERLAY],
                origin: [enums_1.BoxOrigin, "corner"],
            }));
            this.register_alias("box_select", () => new BoxSelectTool());
            this.register_alias("xbox_select", () => new BoxSelectTool({ dimensions: "width" }));
            this.register_alias("ybox_select", () => new BoxSelectTool({ dimensions: "height" }));
        }
        initialize() {
            super.initialize();
            const [resizable, movable] = (() => {
                switch (this.dimensions) {
                    case "width": return ["x", "x"];
                    case "height": return ["y", "y"];
                    case "both": return ["all", "both"];
                }
            })();
            const symmetric = this.origin == "center";
            this.overlay.setv({ resizable, movable, symmetric });
        }
        tool_name = "Box Select";
        event_type = "pan";
        default_order = 30;
        get computed_icon() {
            const icon = super.computed_icon;
            if (icon != null) {
                return icon;
            }
            else {
                switch (this.dimensions) {
                    case "both": return `.${icons.tool_icon_box_select}`;
                    case "width": return `.${icons.tool_icon_x_box_select}`;
                    case "height": return `.${icons.tool_icon_y_box_select}`;
                }
            }
        }
        get tooltip() {
            return this._get_dim_tooltip(this.dimensions);
        }
    }
    exports.BoxSelectTool = BoxSelectTool;
},
/* models/tools/gestures/region_select_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const select_tool_1 = require(617) /* ./select_tool */;
    const enums_1 = require(21) /* ../../../core/enums */;
    class RegionSelectToolView extends select_tool_1.SelectToolView {
        get overlays() {
            return [...super.overlays, this.model.overlay];
        }
        _is_continuous(modifiers) {
            return this.model.continuous != modifiers.alt;
        }
        _select(geometry, final, mode) {
            const renderers_by_source = this._computed_renderers_by_data_source();
            for (const [, renderers] of renderers_by_source) {
                const sm = renderers[0].get_selection_manager();
                const r_views = [];
                for (const r of renderers) {
                    const r_view = this.plot_view.views.find_one(r);
                    if (r_view != null) {
                        r_views.push(r_view);
                    }
                }
                sm.select(r_views, geometry, final, mode);
            }
            this._emit_selection_event(geometry, final);
        }
        _clear_overlay() {
            super._clear_overlay();
            this.model.overlay.clear();
        }
    }
    exports.RegionSelectToolView = RegionSelectToolView;
    class RegionSelectTool extends select_tool_1.SelectTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Bool }) => ({
                mode: [enums_1.RegionSelectionMode, "replace"],
                continuous: [Bool, false],
                persistent: [Bool, false],
                greedy: [Bool, false],
            }));
        }
    }
    exports.RegionSelectTool = RegionSelectTool;
},
/* models/tools/gestures/select_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const gesture_tool_1 = require(390) /* ./gesture_tool */;
    const glyph_renderer_1 = require(302) /* ../../renderers/glyph_renderer */;
    const graph_renderer_1 = require(545) /* ../../renderers/graph_renderer */;
    const data_renderer_1 = require(303) /* ../../renderers/data_renderer */;
    const util_1 = require(120) /* ../../util */;
    const menus_1 = require(380) /* ../../ui/menus */;
    const bokeh_events_1 = require(80) /* ../../../core/bokeh_events */;
    const signaling_1 = require(17) /* ../../../core/signaling */;
    const assert_1 = require(13) /* ../../../core/util/assert */;
    const array_1 = require(10) /* ../../../core/util/array */;
    const icons = tslib_1.__importStar(require(76) /* ../../../styles/icons.css */);
    class SelectToolView extends gesture_tool_1.GestureToolView {
        connect_signals() {
            super.connect_signals();
            this.model.invert.connect(() => this._invert_selection());
            this.model.clear.connect(() => this._clear_selection());
        }
        get computed_renderers() {
            const { renderers } = this.model;
            const all_renderers = this.plot_view.model.data_renderers;
            return (0, util_1.compute_renderers)(renderers, all_renderers);
        }
        _computed_renderers_by_data_source() {
            const renderers_by_source = new Map();
            for (const r of this.computed_renderers) {
                let source;
                if (r instanceof glyph_renderer_1.GlyphRenderer) {
                    source = r.data_source;
                }
                else if (r instanceof graph_renderer_1.GraphRenderer) {
                    source = r.node_renderer.data_source;
                }
                else {
                    continue;
                }
                const renderers = renderers_by_source.get(source) ?? [];
                renderers_by_source.set(source, [...renderers, r]);
            }
            return renderers_by_source;
        }
        _clear_overlay() { }
        _clear_other_overlays() {
            for (const view of this.plot_view.tool_views.values()) {
                if (view instanceof SelectToolView && view != this) {
                    view._clear_overlay();
                }
            }
        }
        _clear_selection() {
            const { computed_renderers } = this;
            const selection_managers = (0, array_1.uniq)(computed_renderers.map((r) => r.selection_manager));
            for (const selection_manager of selection_managers) {
                selection_manager.clear();
            }
            this.plot_view.request_paint(...computed_renderers);
        }
        _invert_selection() {
            const { computed_renderers } = this;
            const selection_managers = (0, array_1.uniq)(computed_renderers.map((r) => r.selection_manager));
            for (const selection_manager of selection_managers) {
                selection_manager.invert();
            }
            this.plot_view.request_paint(...computed_renderers);
        }
        _select_mode(modifiers) {
            const { shift, ctrl } = modifiers;
            if (!shift && !ctrl) {
                return this.model.mode;
            }
            else if (shift && !ctrl) {
                return "append";
            }
            else if (!shift && ctrl) {
                return "intersect";
            }
            else if (shift && ctrl) {
                return "subtract";
            }
            else {
                (0, assert_1.unreachable)();
            }
        }
        _keyup(ev) {
            if (!this.model.active) {
                return;
            }
            if (ev.key == "Escape") {
                this._clear_selection();
            }
        }
        _emit_selection_event(geometry, final = true) {
            const { x_scale, y_scale } = this.plot_view.frame;
            const geometry_data = (() => {
                switch (geometry.type) {
                    case "point": {
                        const { sx, sy } = geometry;
                        const x = x_scale.invert(sx);
                        const y = y_scale.invert(sy);
                        return { ...geometry, x, y };
                    }
                    case "span": {
                        const { sx, sy } = geometry;
                        const x = x_scale.invert(sx);
                        const y = y_scale.invert(sy);
                        return { ...geometry, x, y };
                    }
                    case "rect": {
                        const { sx0, sx1, sy0, sy1 } = geometry;
                        const [x0, x1] = x_scale.r_invert(sx0, sx1);
                        const [y0, y1] = y_scale.r_invert(sy0, sy1);
                        return { ...geometry, x0, y0, x1, y1 };
                    }
                    case "poly": {
                        const { sx, sy } = geometry;
                        const x = x_scale.v_invert(sx);
                        const y = y_scale.v_invert(sy);
                        return { ...geometry, x, y };
                    }
                }
            })();
            this.plot_view.model.trigger_event(new bokeh_events_1.SelectionGeometry(geometry_data, final));
        }
    }
    exports.SelectToolView = SelectToolView;
    class SelectTool extends gesture_tool_1.GestureTool {
        invert = new signaling_1.Signal0(this, "invert");
        clear = new signaling_1.Signal0(this, "clear");
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ List, Ref, Or, Auto }) => ({
                renderers: [Or(List(Ref(data_renderer_1.DataRenderer)), Auto), "auto"],
            }));
        }
        get menu() {
            return [
                new menus_1.MenuItem({
                    icon: `.${icons.tool_icon_replace_mode}`,
                    label: "Replace mode",
                    tooltip: "Replace the current selection",
                    checked: () => this.mode == "replace",
                    action: () => {
                        this.mode = "replace";
                        this.active = true;
                    },
                }),
                new menus_1.MenuItem({
                    icon: `.${icons.tool_icon_append_mode}`,
                    label: "Append mode",
                    tooltip: "Append to the current selection (Shift)",
                    checked: () => this.mode == "append",
                    action: () => {
                        this.mode = "append";
                        this.active = true;
                    },
                }),
                new menus_1.MenuItem({
                    icon: `.${icons.tool_icon_intersect_mode}`,
                    label: "Intersection mode",
                    tooltip: "Intersect with the current selection (Ctrl)",
                    checked: () => this.mode == "intersect",
                    action: () => {
                        this.mode = "intersect";
                        this.active = true;
                    },
                }),
                new menus_1.MenuItem({
                    icon: `.${icons.tool_icon_subtract_mode}`,
                    label: "Subtraction mode",
                    tooltip: "Subtract from the current selection (Shift+Ctrl)",
                    checked: () => this.mode == "subtract",
                    action: () => {
                        this.mode = "subtract";
                        this.active = true;
                    },
                }),
                new menus_1.MenuItem({
                    icon: `.${icons.tool_icon_xor_mode}`,
                    label: "XOR mode",
                    tooltip: "Symmetric difference with the current selection",
                    checked: () => this.mode == "xor",
                    action: () => {
                        this.mode = "xor";
                        this.active = true;
                    },
                }),
                null,
                new menus_1.MenuItem({
                    icon: `.${icons.tool_icon_invert_selection}`,
                    label: "Invert selection",
                    tooltip: "Invert the current selection",
                    action: () => {
                        this.invert.emit();
                    },
                }),
                new menus_1.MenuItem({
                    icon: `.${icons.tool_icon_clear_selection}`,
                    label: "Clear selection",
                    tooltip: "Clear the current selection and/or selection overlay (Esc)",
                    action: () => {
                        this.clear.emit();
                    },
                }),
            ];
        }
    }
    exports.SelectTool = SelectTool;
},
/* models/tools/gestures/box_zoom_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const gesture_tool_1 = require(390) /* ./gesture_tool */;
    const box_annotation_1 = require(345) /* ../../annotations/box_annotation */;
    const menus_1 = require(380) /* ../../ui/menus */;
    const enums_1 = require(21) /* ../../../core/enums */;
    const icons = tslib_1.__importStar(require(76) /* ../../../styles/icons.css */);
    class BoxZoomToolView extends gesture_tool_1.GestureToolView {
        get overlays() {
            return [...super.overlays, this.model.overlay];
        }
        _base_point = null;
        _match_aspect([bx, by], [cx, cy], frame) {
            // aspect ratio of plot frame
            const a = frame.bbox.aspect;
            const hend = frame.bbox.h_range.end;
            const hstart = frame.bbox.h_range.start;
            const vend = frame.bbox.v_range.end;
            const vstart = frame.bbox.v_range.start;
            // current aspect of cursor-defined box
            let vw = Math.abs(bx - cx);
            let vh = Math.abs(by - cy);
            const va = vh == 0 ? 0 : vw / vh;
            const [xmod] = va >= a ? [1, va / a] : [a / va, 1];
            // OK the code blocks below merit some explanation. They do:
            //
            // compute left/right, pin to frame if necessary
            // compute top/bottom (based on new left/right), pin to frame if necessary
            // recompute left/right (based on top/bottom), in case top/bottom were pinned
            // bx is left
            let left;
            let right;
            if (bx <= cx) {
                left = bx;
                right = bx + vw * xmod;
                if (right > hend) {
                    right = hend;
                }
                // bx is right
            }
            else {
                right = bx;
                left = bx - vw * xmod;
                if (left < hstart) {
                    left = hstart;
                }
            }
            vw = Math.abs(right - left);
            // by is bottom
            let top;
            let bottom;
            if (by <= cy) {
                bottom = by;
                top = by + vw / a;
                if (top > vend) {
                    top = vend;
                }
                // by is top
            }
            else {
                top = by;
                bottom = by - vw / a;
                if (bottom < vstart) {
                    bottom = vstart;
                }
            }
            vh = Math.abs(top - bottom);
            if (bx <= cx) {
                // bx is left
                right = bx + a * vh;
            }
            else {
                // bx is right
                left = bx - a * vh;
            }
            return [[left, right], [bottom, top]];
        }
        _get_dimensions(base_point, curr_point) {
            const { dimensions } = this.model;
            if (dimensions == "auto") {
                const [bx, by] = base_point;
                const [cx, cy] = curr_point;
                const dx = Math.abs(bx - cx);
                const dy = Math.abs(by - cy);
                const tol_d = 15;
                const tol_aspect_ratio = 3;
                if (dx < tol_d && dy > tol_d && dy > tol_aspect_ratio * dx) {
                    return "height";
                }
                else if (dx > tol_d && dy < tol_d && dx > tol_aspect_ratio * dy) {
                    return "width";
                }
                else {
                    return "both";
                }
            }
            else {
                return dimensions;
            }
        }
        _compute_limits(base_point, curr_point) {
            const { frame } = this.plot_view;
            if (this.model.origin == "center") {
                const [cx, cy] = base_point;
                const [dx, dy] = curr_point;
                base_point = [cx - (dx - cx), cy - (dy - cy)];
            }
            const dims = this._get_dimensions(base_point, curr_point);
            if (this.model.match_aspect && dims == "both") {
                return this._match_aspect(base_point, curr_point, frame);
            }
            else {
                return this.model._get_dim_limits(base_point, curr_point, frame, dims);
            }
        }
        _pan_start(ev) {
            const { sx, sy } = ev;
            if (this.plot_view.frame.bbox.contains(sx, sy)) {
                this._base_point = [sx, sy];
            }
        }
        _pan(ev) {
            if (this._base_point == null) {
                return;
            }
            const [sxlim, sylim] = this._compute_limits(this._base_point, [ev.sx, ev.sy]);
            const dims = this._get_dimensions(this._base_point, [ev.sx, ev.sy]);
            const { line_width } = this.model.overlay;
            const [[left, right], [top, bottom]] = this.model._compute_overlay_limits(sxlim, sylim, dims, line_width);
            this.model.overlay.update({ left, right, top, bottom });
        }
        _pan_end(ev) {
            if (this._base_point == null) {
                return;
            }
            const [sx, sy] = this._compute_limits(this._base_point, [ev.sx, ev.sy]);
            this._update(sx, sy);
            this._stop();
        }
        _stop() {
            this.model.overlay.clear();
            this._base_point = null;
        }
        _keydown(ev) {
            if (ev.key == "Escape") {
                this._stop();
            }
        }
        _doubletap(_ev) {
            const { state } = this.plot_view;
            if (state.peek()?.type == "box_zoom") {
                state.undo();
            }
        }
        _update([sx0, sx1], [sy0, sy1]) {
            // If the viewing window is too small, no-op: it is likely that the user did
            // not intend to make this box zoom and instead was trying to cancel out of the
            // zoom, a la matplotlib's ToolZoom. Like matplotlib, set the threshold at 5 pixels.
            if (Math.abs(sx1 - sx0) <= 5 || Math.abs(sy1 - sy0) <= 5) {
                return;
            }
            const { x_scales, y_scales } = this.plot_view.frame;
            const xrs = new Map();
            for (const [, scale] of x_scales) {
                const [start, end] = scale.r_invert(sx0, sx1);
                xrs.set(scale.source_range, { start, end });
            }
            const yrs = new Map();
            for (const [, scale] of y_scales) {
                const [start, end] = scale.r_invert(sy0, sy1);
                yrs.set(scale.source_range, { start, end });
            }
            const zoom_info = { xrs, yrs };
            this.plot_view.state.push("box_zoom", { range: zoom_info });
            this.plot_view.update_range(zoom_info);
            this.plot_view.trigger_ranges_update_event();
        }
    }
    exports.BoxZoomToolView = BoxZoomToolView;
    const DEFAULT_BOX_OVERLAY = () => {
        return new box_annotation_1.BoxAnnotation({
            syncable: false,
            level: "overlay",
            visible: false,
            editable: false,
            left: NaN,
            right: NaN,
            top: NaN,
            bottom: NaN,
            top_units: "canvas",
            left_units: "canvas",
            bottom_units: "canvas",
            right_units: "canvas",
            fill_color: "lightgrey",
            fill_alpha: 0.5,
            line_color: "black",
            line_alpha: 1.0,
            line_width: 2,
            line_dash: [4, 4],
        });
    };
    class BoxZoomTool extends gesture_tool_1.GestureTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = BoxZoomToolView;
            this.define(({ Bool, Ref, Or, Auto }) => ({
                dimensions: [Or(enums_1.Dimensions, Auto), "auto"],
                overlay: [Ref(box_annotation_1.BoxAnnotation), DEFAULT_BOX_OVERLAY],
                match_aspect: [Bool, false],
                origin: [enums_1.BoxOrigin, "corner"],
            }));
            this.register_alias("box_zoom", () => new BoxZoomTool({ dimensions: "both" }));
            this.register_alias("xbox_zoom", () => new BoxZoomTool({ dimensions: "width" }));
            this.register_alias("ybox_zoom", () => new BoxZoomTool({ dimensions: "height" }));
            this.register_alias("auto_box_zoom", () => new BoxZoomTool({ dimensions: "auto" }));
        }
        tool_name = "Box Zoom";
        event_type = ["pan", "doubletap"];
        get event_role() {
            return "pan";
        }
        default_order = 20;
        get computed_icon() {
            const icon = super.computed_icon;
            if (icon != null) {
                return icon;
            }
            else {
                switch (this.dimensions) {
                    case "both": return `.${icons.tool_icon_box_zoom}`;
                    case "width": return `.${icons.tool_icon_x_box_zoom}`;
                    case "height": return `.${icons.tool_icon_y_box_zoom}`;
                    case "auto": return `.${icons.tool_icon_auto_box_zoom}`;
                }
            }
        }
        get tooltip() {
            return this._get_dim_tooltip(this.dimensions);
        }
        get menu() {
            return [
                new menus_1.MenuItem({
                    icon: `.${icons.tool_icon_box_zoom}`,
                    label: "XY mode",
                    tooltip: "Box zoom in both dimensions",
                    checked: () => this.dimensions == "both",
                    action: () => {
                        this.dimensions = "both";
                        this.active = true;
                    },
                }),
                new menus_1.MenuItem({
                    icon: `.${icons.tool_icon_x_box_zoom}`,
                    label: "X-only",
                    tooltip: "Box zoom in x-dimension",
                    checked: () => this.dimensions == "width",
                    action: () => {
                        this.dimensions = "width";
                        this.active = true;
                    },
                }),
                new menus_1.MenuItem({
                    icon: `.${icons.tool_icon_y_box_zoom}`,
                    label: "Y-only",
                    tooltip: "Box zoom in y-dimension",
                    checked: () => this.dimensions == "height",
                    action: () => {
                        this.dimensions = "height";
                        this.active = true;
                    },
                }),
                new menus_1.MenuItem({
                    icon: `.${icons.tool_icon_auto_box_zoom}`,
                    label: "Auto mode",
                    tooltip: "Automatic mode (box zoom in x, y or both dimensions, depending on the mouse gesture)",
                    checked: () => this.dimensions == "auto",
                    action: () => {
                        this.dimensions = "auto";
                        this.active = true;
                    },
                }),
            ];
        }
    }
    exports.BoxZoomTool = BoxZoomTool;
},
/* models/tools/gestures/lasso_select_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const region_select_tool_1 = require(616) /* ./region_select_tool */;
    const poly_annotation_1 = require(370) /* ../../annotations/poly_annotation */;
    const poly_select_tool_1 = require(620) /* ./poly_select_tool */;
    const assert_1 = require(13) /* ../../../core/util/assert */;
    const icons_css_1 = require(76) /* ../../../styles/icons.css */;
    class LassoSelectToolView extends region_select_tool_1.RegionSelectToolView {
        _is_selecting = false;
        _mappers() {
            const mapper = (units, scale, view, canvas) => {
                switch (units) {
                    case "canvas": return canvas;
                    case "screen": return view;
                    case "data": return scale;
                }
            };
            const { overlay } = this.model;
            const { frame, canvas } = this.plot_view;
            const { x_scale, y_scale } = frame;
            const { x_view, y_view } = frame.bbox;
            const { x_screen, y_screen } = canvas.bbox;
            return {
                x: mapper(overlay.xs_units, x_scale, x_view, x_screen),
                y: mapper(overlay.ys_units, y_scale, y_view, y_screen),
            };
        }
        _v_compute(xs, ys) {
            const { x, y } = this._mappers();
            return [x.v_compute(xs), y.v_compute(ys)];
        }
        _v_invert(sxs, sys) {
            const { x, y } = this._mappers();
            return [x.v_invert(sxs), y.v_invert(sys)];
        }
        connect_signals() {
            super.connect_signals();
            const { pan } = this.model.overlay;
            this.connect(pan, ([phase, ev]) => {
                if ((phase == "pan" && this._is_continuous(ev)) || phase == "pan:end") {
                    const { xs, ys } = this.model.overlay;
                    const [sxs, sys] = this._v_compute(xs, ys);
                    this._do_select(sxs, sys, false, this._select_mode(ev));
                }
            });
            const { active } = this.model.properties;
            this.on_change(active, () => {
                if (!this.model.active && !this.model.persistent) {
                    this._clear_overlay();
                }
            });
        }
        _pan_start(ev) {
            const { sx, sy } = ev;
            const { frame } = this.plot_view;
            if (!frame.bbox.contains(sx, sy)) {
                return;
            }
            this._clear_other_overlays();
            this._is_selecting = true;
            const [xs, ys] = this._v_invert([sx], [sy]);
            this.model.overlay.update({ xs, ys });
        }
        _pan(ev) {
            (0, assert_1.assert)(this._is_selecting);
            const [sxs, sys] = (() => {
                const { xs, ys } = this.model.overlay;
                const [sxs, sys] = this._v_compute(xs, ys);
                return [[...sxs], [...sys]];
            })();
            const [sx, sy] = this.plot_view.frame.bbox.clip(ev.sx, ev.sy);
            sxs.push(sx);
            sys.push(sy);
            const [xs, ys] = this._v_invert(sxs, sys);
            this.model.overlay.update({ xs, ys });
            if (this._is_continuous(ev.modifiers)) {
                this._do_select(sxs, sys, false, this._select_mode(ev.modifiers));
            }
        }
        _pan_end(ev) {
            (0, assert_1.assert)(this._is_selecting);
            this._is_selecting = false;
            const { xs, ys } = this.model.overlay;
            const [sxs, sys] = this._v_compute(xs, ys);
            this._do_select(sxs, sys, true, this._select_mode(ev.modifiers));
            this.plot_view.state.push("lasso_select", { selection: this.plot_view.get_selection() });
            if (!this.model.persistent) {
                this._clear_overlay();
            }
        }
        _keyup(ev) {
            if (!this.model.active) {
                return;
            }
            if (ev.key == "Escape") {
                if (this.model.overlay.visible) {
                    this._clear_overlay();
                    return;
                }
            }
            super._keyup(ev);
        }
        _clear_selection() {
            if (this.model.overlay.visible) {
                this._clear_overlay();
            }
            else {
                super._clear_selection();
            }
        }
        _do_select(sx, sy, final, mode) {
            const { greedy } = this.model;
            const geometry = { type: "poly", sx, sy, greedy };
            this._select(geometry, final, mode);
        }
    }
    exports.LassoSelectToolView = LassoSelectToolView;
    class LassoSelectTool extends region_select_tool_1.RegionSelectTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = LassoSelectToolView;
            this.define(({ Ref }) => ({
                overlay: [Ref(poly_annotation_1.PolyAnnotation), poly_select_tool_1.DEFAULT_POLY_OVERLAY],
            }));
            this.override({
                continuous: true,
            });
            this.register_alias("lasso_select", () => new LassoSelectTool());
        }
        tool_name = "Lasso Select";
        tool_icon = icons_css_1.tool_icon_lasso_select;
        event_type = "pan";
        default_order = 12;
    }
    exports.LassoSelectTool = LassoSelectTool;
},
/* models/tools/gestures/poly_select_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const region_select_tool_1 = require(616) /* ./region_select_tool */;
    const poly_annotation_1 = require(370) /* ../../annotations/poly_annotation */;
    const icons_css_1 = require(76) /* ../../../styles/icons.css */;
    class PolySelectToolView extends region_select_tool_1.RegionSelectToolView {
        _is_selecting = false;
        _mappers() {
            const mapper = (units, scale, view, canvas) => {
                switch (units) {
                    case "canvas": return canvas;
                    case "screen": return view;
                    case "data": return scale;
                }
            };
            const { overlay } = this.model;
            const { frame, canvas } = this.plot_view;
            const { x_scale, y_scale } = frame;
            const { x_view, y_view } = frame.bbox;
            const { x_screen, y_screen } = canvas.bbox;
            return {
                x: mapper(overlay.xs_units, x_scale, x_view, x_screen),
                y: mapper(overlay.ys_units, y_scale, y_view, y_screen),
            };
        }
        _v_compute(xs, ys) {
            const { x, y } = this._mappers();
            return [x.v_compute(xs), y.v_compute(ys)];
        }
        _v_invert(sxs, sys) {
            const { x, y } = this._mappers();
            return [x.v_invert(sxs), y.v_invert(sys)];
        }
        connect_signals() {
            super.connect_signals();
            const { pan } = this.model.overlay;
            this.connect(pan, ([phase, ev]) => {
                if ((phase == "pan" && this._is_continuous(ev)) || (phase == "pan:end" && !this._is_selecting)) {
                    const { xs, ys } = this.model.overlay;
                    const [sxs, sys] = this._v_compute(xs, ys);
                    this._do_select(sxs, sys, false, this._select_mode(ev));
                }
            });
            const { active } = this.model.properties;
            this.on_change(active, () => {
                if (!this.model.active && !this.model.persistent) {
                    this._clear_overlay();
                }
            });
        }
        _tap(ev) {
            const { sx, sy } = ev;
            const { frame } = this.plot_view;
            if (!frame.bbox.contains(sx, sy)) {
                return;
            }
            this._clear_other_overlays();
            const [sxs, sys] = (() => {
                if (this._is_selecting) {
                    const { xs, ys } = this.model.overlay;
                    const [sxs, sys] = this._v_compute(xs, ys);
                    return [[...sxs], [...sys]];
                }
                else {
                    this._is_selecting = true;
                    return [[], []];
                }
            })();
            sxs.push(sx);
            sys.push(sy);
            const [xs, ys] = this._v_invert(sxs, sys);
            this.model.overlay.update({ xs, ys });
            if (this._is_continuous(ev.modifiers)) {
                this._do_select(sxs, sys, true, this._select_mode(ev.modifiers));
            }
        }
        _finish_selection(ev) {
            this._is_selecting = false;
            const { xs, ys } = this.model.overlay;
            const [sxs, sys] = this._v_compute(xs, ys);
            this._do_select(sxs, sys, true, this._select_mode(ev));
            this.plot_view.state.push("poly_select", { selection: this.plot_view.get_selection() });
            if (!this.model.persistent) {
                this._clear_overlay();
            }
        }
        _press(ev) {
            this._finish_selection(ev.modifiers);
        }
        _keyup(ev) {
            if (!this.model.active) {
                return;
            }
            if (ev.key == "Enter") {
                this._finish_selection(ev.modifiers);
                return;
            }
            if (ev.key == "Escape") {
                if (this.model.overlay.visible) {
                    this._clear_overlay();
                    return;
                }
            }
            super._keyup(ev);
        }
        _clear_selection() {
            if (this.model.overlay.visible) {
                this._clear_overlay();
            }
            else {
                this._is_selecting = false;
                super._clear_selection();
            }
        }
        _clear_overlay() {
            this._is_selecting = false;
            super._clear_overlay();
        }
        _do_select(sx, sy, final, mode) {
            const { greedy } = this.model;
            const geometry = { type: "poly", sx, sy, greedy };
            this._select(geometry, final, mode);
        }
    }
    exports.PolySelectToolView = PolySelectToolView;
    const DEFAULT_POLY_OVERLAY = () => {
        return new poly_annotation_1.PolyAnnotation({
            syncable: false,
            level: "overlay",
            visible: false,
            editable: true,
            xs_units: "data",
            ys_units: "data",
            fill_color: "lightgrey",
            fill_alpha: 0.5,
            line_color: "black",
            line_alpha: 1.0,
            line_width: 2,
            line_dash: [4, 4],
        });
    };
    exports.DEFAULT_POLY_OVERLAY = DEFAULT_POLY_OVERLAY;
    class PolySelectTool extends region_select_tool_1.RegionSelectTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = PolySelectToolView;
            this.define(({ Ref }) => ({
                overlay: [Ref(poly_annotation_1.PolyAnnotation), exports.DEFAULT_POLY_OVERLAY],
            }));
            this.register_alias("poly_select", () => new PolySelectTool());
        }
        tool_name = "Poly Select";
        tool_icon = icons_css_1.tool_icon_polygon_select;
        event_type = "tap";
        default_order = 11;
    }
    exports.PolySelectTool = PolySelectTool;
},
/* models/tools/gestures/range_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const gesture_tool_1 = require(390) /* ../gestures/gesture_tool */;
    const on_off_button_1 = require(391) /* ../on_off_button */;
    const box_annotation_1 = require(345) /* ../../annotations/box_annotation */;
    const range_1 = require(110) /* ../../ranges/range */;
    const logging_1 = require(11) /* ../../../core/logging */;
    const assert_1 = require(13) /* ../../../core/util/assert */;
    const types_1 = require(8) /* ../../../core/util/types */;
    const icons_css_1 = require(76) /* ../../../styles/icons.css */;
    const node_1 = require(57) /* ../../coordinates/node */;
    const kinds_1 = require(22) /* ../../../core/kinds */;
    const StartGesture = (0, kinds_1.Enum)("pan", "tap", "none");
    class RangeToolView extends gesture_tool_1.GestureToolView {
        get overlays() {
            return [...super.overlays, this.model.overlay];
        }
        initialize() {
            super.initialize();
            this.model.update_overlay_from_ranges();
        }
        connect_signals() {
            super.connect_signals();
            const update_overlay = () => this.model.update_overlay_from_ranges();
            this.on_transitive_change(this.model.properties.x_range, update_overlay);
            this.on_transitive_change(this.model.properties.y_range, update_overlay);
            this.model.overlay.pan.connect(([state, _]) => {
                if (state == "pan") {
                    this.model.update_ranges_from_overlay();
                }
                else if (state == "pan:end") {
                    const ranges = [this.model.x_range, this.model.y_range].filter((r) => r != null);
                    this.parent.trigger_ranges_update_event(ranges);
                }
            });
            const { active, x_interaction, y_interaction } = this.model.properties;
            this.on_change([active, x_interaction, y_interaction], () => {
                this.model.update_constraints();
            });
        }
        _mappers() {
            const mapper = (units, scale, view, canvas) => {
                switch (units) {
                    case "canvas": return canvas;
                    case "screen": return view;
                    case "data": return scale;
                }
            };
            const { overlay } = this.model;
            const { frame, canvas } = this.plot_view;
            const { x_scale, y_scale } = frame;
            const { x_view, y_view } = frame.bbox;
            const { x_screen, y_screen } = canvas.bbox;
            return {
                left: mapper(overlay.left_units, x_scale, x_view, x_screen),
                right: mapper(overlay.right_units, x_scale, x_view, x_screen),
                top: mapper(overlay.top_units, y_scale, y_view, y_screen),
                bottom: mapper(overlay.bottom_units, y_scale, y_view, y_screen),
            };
        }
        _invert_lrtb({ left, right, top, bottom }) {
            const lrtb = this._mappers();
            const { x_range, y_range } = this.model;
            const has_x = x_range != null;
            const has_y = y_range != null;
            return {
                left: has_x ? lrtb.left.invert(left) : this.model.nodes.left,
                right: has_x ? lrtb.right.invert(right) : this.model.nodes.right,
                top: has_y ? lrtb.top.invert(top) : this.model.nodes.top,
                bottom: has_y ? lrtb.bottom.invert(bottom) : this.model.nodes.bottom,
            };
        }
        _compute_limits(curr_point) {
            const dims = (() => {
                const { x_range, y_range } = this.model;
                const has_x = x_range != null;
                const has_y = y_range != null;
                if (has_x && has_y) {
                    return "both";
                }
                else if (has_x) {
                    return "width";
                }
                else if (has_y) {
                    return "height";
                }
                else {
                    (0, assert_1.unreachable)();
                }
            })();
            (0, assert_1.assert)(this._base_point != null);
            let base_point = this._base_point;
            if (this.model.overlay.symmetric) {
                const [cx, cy] = base_point;
                const [dx, dy] = curr_point;
                base_point = [cx - (dx - cx), cy - (dy - cy)];
            }
            const { frame } = this.plot_view;
            return this.model._get_dim_limits(base_point, curr_point, frame, dims);
        }
        _base_point;
        _tap(ev) {
            (0, assert_1.assert)(this.model.start_gesture == "tap");
            const { sx, sy } = ev;
            const { frame } = this.plot_view;
            if (!frame.bbox.contains(sx, sy)) {
                return;
            }
            if (this._base_point == null) {
                this._base_point = [sx, sy];
            }
            else {
                this._update_overlay(sx, sy);
                this._base_point = null;
            }
        }
        _move(ev) {
            if (this._base_point != null && this.model.start_gesture == "tap") {
                const { sx, sy } = ev;
                this._update_overlay(sx, sy);
            }
        }
        _pan_start(ev) {
            (0, assert_1.assert)(this.model.start_gesture == "pan");
            (0, assert_1.assert)(this._base_point == null);
            const { sx, sy } = ev;
            const { frame } = this.plot_view;
            if (!frame.bbox.contains(sx, sy)) {
                return;
            }
            this._base_point = [sx, sy];
        }
        _update_overlay(sx, sy) {
            const [sxlim, sylim] = this._compute_limits([sx, sy]);
            const [[left, right], [top, bottom]] = [sxlim, sylim];
            this.model.overlay.update(this._invert_lrtb({ left, right, top, bottom }));
            this.model.update_ranges_from_overlay();
        }
        _pan(ev) {
            if (this._base_point == null) {
                return;
            }
            const { sx, sy } = ev;
            this._update_overlay(sx, sy);
        }
        _pan_end(ev) {
            if (this._base_point == null) {
                return;
            }
            const { sx, sy } = ev;
            this._update_overlay(sx, sy);
            this._base_point = null;
        }
        get _is_selecting() {
            return this._base_point != null;
        }
        _stop() {
            this._base_point = null;
        }
        _keyup(ev) {
            if (!this.model.active) {
                return;
            }
            if (ev.key == "Escape" && this._is_selecting) {
                this._stop();
            }
        }
    }
    exports.RangeToolView = RangeToolView;
    const DEFAULT_RANGE_OVERLAY = () => {
        return new box_annotation_1.BoxAnnotation({
            syncable: false,
            level: "overlay",
            visible: true,
            editable: true,
            propagate_hover: true,
            left: NaN,
            right: NaN,
            top: NaN,
            bottom: NaN,
            left_limit: node_1.Node.frame.left,
            right_limit: node_1.Node.frame.right,
            top_limit: node_1.Node.frame.top,
            bottom_limit: node_1.Node.frame.bottom,
            fill_color: "lightgrey",
            fill_alpha: 0.5,
            line_color: "black",
            line_alpha: 1.0,
            line_width: 0.5,
            line_dash: [2, 2],
        });
    };
    class RangeTool extends gesture_tool_1.GestureTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = RangeToolView;
            this.define(({ Bool, Ref, Nullable }) => ({
                x_range: [Nullable(Ref(range_1.Range)), null],
                y_range: [Nullable(Ref(range_1.Range)), null],
                x_interaction: [Bool, true],
                y_interaction: [Bool, true],
                overlay: [Ref(box_annotation_1.BoxAnnotation), DEFAULT_RANGE_OVERLAY],
                start_gesture: [StartGesture, "none"],
            }));
            this.override({
                active: true,
            });
        }
        initialize() {
            super.initialize();
            this.update_constraints();
        }
        update_constraints() {
            this.overlay.editable = this.active;
            const has_x = this.x_range != null && this.x_interaction;
            const has_y = this.y_range != null && this.y_interaction;
            if (has_x && has_y) {
                this.overlay.movable = "both";
                this.overlay.resizable = "all";
            }
            else if (has_x) {
                this.overlay.movable = "x";
                this.overlay.resizable = "x";
            }
            else if (has_y) {
                this.overlay.movable = "y";
                this.overlay.resizable = "y";
            }
            else {
                this.overlay.movable = "none";
                this.overlay.resizable = "none";
            }
            const { x_range, y_range } = this;
            if (x_range != null) {
                this.overlay.min_width = x_range.min_interval ?? 0;
                this.overlay.max_width = x_range.max_interval ?? Infinity;
            }
            if (y_range != null) {
                this.overlay.min_height = y_range.min_interval ?? 0;
                this.overlay.max_height = y_range.max_interval ?? Infinity;
            }
        }
        update_ranges_from_overlay() {
            const { left, right, top, bottom } = this.overlay;
            const { x_range, y_range } = this;
            const affected_plots = new Set();
            const xrs = new Map();
            const yrs = new Map();
            if (x_range != null && this.x_interaction) {
                (0, assert_1.assert)((0, types_1.isNumber)(left) && (0, types_1.isNumber)(right));
                xrs.set(x_range, { start: left, end: right });
                for (const plot of x_range.linked_plots) {
                    affected_plots.add(plot);
                }
            }
            if (y_range != null && this.y_interaction) {
                (0, assert_1.assert)((0, types_1.isNumber)(bottom) && (0, types_1.isNumber)(top));
                yrs.set(y_range, { start: bottom, end: top });
                for (const plot of y_range.linked_plots) {
                    affected_plots.add(plot);
                }
            }
            if (affected_plots.size == 0) {
                for (const [range, { start, end }] of [...xrs, ...yrs]) {
                    range.setv({ start, end });
                }
            }
            else {
                for (const plot of affected_plots) {
                    plot.update_range({ xrs, yrs }, { panning: true, scrolling: true });
                }
            }
        }
        nodes = node_1.Node.frame.freeze();
        update_overlay_from_ranges() {
            const { x_range, y_range } = this;
            const has_x = x_range != null;
            const has_y = y_range != null;
            this.overlay.update({
                left: has_x ? x_range.start : this.nodes.left,
                right: has_x ? x_range.end : this.nodes.right,
                top: has_y ? y_range.end : this.nodes.top,
                bottom: has_y ? y_range.start : this.nodes.bottom,
            });
            if (!has_x && !has_y) {
                logging_1.logger.warn("RangeTool not configured with any Ranges.");
                this.overlay.clear();
            }
        }
        tool_name = "Range Tool";
        tool_icon = icons_css_1.tool_icon_range;
        get event_type() {
            switch (this.start_gesture) {
                case "pan": return "pan";
                case "tap": return ["tap", "move"];
                case "none": return [];
            }
        }
        default_order = 40;
        supports_auto() {
            return true;
        }
        tool_button() {
            return new on_off_button_1.OnOffButton({ tool: this });
        }
    }
    exports.RangeTool = RangeTool;
},
/* models/tools/gestures/tap_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const select_tool_1 = require(617) /* ./select_tool */;
    const common_1 = require(623) /* ./common */;
    const menus_1 = require(380) /* ../../ui/menus */;
    const callbacks_1 = require(51) /* ../../../core/util/callbacks */;
    const enums_1 = require(21) /* ../../../core/enums */;
    const enums_2 = require(21) /* ../../../core/enums */;
    const icons_css_1 = require(76) /* ../../../styles/icons.css */;
    class TapToolView extends select_tool_1.SelectToolView {
        _tap(ev) {
            const is_tap = this.model.gesture == "tap";
            if (is_tap) {
                this._handle_tap(ev);
            }
            return is_tap;
        }
        _doubletap(ev) {
            const is_doubletap = this.model.gesture == "doubletap";
            if (is_doubletap) {
                this._handle_tap(ev);
            }
            return is_doubletap;
        }
        _handle_tap(ev) {
            if (!(0, common_1.satisfies_modifiers)(this.model.modifiers, ev.modifiers)) {
                return;
            }
            const { sx, sy } = ev;
            const { frame } = this.plot_view;
            if (!frame.bbox.contains(sx, sy)) {
                return;
            }
            this._clear_other_overlays();
            const geometry = { type: "point", sx, sy };
            if (this.model.behavior == "select") {
                this._select(geometry, true, this._select_mode(ev.modifiers));
            }
            else {
                this._inspect(geometry, ev.modifiers);
            }
        }
        _select(geometry, final, mode) {
            const renderers_by_source = this._computed_renderers_by_data_source();
            for (const [, renderers] of renderers_by_source) {
                const sm = renderers[0].get_selection_manager();
                const r_views = renderers.map((r) => this.plot_view.views.find_one(r)).filter((r) => r != null);
                const did_hit = sm.select(r_views, geometry, final, mode);
                if (did_hit) {
                    const [rv] = r_views;
                    this._emit_callback(rv, geometry, sm.source);
                }
            }
            this._emit_selection_event(geometry);
            this.plot_view.state.push("tap", { selection: this.plot_view.get_selection() });
        }
        _inspect(geometry, modifiers) {
            for (const r of this.computed_renderers) {
                const rv = this.plot_view.views.find_one(r);
                if (rv == null) {
                    continue;
                }
                const sm = r.get_selection_manager();
                const did_hit = sm.inspect(rv, geometry);
                if (did_hit) {
                    this._emit_callback(rv, geometry, sm.source, modifiers);
                }
            }
        }
        _emit_callback(rv, geometry, source, modifiers) {
            const { callback } = this.model;
            if (callback != null) {
                const x = rv.coordinates.x_scale.invert(geometry.sx);
                const y = rv.coordinates.y_scale.invert(geometry.sy);
                const data = {
                    geometries: { ...geometry, x, y },
                    source,
                    event: { modifiers },
                };
                void (0, callbacks_1.execute)(callback, this.model, data);
            }
        }
    }
    exports.TapToolView = TapToolView;
    class TapTool extends select_tool_1.SelectTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = TapToolView;
            this.define(({ Any, Nullable }) => ({
                mode: [enums_1.SelectionMode, "toggle"],
                behavior: [enums_2.TapBehavior, "select"],
                gesture: [enums_2.TapGesture, "tap"],
                modifiers: [common_1.Modifiers, {}],
                callback: [Nullable(Any /*TODO*/), null],
            }));
            this.register_alias("click", () => new TapTool({ behavior: "inspect" }));
            this.register_alias("tap", () => new TapTool());
            this.register_alias("doubletap", () => new TapTool({ gesture: "doubletap" }));
        }
        tool_name = "Tap";
        tool_icon = icons_css_1.tool_icon_tap_select;
        event_type = "tap";
        default_order = 10;
        get menu() {
            return [
                new menus_1.MenuItem({
                    icon: `.${icons_css_1.tool_icon_toggle_mode}`,
                    label: "Toggle mode",
                    tooltip: "Toggle the current selection",
                    checked: () => this.mode == "toggle",
                    action: () => {
                        this.mode = "toggle";
                        this.active = true;
                    },
                }),
                ...super.menu,
            ];
        }
    }
    exports.TapTool = TapTool;
},
/* models/tools/gestures/common.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.satisfies_modifiers = satisfies_modifiers;
    exports.print_modifiers = print_modifiers;
    const kinds_1 = require(22) /* ../../../core/kinds */;
    exports.Modifiers = (0, kinds_1.PartialStruct)({ shift: kinds_1.Bool, ctrl: kinds_1.Bool, alt: kinds_1.Bool });
    function satisfies_modifiers(expected, received) {
        const { alt, ctrl, shift } = expected;
        if (shift != null && shift != received.shift) {
            return false;
        }
        if (ctrl != null && ctrl != received.ctrl) {
            return false;
        }
        if (alt != null && alt != received.alt) {
            return false;
        }
        return true;
    }
    function print_modifiers(modifiers) {
        const { alt, ctrl, shift } = modifiers;
        const result = [];
        if (alt === true) {
            result.push("alt");
        }
        if (ctrl === true) {
            result.push("ctrl");
        }
        if (shift === true) {
            result.push("shift");
        }
        return result.join(" + ");
    }
},
/* models/tools/gestures/wheel_pan_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const gesture_tool_1 = require(390) /* ./gesture_tool */;
    const common_1 = require(623) /* ./common */;
    const enums_1 = require(21) /* ../../../core/enums */;
    const math_1 = require(12) /* ../../../core/util/math */;
    const icons_css_1 = require(76) /* ../../../styles/icons.css */;
    const pan_tool_1 = require(595) /* ./pan_tool */;
    class WheelPanToolView extends gesture_tool_1.GestureToolView {
        _scroll(ev) {
            const { modifiers } = this.model;
            if (!(0, common_1.satisfies_modifiers)(modifiers, ev.modifiers)) {
                this.plot_view.notify_about(`use ${(0, common_1.print_modifiers)(modifiers)} + scroll to pan`);
                return false;
            }
            // clamp the magnitude of factor, if it is > 1 bad things happen
            const factor = (0, math_1.clamp)(this.model.speed * ev.delta, -0.9, 0.9);
            this._update_ranges(factor);
            return true;
        }
        _update_ranges(factor) {
            const { frame } = this.plot_view;
            const hr = frame.bbox.h_range;
            const vr = frame.bbox.v_range;
            const [sx_low, sx_high] = [hr.start, hr.end];
            const [sy_low, sy_high] = [vr.start, vr.end];
            let xrs;
            let yrs;
            const { x_scales, y_scales } = frame;
            // Here we are a bit careful to only update the range info for dimensions that
            // are "in play". This is to avoid superfluous noise updates to dataranges that
            // would cause windowed auto-ranging to turn off.
            switch (this.model.dimension) {
                case "height": {
                    const sy_range = Math.abs(sy_high - sy_low);
                    const sy0 = sy_low - sy_range * factor;
                    const sy1 = sy_high - sy_range * factor;
                    xrs = new Map();
                    yrs = (0, pan_tool_1.update_ranges)(y_scales, sy0, sy1);
                    break;
                }
                case "width": {
                    const sx_range = Math.abs(sx_high - sx_low);
                    const sx0 = sx_low - sx_range * factor;
                    const sx1 = sx_high - sx_range * factor;
                    xrs = (0, pan_tool_1.update_ranges)(x_scales, sx0, sx1);
                    yrs = new Map();
                    break;
                }
            }
            // OK this sucks we can't set factor independently in each direction. It is used
            // for GMap plots, and GMap plots always preserve aspect, so effective the value
            // of 'dimensions' is ignored.
            const pan_info = { xrs, yrs, factor };
            this.plot_view.state.push("wheel_pan", { range: pan_info });
            this.plot_view.update_range(pan_info, { scrolling: true });
            this.model.document?.interactive_start(this.plot_view.model, () => this.plot_view.trigger_ranges_update_event());
        }
    }
    exports.WheelPanToolView = WheelPanToolView;
    class WheelPanTool extends gesture_tool_1.GestureTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = WheelPanToolView;
            this.define(() => ({
                dimension: [enums_1.Dimension, "width"],
                modifiers: [common_1.Modifiers, {}],
            }));
            this.internal(({ Float }) => ({
                speed: [Float, 1 / 1000],
            }));
            this.register_alias("xwheel_pan", () => new WheelPanTool({ dimension: "width" }));
            this.register_alias("ywheel_pan", () => new WheelPanTool({ dimension: "height" }));
        }
        tool_name = "Wheel Pan";
        tool_icon = icons_css_1.tool_icon_wheel_pan;
        event_type = "scroll";
        default_order = 12;
        get tooltip() {
            return this._get_dim_tooltip(this.dimension);
        }
        supports_auto() {
            const { alt, ctrl, shift } = this.modifiers;
            return alt != null || ctrl != null || shift != null;
        }
    }
    exports.WheelPanTool = WheelPanTool;
},
/* models/tools/gestures/wheel_zoom_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const gesture_tool_1 = require(390) /* ./gesture_tool */;
    const common_1 = require(623) /* ./common */;
    const data_renderer_1 = require(303) /* ../../renderers/data_renderer */;
    const composite_scale_1 = require(117) /* ../../scales/composite_scale */;
    const group_by_1 = require(523) /* ../../misc/group_by */;
    const math_1 = require(12) /* ../../../core/util/math */;
    const zoom_1 = require(602) /* ../../../core/util/zoom */;
    const enums_1 = require(21) /* ../../../core/enums */;
    const logging_1 = require(11) /* ../../../core/logging */;
    const icons_css_1 = require(76) /* ../../../styles/icons.css */;
    const kinds_1 = require(22) /* ../../../core/kinds */;
    const ZoomTogether = (0, kinds_1.Enum)("none", "cross", "all");
    const Renderers = (0, kinds_1.Or)((0, kinds_1.List)((0, kinds_1.Ref)(data_renderer_1.DataRenderer)), kinds_1.Auto);
    class WheelZoomToolView extends gesture_tool_1.GestureToolView {
        _scroll(ev) {
            const { modifiers } = this.model;
            if (!(0, common_1.satisfies_modifiers)(modifiers, ev.modifiers)) {
                this.plot_view.notify_about(`use ${(0, common_1.print_modifiers)(modifiers)} + scroll to zoom`);
                return false;
            }
            const { sx, sy, delta } = ev;
            this.zoom(sx, sy, delta);
            return true;
        }
        _pinch(ev) {
            const { sx, sy, scale } = ev;
            const delta = scale >= 1 ? (scale - 1) * 20.0 : -20.0 / scale;
            this.zoom(sx, sy, delta);
        }
        zoom(sx, sy, delta) {
            const axis_view = this.plot_view.axis_views.find((view) => view.bbox.contains(sx, sy));
            if (axis_view != null && !this.model.zoom_on_axis) {
                return;
            }
            const { frame } = this.plot_view;
            if (axis_view == null && !frame.bbox.contains(sx, sy)) {
                return;
            }
            const [x_frame_scales_, y_frame_scales_] = (() => {
                const x_frame = [...frame.x_scales.values()];
                const y_frame = [...frame.y_scales.values()];
                if (axis_view == null) {
                    return [x_frame, y_frame];
                }
                else {
                    const { zoom_together } = this.model;
                    if (zoom_together == "all") {
                        if (axis_view.dimension == 0) {
                            return [x_frame, []];
                        }
                        else {
                            return [[], y_frame];
                        }
                    }
                    else {
                        const { x_scale, y_scale } = axis_view.coordinates;
                        switch (zoom_together) {
                            case "cross": {
                                return [[x_scale], [y_scale]];
                            }
                            case "none": {
                                if (axis_view.dimension == 0) {
                                    return [[x_scale], []];
                                }
                                else {
                                    return [[], [y_scale]];
                                }
                            }
                        }
                    }
                }
            })();
            const data_renderers = (() => {
                const { renderers } = this.model;
                const data_renderers = new Set(renderers != "auto" ? renderers : this.plot_view.model.data_renderers);
                if (!this.model.hit_test) {
                    return data_renderers;
                }
                else {
                    const collected_renderers = new Set();
                    const hit_renderers = new Set();
                    for (const renderer of data_renderers) {
                        if (renderer.coordinates == null) {
                            collected_renderers.add(renderer);
                            continue;
                        }
                        const geometry = (() => {
                            switch (this.model.hit_test_mode) {
                                case "point": return { type: "point", sx, sy };
                                case "hline": return { type: "span", sx, sy, direction: "v" };
                                case "vline": return { type: "span", sx, sy, direction: "h" };
                            }
                        })();
                        const rv = this.plot_view.views.get_one(renderer);
                        const did_hit = rv.hit_test(geometry);
                        if (did_hit != null && !did_hit.is_empty()) {
                            hit_renderers.add(rv.model);
                        }
                    }
                    if (hit_renderers.size != 0) {
                        const { hit_test_behavior } = this.model;
                        if (hit_test_behavior == "only_hit") {
                            for (const hit of hit_renderers) {
                                collected_renderers.add(hit);
                            }
                        }
                        else {
                            for (const group of hit_test_behavior.query_groups(hit_renderers, data_renderers)) {
                                for (const renderer of group) {
                                    if (renderer instanceof data_renderer_1.DataRenderer && data_renderers.has(renderer)) {
                                        collected_renderers.add(renderer);
                                    }
                                }
                            }
                        }
                    }
                    return [...collected_renderers];
                }
            })();
            const x_frame_scales = new Set(x_frame_scales_);
            const y_frame_scales = new Set(y_frame_scales_);
            const x_renderer_scales = new Set();
            const y_renderer_scales = new Set();
            for (const renderer of data_renderers) {
                if (renderer.coordinates == null) {
                    continue;
                }
                const rv = this.plot_view.views.get_one(renderer);
                const { x_scale, y_scale } = rv.coordinates;
                if (x_scale instanceof composite_scale_1.CompositeScale) {
                    if (x_frame_scales.has(x_scale.target_scale)) {
                        x_renderer_scales.add(x_scale);
                    }
                }
                if (y_scale instanceof composite_scale_1.CompositeScale) {
                    if (y_frame_scales.has(y_scale.target_scale)) {
                        y_renderer_scales.add(y_scale);
                    }
                }
            }
            const [x_all_scales, y_all_scales] = (() => {
                if (this.model.renderers == "auto") {
                    return [
                        new Set([...x_frame_scales, ...x_renderer_scales]),
                        new Set([...y_frame_scales, ...y_renderer_scales]),
                    ];
                }
                else {
                    return [
                        x_renderer_scales,
                        y_renderer_scales,
                    ];
                }
            })();
            const subcoord = { x: false, y: false };
            const traverse = (scale, dim) => {
                const { level } = this.model;
                for (let i = 0; i < level; i++) {
                    if (scale instanceof composite_scale_1.CompositeScale) {
                        subcoord[dim] = true;
                        scale = scale.source_scale;
                    }
                    else {
                        logging_1.logger.warn(`can't reach sub-coordinate level ${level} for ${scale} in ${dim} dimension; stopped at ${i}`);
                        break;
                    }
                }
                if (scale instanceof composite_scale_1.CompositeScale) {
                    return scale.target_scale;
                }
                else {
                    return scale;
                }
            };
            const x_scales = new Set();
            const y_scales = new Set();
            for (const x_scale of x_all_scales) {
                x_scales.add(traverse(x_scale, "x"));
            }
            for (const y_scale of y_all_scales) {
                y_scales.add(traverse(y_scale, "y"));
            }
            const center = (() => {
                const x = subcoord.x ? null : sx;
                const y = subcoord.y ? null : sy;
                if (axis_view != null) {
                    return axis_view.dimension == 0 ? { x, y: null } : { x: null, y };
                }
                else {
                    return { x, y };
                }
            })();
            // restrict to axis configured in tool's dimensions property and if
            // zoom origin is inside of frame range/domain
            const dims = this.model.dimensions;
            const x_axis = dims == "width" || dims == "both";
            const y_axis = dims == "height" || dims == "both";
            const { x_target, y_target } = frame;
            // The interval scaling functions assume factor < 1 (otherwise range
            // start and end can get "flipped"), so clamp to [-0.95, 0.95] here
            const factor = (0, math_1.clamp)(this.model.speed * delta, -0.95, 0.95);
            const zoom_info = (0, zoom_1.scale_range)(x_scales, y_scales, x_target, y_target, factor, x_axis, y_axis, center);
            this.plot_view.state.push("wheel_zoom", { range: zoom_info });
            const { maintain_focus } = this.model;
            this.plot_view.update_range(zoom_info, { scrolling: true, maintain_focus });
            this.model.document?.interactive_start(this.plot_view.model, () => this.plot_view.trigger_ranges_update_event());
        }
    }
    exports.WheelZoomToolView = WheelZoomToolView;
    class WheelZoomTool extends gesture_tool_1.GestureTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = WheelZoomToolView;
            this.define(({ Bool, Float, NonNegative, Int, Ref, Or }) => ({
                dimensions: [enums_1.Dimensions, "both"],
                renderers: [Renderers, "auto"],
                level: [NonNegative(Int), 0],
                hit_test: [Bool, false],
                hit_test_mode: [(0, kinds_1.Enum)("point", "hline", "vline"), "point"],
                hit_test_behavior: [Or(Ref(group_by_1.GroupBy), (0, kinds_1.Enum)("only_hit")), "only_hit"],
                maintain_focus: [Bool, true],
                zoom_on_axis: [Bool, true],
                zoom_together: [ZoomTogether, "all"],
                speed: [Float, 1 / 600],
                modifiers: [common_1.Modifiers, {}],
            }));
            this.register_alias("wheel_zoom", () => new WheelZoomTool({ dimensions: "both" }));
            this.register_alias("xwheel_zoom", () => new WheelZoomTool({ dimensions: "width" }));
            this.register_alias("ywheel_zoom", () => new WheelZoomTool({ dimensions: "height" }));
        }
        tool_name = "Wheel Zoom";
        tool_icon = icons_css_1.tool_icon_wheel_zoom;
        event_type = "scroll";
        default_order = 10;
        get tooltip() {
            return this._get_dim_tooltip(this.dimensions);
        }
        supports_auto() {
            const { alt, ctrl, shift } = this.modifiers;
            return alt != null || ctrl != null || shift != null;
        }
    }
    exports.WheelZoomTool = WheelZoomTool;
},
/* models/tools/inspectors/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var crosshair_tool_1 = require(627) /* ./crosshair_tool */;
    __esExport("CrosshairTool", crosshair_tool_1.CrosshairTool);
    var customjs_hover_1 = require(628) /* ./customjs_hover */;
    __esExport("CustomJSHover", customjs_hover_1.CustomJSHover);
    var hover_tool_1 = require(629) /* ./hover_tool */;
    __esExport("HoverTool", hover_tool_1.HoverTool);
    var inspect_tool_1 = require(392) /* ./inspect_tool */;
    __esExport("InspectTool", inspect_tool_1.InspectTool);
},
/* models/tools/inspectors/crosshair_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const inspect_tool_1 = require(392) /* ./inspect_tool */;
    const span_1 = require(415) /* ../../annotations/span */;
    const enums_1 = require(21) /* ../../../core/enums */;
    const types_1 = require(8) /* ../../../core/util/types */;
    const icons_css_1 = require(76) /* ../../../styles/icons.css */;
    class CrosshairToolView extends inspect_tool_1.InspectToolView {
        _spans;
        get overlays() {
            return [...super.overlays, ...this._spans];
        }
        initialize() {
            super.initialize();
            this._update_overlays();
        }
        connect_signals() {
            super.connect_signals();
            const { overlay, dimensions, line_color, line_width, line_alpha } = this.model.properties;
            this.on_change([overlay, dimensions, line_color, line_width, line_alpha], () => {
                this._update_overlays();
                // TODO: notify change
            });
        }
        _update_overlays() {
            const { overlay } = this.model;
            if (overlay == "auto") {
                const { dimensions, line_color, line_alpha, line_width } = this.model;
                function span(dimension) {
                    return new span_1.Span({
                        dimension,
                        location_units: "canvas",
                        level: "overlay",
                        line_color,
                        line_width,
                        line_alpha,
                    });
                }
                switch (dimensions) {
                    case "width": {
                        this._spans = [span("width")];
                        break;
                    }
                    case "height": {
                        this._spans = [span("height")];
                        break;
                    }
                    case "both": {
                        this._spans = [span("width"), span("height")];
                        break;
                    }
                }
            }
            else if ((0, types_1.isArray)(overlay)) {
                this._spans = [...overlay];
            }
            else {
                this._spans = [overlay];
            }
        }
        _move(ev) {
            if (!this.model.active) {
                return;
            }
            const { sx, sy } = (() => {
                const { sx, sy } = ev;
                if (this.plot_view.frame.bbox.contains(sx, sy)) {
                    return { sx, sy };
                }
                const axis_view = this.plot_view.axis_views.find((view) => view.bbox.contains(sx, sy));
                if (axis_view != null) {
                    switch (axis_view.dimension) {
                        case 0: return { sx, sy: NaN };
                        case 1: return { sx: NaN, sy };
                    }
                }
                return { sx: NaN, sy: NaN };
            })();
            this._update_spans(sx, sy);
        }
        _move_exit(_e) {
            this._update_spans(NaN, NaN);
        }
        _update_spans(sx, sy) {
            const { frame } = this.plot_view;
            function invert(span, sx, sy) {
                const { dimension } = span;
                switch (span.location_units) {
                    case "canvas": {
                        return dimension == "width" ? sy : sx;
                    }
                    case "screen": {
                        const { xview, yview } = frame.bbox;
                        return dimension == "width" ? yview.invert(sy) : xview.invert(sx);
                    }
                    case "data": {
                        const { x_scale, y_scale } = frame;
                        return dimension == "width" ? y_scale.invert(sy) : x_scale.invert(sx);
                    }
                }
            }
            for (const span of this._spans) {
                span.location = invert(span, sx, sy);
            }
        }
    }
    exports.CrosshairToolView = CrosshairToolView;
    class CrosshairTool extends inspect_tool_1.InspectTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = CrosshairToolView;
            this.define(({ Alpha, Float, Color, Auto, Tuple, Ref, Or }) => ({
                overlay: [Or(Auto, Ref(span_1.Span), Tuple(Ref(span_1.Span), Ref(span_1.Span))), "auto"],
                dimensions: [enums_1.Dimensions, "both"],
                line_color: [Color, "black"],
                line_width: [Float, 1],
                line_alpha: [Alpha, 1],
            }));
            this.register_alias("crosshair", () => new CrosshairTool());
            this.register_alias("xcrosshair", () => new CrosshairTool({ dimensions: "width" }));
            this.register_alias("ycrosshair", () => new CrosshairTool({ dimensions: "height" }));
        }
        tool_name = "Crosshair";
        tool_icon = icons_css_1.tool_icon_crosshair;
        get tooltip() {
            return this._get_dim_tooltip(this.dimensions);
        }
    }
    exports.CrosshairTool = CrosshairTool;
},
/* models/tools/inspectors/customjs_hover.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../../model */;
    const object_1 = require(9) /* ../../../core/util/object */;
    const string_1 = require(41) /* ../../../core/util/string */;
    class CustomJSHover extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.define(({ Unknown, Str, Dict }) => ({
                args: [Dict(Unknown), {}],
                code: [Str, ""],
            }));
        }
        get values() {
            return (0, object_1.values)(this.args);
        }
        /*protected*/ _make_code(valname, formatname, varsname, fn) {
            // this relies on keys(args) and values(args) returning keys and values
            // in the same order
            return new Function(...(0, object_1.keys)(this.args), valname, formatname, varsname, (0, string_1.use_strict)(fn));
        }
        format(value, format, special_vars) {
            const formatter = this._make_code("value", "format", "special_vars", this.code);
            return formatter(...this.values, value, format, special_vars);
        }
    }
    exports.CustomJSHover = CustomJSHover;
},
/* models/tools/inspectors/hover_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports._nearest_line_hit = _nearest_line_hit;
    exports._line_hit = _line_hit;
    const tslib_1 = require(1) /* tslib */;
    const build_views_1 = require(69) /* ../../../core/build_views */;
    const dom_1 = require(61) /* ../../../core/dom */;
    const enums_1 = require(21) /* ../../../core/enums */;
    const hittest = tslib_1.__importStar(require(311) /* ../../../core/hittest */);
    const signaling_1 = require(17) /* ../../../core/signaling */;
    const assert_1 = require(13) /* ../../../core/util/assert */;
    const color_1 = require(23) /* ../../../core/util/color */;
    const iterator_1 = require(15) /* ../../../core/util/iterator */;
    const object_1 = require(9) /* ../../../core/util/object */;
    const callbacks_1 = require(51) /* ../../../core/util/callbacks */;
    const customjs_1 = require(423) /* ../../callbacks/customjs */;
    const templating_1 = require(329) /* ../../../core/util/templating */;
    const types_1 = require(8) /* ../../../core/util/types */;
    const icons_css_1 = require(76) /* ../../../styles/icons.css */;
    const styles = tslib_1.__importStar(require(518) /* ../../../styles/tooltips.css */);
    const tooltip_1 = require(516) /* ../../ui/tooltip */;
    const dom_element_1 = require(134) /* ../../dom/dom_element */;
    const placeholder_1 = require(630) /* ../../dom/placeholder */;
    const template_1 = require(631) /* ../../dom/template */;
    const harea_1 = require(317) /* ../../glyphs/harea */;
    const harea_step_1 = require(314) /* ../../glyphs/harea_step */;
    const image_base_1 = require(471) /* ../../glyphs/image_base */;
    const line_1 = require(304) /* ../../glyphs/line */;
    const multi_line_1 = require(478) /* ../../glyphs/multi_line */;
    const step_1 = require(312) /* ../../glyphs/step */;
    const patch_1 = require(313) /* ../../glyphs/patch */;
    const varea_1 = require(319) /* ../../glyphs/varea */;
    const varea_step_1 = require(318) /* ../../glyphs/varea_step */;
    const data_renderer_1 = require(303) /* ../../renderers/data_renderer */;
    const glyph_renderer_1 = require(302) /* ../../renderers/glyph_renderer */;
    const graph_renderer_1 = require(545) /* ../../renderers/graph_renderer */;
    const util_1 = require(120) /* ../../util */;
    const customjs_hover_1 = require(628) /* ./customjs_hover */;
    const inspect_tool_1 = require(392) /* ./inspect_tool */;
    const kinds_1 = require(22) /* ../../../core/kinds */;
    const value_ref_1 = require(633) /* ../../dom/value_ref */;
    const Field = kinds_1.Str;
    const SortDirection = (0, kinds_1.Or)((0, kinds_1.Enum)("ascending", "descending"), (0, kinds_1.Enum)(1, -1));
    const SortColumn = (0, kinds_1.Tuple)(Field, SortDirection);
    const SortBy = (0, kinds_1.Nullable)((0, kinds_1.Or)(Field, (0, kinds_1.List)((0, kinds_1.Or)(Field, SortColumn))));
    function _nearest_line_hit(i, geometry, dx, dy) {
        const p1 = { x: dx[i], y: dy[i] };
        const p2 = { x: dx[i + 1], y: dy[i + 1] };
        const { sx, sy } = geometry;
        const [d1, d2] = (function () {
            if (geometry.type == "span") {
                if (geometry.direction == "h") {
                    return [Math.abs(p1.x - sx), Math.abs(p2.x - sx)];
                }
                else {
                    return [Math.abs(p1.y - sy), Math.abs(p2.y - sy)];
                }
            }
            // point geometry case
            const s = { x: sx, y: sy };
            const d1 = hittest.dist_2_pts(p1, s);
            const d2 = hittest.dist_2_pts(p2, s);
            return [d1, d2];
        })();
        return d1 < d2 ? [[p1.x, p1.y], i] : [[p2.x, p2.y], i + 1];
    }
    function _line_hit(xs, ys, i) {
        return [[xs[i], ys[i]], i];
    }
    const COLOR_RE = /\$color(\[.*\])?:(\w*)/;
    const SWATCH_RE = /\$swatch:(\w*)/;
    class HoverToolView extends inspect_tool_1.InspectToolView {
        _current_sxy = null;
        _current_bbox = null;
        ttmodels = new Map();
        _ttviews = new Map();
        _template_el;
        _template_view;
        children_views() {
            return [...super.children_views(), ...this._ttviews.values(), this._template_view];
        }
        async _update_filters() {
            for (const [_, filter] of (0, object_1.entries)(this.model.filters)) {
                for (const fn of (0, types_1.isArray)(filter) ? filter : [filter]) {
                    if (fn instanceof customjs_1.CustomJS) {
                        await fn.compile();
                    }
                }
            }
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._update_ttmodels();
            const { tooltips } = this.model;
            if (tooltips instanceof dom_element_1.DOMElement) {
                this._template_view = await (0, build_views_1.build_view)(tooltips, { parent: this.plot_view.canvas });
                this._template_view.render();
            }
            await this._update_filters();
        }
        connect_signals() {
            super.connect_signals();
            const plot_renderers = this.plot_view.model.properties.renderers;
            const { renderers, tooltips } = this.model.properties;
            this.on_change(tooltips, () => delete this._template_el);
            this.on_change([plot_renderers, renderers, tooltips], async () => await this._update_ttmodels());
            this.connect(this.plot_view.repainted, () => {
                if (this.model.active && this._current_sxy != null) {
                    const [sx, sy, dims] = this._current_sxy;
                    // Avoid triggering inspections if the bbox moves below, as this can lead to infinite
                    // loops if bbox changes are caused by the inspection itself.
                    if (this._current_bbox != null && this._current_bbox.equals(this.plot_view.frame.bbox)) {
                        this._inspect(sx, sy, dims);
                    }
                }
            });
            const { filters } = this.model.properties;
            this.on_change(filters, () => this._update_filters());
        }
        async _update_ttmodels() {
            const { ttmodels } = this;
            ttmodels.clear();
            const { tooltips } = this.model;
            if (tooltips == null) {
                return;
            }
            const { computed_renderers } = this;
            for (const r of computed_renderers) {
                const tooltip = new tooltip_1.Tooltip({
                    content: document.createElement("div"),
                    attachment: this.model.attachment,
                    show_arrow: this.model.show_arrow,
                    interactive: false,
                    visible: true,
                    position: null,
                });
                if (r instanceof glyph_renderer_1.GlyphRenderer) {
                    ttmodels.set(r, tooltip);
                }
                else if (r instanceof graph_renderer_1.GraphRenderer) {
                    ttmodels.set(r.node_renderer, tooltip);
                    ttmodels.set(r.edge_renderer, tooltip);
                }
            }
            await (0, build_views_1.build_views)(this._ttviews, [...ttmodels.values()], { parent: this.plot_view });
            const glyph_renderers = [...(function* () {
                    for (const r of computed_renderers) {
                        if (r instanceof glyph_renderer_1.GlyphRenderer) {
                            yield r;
                        }
                        else if (r instanceof graph_renderer_1.GraphRenderer) {
                            yield r.node_renderer;
                            yield r.edge_renderer;
                        }
                    }
                })()];
            const slot = this._slots.get(this.update);
            if (slot != null) {
                const except = new Set(glyph_renderers.map((r) => r.data_source));
                signaling_1.Signal.disconnect_receiver(this, slot, except);
            }
            for (const r of glyph_renderers) {
                this.connect(r.data_source.inspect, this.update);
            }
        }
        get computed_renderers() {
            const { renderers } = this.model;
            const all_renderers = this.plot_view.model.data_renderers;
            return (0, util_1.compute_renderers)(renderers, all_renderers);
        }
        _clear() {
            this._inspect(Infinity, Infinity, "xy");
            for (const [, tooltip] of this.ttmodels) {
                tooltip.clear();
            }
        }
        _move(ev) {
            if (!this.model.active) {
                return;
            }
            const { sx, sy } = ev;
            const dims = (() => {
                if (this.plot_view.frame.bbox.contains(sx, sy)) {
                    return "xy";
                }
                const axis_view = this.plot_view.axis_views.find((view) => view.bbox.contains(sx, sy));
                if (axis_view != null) {
                    switch (axis_view.dimension) {
                        case 0: return "x";
                        case 1: return "y";
                    }
                }
                return null;
            })();
            if (dims != null) {
                this._current_sxy = [sx, sy, dims];
                this._current_bbox = this.plot_view.frame.bbox.clone();
                this._inspect(sx, sy, dims);
            }
            else {
                this._clear();
            }
        }
        _move_exit() {
            this._current_sxy = null;
            this._current_bbox = null;
            this._clear();
        }
        _inspect(sx, sy, dims) {
            const geometry = (() => {
                if (this.model.mode == "mouse") {
                    return { type: "point", sx, sy };
                }
                else {
                    const direction = this.model.mode == "vline" ? "h" : "v";
                    return { type: "span", direction, sx, sy };
                }
            })();
            if (isFinite(sx + sy)) {
                switch (geometry.type) {
                    case "point": {
                        if (dims != "xy") {
                            return;
                        }
                        break;
                    }
                    case "span": {
                        if ((dims == "x" || dims == "xy") && geometry.direction == "h") {
                            break;
                        }
                        if ((dims == "y" || dims == "xy") && geometry.direction == "v") {
                            break;
                        }
                        this._clear();
                        return;
                    }
                }
            }
            for (const r of this.computed_renderers) {
                const sm = r.get_selection_manager();
                const rview = this.plot_view.views.find_one(r);
                if (rview != null) {
                    sm.inspect(rview, geometry);
                }
            }
            this._emit_callback(geometry);
        }
        render_entries(renderer, geometry) {
            const selection_manager = renderer.get_selection_manager();
            const fullset_indices = selection_manager.inspectors.get(renderer);
            (0, assert_1.assert)(fullset_indices != null);
            const ds = selection_manager.source;
            const renderer_view = this.plot_view.views.find_one(renderer);
            if (renderer_view == null) {
                return [];
            }
            const { sx, sy } = geometry;
            const xscale = renderer_view.coordinates.x_scale;
            const yscale = renderer_view.coordinates.y_scale;
            const x = xscale.invert(sx);
            const y = yscale.invert(sy);
            const { glyph } = renderer_view;
            const subset_indices = renderer.view.convert_selection_to_subset(fullset_indices);
            const collected = [];
            if (glyph instanceof patch_1.PatchView) {
                const [snap_sx, snap_sy] = [sx, sy];
                const [snap_x, snap_y] = [x, y];
                const vars = {
                    index: null,
                    glyph_view: glyph,
                    type: glyph.model.type,
                    x, y, sx, sy, snap_x, snap_y, snap_sx, snap_sy,
                    name: renderer.name,
                };
                collected.push({ ds, vars });
            }
            else if (glyph instanceof harea_step_1.HAreaStepView ||
                glyph instanceof harea_1.HAreaView ||
                glyph instanceof varea_step_1.VAreaStepView ||
                glyph instanceof varea_1.VAreaView) {
                for (const i of subset_indices.line_indices) {
                    const [snap_x, snap_y] = [x, y];
                    const [snap_sx, snap_sy] = [sx, sy];
                    const vars = {
                        index: i,
                        glyph_view: glyph,
                        type: glyph.model.type,
                        x, y, sx, sy, snap_x, snap_y, snap_sx, snap_sy,
                        name: renderer.name,
                        indices: subset_indices.line_indices,
                    };
                    collected.push({ ds, vars });
                }
            }
            else if (glyph instanceof line_1.LineView || glyph instanceof step_1.StepView) {
                const { line_policy } = this.model;
                for (const i of subset_indices.line_indices) {
                    const [[snap_x, snap_y], [snap_sx, snap_sy], ii] = (() => {
                        const { x, y } = glyph;
                        switch (line_policy) {
                            case "interp": {
                                const [snap_x, snap_y] = glyph.get_interpolation_hit(i, geometry);
                                const snap_sxy = [xscale.compute(snap_x), yscale.compute(snap_y)];
                                return [[snap_x, snap_y], snap_sxy, i];
                            }
                            case "prev": {
                                const [snap_sxy, ii] = _line_hit(glyph.sx, glyph.sy, i);
                                return [[x[i + 1], y[i + 1]], snap_sxy, ii];
                            }
                            case "next": {
                                const [snap_sxy, ii] = _line_hit(glyph.sx, glyph.sy, i + 1);
                                return [[x[i + 1], y[i + 1]], snap_sxy, ii];
                            }
                            case "nearest": {
                                const [snap_sxy, ii] = _nearest_line_hit(i, geometry, glyph.sx, glyph.sy);
                                return [[x[ii], y[ii]], snap_sxy, ii];
                            }
                            case "none": {
                                const xscale = renderer_view.coordinates.x_scale;
                                const yscale = renderer_view.coordinates.y_scale;
                                const x = xscale.invert(sx);
                                const y = yscale.invert(sy);
                                return [[x, y], [sx, sy], i];
                            }
                        }
                    })();
                    const vars = {
                        index: ii,
                        glyph_view: glyph,
                        type: glyph.model.type,
                        x, y, sx, sy, snap_x, snap_y, snap_sx, snap_sy,
                        name: renderer.name,
                        indices: subset_indices.line_indices,
                    };
                    collected.push({ ds, vars });
                }
            }
            else if (glyph instanceof image_base_1.ImageBaseView) {
                for (const image_index of fullset_indices.image_indices) {
                    const [snap_sx, snap_sy] = [sx, sy];
                    const [snap_x, snap_y] = [x, y];
                    const vars = {
                        index: image_index.index,
                        glyph_view: glyph,
                        type: glyph.model.type,
                        x, y, sx, sy, snap_x, snap_y, snap_sx, snap_sy,
                        name: renderer.name,
                        image_index,
                    };
                    collected.push({ ds, vars });
                }
            }
            else {
                for (const i of subset_indices.indices) {
                    // multiglyphs set additional indices, e.g. multiline_indices for different tooltips
                    if (glyph instanceof multi_line_1.MultiLineView && subset_indices.multiline_indices.size != 0) {
                        const { line_policy } = this.model;
                        for (const j of subset_indices.multiline_indices.get(i) ?? []) {
                            const [[snap_x, snap_y], [snap_sx, snap_sy], jj] = (() => {
                                if (line_policy == "interp") {
                                    const [snap_x, snap_y] = glyph.get_interpolation_hit(i, j, geometry);
                                    const snap_sxy = [xscale.compute(snap_x), yscale.compute(snap_y)];
                                    return [[snap_x, snap_y], snap_sxy, j];
                                }
                                const [xs, ys] = [glyph.xs.get(i), glyph.ys.get(i)];
                                if (line_policy == "prev") {
                                    const [snap_sxy, jj] = _line_hit(glyph.sxs.get(i), glyph.sys.get(i), j);
                                    return [[xs[j], ys[j]], snap_sxy, jj];
                                }
                                if (line_policy == "next") {
                                    const [snap_sxy, jj] = _line_hit(glyph.sxs.get(i), glyph.sys.get(i), j + 1);
                                    return [[xs[j], ys[j]], snap_sxy, jj];
                                }
                                if (line_policy == "nearest") {
                                    const [snap_sxy, jj] = _nearest_line_hit(j, geometry, glyph.sxs.get(i), glyph.sys.get(i));
                                    return [[xs[jj], ys[jj]], snap_sxy, jj];
                                }
                                (0, assert_1.unreachable)();
                            })();
                            const index = renderer.view.convert_indices_from_subset([i])[0];
                            const vars = {
                                index,
                                glyph_view: glyph,
                                type: glyph.model.type,
                                x, y, sx, sy, snap_x, snap_y, snap_sx, snap_sy,
                                name: renderer.name,
                                indices: subset_indices.multiline_indices,
                                segment_index: jj,
                            };
                            collected.push({ ds, vars });
                        }
                    }
                    else {
                        // handle non-multiglyphs
                        const snap_x = glyph.x?.[i];
                        const snap_y = glyph.y?.[i];
                        const { point_policy, anchor } = this.model;
                        const [snap_sx, snap_sy] = (function () {
                            if (point_policy == "snap_to_data") {
                                const pt = glyph.get_anchor_point(anchor, i, [sx, sy]);
                                if (pt != null) {
                                    return [pt.x, pt.y];
                                }
                                const ptc = glyph.get_anchor_point("center", i, [sx, sy]);
                                if (ptc != null) {
                                    return [ptc.x, ptc.y];
                                }
                                return [sx, sy];
                            }
                            return [sx, sy];
                        })();
                        const index = renderer.view.convert_indices_from_subset([i])[0];
                        const vars = {
                            index,
                            glyph_view: glyph,
                            type: glyph.model.type,
                            x, y, sx, sy, snap_x, snap_y, snap_sx, snap_sy,
                            name: renderer.name,
                            indices: subset_indices.indices,
                        };
                        collected.push({ ds, vars });
                    }
                }
            }
            const { bbox } = this.plot_view.frame;
            const entries = collected
                .map((entry, i) => ({ ...entry, i }))
                .filter(({ vars }) => bbox.contains(vars.snap_sx, vars.snap_sy))
                .filter(({ ds, vars }) => this._can_render_tooltip(ds, vars))
                .map(({ ds, vars, i }) => ({ html: this._render_tooltips_if_can(ds, vars), vars, i }))
                .filter((entry) => entry.html != null)
                .map((entry, j) => ({ ...entry, j }));
            const { sort_by } = this.model;
            if (sort_by != null) {
                const sign = (dir) => {
                    switch (dir) {
                        case 1:
                        case "ascending": return 1;
                        case -1:
                        case "descending": return -1;
                    }
                };
                const columns = (() => {
                    if ((0, types_1.isString)(sort_by)) {
                        return [[sort_by, 1]];
                    }
                    else {
                        return sort_by.map((val) => {
                            if ((0, types_1.isString)(val)) {
                                return [val, 1];
                            }
                            else {
                                const [field, dir] = val;
                                return [field, sign(dir)];
                            }
                        });
                    }
                })();
                const records = Array.from(entries, ({ vars }) => {
                    const record = new Map();
                    for (const [field] of columns) {
                        const value = this._get_value(field, ds, vars);
                        record.set(field, value);
                    }
                    return record;
                });
                function lookup(i, field) {
                    return records[i].get(field) ?? NaN;
                }
                entries.sort((e0, e1) => {
                    for (const [field, sign] of columns) {
                        const v0 = lookup(e0.j, field);
                        const v1 = lookup(e1.j, field);
                        if (v0 === v1) {
                            continue;
                        }
                        if ((0, types_1.isNumber)(v0) && (0, types_1.isNumber)(v1)) {
                            /* eslint-disable @typescript-eslint/strict-boolean-expressions */
                            return sign * (v0 - v1 || +isNaN(v0) - +isNaN(v1));
                        }
                        else {
                            const result = `${v0}`.localeCompare(`${v1}`);
                            if (result == 0) {
                                continue;
                            }
                            else {
                                return sign * result;
                            }
                        }
                    }
                    return 0;
                });
            }
            const { limit } = this.model;
            if (limit != null) {
                entries.splice(limit);
            }
            return entries; // because filter() can't narrow null
        }
        /**
         * This is used exclusively for testing.
         */
        _current_entries = [];
        _update(renderer, geometry, tooltip) {
            const selection_manager = renderer.get_selection_manager();
            const fullset_indices = selection_manager.inspectors.get(renderer);
            (0, assert_1.assert)(fullset_indices != null);
            // XXX: https://github.com/bokeh/bokeh/pull/11992#pullrequestreview-897552484
            if (fullset_indices.is_empty() && fullset_indices.view == null) {
                this._current_entries = [];
                tooltip.clear();
                return;
            }
            const entries = this.render_entries(renderer, geometry);
            this._current_entries = entries;
            if (entries.length == 0) {
                tooltip.clear();
            }
            else {
                const { content } = tooltip;
                (0, assert_1.assert)(content instanceof Node);
                (0, dom_1.empty)(content);
                for (const { html } of entries) {
                    content.appendChild(html);
                }
                const { vars } = entries.at(-1);
                tooltip.show({ x: vars.snap_sx, y: vars.snap_sy });
            }
        }
        _get_value(field, ds, vars) {
            const [type, name] = (() => {
                switch (field[0]) {
                    case "@": return ["@", field.substring(1)];
                    case "$": return ["$", field.substring(1)];
                    default: return ["@", field];
                }
            })();
            const index = vars.image_index ?? vars.index;
            return (0, templating_1.get_value)(type, name, ds, index, vars);
        }
        _can_render_tooltip(data_source, vars) {
            const { filters } = this.model;
            for (const [field, filter] of (0, object_1.entries)(filters)) {
                const value = this._get_value(field, data_source, vars);
                const index = vars.image_index ?? vars.index;
                const row = index != null ? data_source.get_row(index) : {};
                for (const fn of (0, types_1.isArray)(filter) ? filter : [filter]) {
                    const args = { value, field, row, data_source, vars };
                    const result = (() => {
                        if (fn instanceof customjs_1.CustomJS) {
                            return fn.execute_sync(this.model, args);
                        }
                        else {
                            return (0, callbacks_1.execute_sync)(fn, this.model, args);
                        }
                    })();
                    if ((0, types_1.isBoolean)(result) && !result) {
                        return false;
                    }
                }
            }
            return true;
        }
        update([renderer, { geometry }]) {
            if (!this.model.active) {
                return;
            }
            if (!(geometry.type == "point" || geometry.type == "span")) {
                return;
            }
            if (this.model.muted_policy == "ignore" && renderer.muted) {
                return;
            }
            const tooltip = this.ttmodels.get(renderer);
            if ((0, types_1.is_undefined)(tooltip)) {
                return;
            }
            this._update(renderer, geometry, tooltip);
        }
        _emit_callback(geometry) {
            const { callback } = this.model;
            if (callback == null) {
                return;
            }
            for (const renderer of this.computed_renderers) {
                if (!(renderer instanceof glyph_renderer_1.GlyphRenderer)) {
                    continue;
                }
                const glyph_renderer_view = this.plot_view.views.find_one(renderer);
                if (glyph_renderer_view == null) {
                    continue;
                }
                const { x_scale, y_scale } = glyph_renderer_view.coordinates;
                const x = x_scale.invert(geometry.sx);
                const y = y_scale.invert(geometry.sy);
                const index = renderer.data_source.inspected;
                void (0, callbacks_1.execute)(callback, this.model, {
                    geometry: { x, y, ...geometry },
                    renderer,
                    index,
                });
            }
        }
        _create_template(tooltips) {
            const rows = (0, dom_1.div)({ style: { display: "table", borderSpacing: "2px" } });
            for (const [label] of tooltips) {
                const row = (0, dom_1.div)({ style: { display: "table-row" } });
                rows.appendChild(row);
                const label_cell = (0, dom_1.div)({ style: { display: "table-cell" }, class: styles.tooltip_row_label }, label.length != 0 ? `${label}: ` : "");
                row.appendChild(label_cell);
                const value_el = (0, dom_1.span)();
                value_el.dataset.value = "";
                const swatch_el = (0, dom_1.span)({ class: styles.tooltip_color_block }, " ");
                swatch_el.dataset.swatch = "";
                (0, dom_1.undisplay)(swatch_el);
                const value_cell = (0, dom_1.div)({ style: { display: "table-cell" }, class: styles.tooltip_row_value }, value_el, swatch_el);
                row.appendChild(value_cell);
            }
            return rows;
        }
        _render_template(template, tooltips, ds, index, vars) {
            const el = template.cloneNode(true);
            const value_els = el.querySelectorAll("[data-value]");
            const swatch_els = el.querySelectorAll("[data-swatch]");
            for (const [[, value], j] of (0, iterator_1.enumerate)(tooltips)) {
                const swatch_match = value.match(SWATCH_RE);
                const color_match = value.match(COLOR_RE);
                if (swatch_match == null && color_match == null) {
                    const content = (0, templating_1.replace_placeholders_html)(value.replace("$~", "$data_"), ds, index, this.model.formatters, vars);
                    value_els[j].append(...content);
                    continue;
                }
                if (swatch_match != null) {
                    const [, colname] = swatch_match;
                    const column = ds.get_column(colname);
                    if (column == null) {
                        value_els[j].textContent = `${colname} unknown`;
                    }
                    else {
                        const color = (0, types_1.isNumber)(index) ? column[index] : null;
                        if (color != null) {
                            swatch_els[j].style.backgroundColor = (0, color_1.color2css)(color);
                            (0, dom_1.display)(swatch_els[j]);
                        }
                    }
                }
                if (color_match != null) {
                    const [, opts = "", colname] = color_match;
                    const column = ds.get_column(colname); // XXX: change to columnar ds
                    if (column == null) {
                        value_els[j].textContent = `${colname} unknown`;
                        continue;
                    }
                    const hex = opts.indexOf("hex") >= 0;
                    const swatch = opts.indexOf("swatch") >= 0;
                    const color = (0, types_1.isNumber)(index) ? column[index] : null;
                    if (color == null) {
                        value_els[j].textContent = "(null)";
                        continue;
                    }
                    value_els[j].textContent = hex ? (0, color_1.color2hex)(color) : (0, color_1.color2css)(color); // TODO: color2pretty
                    if (swatch) {
                        swatch_els[j].style.backgroundColor = (0, color_1.color2css)(color);
                        (0, dom_1.display)(swatch_els[j]);
                    }
                }
            }
            return el;
        }
        _render_tooltips_if_can(ds, vars) {
            try {
                return this._render_tooltips(ds, vars);
            }
            catch (error) {
                if (error instanceof templating_1.Skip) {
                    return null;
                }
                else {
                    throw error;
                }
            }
        }
        _render_tooltips(ds, vars) {
            const { tooltips } = this.model;
            // if we have an image_index, that is what replace_placeholders needs
            const index = vars.image_index ?? vars.index;
            if ((0, types_1.isString)(tooltips)) {
                const content = (0, templating_1.replace_placeholders_html)(tooltips, ds, index, this.model.formatters, vars);
                return (0, dom_1.div)(content);
            }
            else if ((0, types_1.isFunction)(tooltips)) {
                return tooltips(ds, vars);
            }
            else if (tooltips instanceof dom_element_1.DOMElement) {
                const { _template_view } = this;
                (0, assert_1.assert)(_template_view != null);
                this._update_template(_template_view, ds, index, vars);
                return _template_view.el.cloneNode(true);
            }
            else if (tooltips != null) {
                const template = this._template_el ?? (this._template_el = this._create_template(tooltips));
                return this._render_template(template, tooltips, ds, index, vars);
            }
            else {
                return null;
            }
        }
        _update_template(template_view, ds, i, vars) {
            const { formatters } = this.model;
            if (template_view instanceof template_1.TemplateView) {
                template_view.update(ds, i, vars, formatters);
            }
            else {
                (0, build_views_1.traverse_views)([template_view], (view) => {
                    if (view instanceof placeholder_1.PlaceholderView) {
                        view.update(ds, i, vars, formatters);
                    }
                });
            }
        }
    }
    exports.HoverToolView = HoverToolView;
    class HoverTool extends inspect_tool_1.InspectTool {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = HoverToolView;
            this.define(({ Any, Bool, Int, Str, Positive, List, Tuple, Dict, Or, Ref, Func, Auto, Nullable }) => ({
                tooltips: [Nullable(Or(Ref(dom_element_1.DOMElement), Str, List(Tuple(Str, Str)), Func())), [
                        ["index", "$index"],
                        ["data (x, y)", "($x, $y)"],
                        ["screen (x, y)", "($sx, $sy)"],
                    ]],
                formatters: [Dict(Or(Ref(customjs_hover_1.CustomJSHover), enums_1.BuiltinFormatter)), {}],
                filters: [Dict(Or(value_ref_1.FilterDef, List(value_ref_1.FilterDef))), {}], // XXX `any` cast because of CustomJS/Func types
                sort_by: [SortBy, null],
                limit: [Nullable(Positive(Int)), null],
                renderers: [Or(List(Ref(data_renderer_1.DataRenderer)), Auto), "auto"],
                mode: [enums_1.HoverMode, "mouse"],
                muted_policy: [enums_1.MutedPolicy, "show"],
                point_policy: [enums_1.PointPolicy, "snap_to_data"],
                line_policy: [enums_1.LinePolicy, "nearest"],
                show_arrow: [Bool, true],
                anchor: [enums_1.Anchor, "center"],
                attachment: [enums_1.TooltipAttachment, "horizontal"],
                callback: [Nullable(Any /*TODO*/), null],
            }));
            this.register_alias("hover", () => new HoverTool());
        }
        tool_name = "Hover";
        tool_icon = icons_css_1.tool_icon_hover;
    }
    exports.HoverTool = HoverTool;
},
/* models/dom/placeholder.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const dom_element_1 = require(134) /* ./dom_element */;
    const customjs_1 = require(423) /* ../callbacks/customjs */;
    const customjs_hover_1 = require(628) /* ../tools/inspectors/customjs_hover */;
    const enums_1 = require(21) /* ../../core/enums */;
    const kinds_1 = require(22) /* ../../core/kinds */;
    exports.Formatter = (0, kinds_1.Or)(enums_1.BuiltinFormatter, (0, kinds_1.Ref)(customjs_1.CustomJS), (0, kinds_1.Ref)(customjs_hover_1.CustomJSHover));
    class PlaceholderView extends dom_element_1.DOMElementView {
        static tag_name = "span";
    }
    exports.PlaceholderView = PlaceholderView;
    class Placeholder extends dom_element_1.DOMElement {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Placeholder = Placeholder;
},
/* models/dom/template.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const dom_element_1 = require(134) /* ./dom_element */;
    const action_1 = require(632) /* ./action */;
    const placeholder_1 = require(630) /* ./placeholder */;
    const build_views_1 = require(69) /* ../../core/build_views */;
    class TemplateView extends dom_element_1.DOMElementView {
        _action_views = new Map();
        get actions() {
            return this.model.actions;
        }
        get action_views() {
            return this.actions.map((model) => this._action_views.get(model)).filter((view) => view != null);
        }
        async _update_actions() {
            await (0, build_views_1.build_views)(this._action_views, this.actions);
        }
        children_views() {
            return [...super.children_views(), ...this.action_views];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._update_actions();
        }
        update(source, i, vars, formatters) {
            (0, build_views_1.traverse_views)([this], (view) => {
                if (view instanceof placeholder_1.PlaceholderView) {
                    view.update(source, i, vars, formatters);
                }
            });
            for (const action of this.action_views) {
                action.update(source, i, vars);
            }
        }
    }
    exports.TemplateView = TemplateView;
    class Template extends dom_element_1.DOMElement {
        static {
            this.prototype.default_view = TemplateView;
            this.define(({ List, Ref }) => ({
                actions: [List(Ref(action_1.Action)), []],
            }));
        }
    }
    exports.Template = Template;
},
/* models/dom/action.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(52) /* ../../model */;
    const view_1 = require(65) /* ../../core/view */;
    class ActionView extends view_1.View {
    }
    exports.ActionView = ActionView;
    class Action extends model_1.Model {
        static __module__ = "bokeh.models.dom";
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Action = Action;
},
/* models/dom/value_ref.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const placeholder_1 = require(630) /* ./placeholder */;
    const customjs_1 = require(423) /* ../callbacks/customjs */;
    const customjs_hover_1 = require(628) /* ../tools/inspectors/customjs_hover */;
    const templating_1 = require(329) /* ../../core/util/templating */;
    const callbacks_1 = require(51) /* ../../core/util/callbacks */;
    const types_1 = require(8) /* ../../core/util/types */;
    const kinds_1 = require(22) /* ../../core/kinds */;
    exports.FilterDef = (0, kinds_1.Or)((0, kinds_1.Func)(), (0, kinds_1.Ref)(customjs_1.CustomJS));
    class ValueRefView extends placeholder_1.PlaceholderView {
        connect_signals() {
            super.connect_signals();
            const { filter } = this.model.properties;
            this.on_change(filter, () => this._update_filter());
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._update_filter();
        }
        async _update_filter() {
            const { filter } = this.model;
            for (const fn of (0, types_1.isArray)(filter) ? filter : [filter]) {
                if (fn instanceof customjs_1.CustomJS) {
                    await fn.compile();
                }
            }
        }
        update(data_source, index, vars, _formatters) {
            const { field, format, formatter, filter } = this.model;
            const value = (0, templating_1._get_column_value)(field, data_source, index);
            const row = index != null ? data_source.get_row(index) : {};
            if (filter != null) {
                for (const fn of (0, types_1.isArray)(filter) ? filter : [filter]) {
                    const args = { value, field, row, data_source, vars };
                    const result = (() => {
                        if (fn instanceof customjs_1.CustomJS) {
                            return fn.execute_sync(this.model, args);
                        }
                        else {
                            return (0, callbacks_1.execute_sync)(fn, this.model, args);
                        }
                    })();
                    if ((0, types_1.isBoolean)(result) && !result) {
                        throw new templating_1.Skip();
                    }
                }
            }
            const render = (output) => {
                if (output == null) {
                    this.el.textContent = templating_1.MISSING;
                }
                else if (output instanceof Node) {
                    this.el.replaceChildren(output);
                }
                else if ((0, types_1.isArray)(output)) {
                    this.el.replaceChildren(...output.map((item) => item instanceof Node ? item : `${item}`));
                }
                else {
                    this.el.textContent = `${output}`;
                }
            };
            if (formatter instanceof customjs_1.CustomJS) {
                void (async () => {
                    const output = await (0, callbacks_1.execute)(formatter, this.model, { value, format, vars });
                    render(output);
                })();
            }
            else {
                const output = (() => {
                    if (format == null) {
                        return templating_1.DEFAULT_FORMATTERS.basic(value, "", vars);
                    }
                    else {
                        if (formatter instanceof customjs_hover_1.CustomJSHover) {
                            return formatter.format(value, format, vars);
                        }
                        else {
                            return templating_1.DEFAULT_FORMATTERS[formatter](value, format, vars);
                        }
                    }
                })();
                render(output);
            }
        }
    }
    exports.ValueRefView = ValueRefView;
    class ValueRef extends placeholder_1.Placeholder {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ValueRefView;
            this.define(({ Str, Nullable, List, Or }) => ({
                field: [Str],
                format: [Nullable(Str), null],
                formatter: [placeholder_1.Formatter, "raw"],
                filter: [Nullable(Or(exports.FilterDef, List(exports.FilterDef))), null], // XXX `any` cast because of CustomJS/Func types
            }));
        }
    }
    exports.ValueRef = ValueRef;
},
/* models/dom/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var action_1 = require(632) /* ./action */;
    __esExport("Action", action_1.Action);
    var color_ref_1 = require(635) /* ./color_ref */;
    __esExport("ColorRef", color_ref_1.ColorRef);
    var dom_element_1 = require(134) /* ./dom_element */;
    __esExport("DOMElement", dom_element_1.DOMElement);
    var dom_node_1 = require(130) /* ./dom_node */;
    __esExport("DOMNode", dom_node_1.DOMNode);
    var elements_1 = require(407) /* ./elements */;
    __esExport("Span", elements_1.Span);
    __esExport("Div", elements_1.Div);
    __esExport("Table", elements_1.Table);
    __esExport("TableRow", elements_1.TableRow);
    var html_1 = require(133) /* ./html */;
    __esExport("HTML", html_1.HTML);
    var index_1 = require(636) /* ./index_ */;
    __esExport("Index", index_1.Index);
    var placeholder_1 = require(630) /* ./placeholder */;
    __esExport("Placeholder", placeholder_1.Placeholder);
    var styles_1 = require(59) /* ./styles */;
    __esExport("Styles", styles_1.Styles);
    var stylesheets_1 = require(60) /* ./stylesheets */;
    __esExport("InlineStyleSheet", stylesheets_1.InlineStyleSheet);
    __esExport("GlobalInlineStyleSheet", stylesheets_1.GlobalInlineStyleSheet);
    __esExport("ImportedStyleSheet", stylesheets_1.ImportedStyleSheet);
    __esExport("GlobalImportedStyleSheet", stylesheets_1.GlobalImportedStyleSheet);
    var template_1 = require(631) /* ./template */;
    __esExport("Template", template_1.Template);
    var text_1 = require(429) /* ./text */;
    __esExport("Text", text_1.Text);
    var toggle_group_1 = require(637) /* ./toggle_group */;
    __esExport("ToggleGroup", toggle_group_1.ToggleGroup);
    var value_of_1 = require(638) /* ./value_of */;
    __esExport("ValueOf", value_of_1.ValueOf);
    var value_ref_1 = require(633) /* ./value_ref */;
    __esExport("ValueRef", value_ref_1.ValueRef);
},
/* models/dom/color_ref.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const value_ref_1 = require(633) /* ./value_ref */;
    const templating_1 = require(329) /* ../../core/util/templating */;
    const dom_1 = require(61) /* ../../core/dom */;
    const styles = tslib_1.__importStar(require(518) /* ../../styles/tooltips.css */);
    class ColorRefView extends value_ref_1.ValueRefView {
        value_el;
        swatch_el;
        connect_signals() {
            super.connect_signals();
            const { hex, swatch } = this.model.properties;
            this.on_change([hex, swatch], () => this.render());
        }
        render() {
            super.render();
            this.value_el = (0, dom_1.span)();
            this.swatch_el = (0, dom_1.span)({ class: styles.tooltip_color_block }, " ");
            this.el.append(this.value_el, this.swatch_el);
        }
        update(source, i, _vars, _formatters) {
            const value = (0, templating_1._get_column_value)(this.model.field, source, i);
            const text = value == null ? "???" : `${value}`;
            this.el.textContent = text;
        }
    }
    exports.ColorRefView = ColorRefView;
    class ColorRef extends value_ref_1.ValueRef {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ColorRefView;
            this.define(({ Bool }) => ({
                hex: [Bool, true],
                swatch: [Bool, true],
            }));
        }
    }
    exports.ColorRef = ColorRef;
},
/* models/dom/index_.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const placeholder_1 = require(630) /* ./placeholder */;
    class IndexView extends placeholder_1.PlaceholderView {
        update(_source, i, _vars, _formatters) {
            this.el.textContent = i == null ? "(null)" : `${i}`;
        }
    }
    exports.IndexView = IndexView;
    class Index extends placeholder_1.Placeholder {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = IndexView;
        }
    }
    exports.Index = Index;
},
/* models/dom/toggle_group.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const action_1 = require(632) /* ./action */;
    const renderer_group_1 = require(129) /* ../renderers/renderer_group */;
    const iterator_1 = require(15) /* ../../core/util/iterator */;
    class ToggleGroupView extends action_1.ActionView {
        update(_source, i, _vars /*, formatters?: Formatters*/) {
            for (const [group, j] of (0, iterator_1.enumerate)(this.model.groups)) {
                group.visible = i == j;
            }
        }
    }
    exports.ToggleGroupView = ToggleGroupView;
    class ToggleGroup extends action_1.Action {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ToggleGroupView;
            this.define(({ List, Ref }) => ({
                groups: [List(Ref(renderer_group_1.RendererGroup)), []],
            }));
        }
    }
    exports.ToggleGroup = ToggleGroup;
},
/* models/dom/value_of.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const dom_element_1 = require(134) /* ./dom_element */;
    const has_props_1 = require(16) /* ../../core/has_props */;
    const customjs_1 = require(423) /* ../callbacks/customjs */;
    const templating_1 = require(329) /* ../../core/util/templating */;
    const callbacks_1 = require(51) /* ../../core/util/callbacks */;
    const types_1 = require(8) /* ../../core/util/types */;
    const enums_1 = require(21) /* ../../core/enums */;
    const kinds_1 = require(22) /* ../../core/kinds */;
    const Formatter = (0, kinds_1.Or)(enums_1.BuiltinFormatter, (0, kinds_1.Ref)(customjs_1.CustomJS));
    class ValueOfView extends dom_element_1.DOMElementView {
        connect_signals() {
            super.connect_signals();
            const fn = () => this.render();
            let prop = null;
            const reconnect = () => {
                if (prop != null) {
                    this.disconnect(prop.change, fn);
                }
                const { obj, attr } = this.model;
                if (attr in obj.properties) {
                    prop = obj.properties[attr];
                    this.connect(prop.change, fn);
                }
                else {
                    prop = null;
                }
            };
            reconnect();
            const { obj, attr } = this.model.properties;
            this.on_change([obj, attr], () => reconnect());
        }
        _render_value(value) {
            const { format, formatter } = this.model;
            const vars = {};
            const render = (contents) => {
                if (contents instanceof Node) {
                    this.el.append(contents);
                }
                else if ((0, types_1.isArray)(contents)) {
                    this.el.append(...contents.map((item) => item instanceof Node ? item : `${item}`));
                }
                else {
                    this.el.textContent = `${contents}`;
                }
            };
            if (formatter instanceof customjs_1.CustomJS) {
                const promise = (async () => {
                    const contents = await (0, callbacks_1.execute)(formatter, this.model, { value, format, vars });
                    render(contents);
                })();
                this._await_ready(promise);
            }
            else {
                const contents = templating_1.DEFAULT_FORMATTERS[formatter](value, format ?? "", vars);
                render(contents);
            }
        }
        render() {
            super.render();
            this.el.style.display = "contents";
            const { obj, attr } = this.model;
            if (attr in obj.properties) {
                const value = obj.properties[attr].get_value();
                this._render_value(value);
            }
            else {
                this.el.textContent = `<not found: ${obj.type}.${attr}>`;
            }
        }
    }
    exports.ValueOfView = ValueOfView;
    class ValueOf extends dom_element_1.DOMElement {
        constructor(attrs) {
            super(attrs);
        }
        static {
            this.prototype.default_view = ValueOfView;
            this.define(({ Str, Ref, Nullable }) => ({
                obj: [Ref(has_props_1.HasProps)],
                attr: [Str],
                format: [Nullable(Str), null],
                formatter: [Formatter, "raw"],
            }));
        }
    }
    exports.ValueOf = ValueOf;
},
], 0, {"main":0,"tslib":1,"index":2,"version":3,"embed/index":4,"document/index":5,"document/document":6,"base":7,"core/util/types":8,"core/util/object":9,"core/util/array":10,"core/logging":11,"core/util/math":12,"core/util/assert":13,"core/util/arrayable":14,"core/util/iterator":15,"core/has_props":16,"core/signaling":17,"core/util/defer":18,"core/util/refs":19,"core/properties":20,"core/enums":21,"core/kinds":22,"core/util/color":23,"core/util/svg_colors":24,"core/types":25,"core/util/bitset":26,"core/util/eq":27,"core/util/platform":28,"core/vectorization":29,"core/settings":30,"core/util/ndarray":31,"core/util/cloneable":32,"core/serialization/index":33,"core/serialization/serializer":34,"core/serialization/buffer":35,"core/util/buffer":36,"core/serialization/reps":38,"core/diagnostics":39,"core/uniforms":40,"core/util/string":41,"document/events":42,"core/util/pretty":43,"core/patching":44,"core/util/set":45,"core/util/typed_array":46,"core/resolvers":47,"core/serialization/deserializer":48,"core/util/slice":49,"core/util/version":50,"core/util/callbacks":51,"model":52,"document/config":53,"models/ui/notifications":54,"models/ui/ui_element":55,"models/ui/styled_element":56,"models/coordinates/node":57,"models/coordinates/coordinate":58,"models/dom/styles":59,"models/dom/stylesheets":60,"core/dom":61,"core/util/bbox":62,"core/css":63,"core/dom_view":64,"core/view":65,"models/coordinates/xy":66,"models/coordinates/indexed":67,"core/view_manager":68,"core/build_views":69,"styles/base.css":70,"core/util/canvas":71,"core/util/svg":72,"core/util/affine":73,"core/util/random":74,"styles/ui.css":75,"styles/icons.css":76,"styles/buttons.css":77,"styles/notifications.css":78,"document/defs":79,"core/bokeh_events":80,"embed/standalone":81,"embed/server":82,"client/connection":83,"protocol/message":84,"protocol/receiver":85,"client/session":86,"embed/dom":87,"embed/notebook":88,"protocol/index":89,"safely":90,"models/main":91,"models/index":92,"models/annotations/index":93,"models/annotations/area_visuals":94,"core/property_mixins":95,"models/annotations/annotation":96,"models/renderers/composite_renderer":97,"models/renderers/renderer":98,"core/visuals/index":99,"core/visuals/line":100,"core/visuals/visual":101,"core/visuals/fill":102,"core/visuals/text":103,"core/visuals/hatch":104,"core/visuals/patterns":105,"core/visuals/image":106,"models/coordinates/coordinate_mapping":107,"models/scales/scale":108,"models/transforms/transform":109,"models/ranges/range":110,"models/ranges/range1d":111,"models/ranges/numerical_range":112,"models/scales/linear_scale":113,"models/scales/continuous_scale":114,"models/scales/log_scale":115,"models/scales/categorical_scale":116,"models/scales/composite_scale":117,"models/ranges/data_range1d":118,"models/ranges/data_range":119,"models/util":120,"models/ranges/factor_range":121,"models/ui/menus/menu":122,"models/ui/menus/menu_item":123,"models/common/kinds":124,"models/callbacks/callback":125,"models/ui/menus/divider_item":126,"models/common/resolve":127,"styles/menus.css":128,"models/renderers/renderer_group":129,"models/dom/dom_node":130,"models/layouts/layout_dom":131,"models/ui/pane":132,"models/dom/html":133,"models/dom/dom_element":134,"core/layout/index":135,"core/layout/types":136,"core/layout/layoutable":137,"core/layout/alignments":138,"core/layout/grid":139,"models/annotations/arrow":140,"models/annotations/data_annotation":141,"models/sources/columnar_data_source":142,"core/selection_manager":143,"models/selections/selection":144,"models/selections/interaction_policy":145,"models/sources/data_source":146,"models/sources/column_data_source":147,"core/util/projections":148,"models/annotations/arrow_head":252,"models/graphics/marking":253,"models/annotations/base_color_bar":254,"models/annotations/title":255,"models/annotations/text_annotation":256,"core/layout/side_panel":257,"models/text/base_text":258,"models/text/utils":259,"models/text/math_text":260,"core/util/image":261,"core/graphics":262,"core/util/text":263,"models/text/providers":264,"core/util/modules":265,"models/text/plain_text":266,"models/common/painting":267,"models/canvas/cartesian_frame":268,"models/canvas/canvas_panel":269,"styles/canvas_panel.css":270,"styles/cartesian_frame.css":271,"models/axes/axis":272,"models/renderers/guide_renderer":273,"models/tickers/ticker":274,"models/formatters/tick_formatter":275,"models/policies/labeling":276,"models/axes/linear_axis":277,"models/axes/continuous_axis":278,"models/formatters/basic_tick_formatter":279,"models/tickers/basic_ticker":280,"models/tickers/adaptive_ticker":281,"models/tickers/continuous_ticker":282,"models/tickers/index":283,"models/tickers/categorical_ticker":284,"models/tickers/composite_ticker":285,"models/tickers/customjs_ticker":286,"models/tickers/datetime_ticker":287,"models/tickers/days_ticker":288,"models/tickers/single_interval_ticker":289,"models/tickers/util":290,"models/tickers/months_ticker":291,"models/tickers/years_ticker":292,"models/tickers/fixed_ticker":293,"models/tickers/log_ticker":294,"models/tickers/mercator_ticker":295,"models/tickers/timedelta_ticker":296,"models/tickers/binned_ticker":297,"models/mappers/scanning_color_mapper":298,"models/mappers/continuous_color_mapper":299,"models/mappers/color_mapper":300,"models/mappers/mapper":301,"models/renderers/glyph_renderer":302,"models/renderers/data_renderer":303,"models/glyphs/line":304,"models/glyphs/xy_glyph":305,"models/glyphs/glyph":306,"core/util/ragged_array":307,"core/util/spatial":308,"models/graphics/decoration":309,"models/glyphs/utils":310,"core/hittest":311,"models/glyphs/step":312,"models/glyphs/patch":313,"models/glyphs/harea_step":314,"models/glyphs/area":315,"core/util/flip_step_mode":316,"models/glyphs/harea":317,"models/glyphs/varea_step":318,"models/glyphs/varea":319,"models/sources/cds_view":320,"core/util/indices":321,"models/filters/filter":322,"models/filters/all_indices":323,"models/filters/intersection_filter":324,"models/filters/composite_filter":325,"models/formatters/index":326,"models/formatters/categorical_tick_formatter":327,"models/formatters/datetime_tick_formatter":328,"core/util/templating":329,"models/formatters/customjs_tick_formatter":333,"models/formatters/log_tick_formatter":334,"models/formatters/mercator_tick_formatter":335,"models/formatters/numeral_tick_formatter":336,"models/formatters/printf_tick_formatter":337,"models/formatters/timedelta_tick_formatter":338,"models/scales/index":339,"models/scales/linear_interpolation_scale":340,"models/ranges/index":341,"core/layout/border":342,"models/annotations/band":343,"models/annotations/upper_lower":344,"models/annotations/box_annotation":345,"models/common/box_kinds":346,"models/annotations/color_bar":347,"models/axes/index":348,"models/axes/categorical_axis":349,"models/axes/datetime_axis":350,"models/axes/log_axis":351,"models/axes/mercator_axis":352,"models/axes/timedelta_axis":353,"models/mappers/index":354,"models/mappers/categorical_color_mapper":355,"models/mappers/categorical_mapper":356,"models/mappers/categorical_marker_mapper":357,"models/mappers/categorical_pattern_mapper":358,"models/mappers/linear_color_mapper":359,"models/mappers/log_color_mapper":360,"models/mappers/eqhist_color_mapper":361,"models/mappers/stack_color_mapper":362,"models/mappers/weighted_stack_color_mapper":363,"models/annotations/contour_color_bar":364,"models/annotations/label":365,"models/annotations/label_set":366,"models/annotations/legend":367,"models/annotations/legend_item":368,"styles/legend.css":369,"models/annotations/poly_annotation":370,"models/annotations/scale_bar":371,"models/annotations/dimensional":372,"models/annotations/size_bar":373,"models/annotations/base_bar":374,"models/glyphs/radial_glyph":375,"models/plots/plot":376,"models/grids/grid":377,"models/tools/toolbar":378,"models/tools/tool":379,"models/ui/menus/index":380,"models/ui/menus/action_item":381,"models/ui/menus/checkable_item":382,"models/tools/tool_proxy":383,"models/tools/tool_group":384,"models/tools/tool_button":385,"core/ui_gestures":386,"core/util/menus":387,"styles/legacy_menus.css":388,"styles/tool_button.css":389,"models/tools/gestures/gesture_tool":390,"models/tools/on_off_button":391,"models/tools/inspectors/inspect_tool":392,"models/tools/actions/action_tool":393,"models/tools/click_button":394,"models/tools/actions/help_tool":395,"styles/toolbar.css":396,"styles/logo.css":397,"models/plots/plot_canvas":398,"models/canvas/canvas":399,"core/ui_events":400,"core/util/wheel":401,"styles/canvas.css":402,"models/tools/tool_menu":403,"models/annotations/toolbar_panel":404,"models/ui/panel":405,"styles/panels.css":406,"models/dom/elements":407,"core/util/throttle":408,"models/plots/range_manager":409,"models/plots/state_manager":410,"styles/plots.css":411,"styles/attribution.css":412,"models/glyphs/circle":413,"models/annotations/slope":414,"models/annotations/span":415,"models/annotations/whisker":416,"models/annotations/html/index":417,"models/annotations/html/label":418,"models/annotations/html/text_annotation":419,"models/annotations/html/label_set":420,"models/annotations/html/title":421,"models/callbacks/index":422,"models/callbacks/customjs":423,"models/callbacks/open_url":424,"models/callbacks/set_value":425,"models/callbacks/toggle_visibility":426,"models/callbacks/open_dialog":427,"models/ui/dialog":428,"models/dom/text":429,"styles/dialogs.css":430,"models/callbacks/close_dialog":431,"models/canvas/index":432,"models/comparisons/index":433,"models/comparisons/comparison":434,"models/comparisons/customjs_compare":435,"models/comparisons/nan_compare":436,"models/coordinates/index":437,"models/expressions/index":438,"models/expressions/expression":439,"models/expressions/customjs_expr":440,"models/expressions/stack":441,"models/expressions/cumsum":442,"models/expressions/minimum":443,"models/expressions/maximum":444,"models/expressions/coordinate_transform":445,"models/expressions/polar":446,"models/filters/index":447,"models/filters/boolean_filter":448,"models/filters/customjs_filter":449,"models/filters/group_filter":450,"models/filters/index_filter":451,"models/filters/inversion_filter":452,"models/filters/union_filter":453,"models/filters/difference_filter":454,"models/filters/symmetric_difference_filter":455,"models/glyphs/index":456,"models/glyphs/annular_wedge":457,"models/glyphs/annulus":458,"models/glyphs/arc":459,"models/glyphs/bezier":460,"core/util/algorithms":461,"models/glyphs/block":462,"models/glyphs/lrtb":463,"models/glyphs/ellipse":464,"models/glyphs/center_rotatable":465,"models/glyphs/hbar":466,"models/glyphs/hex_tile":467,"models/glyphs/hspan":468,"models/glyphs/hstrip":469,"models/glyphs/image":470,"models/glyphs/image_base":471,"models/glyphs/image_rgba":472,"models/glyphs/image_stack":473,"models/glyphs/image_url":474,"models/glyphs/mathml_glyph":475,"models/glyphs/math_text_glyph":476,"models/glyphs/text":477,"models/glyphs/multi_line":478,"models/glyphs/multi_polygons":479,"models/glyphs/ngon":480,"models/glyphs/patches":481,"models/glyphs/quad":482,"models/glyphs/quadratic":483,"models/glyphs/ray":484,"models/glyphs/rect":485,"models/glyphs/scatter":486,"models/glyphs/marker":487,"models/glyphs/defs":488,"models/glyphs/segment":489,"models/glyphs/spline":490,"core/util/interpolation":491,"models/glyphs/tex_glyph":492,"models/glyphs/vbar":493,"models/glyphs/vspan":494,"models/glyphs/vstrip":495,"models/glyphs/wedge":496,"models/graphics/index":497,"models/graphs/index":498,"models/graphs/graph_hit_test_policy":499,"models/graphs/layout_provider":500,"models/graphs/static_layout_provider":501,"models/grids/index":502,"models/layouts/index":503,"models/layouts/column":504,"models/layouts/flex_box":505,"models/layouts/alignments":506,"models/layouts/grid_box":507,"models/layouts/css_grid_box":508,"models/layouts/group_box":509,"styles/group_box.css":510,"models/layouts/hbox":511,"models/layouts/row":512,"models/layouts/scroll_box":513,"models/layouts/spacer":514,"models/layouts/tab_panel":515,"models/ui/tooltip":516,"models/selectors/selector":517,"styles/tooltips.css":518,"models/layouts/tabs":519,"styles/tabs.css":520,"models/layouts/vbox":521,"models/misc/index":522,"models/misc/group_by":523,"models/text/index":524,"models/transforms/index":525,"models/transforms/customjs_transform":526,"models/transforms/dodge":527,"models/transforms/range_transform":528,"models/transforms/interpolator":529,"models/transforms/jitter":530,"models/random/random_generator":531,"models/transforms/linear_interpolator":532,"models/transforms/step_interpolator":533,"models/plots/index":534,"models/plots/gmap_plot":535,"models/plots/gmap_plot_canvas":536,"models/plots/gmap":537,"models/plots/grid_plot":538,"models/plots/figure":539,"models/policies/index":540,"models/random/index":541,"models/random/park_miller_lcg":542,"models/renderers/index":543,"models/renderers/contour_renderer":544,"models/renderers/graph_renderer":545,"models/selections/index":546,"models/selectors/index":547,"models/selectors/by_id":548,"models/selectors/by_class":549,"models/selectors/by_css":550,"models/selectors/by_xpath":551,"models/sources/index":552,"models/sources/server_sent_data_source":553,"models/sources/web_data_source":554,"models/sources/ajax_data_source":555,"models/sources/geojson_data_source":556,"models/tiles/index":557,"models/tiles/bbox_tile_source":558,"models/tiles/mercator_tile_source":559,"models/tiles/tile_source":560,"models/tiles/tile_utils":561,"models/tiles/quadkey_tile_source":562,"models/tiles/tile_renderer":563,"models/tiles/wmts_tile_source":564,"models/tiles/tms_tile_source":565,"models/textures/index":566,"models/textures/canvas_texture":567,"models/textures/texture":568,"models/textures/image_url_texture":569,"models/ui/index":570,"models/ui/icons/index":571,"models/ui/icons/builtin_icon":572,"models/ui/icons/icon":573,"models/ui/icons/svg_icon":574,"models/ui/icons/tabler_icon":575,"models/ui/drawer":576,"styles/drawers.css":577,"models/ui/examiner":578,"models/ui/printers":581,"styles/pretty.css":582,"styles/examiner.css":583,"models/tools/index":587,"models/tools/actions/index":588,"models/tools/actions/copy_tool":589,"models/tools/actions/custom_action":590,"models/tools/actions/fullscreen_tool":591,"models/tools/actions/examine_tool":592,"models/tools/actions/click_pan_tool":593,"models/tools/actions/plot_action_tool":594,"models/tools/gestures/pan_tool":595,"models/tools/actions/redo_tool":596,"models/tools/actions/reset_tool":597,"models/tools/actions/save_tool":598,"models/tools/actions/undo_tool":599,"models/tools/actions/zoom_in_tool":600,"models/tools/actions/zoom_base_tool":601,"core/util/zoom":602,"models/tools/actions/zoom_out_tool":603,"models/tools/edit/index":604,"models/tools/edit/edit_tool":605,"models/tools/edit/box_edit_tool":606,"models/tools/edit/freehand_draw_tool":607,"models/tools/edit/line_edit_tool":608,"models/tools/edit/line_tool":609,"models/tools/edit/point_draw_tool":610,"models/tools/edit/poly_draw_tool":611,"models/tools/edit/poly_tool":612,"models/tools/edit/poly_edit_tool":613,"models/tools/gestures/index":614,"models/tools/gestures/box_select_tool":615,"models/tools/gestures/region_select_tool":616,"models/tools/gestures/select_tool":617,"models/tools/gestures/box_zoom_tool":618,"models/tools/gestures/lasso_select_tool":619,"models/tools/gestures/poly_select_tool":620,"models/tools/gestures/range_tool":621,"models/tools/gestures/tap_tool":622,"models/tools/gestures/common":623,"models/tools/gestures/wheel_pan_tool":624,"models/tools/gestures/wheel_zoom_tool":625,"models/tools/inspectors/index":626,"models/tools/inspectors/crosshair_tool":627,"models/tools/inspectors/customjs_hover":628,"models/tools/inspectors/hover_tool":629,"models/dom/placeholder":630,"models/dom/template":631,"models/dom/action":632,"models/dom/value_ref":633,"models/dom/index":634,"models/dom/color_ref":635,"models/dom/index_":636,"models/dom/toggle_group":637,"models/dom/value_of":638}, {});});
//# sourceMappingURL=bokeh.js.map
