(function () { 'use strict'; function noop() { } function safe_not_equal(a, b) { return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function'); } Promise.resolve(); const subscriber_queue = []; /** * Create a `Writable` store that allows both updating and reading by subscription. * @param {*=}value initial value * @param {StartStopNotifier=}start start and stop notifications for subscriptions */ function writable(value, start = noop) { let stop; const subscribers = new Set(); function set(new_value) { if (safe_not_equal(value, new_value)) { value = new_value; if (stop) { // store is ready const run_queue = !subscriber_queue.length; for (const subscriber of subscribers) { subscriber[1](); subscriber_queue.push(subscriber, value); } if (run_queue) { for (let i = 0; i < subscriber_queue.length; i += 2) { subscriber_queue[i][0](subscriber_queue[i + 1]); } subscriber_queue.length = 0; } } } } function update(fn) { set(fn(value)); } function subscribe(run, invalidate = noop) { const subscriber = [run, invalidate]; subscribers.add(subscriber); if (subscribers.size === 1) { stop = start(set) || noop; } run(value); return () => { subscribers.delete(subscriber); if (subscribers.size === 0) { stop(); stop = null; } }; } return { set, update, subscribe }; } /* Very simple logger interface. Each module is expected to create its own logger by doing e.g.: const logger = getLogger('my-prefix'); and then use it instead of console: logger.info('hello', 'world'); logger.warn('...'); logger.error('...'); The logger automatically adds the prefix "[my-prefix]" to all logs; so e.g., the above call would print: [my-prefix] hello world logger.log is intentionally omitted. The idea is that PyScript should not write anything to console.log, to leave it free for the user. Currently, the logger does not to anything more than that. In the future, we might want to add additional features such as the ability to enable/disable logs on a global or per-module basis. */ const _cache = new Map(); function getLogger(prefix) { let logger = _cache.get(prefix); if (logger === undefined) { logger = _makeLogger(prefix); _cache.set(prefix, logger); } return logger; } function _makeLogger(prefix) { prefix = "[" + prefix + "] "; function make(level) { const out_fn = console[level].bind(console); function fn(fmt, ...args) { out_fn(prefix + fmt, ...args); } return fn; } // 'log' is intentionally omitted const debug = make('debug'); const info = make('info'); const warn = make('warn'); const error = make('error'); return { debug, info, warn, error }; } /* A store for Runtime which can encompass any runtime, but currently only has Pyodide as its offering. */ const runtimeLoaded = writable(); const loadedEnvironments = writable({}); const scriptsQueue = writable([]); const initializers = writable([]); const postInitializers = writable([]); const globalLoader = writable(); const appConfig = writable(); const addToScriptsQueue = (script) => { scriptsQueue.update(scriptsQueue => [...scriptsQueue, script]); }; const addInitializer = (initializer) => { initializers.update(initializers => [...initializers, initializer]); }; const addPostInitializer = (initializer) => { postInitializers.update(postInitializers => [...postInitializers, initializer]); }; // taken from https://github.com/Gin-Quin/fast-toml let e = "", t$1 = 0; function i$2(e, t = 0) { let i; for (; (i = e[t++]) && (" " == i || "\t" == i || "\r" == i);) ; return t - 1; } function n(e) { switch (e[0]) { case void 0: return ""; case '"': return (function (e) { let t, i = 0, n = ""; for (; (t = e.indexOf("\\", i) + 1);) { switch (((n += e.slice(i, t - 1)), e[t])) { case "\\": n += "\\"; break; case '"': n += '"'; break; case "\r": "\n" == e[t + 1] && t++; case "\n": break; case "b": n += "\b"; break; case "t": n += "\t"; break; case "n": n += "\n"; break; case "f": n += "\f"; break; case "r": n += "\r"; break; case "u": (n += String.fromCharCode(parseInt(e.substr(t + 1, 4), 16))), (t += 4); break; case "U": (n += String.fromCharCode(parseInt(e.substr(t + 1, 8), 16))), (t += 8); break; default: throw r(e[t]); } i = t + 1; } return n + e.slice(i); })(e.slice(1, -1)); case "'": return e.slice(1, -1); case "0": case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": case "+": case "-": case ".": let t = e; if ((-1 != t.indexOf("_") && (t = t.replace(/_/g, "")), !isNaN(t))) return +t; if ("-" == e[4] && "-" == e[7]) { let t = new Date(e); if ("Invalid Date" != t.toString()) return t; } else if (":" == e[2] && ":" == e[5] && e.length >= 7) { let t = new Date("0000-01-01T" + e + "Z"); if ("Invalid Date" != t.toString()) return t; } return e; } switch (e) { case "true": return !0; case "false": return !1; case "nan": case "NaN": return !1; case "null": return null; case "inf": case "+inf": case "Infinity": case "+Infinity": return 1 / 0; case "-inf": case "-Infinity": return -1 / 0; } return e; } function r(i) { let n = (function () { let i = e[t$1], n = t$1; "\n" == i && n--; let r = 1, s = e.lastIndexOf("\n", n), a = e.indexOf("\n", n); -1 == a && (a = 1 / 0); ("," != i && "\n" != i) || (n = s + 1); if (-1 == s) return { line: r, column: n + 1, position: n, lineContent: e.slice(0, a).trim() }; const c = n - s + 1, o = e.slice(s + 1, a).trim(); r++; for (; -1 != (s = e.lastIndexOf("\n", s - 1));) r++; return { line: r, column: c, position: n, lineContent: o }; })(), r = String(n.line); return (i += "\n" + r + " | " + n.lineContent + "\n"), (i += " ".repeat(r.length + n.column + 2) + "^"), SyntaxError(i); } function s(e, i = 0, n = !1) { let a, c = e[i], o = c, f = c, l = !0, u = !1; switch (c) { case '"': case "'": if (((a = i + 1), n && e[i + 1] == c && e[i + 2] == c ? ((f = c + c + c), (a += 2)) : (u = !0), "'" == c)) a = e.indexOf(f, a) + 1; else for (; (a = e.indexOf(f, a) + 1);) { let t = !0, i = a - 1; for (; "\\" == e[--i];) t = !t; if (t) break; } if (!a) throw r("Missing " + f + " closer"); if (c != f) a += 2; else if (u) { let n = e.indexOf("\n", i + 1) + 1; if (n && n < a) throw ((t$1 = n - 2), r("Forbidden end-of-line character in single-line string")); } return a; case "(": f = ")"; break; case "{": f = "}"; break; case "[": f = "]"; break; case "<": f = ">"; break; default: l = !1; } let h = 0; for (; (c = e[++i]);) if (c == f) { if (0 == h) return i + 1; h--; } else if ('"' == c || "'" == c) { i = s(e, i, n) - 1; } else l && c == o && h++; throw r("Missing " + f); } function a(e) { "string" != typeof e && (e = String(e)); let t, i, n = -1, a = "", c = []; for (; (i = e[++n]);) switch (i) { case ".": if (!a) throw r('Unexpected "."'); c.push(a), (a = ""); continue; case '"': case "'": if (((t = s(e, n)), t == n + 2)) throw r("Empty string key"); (a += e.slice(n + 1, t - 1)), (n = t - 1); continue; default: a += i; } return a && c.push(a), c; } function c(e, t = []) { const i = t.pop(); for (let i of t) { if ("object" != typeof e) { throw r('["' + t.slice(0, t.indexOf(i) + 1).join('"].["') + '"]' + " must be an object"); } void 0 === e[i] && (e[i] = {}), (e = e[i]) instanceof Array && (e = e[e.length - 1]); } return [e, i]; } class o { root; data; inlineScopeList; constructor() { this.root = {}; this.data = this.root; this.inlineScopeList = []; } get isRoot() { return this.data == this.root; } set(e, t) { let [i, n] = c(this.data, a(e)); if ("string" == typeof i) throw "Wtf the scope is a string. Please report the bug"; if (n in i) throw r(`Re-writing the key '${e}'`); return (i[n] = t), t; } push(e) { if (!(this.data instanceof Array)) { if (!this.isRoot) throw r("Missing key"); (this.data = Object.assign([], this.data)), (this.root = this.data); } return this.data.push(e), this; } use(e) { return ((this.data = (function (e, t = []) { for (let i of t) { //if (void 0 === e) e = lastData[lastElt] = {}; //else if ("object" != typeof e) { throw r('["' + t.slice(0, t.indexOf(i) + 1).join('"].["') + '"]' + " must be an object"); } void 0 === e[i] && (e[i] = {}), (e = e[i]) instanceof Array && (e = e[e.length - 1]); } return e; })(this.root, a(e))), this); } useArray(e) { let [t, i] = c(this.root, a(e)); return (this.data = {}), void 0 === t[i] && (t[i] = []), t[i].push(this.data), this; } enter(e, t) { return this.inlineScopeList.push(this.data), this.set(e, t), (this.data = t), this; } enterArray(e) { return this.inlineScopeList.push(this.data), this.push(e), (this.data = e), this; } exit() { return (this.data = this.inlineScopeList.pop()), this; } } function f(a) { "string" != typeof a && (a = String(a)); const c = new o(), f = []; (e = a), (t$1 = 0); let l, u, h = "", d = "", p = e[0], w = !0; const g = () => { if (((h = h.trimEnd()), w)) h && c.push(n(h)); else { if (!h) throw r("Expected key before ="); if (!d) throw r("Expected value after ="); c.set(h, n(d.trimEnd())); } (h = ""), (d = ""), (w = !0); }; do { switch (p) { case " ": w ? h && (h += p) : d && (d += p); case "\t": case "\r": continue; case "#": (t$1 = e.indexOf("\n", t$1 + 1) - 1), -2 == t$1 && (t$1 = 1 / 0); continue; case '"': case "'": if (!w && d) { d += p; continue; } let n = e[t$1 + 1] == p && e[t$1 + 2] == p; if (((l = s(e, t$1, !0)), w)) { if (h) throw r("Unexpected " + p); (h += n ? e.slice(t$1 + 2, l - 2) : e.slice(t$1, l)), (t$1 = l); } else (d = e.slice(t$1, l)), (t$1 = l), n && ((d = d.slice(2, -2)), "\n" == d[1] ? (d = d[0] + d.slice(2)) : "\r" == d[1] && "\n" == d[2] && (d = d[0] + d.slice(3))); if (((t$1 = i$2(e, t$1)), (p = e[t$1]), p && "," != p && "\n" != p && "#" != p && "}" != p && "]" != p && "=" != p)) throw r("Unexpected character after end of string"); t$1--; continue; case "\n": case ",": case void 0: g(); continue; case "[": case "{": if (((u = "[" == p ? "]" : "}"), w && !f.length)) { if (h) throw r("Unexpected " + p); if (((l = s(e, t$1)), "[" == p && "[" == e[t$1 + 1])) { if ("]" != e[l - 2]) throw r("Missing ]]"); c.useArray(e.slice(t$1 + 2, l - 2)); } else c.use(e.slice(t$1 + 1, l - 1)); t$1 = l; } else if (w) { if (h) throw r("Unexpected " + p); c.enterArray("[" == p ? [] : {}), f.push(u); } else { if (d) throw r("Unexpected " + p); c.enter(h.trimEnd(), "[" == p ? [] : {}), f.push(u), (h = ""), (w = !0); } continue; case "]": case "}": if ((h && g(), f.pop() != p)) throw r("Unexpected " + p); if ((c.exit(), (t$1 = i$2(e, t$1 + 1)), (p = e[t$1]), p && "," != p && "\n" != p && "#" != p && "}" != p && "]" != p)) throw r("Unexpected character after end of scope"); t$1--; continue; case "=": if (!w) throw r("Unexpected " + p); if (!h) throw r("Missing key before " + p); w = !1; continue; default: w ? (h += p) : (d += p); } } while ((p = e[++t$1]) || h); if (f.length) throw r("Missing " + f.pop()); return c.root; } function h() { let e = ""; for (let t of arguments) e += "string" == typeof t ? t : t[0]; return f(e); } const toml = ((h.parse = f), h); const allKeys = { "string": ["name", "description", "version", "type", "author_name", "author_email", "license"], "number": ["schema_version"], "boolean": ["autoclose_loader"], "array": ["runtimes", "packages", "paths", "plugins"] }; const defaultConfig$1 = { "schema_version": 1, "type": "app", "autoclose_loader": true, "runtimes": [{ "src": "https://cdn.jsdelivr.net/pyodide/v0.21.2/full/pyodide.js", "name": "pyodide-0.21.2", "lang": "python" }], "packages": [], "paths": [], "plugins": [] }; function addClasses(element, classes) { for (const entry of classes) { element.classList.add(entry); } } function removeClasses(element, classes) { for (const entry of classes) { element.classList.remove(entry); } } function getLastPath(str) { return str.split('\\').pop().split('/').pop(); } function escape(str) { return str.replace(//g, ">"); } function htmlDecode(input) { const doc = new DOMParser().parseFromString(ltrim(escape(input)), 'text/html'); return doc.documentElement.textContent; } function ltrim(code) { const lines = code.split('\n'); if (lines.length == 0) return code; const lengths = lines .filter(line => line.trim().length != 0) .map(line => { const [prefix] = line.match(/^\s*/); return prefix.length; }); const k = Math.min(...lengths); return k != 0 ? lines.map(line => line.substring(k)).join('\n') : code; } function guidGenerator() { const S4 = function () { return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); }; return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4(); } /* * Display a page-wide error message to show that something has gone wrong with * PyScript or Pyodide during loading. Probably not be used for issues that occur within * Python scripts, since stderr can be routed to somewhere in the DOM */ function showError(msg) { const warning = document.createElement('div'); warning.style.backgroundColor = 'LightCoral'; warning.style.alignContent = 'center'; warning.style.margin = '4px'; warning.style.padding = '4px'; warning.innerHTML = msg; document.body.prepend(warning); } function handleFetchError(e, singleFile) { //Should we still export full error contents to console? console.warn(`Caught an error in loadPaths:\r\n ${e.toString()}`); let errorContent; if (e.message.includes('TypeError: Failed to fetch')) { errorContent = `

PyScript: Access to local files (using "Paths:" in <py-env>) is not available when directly opening a HTML file; you must use a webserver to serve the additional files. See this reference on starting a simple webserver with Python.

`; } else if (e.message.includes('404')) { errorContent = `

PyScript: Loading from file ` + singleFile + ` failed with error 404 (File not Found). Are your filename and path are correct?

`; } else { errorContent = '

PyScript encountered an error while loading from file: ' + e.message + '

'; } showError(errorContent); } function readTextFromPath(path) { const request = new XMLHttpRequest(); request.open("GET", path, false); request.send(); const returnValue = request.responseText; return returnValue; } function fillUserData(inputConfig, resultConfig) { for (const key in inputConfig) { // fill in all extra keys ignored by the validator if (!(key in defaultConfig$1)) { resultConfig[key] = inputConfig[key]; } } return resultConfig; } function mergeConfig(inlineConfig, externalConfig) { if (Object.keys(inlineConfig).length === 0 && Object.keys(externalConfig).length === 0) { return defaultConfig$1; } else if (Object.keys(inlineConfig).length === 0) { return externalConfig; } else if (Object.keys(externalConfig).length === 0) { return inlineConfig; } else { let merged = {}; for (const keyType in allKeys) { const keys = allKeys[keyType]; keys.forEach(function (item) { if (keyType === "boolean") { merged[item] = (typeof inlineConfig[item] !== "undefined") ? inlineConfig[item] : externalConfig[item]; } else { merged[item] = inlineConfig[item] || externalConfig[item]; } }); } // fill extra keys from external first // they will be overridden by inline if extra keys also clash merged = fillUserData(externalConfig, merged); merged = fillUserData(inlineConfig, merged); return merged; } } function parseConfig(configText, configType = "toml") { let config; if (configType === "toml") { try { // TOML parser is soft and can parse even JSON strings, this additional check prevents it. if (configText.trim()[0] === "{") { const errMessage = `config supplied: ${configText} is an invalid TOML and cannot be parsed`; showError(`

${errMessage}

`); throw Error(errMessage); } config = toml.parse(configText); } catch (err) { const errMessage = err.toString(); showError(`

config supplied: ${configText} is an invalid TOML and cannot be parsed: ${errMessage}

`); throw err; } } else if (configType === "json") { try { config = JSON.parse(configText); } catch (err) { const errMessage = err.toString(); showError(`

config supplied: ${configText} is an invalid JSON and cannot be parsed: ${errMessage}

`); throw err; } } else { showError(`

type of config supplied is: ${configType}, supported values are ["toml", "json"].

`); } return config; } function validateConfig(configText, configType = "toml") { const config = parseConfig(configText, configType); const finalConfig = {}; for (const keyType in allKeys) { const keys = allKeys[keyType]; keys.forEach(function (item) { if (validateParamInConfig(item, keyType, config)) { if (item === "runtimes") { finalConfig[item] = []; const runtimes = config[item]; runtimes.forEach(function (eachRuntime) { const runtimeConfig = {}; for (const eachRuntimeParam in eachRuntime) { if (validateParamInConfig(eachRuntimeParam, "string", eachRuntime)) { runtimeConfig[eachRuntimeParam] = eachRuntime[eachRuntimeParam]; } } finalConfig[item].push(runtimeConfig); }); } else { finalConfig[item] = config[item]; } } }); } return fillUserData(config, finalConfig); } function validateParamInConfig(paramName, paramType, config) { if (paramName in config) { return paramType === "array" ? Array.isArray(config[paramName]) : typeof config[paramName] === paramType; } return false; } const logger$b = getLogger('pyscript/base'); // Global `Runtime` that implements the generic runtimes API let runtime$2; let Element; runtimeLoaded.subscribe(value => { runtime$2 = value; }); class BaseEvalElement extends HTMLElement { shadow; wrapper; code; source; btnConfig; btnRun; outputElement; errorElement; theme; appendOutput; constructor() { super(); // attach shadow so we can preserve the element original innerHtml content this.shadow = this.attachShadow({ mode: 'open' }); this.wrapper = document.createElement('slot'); this.shadow.appendChild(this.wrapper); this.setOutputMode("append"); } addToOutput(s) { this.outputElement.innerHTML += '
' + s + '
'; this.outputElement.hidden = false; } setOutputMode(defaultMode = "append") { const mode = this.hasAttribute('output-mode') ? this.getAttribute('output-mode') : defaultMode; switch (mode) { case "append": this.appendOutput = true; break; case "replace": this.appendOutput = false; break; default: logger$b.warn(`${this.id}: custom output-modes are currently not implemented`); } } // subclasses should overwrite this method to define custom logic // before code gets evaluated preEvaluate() { return null; } // subclasses should overwrite this method to define custom logic // after code has been evaluated postEvaluate() { return null; } checkId() { if (!this.id) this.id = 'py-' + guidGenerator(); } getSourceFromElement() { return ''; } async getSourceFromFile(s) { const response = await fetch(s); this.code = await response.text(); return this.code; } async _register_esm(runtime) { const imports = {}; const nodes = document.querySelectorAll("script[type='importmap']"); const importmaps = []; nodes.forEach(node => { let importmap; try { importmap = JSON.parse(node.textContent); if (importmap?.imports == null) return; importmaps.push(importmap); } catch { return; } }); for (const importmap of importmaps) { for (const [name, url] of Object.entries(importmap.imports)) { if (typeof name != 'string' || typeof url != 'string') continue; try { // XXX: pyodide doesn't like Module(), failing with // "can't read 'name' of undefined" at import time imports[name] = { ...(await import(url)) }; } catch { logger$b.error(`failed to fetch '${url}' for '${name}'`); } } } runtime.registerJsModule('esm', imports); } async evaluate() { this.preEvaluate(); let source; let output; try { source = this.source ? await this.getSourceFromFile(this.source) : this.getSourceFromElement(); this._register_esm(runtime$2); await runtime$2.run(`output_manager.change(out="${this.outputElement.id}", err="${this.errorElement.id}", append=${this.appendOutput ? 'True' : 'False'})`); output = await runtime$2.run(source); if (output !== undefined) { if (Element === undefined) { Element = runtime$2.globals.get('Element'); } const out = Element(this.outputElement.id); out.write.callKwargs(output, { append: this.appendOutput }); this.outputElement.hidden = false; this.outputElement.style.display = 'block'; } await runtime$2.run(`output_manager.revert()`); // check if this REPL contains errors, delete them and remove error classes const errorElements = document.querySelectorAll(`div[id^='${this.errorElement.id}'][error]`); if (errorElements.length > 0) { errorElements.forEach(errorElement => { errorElement.classList.add('hidden'); if (this.hasAttribute('std-err')) { this.errorElement.hidden = true; this.errorElement.style.removeProperty('display'); } }); } removeClasses(this.errorElement, ['bg-red-200', 'p-2']); this.postEvaluate(); } catch (err) { logger$b.error(err); try { if (Element === undefined) { Element = runtime$2.globals.get('Element'); } const out = Element(this.errorElement.id); addClasses(this.errorElement, ['bg-red-200', 'p-2']); out.write.callKwargs(err.toString(), { append: this.appendOutput }); if (this.errorElement.children.length === 0) { this.errorElement.setAttribute('error', ''); } else { this.errorElement.children[this.errorElement.children.length - 1].setAttribute('error', ''); } this.errorElement.hidden = false; this.errorElement.style.display = 'block'; this.errorElement.style.visibility = 'visible'; } catch (internalErr) { logger$b.error("Unnable to write error to error element in page."); } } } // end evaluate async eval(source) { try { const output = await runtime$2.run(source); if (output !== undefined) { logger$b.info(output); } } catch (err) { logger$b.error(err); } } // end eval runAfterRuntimeInitialized(callback) { runtimeLoaded.subscribe(value => { if ('run' in value) { setTimeout(() => { void callback(); }, 100); } }); } } function createWidget(name, code, klass) { class CustomWidget extends HTMLElement { shadow; wrapper; name = name; klass = klass; code = code; proxy; proxyClass; constructor() { super(); // attach shadow so we can preserve the element original innerHtml content this.shadow = this.attachShadow({ mode: 'open' }); this.wrapper = document.createElement('slot'); this.shadow.appendChild(this.wrapper); } connectedCallback() { // TODO: we are calling with a 2secs delay to allow pyodide to load // ideally we can just wait for it to load and then run. To do // so we need to replace using the promise and actually using // the interpreter after it loads completely // setTimeout(() => { // void (async () => { // await this.eval(this.code); // this.proxy = this.proxyClass(this); // console.log('proxy', this.proxy); // this.proxy.connect(); // this.registerWidget(); // })(); // }, 2000); runtimeLoaded.subscribe(value => { if ('run' in value) { runtime$2 = value; setTimeout(() => { void (async () => { await this.eval(this.code); this.proxy = this.proxyClass(this); this.proxy.connect(); this.registerWidget(); })(); }, 1000); } }); } registerWidget() { logger$b.info('new widget registered:', this.name); runtime$2.globals.set(this.id, this.proxy); } async eval(source) { try { const output = await runtime$2.run(source); this.proxyClass = runtime$2.globals.get(this.klass); if (output !== undefined) { logger$b.info('CustomWidget.eval: ', output); } } catch (err) { logger$b.error('CustomWidget.eval: ', err); } } } customElements.define(name, CustomWidget); } class PyWidget extends HTMLElement { shadow; name; klass; outputElement; errorElement; wrapper; theme; source; code; constructor() { super(); // attach shadow so we can preserve the element original innerHtml content this.shadow = this.attachShadow({ mode: 'open' }); this.wrapper = document.createElement('slot'); this.shadow.appendChild(this.wrapper); this.addAttributes('src', 'name', 'klass'); } addAttributes(...attrs) { for (const each of attrs) { const property = each === "src" ? "source" : each; if (this.hasAttribute(each)) { this[property] = this.getAttribute(each); } } } async connectedCallback() { if (this.id === undefined) { throw new ReferenceError(`No id specified for component. Components must have an explicit id. Please use id="" to specify your component id.`); } const mainDiv = document.createElement('div'); mainDiv.id = this.id + '-main'; this.appendChild(mainDiv); logger$b.debug('PyWidget: reading source', this.source); this.code = await this.getSourceFromFile(this.source); createWidget(this.name, this.code, this.klass); } initOutErr() { if (this.hasAttribute('output')) { this.errorElement = this.outputElement = document.getElementById(this.getAttribute('output')); // in this case, the default output-mode is append, if hasn't been specified if (!this.hasAttribute('output-mode')) { this.setAttribute('output-mode', 'append'); } } else { if (this.hasAttribute('std-out')) { this.outputElement = document.getElementById(this.getAttribute('std-out')); } else { // In this case neither output or std-out have been provided so we need // to create a new output div to output to this.outputElement = document.createElement('div'); this.outputElement.classList.add('output'); this.outputElement.hidden = true; this.outputElement.id = this.id + '-' + this.getAttribute('exec-id'); } if (this.hasAttribute('std-err')) { this.errorElement = document.getElementById(this.getAttribute('std-err')); } else { this.errorElement = this.outputElement; } } } async getSourceFromFile(s) { const response = await fetch(s); return await response.text(); } async eval(source) { try { const output = await runtime$2.run(source); if (output !== undefined) { logger$b.info('PyWidget.eval: ', output); } } catch (err) { logger$b.error('PyWidget.eval: ', err); } } } const logger$a = getLogger('py-script'); // Premise used to connect to the first available runtime (can be pyodide or others) let runtime$1; runtimeLoaded.subscribe(value => { runtime$1 = value; }); loadedEnvironments.subscribe(value => { }); class PyScript extends BaseEvalElement { constructor() { super(); // add an extra div where we can attach the codemirror editor this.shadow.appendChild(this.wrapper); } connectedCallback() { this.checkId(); this.code = htmlDecode(this.innerHTML); this.innerHTML = ''; const mainDiv = document.createElement('div'); addClasses(mainDiv, ['output']); // add Editor to main PyScript div if (this.hasAttribute('output')) { this.errorElement = this.outputElement = document.getElementById(this.getAttribute('output')); // in this case, the default output-mode is append, if hasn't been specified if (!this.hasAttribute('output-mode')) { this.setAttribute('output-mode', 'append'); } } else { if (this.hasAttribute('std-out')) { this.outputElement = document.getElementById(this.getAttribute('std-out')); } else { // In this case neither output or std-out have been provided so we need // to create a new output div to output to // Let's check if we have an id first and create one if not this.outputElement = document.createElement('div'); const exec_id = this.getAttribute('exec-id'); this.outputElement.id = this.id + (exec_id ? '-' + exec_id : ''); // add the output div id if there's not output pre-defined mainDiv.appendChild(this.outputElement); } if (this.hasAttribute('std-err')) { this.errorElement = document.getElementById(this.getAttribute('std-err')); } else { this.errorElement = this.outputElement; } } this.appendChild(mainDiv); addToScriptsQueue(this); if (this.hasAttribute('src')) { this.source = this.getAttribute('src'); } } async _register_esm(runtime) { for (const node of document.querySelectorAll("script[type='importmap']")) { const importmap = (() => { try { return JSON.parse(node.textContent); } catch { return null; } })(); if (importmap?.imports == null) continue; for (const [name, url] of Object.entries(importmap.imports)) { if (typeof name != 'string' || typeof url != 'string') continue; let exports; try { // XXX: pyodide doesn't like Module(), failing with // "can't read 'name' of undefined" at import time exports = { ...(await import(url)) }; } catch { logger$a.warn(`failed to fetch '${url}' for '${name}'`); continue; } runtime.registerJsModule(name, exports); } } } getSourceFromElement() { return htmlDecode(this.code); } } /** Defines all possible py-on* and their corresponding event types */ const pyAttributeToEvent = new Map([ // Leaving pys-onClick and pys-onKeyDown for backward compatibility ["pys-onClick", "click"], ["pys-onKeyDown", "keydown"], ["py-onClick", "click"], ["py-onKeyDown", "keydown"], // Window Events ["py-afterprint", "afterprint"], ["py-beforeprint", "beforeprint"], ["py-beforeunload", "beforeunload"], ["py-error", "error"], ["py-hashchange", "hashchange"], ["py-load", "load"], ["py-message", "message"], ["py-offline", "offline"], ["py-online", "online"], ["py-pagehide", "pagehide"], ["py-pageshow", "pageshow"], ["py-popstate", "popstate"], ["py-resize", "resize"], ["py-storage", "storage"], ["py-unload", "unload"], // Form Events ["py-blur", "blur"], ["py-change", "change"], ["py-contextmenu", "contextmenu"], ["py-focus", "focus"], ["py-input", "input"], ["py-invalid", "invalid"], ["py-reset", "reset"], ["py-search", "search"], ["py-select", "select"], ["py-submit", "submit"], // Keyboard Events ["py-keydown", "keydown"], ["py-keypress", "keypress"], ["py-keyup", "keyup"], // Mouse Events ["py-click", "click"], ["py-dblclick", "dblclick"], ["py-mousedown", "mousedown"], ["py-mousemove", "mousemove"], ["py-mouseout", "mouseout"], ["py-mouseover", "mouseover"], ["py-mouseup", "mouseup"], ["py-mousewheel", "mousewheel"], ["py-wheel", "wheel"], // Drag Events ["py-drag", "drag"], ["py-dragend", "dragend"], ["py-dragenter", "dragenter"], ["py-dragleave", "dragleave"], ["py-dragover", "dragover"], ["py-dragstart", "dragstart"], ["py-drop", "drop"], ["py-scroll", "scroll"], // Clipboard Events ["py-copy", "copy"], ["py-cut", "cut"], ["py-paste", "paste"], // Media Events ["py-abort", "abort"], ["py-canplay", "canplay"], ["py-canplaythrough", "canplaythrough"], ["py-cuechange", "cuechange"], ["py-durationchange", "durationchange"], ["py-emptied", "emptied"], ["py-ended", "ended"], ["py-loadeddata", "loadeddata"], ["py-loadedmetadata", "loadedmetadata"], ["py-loadstart", "loadstart"], ["py-pause", "pause"], ["py-play", "play"], ["py-playing", "playing"], ["py-progress", "progress"], ["py-ratechange", "ratechange"], ["py-seeked", "seeked"], ["py-seeking", "seeking"], ["py-stalled", "stalled"], ["py-suspend", "suspend"], ["py-timeupdate", "timeupdate"], ["py-volumechange", "volumechange"], ["py-waiting", "waiting"], // Misc Events ["py-toggle", "toggle"], ]); /** Initialize all elements with py-* handlers attributes */ async function initHandlers() { logger$a.debug('Initializing py-* event handlers...'); for (const pyAttribute of pyAttributeToEvent.keys()) { await createElementsWithEventListeners(runtime$1, pyAttribute); } } /** Initializes an element with the given py-on* attribute and its handler */ async function createElementsWithEventListeners(runtime, pyAttribute) { const matches = document.querySelectorAll(`[${pyAttribute}]`); for (const el of matches) { if (el.id.length === 0) { throw new TypeError(`<${el.tagName.toLowerCase()}> must have an id attribute, when using the ${pyAttribute} attribute`); } const handlerCode = el.getAttribute(pyAttribute); const event = pyAttributeToEvent.get(pyAttribute); if (pyAttribute === 'pys-onClick' || pyAttribute === 'pys-onKeyDown') { console.warn("Use of pys-onClick and pys-onKeyDown attributes is deprecated in favor of py-onClick() and py-onKeyDown(). pys-on* attributes will be deprecated in a future version of PyScript."); const source = ` from pyodide.ffi import create_proxy Element("${el.id}").element.addEventListener("${event}", create_proxy(${handlerCode})) `; await runtime.run(source); } else { el.addEventListener(event, () => { (async () => { await runtime.run(handlerCode); })(); }); } // TODO: Should we actually map handlers in JS instead of Python? // el.onclick = (evt: any) => { // console.log("click"); // new Promise((resolve, reject) => { // setTimeout(() => { // console.log('Inside') // }, 300); // }).then(() => { // console.log("resolved") // }); // // let handlerCode = el.getAttribute('py-onClick'); // // pyodide.runPython(handlerCode); // } } } /** Mount all elements with attribute py-mount into the Python namespace */ async function mountElements() { const matches = document.querySelectorAll('[py-mount]'); logger$a.info(`py-mount: found ${matches.length} elements`); let source = ''; for (const el of matches) { const mountName = el.getAttribute('py-mount') || el.id.split('-').join('_'); source += `\n${mountName} = Element("${el.id}")`; } await runtime$1.run(source); } addInitializer(mountElements); addPostInitializer(initHandlers); /*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT */ function isNothing(subject) { return (typeof subject === 'undefined') || (subject === null); } function isObject(subject) { return (typeof subject === 'object') && (subject !== null); } function toArray(sequence) { if (Array.isArray(sequence)) return sequence; else if (isNothing(sequence)) return []; return [ sequence ]; } function extend$1(target, source) { var index, length, key, sourceKeys; if (source) { sourceKeys = Object.keys(source); for (index = 0, length = sourceKeys.length; index < length; index += 1) { key = sourceKeys[index]; target[key] = source[key]; } } return target; } function repeat(string, count) { var result = '', cycle; for (cycle = 0; cycle < count; cycle += 1) { result += string; } return result; } function isNegativeZero(number) { return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); } var isNothing_1 = isNothing; var isObject_1 = isObject; var toArray_1 = toArray; var repeat_1 = repeat; var isNegativeZero_1 = isNegativeZero; var extend_1 = extend$1; var common = { isNothing: isNothing_1, isObject: isObject_1, toArray: toArray_1, repeat: repeat_1, isNegativeZero: isNegativeZero_1, extend: extend_1 }; // YAML error class. http://stackoverflow.com/questions/8458984 function formatError(exception, compact) { var where = '', message = exception.reason || '(unknown reason)'; if (!exception.mark) return message; if (exception.mark.name) { where += 'in "' + exception.mark.name + '" '; } where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'; if (!compact && exception.mark.snippet) { where += '\n\n' + exception.mark.snippet; } return message + ' ' + where; } function YAMLException$1(reason, mark) { // Super constructor Error.call(this); this.name = 'YAMLException'; this.reason = reason; this.mark = mark; this.message = formatError(this, false); // Include stack trace in error object if (Error.captureStackTrace) { // Chrome and NodeJS Error.captureStackTrace(this, this.constructor); } else { // FF, IE 10+ and Safari 6+. Fallback for others this.stack = (new Error()).stack || ''; } } // Inherit from Error YAMLException$1.prototype = Object.create(Error.prototype); YAMLException$1.prototype.constructor = YAMLException$1; YAMLException$1.prototype.toString = function toString(compact) { return this.name + ': ' + formatError(this, compact); }; var exception = YAMLException$1; // get snippet for a single line, respecting maxLength function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { var head = ''; var tail = ''; var maxHalfLength = Math.floor(maxLineLength / 2) - 1; if (position - lineStart > maxHalfLength) { head = ' ... '; lineStart = position - maxHalfLength + head.length; } if (lineEnd - position > maxHalfLength) { tail = ' ...'; lineEnd = position + maxHalfLength - tail.length; } return { str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, pos: position - lineStart + head.length // relative position }; } function padStart(string, max) { return common.repeat(' ', max - string.length) + string; } function makeSnippet(mark, options) { options = Object.create(options || null); if (!mark.buffer) return null; if (!options.maxLength) options.maxLength = 79; if (typeof options.indent !== 'number') options.indent = 1; if (typeof options.linesBefore !== 'number') options.linesBefore = 3; if (typeof options.linesAfter !== 'number') options.linesAfter = 2; var re = /\r?\n|\r|\0/g; var lineStarts = [ 0 ]; var lineEnds = []; var match; var foundLineNo = -1; while ((match = re.exec(mark.buffer))) { lineEnds.push(match.index); lineStarts.push(match.index + match[0].length); if (mark.position <= match.index && foundLineNo < 0) { foundLineNo = lineStarts.length - 2; } } if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; var result = '', i, line; var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); for (i = 1; i <= options.linesBefore; i++) { if (foundLineNo - i < 0) break; line = getLine( mark.buffer, lineStarts[foundLineNo - i], lineEnds[foundLineNo - i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), maxLineLength ); result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + ' | ' + line.str + '\n' + result; } line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + ' | ' + line.str + '\n'; result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; for (i = 1; i <= options.linesAfter; i++) { if (foundLineNo + i >= lineEnds.length) break; line = getLine( mark.buffer, lineStarts[foundLineNo + i], lineEnds[foundLineNo + i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), maxLineLength ); result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + ' | ' + line.str + '\n'; } return result.replace(/\n$/, ''); } var snippet = makeSnippet; var TYPE_CONSTRUCTOR_OPTIONS = [ 'kind', 'multi', 'resolve', 'construct', 'instanceOf', 'predicate', 'represent', 'representName', 'defaultStyle', 'styleAliases' ]; var YAML_NODE_KINDS = [ 'scalar', 'sequence', 'mapping' ]; function compileStyleAliases(map) { var result = {}; if (map !== null) { Object.keys(map).forEach(function (style) { map[style].forEach(function (alias) { result[String(alias)] = style; }); }); } return result; } function Type$1(tag, options) { options = options || {}; Object.keys(options).forEach(function (name) { if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); } }); // TODO: Add tag format check. this.options = options; // keep original options in case user wants to extend this type later this.tag = tag; this.kind = options['kind'] || null; this.resolve = options['resolve'] || function () { return true; }; this.construct = options['construct'] || function (data) { return data; }; this.instanceOf = options['instanceOf'] || null; this.predicate = options['predicate'] || null; this.represent = options['represent'] || null; this.representName = options['representName'] || null; this.defaultStyle = options['defaultStyle'] || null; this.multi = options['multi'] || false; this.styleAliases = compileStyleAliases(options['styleAliases'] || null); if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); } } var type = Type$1; /*eslint-disable max-len*/ function compileList(schema, name) { var result = []; schema[name].forEach(function (currentType) { var newIndex = result.length; result.forEach(function (previousType, previousIndex) { if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) { newIndex = previousIndex; } }); result[newIndex] = currentType; }); return result; } function compileMap(/* lists... */) { var result = { scalar: {}, sequence: {}, mapping: {}, fallback: {}, multi: { scalar: [], sequence: [], mapping: [], fallback: [] } }, index, length; function collectType(type) { if (type.multi) { result.multi[type.kind].push(type); result.multi['fallback'].push(type); } else { result[type.kind][type.tag] = result['fallback'][type.tag] = type; } } for (index = 0, length = arguments.length; index < length; index += 1) { arguments[index].forEach(collectType); } return result; } function Schema$1(definition) { return this.extend(definition); } Schema$1.prototype.extend = function extend(definition) { var implicit = []; var explicit = []; if (definition instanceof type) { // Schema.extend(type) explicit.push(definition); } else if (Array.isArray(definition)) { // Schema.extend([ type1, type2, ... ]) explicit = explicit.concat(definition); } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) if (definition.implicit) implicit = implicit.concat(definition.implicit); if (definition.explicit) explicit = explicit.concat(definition.explicit); } else { throw new exception('Schema.extend argument should be a Type, [ Type ], ' + 'or a schema definition ({ implicit: [...], explicit: [...] })'); } implicit.forEach(function (type$1) { if (!(type$1 instanceof type)) { throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); } if (type$1.loadKind && type$1.loadKind !== 'scalar') { throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); } if (type$1.multi) { throw new exception('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); } }); explicit.forEach(function (type$1) { if (!(type$1 instanceof type)) { throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); } }); var result = Object.create(Schema$1.prototype); result.implicit = (this.implicit || []).concat(implicit); result.explicit = (this.explicit || []).concat(explicit); result.compiledImplicit = compileList(result, 'implicit'); result.compiledExplicit = compileList(result, 'explicit'); result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); return result; }; var schema = Schema$1; var str = new type('tag:yaml.org,2002:str', { kind: 'scalar', construct: function (data) { return data !== null ? data : ''; } }); var seq = new type('tag:yaml.org,2002:seq', { kind: 'sequence', construct: function (data) { return data !== null ? data : []; } }); var map = new type('tag:yaml.org,2002:map', { kind: 'mapping', construct: function (data) { return data !== null ? data : {}; } }); var failsafe = new schema({ explicit: [ str, seq, map ] }); function resolveYamlNull(data) { if (data === null) return true; var max = data.length; return (max === 1 && data === '~') || (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); } function constructYamlNull() { return null; } function isNull(object) { return object === null; } var _null = new type('tag:yaml.org,2002:null', { kind: 'scalar', resolve: resolveYamlNull, construct: constructYamlNull, predicate: isNull, represent: { canonical: function () { return '~'; }, lowercase: function () { return 'null'; }, uppercase: function () { return 'NULL'; }, camelcase: function () { return 'Null'; }, empty: function () { return ''; } }, defaultStyle: 'lowercase' }); function resolveYamlBoolean(data) { if (data === null) return false; var max = data.length; return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); } function constructYamlBoolean(data) { return data === 'true' || data === 'True' || data === 'TRUE'; } function isBoolean(object) { return Object.prototype.toString.call(object) === '[object Boolean]'; } var bool = new type('tag:yaml.org,2002:bool', { kind: 'scalar', resolve: resolveYamlBoolean, construct: constructYamlBoolean, predicate: isBoolean, represent: { lowercase: function (object) { return object ? 'true' : 'false'; }, uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, camelcase: function (object) { return object ? 'True' : 'False'; } }, defaultStyle: 'lowercase' }); function isHexCode(c) { return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || ((0x61/* a */ <= c) && (c <= 0x66/* f */)); } function isOctCode(c) { return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); } function isDecCode(c) { return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); } function resolveYamlInteger(data) { if (data === null) return false; var max = data.length, index = 0, hasDigits = false, ch; if (!max) return false; ch = data[index]; // sign if (ch === '-' || ch === '+') { ch = data[++index]; } if (ch === '0') { // 0 if (index + 1 === max) return true; ch = data[++index]; // base 2, base 8, base 16 if (ch === 'b') { // base 2 index++; for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (ch !== '0' && ch !== '1') return false; hasDigits = true; } return hasDigits && ch !== '_'; } if (ch === 'x') { // base 16 index++; for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (!isHexCode(data.charCodeAt(index))) return false; hasDigits = true; } return hasDigits && ch !== '_'; } if (ch === 'o') { // base 8 index++; for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (!isOctCode(data.charCodeAt(index))) return false; hasDigits = true; } return hasDigits && ch !== '_'; } } // base 10 (except 0) // value should not start with `_`; if (ch === '_') return false; for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (!isDecCode(data.charCodeAt(index))) { return false; } hasDigits = true; } // Should have digits and should not end with `_` if (!hasDigits || ch === '_') return false; return true; } function constructYamlInteger(data) { var value = data, sign = 1, ch; if (value.indexOf('_') !== -1) { value = value.replace(/_/g, ''); } ch = value[0]; if (ch === '-' || ch === '+') { if (ch === '-') sign = -1; value = value.slice(1); ch = value[0]; } if (value === '0') return 0; if (ch === '0') { if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); } return sign * parseInt(value, 10); } function isInteger(object) { return (Object.prototype.toString.call(object)) === '[object Number]' && (object % 1 === 0 && !common.isNegativeZero(object)); } var int = new type('tag:yaml.org,2002:int', { kind: 'scalar', resolve: resolveYamlInteger, construct: constructYamlInteger, predicate: isInteger, represent: { binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, decimal: function (obj) { return obj.toString(10); }, /* eslint-disable max-len */ hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } }, defaultStyle: 'decimal', styleAliases: { binary: [ 2, 'bin' ], octal: [ 8, 'oct' ], decimal: [ 10, 'dec' ], hexadecimal: [ 16, 'hex' ] } }); var YAML_FLOAT_PATTERN = new RegExp( // 2.5e4, 2.5 and integers '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + // .2e4, .2 // special case, seems not from spec '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + // .inf '|[-+]?\\.(?:inf|Inf|INF)' + // .nan '|\\.(?:nan|NaN|NAN))$'); function resolveYamlFloat(data) { if (data === null) return false; if (!YAML_FLOAT_PATTERN.test(data) || // Quick hack to not allow integers end with `_` // Probably should update regexp & check speed data[data.length - 1] === '_') { return false; } return true; } function constructYamlFloat(data) { var value, sign; value = data.replace(/_/g, '').toLowerCase(); sign = value[0] === '-' ? -1 : 1; if ('+-'.indexOf(value[0]) >= 0) { value = value.slice(1); } if (value === '.inf') { return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; } else if (value === '.nan') { return NaN; } return sign * parseFloat(value, 10); } var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; function representYamlFloat(object, style) { var res; if (isNaN(object)) { switch (style) { case 'lowercase': return '.nan'; case 'uppercase': return '.NAN'; case 'camelcase': return '.NaN'; } } else if (Number.POSITIVE_INFINITY === object) { switch (style) { case 'lowercase': return '.inf'; case 'uppercase': return '.INF'; case 'camelcase': return '.Inf'; } } else if (Number.NEGATIVE_INFINITY === object) { switch (style) { case 'lowercase': return '-.inf'; case 'uppercase': return '-.INF'; case 'camelcase': return '-.Inf'; } } else if (common.isNegativeZero(object)) { return '-0.0'; } res = object.toString(10); // JS stringifier can build scientific format without dots: 5e-100, // while YAML requres dot: 5.e-100. Fix it with simple hack return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; } function isFloat(object) { return (Object.prototype.toString.call(object) === '[object Number]') && (object % 1 !== 0 || common.isNegativeZero(object)); } var float = new type('tag:yaml.org,2002:float', { kind: 'scalar', resolve: resolveYamlFloat, construct: constructYamlFloat, predicate: isFloat, represent: representYamlFloat, defaultStyle: 'lowercase' }); var json = failsafe.extend({ implicit: [ _null, bool, int, float ] }); var core = json; var YAML_DATE_REGEXP = new RegExp( '^([0-9][0-9][0-9][0-9])' + // [1] year '-([0-9][0-9])' + // [2] month '-([0-9][0-9])$'); // [3] day var YAML_TIMESTAMP_REGEXP = new RegExp( '^([0-9][0-9][0-9][0-9])' + // [1] year '-([0-9][0-9]?)' + // [2] month '-([0-9][0-9]?)' + // [3] day '(?:[Tt]|[ \\t]+)' + // ... '([0-9][0-9]?)' + // [4] hour ':([0-9][0-9])' + // [5] minute ':([0-9][0-9])' + // [6] second '(?:\\.([0-9]*))?' + // [7] fraction '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour '(?::([0-9][0-9]))?))?$'); // [11] tz_minute function resolveYamlTimestamp(data) { if (data === null) return false; if (YAML_DATE_REGEXP.exec(data) !== null) return true; if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; return false; } function constructYamlTimestamp(data) { var match, year, month, day, hour, minute, second, fraction = 0, delta = null, tz_hour, tz_minute, date; match = YAML_DATE_REGEXP.exec(data); if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); if (match === null) throw new Error('Date resolve error'); // match: [1] year [2] month [3] day year = +(match[1]); month = +(match[2]) - 1; // JS month starts with 0 day = +(match[3]); if (!match[4]) { // no hour return new Date(Date.UTC(year, month, day)); } // match: [4] hour [5] minute [6] second [7] fraction hour = +(match[4]); minute = +(match[5]); second = +(match[6]); if (match[7]) { fraction = match[7].slice(0, 3); while (fraction.length < 3) { // milli-seconds fraction += '0'; } fraction = +fraction; } // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute if (match[9]) { tz_hour = +(match[10]); tz_minute = +(match[11] || 0); delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds if (match[9] === '-') delta = -delta; } date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); if (delta) date.setTime(date.getTime() - delta); return date; } function representYamlTimestamp(object /*, style*/) { return object.toISOString(); } var timestamp = new type('tag:yaml.org,2002:timestamp', { kind: 'scalar', resolve: resolveYamlTimestamp, construct: constructYamlTimestamp, instanceOf: Date, represent: representYamlTimestamp }); function resolveYamlMerge(data) { return data === '<<' || data === null; } var merge = new type('tag:yaml.org,2002:merge', { kind: 'scalar', resolve: resolveYamlMerge }); /*eslint-disable no-bitwise*/ // [ 64, 65, 66 ] -> [ padding, CR, LF ] var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; function resolveYamlBinary(data) { if (data === null) return false; var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; // Convert one by one. for (idx = 0; idx < max; idx++) { code = map.indexOf(data.charAt(idx)); // Skip CR/LF if (code > 64) continue; // Fail on illegal characters if (code < 0) return false; bitlen += 6; } // If there are any bits left, source was corrupted return (bitlen % 8) === 0; } function constructYamlBinary(data) { var idx, tailbits, input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan max = input.length, map = BASE64_MAP, bits = 0, result = []; // Collect by 6*4 bits (3 bytes) for (idx = 0; idx < max; idx++) { if ((idx % 4 === 0) && idx) { result.push((bits >> 16) & 0xFF); result.push((bits >> 8) & 0xFF); result.push(bits & 0xFF); } bits = (bits << 6) | map.indexOf(input.charAt(idx)); } // Dump tail tailbits = (max % 4) * 6; if (tailbits === 0) { result.push((bits >> 16) & 0xFF); result.push((bits >> 8) & 0xFF); result.push(bits & 0xFF); } else if (tailbits === 18) { result.push((bits >> 10) & 0xFF); result.push((bits >> 2) & 0xFF); } else if (tailbits === 12) { result.push((bits >> 4) & 0xFF); } return new Uint8Array(result); } function representYamlBinary(object /*, style*/) { var result = '', bits = 0, idx, tail, max = object.length, map = BASE64_MAP; // Convert every three bytes to 4 ASCII characters. for (idx = 0; idx < max; idx++) { if ((idx % 3 === 0) && idx) { result += map[(bits >> 18) & 0x3F]; result += map[(bits >> 12) & 0x3F]; result += map[(bits >> 6) & 0x3F]; result += map[bits & 0x3F]; } bits = (bits << 8) + object[idx]; } // Dump tail tail = max % 3; if (tail === 0) { result += map[(bits >> 18) & 0x3F]; result += map[(bits >> 12) & 0x3F]; result += map[(bits >> 6) & 0x3F]; result += map[bits & 0x3F]; } else if (tail === 2) { result += map[(bits >> 10) & 0x3F]; result += map[(bits >> 4) & 0x3F]; result += map[(bits << 2) & 0x3F]; result += map[64]; } else if (tail === 1) { result += map[(bits >> 2) & 0x3F]; result += map[(bits << 4) & 0x3F]; result += map[64]; result += map[64]; } return result; } function isBinary(obj) { return Object.prototype.toString.call(obj) === '[object Uint8Array]'; } var binary = new type('tag:yaml.org,2002:binary', { kind: 'scalar', resolve: resolveYamlBinary, construct: constructYamlBinary, predicate: isBinary, represent: representYamlBinary }); var _hasOwnProperty$3 = Object.prototype.hasOwnProperty; var _toString$2 = Object.prototype.toString; function resolveYamlOmap(data) { if (data === null) return true; var objectKeys = [], index, length, pair, pairKey, pairHasKey, object = data; for (index = 0, length = object.length; index < length; index += 1) { pair = object[index]; pairHasKey = false; if (_toString$2.call(pair) !== '[object Object]') return false; for (pairKey in pair) { if (_hasOwnProperty$3.call(pair, pairKey)) { if (!pairHasKey) pairHasKey = true; else return false; } } if (!pairHasKey) return false; if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); else return false; } return true; } function constructYamlOmap(data) { return data !== null ? data : []; } var omap = new type('tag:yaml.org,2002:omap', { kind: 'sequence', resolve: resolveYamlOmap, construct: constructYamlOmap }); var _toString$1 = Object.prototype.toString; function resolveYamlPairs(data) { if (data === null) return true; var index, length, pair, keys, result, object = data; result = new Array(object.length); for (index = 0, length = object.length; index < length; index += 1) { pair = object[index]; if (_toString$1.call(pair) !== '[object Object]') return false; keys = Object.keys(pair); if (keys.length !== 1) return false; result[index] = [ keys[0], pair[keys[0]] ]; } return true; } function constructYamlPairs(data) { if (data === null) return []; var index, length, pair, keys, result, object = data; result = new Array(object.length); for (index = 0, length = object.length; index < length; index += 1) { pair = object[index]; keys = Object.keys(pair); result[index] = [ keys[0], pair[keys[0]] ]; } return result; } var pairs = new type('tag:yaml.org,2002:pairs', { kind: 'sequence', resolve: resolveYamlPairs, construct: constructYamlPairs }); var _hasOwnProperty$2 = Object.prototype.hasOwnProperty; function resolveYamlSet(data) { if (data === null) return true; var key, object = data; for (key in object) { if (_hasOwnProperty$2.call(object, key)) { if (object[key] !== null) return false; } } return true; } function constructYamlSet(data) { return data !== null ? data : {}; } var set = new type('tag:yaml.org,2002:set', { kind: 'mapping', resolve: resolveYamlSet, construct: constructYamlSet }); var _default = core.extend({ implicit: [ timestamp, merge ], explicit: [ binary, omap, pairs, set ] }); /*eslint-disable max-len,no-use-before-define*/ var _hasOwnProperty$1 = Object.prototype.hasOwnProperty; var CONTEXT_FLOW_IN = 1; var CONTEXT_FLOW_OUT = 2; var CONTEXT_BLOCK_IN = 3; var CONTEXT_BLOCK_OUT = 4; var CHOMPING_CLIP = 1; var CHOMPING_STRIP = 2; var CHOMPING_KEEP = 3; var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; function _class(obj) { return Object.prototype.toString.call(obj); } function is_EOL(c) { return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); } function is_WHITE_SPACE(c) { return (c === 0x09/* Tab */) || (c === 0x20/* Space */); } function is_WS_OR_EOL(c) { return (c === 0x09/* Tab */) || (c === 0x20/* Space */) || (c === 0x0A/* LF */) || (c === 0x0D/* CR */); } function is_FLOW_INDICATOR(c) { return c === 0x2C/* , */ || c === 0x5B/* [ */ || c === 0x5D/* ] */ || c === 0x7B/* { */ || c === 0x7D/* } */; } function fromHexCode(c) { var lc; if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { return c - 0x30; } /*eslint-disable no-bitwise*/ lc = c | 0x20; if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { return lc - 0x61 + 10; } return -1; } function escapedHexLen(c) { if (c === 0x78/* x */) { return 2; } if (c === 0x75/* u */) { return 4; } if (c === 0x55/* U */) { return 8; } return 0; } function fromDecimalCode(c) { if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { return c - 0x30; } return -1; } function simpleEscapeSequence(c) { /* eslint-disable indent */ return (c === 0x30/* 0 */) ? '\x00' : (c === 0x61/* a */) ? '\x07' : (c === 0x62/* b */) ? '\x08' : (c === 0x74/* t */) ? '\x09' : (c === 0x09/* Tab */) ? '\x09' : (c === 0x6E/* n */) ? '\x0A' : (c === 0x76/* v */) ? '\x0B' : (c === 0x66/* f */) ? '\x0C' : (c === 0x72/* r */) ? '\x0D' : (c === 0x65/* e */) ? '\x1B' : (c === 0x20/* Space */) ? ' ' : (c === 0x22/* " */) ? '\x22' : (c === 0x2F/* / */) ? '/' : (c === 0x5C/* \ */) ? '\x5C' : (c === 0x4E/* N */) ? '\x85' : (c === 0x5F/* _ */) ? '\xA0' : (c === 0x4C/* L */) ? '\u2028' : (c === 0x50/* P */) ? '\u2029' : ''; } function charFromCodepoint(c) { if (c <= 0xFFFF) { return String.fromCharCode(c); } // Encode UTF-16 surrogate pair // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF return String.fromCharCode( ((c - 0x010000) >> 10) + 0xD800, ((c - 0x010000) & 0x03FF) + 0xDC00 ); } var simpleEscapeCheck = new Array(256); // integer, for fast access var simpleEscapeMap = new Array(256); for (var i$1 = 0; i$1 < 256; i$1++) { simpleEscapeCheck[i$1] = simpleEscapeSequence(i$1) ? 1 : 0; simpleEscapeMap[i$1] = simpleEscapeSequence(i$1); } function State$1(input, options) { this.input = input; this.filename = options['filename'] || null; this.schema = options['schema'] || _default; this.onWarning = options['onWarning'] || null; // (Hidden) Remove? makes the loader to expect YAML 1.1 documents // if such documents have no explicit %YAML directive this.legacy = options['legacy'] || false; this.json = options['json'] || false; this.listener = options['listener'] || null; this.implicitTypes = this.schema.compiledImplicit; this.typeMap = this.schema.compiledTypeMap; this.length = input.length; this.position = 0; this.line = 0; this.lineStart = 0; this.lineIndent = 0; // position of first leading tab in the current line, // used to make sure there are no tabs in the indentation this.firstTabInLine = -1; this.documents = []; /* this.version; this.checkLineBreaks; this.tagMap; this.anchorMap; this.tag; this.anchor; this.kind; this.result;*/ } function generateError(state, message) { var mark = { name: state.filename, buffer: state.input.slice(0, -1), // omit trailing \0 position: state.position, line: state.line, column: state.position - state.lineStart }; mark.snippet = snippet(mark); return new exception(message, mark); } function throwError(state, message) { throw generateError(state, message); } function throwWarning(state, message) { if (state.onWarning) { state.onWarning.call(null, generateError(state, message)); } } var directiveHandlers = { YAML: function handleYamlDirective(state, name, args) { var match, major, minor; if (state.version !== null) { throwError(state, 'duplication of %YAML directive'); } if (args.length !== 1) { throwError(state, 'YAML directive accepts exactly one argument'); } match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); if (match === null) { throwError(state, 'ill-formed argument of the YAML directive'); } major = parseInt(match[1], 10); minor = parseInt(match[2], 10); if (major !== 1) { throwError(state, 'unacceptable YAML version of the document'); } state.version = args[0]; state.checkLineBreaks = (minor < 2); if (minor !== 1 && minor !== 2) { throwWarning(state, 'unsupported YAML version of the document'); } }, TAG: function handleTagDirective(state, name, args) { var handle, prefix; if (args.length !== 2) { throwError(state, 'TAG directive accepts exactly two arguments'); } handle = args[0]; prefix = args[1]; if (!PATTERN_TAG_HANDLE.test(handle)) { throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); } if (_hasOwnProperty$1.call(state.tagMap, handle)) { throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); } if (!PATTERN_TAG_URI.test(prefix)) { throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); } try { prefix = decodeURIComponent(prefix); } catch (err) { throwError(state, 'tag prefix is malformed: ' + prefix); } state.tagMap[handle] = prefix; } }; function captureSegment(state, start, end, checkJson) { var _position, _length, _character, _result; if (start < end) { _result = state.input.slice(start, end); if (checkJson) { for (_position = 0, _length = _result.length; _position < _length; _position += 1) { _character = _result.charCodeAt(_position); if (!(_character === 0x09 || (0x20 <= _character && _character <= 0x10FFFF))) { throwError(state, 'expected valid JSON character'); } } } else if (PATTERN_NON_PRINTABLE.test(_result)) { throwError(state, 'the stream contains non-printable characters'); } state.result += _result; } } function mergeMappings(state, destination, source, overridableKeys) { var sourceKeys, key, index, quantity; if (!common.isObject(source)) { throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); } sourceKeys = Object.keys(source); for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { key = sourceKeys[index]; if (!_hasOwnProperty$1.call(destination, key)) { destination[key] = source[key]; overridableKeys[key] = true; } } } function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) { var index, quantity; // The output is a plain object here, so keys can only be strings. // We need to convert keyNode to a string, but doing so can hang the process // (deeply nested arrays that explode exponentially using aliases). if (Array.isArray(keyNode)) { keyNode = Array.prototype.slice.call(keyNode); for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { if (Array.isArray(keyNode[index])) { throwError(state, 'nested arrays are not supported inside keys'); } if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { keyNode[index] = '[object Object]'; } } } // Avoid code execution in load() via toString property // (still use its own toString for arrays, timestamps, // and whatever user schema extensions happen to have @@toStringTag) if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { keyNode = '[object Object]'; } keyNode = String(keyNode); if (_result === null) { _result = {}; } if (keyTag === 'tag:yaml.org,2002:merge') { if (Array.isArray(valueNode)) { for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { mergeMappings(state, _result, valueNode[index], overridableKeys); } } else { mergeMappings(state, _result, valueNode, overridableKeys); } } else { if (!state.json && !_hasOwnProperty$1.call(overridableKeys, keyNode) && _hasOwnProperty$1.call(_result, keyNode)) { state.line = startLine || state.line; state.lineStart = startLineStart || state.lineStart; state.position = startPos || state.position; throwError(state, 'duplicated mapping key'); } // used for this specific key only because Object.defineProperty is slow if (keyNode === '__proto__') { Object.defineProperty(_result, keyNode, { configurable: true, enumerable: true, writable: true, value: valueNode }); } else { _result[keyNode] = valueNode; } delete overridableKeys[keyNode]; } return _result; } function readLineBreak(state) { var ch; ch = state.input.charCodeAt(state.position); if (ch === 0x0A/* LF */) { state.position++; } else if (ch === 0x0D/* CR */) { state.position++; if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { state.position++; } } else { throwError(state, 'a line break is expected'); } state.line += 1; state.lineStart = state.position; state.firstTabInLine = -1; } function skipSeparationSpace(state, allowComments, checkIndent) { var lineBreaks = 0, ch = state.input.charCodeAt(state.position); while (ch !== 0) { while (is_WHITE_SPACE(ch)) { if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { state.firstTabInLine = state.position; } ch = state.input.charCodeAt(++state.position); } if (allowComments && ch === 0x23/* # */) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); } if (is_EOL(ch)) { readLineBreak(state); ch = state.input.charCodeAt(state.position); lineBreaks++; state.lineIndent = 0; while (ch === 0x20/* Space */) { state.lineIndent++; ch = state.input.charCodeAt(++state.position); } } else { break; } } if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { throwWarning(state, 'deficient indentation'); } return lineBreaks; } function testDocumentSeparator(state) { var _position = state.position, ch; ch = state.input.charCodeAt(_position); // Condition state.position === state.lineStart is tested // in parent on each call, for efficiency. No needs to test here again. if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) { _position += 3; ch = state.input.charCodeAt(_position); if (ch === 0 || is_WS_OR_EOL(ch)) { return true; } } return false; } function writeFoldedLines(state, count) { if (count === 1) { state.result += ' '; } else if (count > 1) { state.result += common.repeat('\n', count - 1); } } function readPlainScalar(state, nodeIndent, withinFlowCollection) { var preceding, following, captureStart, captureEnd, hasPendingContent, _line, _lineStart, _lineIndent, _kind = state.kind, _result = state.result, ch; ch = state.input.charCodeAt(state.position); if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(ch) || ch === 0x23/* # */ || ch === 0x26/* & */ || ch === 0x2A/* * */ || ch === 0x21/* ! */ || ch === 0x7C/* | */ || ch === 0x3E/* > */ || ch === 0x27/* ' */ || ch === 0x22/* " */ || ch === 0x25/* % */ || ch === 0x40/* @ */ || ch === 0x60/* ` */) { return false; } if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) { return false; } } state.kind = 'scalar'; state.result = ''; captureStart = captureEnd = state.position; hasPendingContent = false; while (ch !== 0) { if (ch === 0x3A/* : */) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) { break; } } else if (ch === 0x23/* # */) { preceding = state.input.charCodeAt(state.position - 1); if (is_WS_OR_EOL(preceding)) { break; } } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || withinFlowCollection && is_FLOW_INDICATOR(ch)) { break; } else if (is_EOL(ch)) { _line = state.line; _lineStart = state.lineStart; _lineIndent = state.lineIndent; skipSeparationSpace(state, false, -1); if (state.lineIndent >= nodeIndent) { hasPendingContent = true; ch = state.input.charCodeAt(state.position); continue; } else { state.position = captureEnd; state.line = _line; state.lineStart = _lineStart; state.lineIndent = _lineIndent; break; } } if (hasPendingContent) { captureSegment(state, captureStart, captureEnd, false); writeFoldedLines(state, state.line - _line); captureStart = captureEnd = state.position; hasPendingContent = false; } if (!is_WHITE_SPACE(ch)) { captureEnd = state.position + 1; } ch = state.input.charCodeAt(++state.position); } captureSegment(state, captureStart, captureEnd, false); if (state.result) { return true; } state.kind = _kind; state.result = _result; return false; } function readSingleQuotedScalar(state, nodeIndent) { var ch, captureStart, captureEnd; ch = state.input.charCodeAt(state.position); if (ch !== 0x27/* ' */) { return false; } state.kind = 'scalar'; state.result = ''; state.position++; captureStart = captureEnd = state.position; while ((ch = state.input.charCodeAt(state.position)) !== 0) { if (ch === 0x27/* ' */) { captureSegment(state, captureStart, state.position, true); ch = state.input.charCodeAt(++state.position); if (ch === 0x27/* ' */) { captureStart = state.position; state.position++; captureEnd = state.position; } else { return true; } } else if (is_EOL(ch)) { captureSegment(state, captureStart, captureEnd, true); writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); captureStart = captureEnd = state.position; } else if (state.position === state.lineStart && testDocumentSeparator(state)) { throwError(state, 'unexpected end of the document within a single quoted scalar'); } else { state.position++; captureEnd = state.position; } } throwError(state, 'unexpected end of the stream within a single quoted scalar'); } function readDoubleQuotedScalar(state, nodeIndent) { var captureStart, captureEnd, hexLength, hexResult, tmp, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x22/* " */) { return false; } state.kind = 'scalar'; state.result = ''; state.position++; captureStart = captureEnd = state.position; while ((ch = state.input.charCodeAt(state.position)) !== 0) { if (ch === 0x22/* " */) { captureSegment(state, captureStart, state.position, true); state.position++; return true; } else if (ch === 0x5C/* \ */) { captureSegment(state, captureStart, state.position, true); ch = state.input.charCodeAt(++state.position); if (is_EOL(ch)) { skipSeparationSpace(state, false, nodeIndent); // TODO: rework to inline fn with no type cast? } else if (ch < 256 && simpleEscapeCheck[ch]) { state.result += simpleEscapeMap[ch]; state.position++; } else if ((tmp = escapedHexLen(ch)) > 0) { hexLength = tmp; hexResult = 0; for (; hexLength > 0; hexLength--) { ch = state.input.charCodeAt(++state.position); if ((tmp = fromHexCode(ch)) >= 0) { hexResult = (hexResult << 4) + tmp; } else { throwError(state, 'expected hexadecimal character'); } } state.result += charFromCodepoint(hexResult); state.position++; } else { throwError(state, 'unknown escape sequence'); } captureStart = captureEnd = state.position; } else if (is_EOL(ch)) { captureSegment(state, captureStart, captureEnd, true); writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); captureStart = captureEnd = state.position; } else if (state.position === state.lineStart && testDocumentSeparator(state)) { throwError(state, 'unexpected end of the document within a double quoted scalar'); } else { state.position++; captureEnd = state.position; } } throwError(state, 'unexpected end of the stream within a double quoted scalar'); } function readFlowCollection(state, nodeIndent) { var readNext = true, _line, _lineStart, _pos, _tag = state.tag, _result, _anchor = state.anchor, following, terminator, isPair, isExplicitPair, isMapping, overridableKeys = Object.create(null), keyNode, keyTag, valueNode, ch; ch = state.input.charCodeAt(state.position); if (ch === 0x5B/* [ */) { terminator = 0x5D;/* ] */ isMapping = false; _result = []; } else if (ch === 0x7B/* { */) { terminator = 0x7D;/* } */ isMapping = true; _result = {}; } else { return false; } if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(++state.position); while (ch !== 0) { skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if (ch === terminator) { state.position++; state.tag = _tag; state.anchor = _anchor; state.kind = isMapping ? 'mapping' : 'sequence'; state.result = _result; return true; } else if (!readNext) { throwError(state, 'missed comma between flow collection entries'); } else if (ch === 0x2C/* , */) { // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 throwError(state, "expected the node content, but found ','"); } keyTag = keyNode = valueNode = null; isPair = isExplicitPair = false; if (ch === 0x3F/* ? */) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following)) { isPair = isExplicitPair = true; state.position++; skipSeparationSpace(state, true, nodeIndent); } } _line = state.line; // Save the current line. _lineStart = state.lineStart; _pos = state.position; composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); keyTag = state.tag; keyNode = state.result; skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { isPair = true; ch = state.input.charCodeAt(++state.position); skipSeparationSpace(state, true, nodeIndent); composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); valueNode = state.result; } if (isMapping) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); } else if (isPair) { _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); } else { _result.push(keyNode); } skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if (ch === 0x2C/* , */) { readNext = true; ch = state.input.charCodeAt(++state.position); } else { readNext = false; } } throwError(state, 'unexpected end of the stream within a flow collection'); } function readBlockScalar(state, nodeIndent) { var captureStart, folding, chomping = CHOMPING_CLIP, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false, tmp, ch; ch = state.input.charCodeAt(state.position); if (ch === 0x7C/* | */) { folding = false; } else if (ch === 0x3E/* > */) { folding = true; } else { return false; } state.kind = 'scalar'; state.result = ''; while (ch !== 0) { ch = state.input.charCodeAt(++state.position); if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { if (CHOMPING_CLIP === chomping) { chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; } else { throwError(state, 'repeat of a chomping mode identifier'); } } else if ((tmp = fromDecimalCode(ch)) >= 0) { if (tmp === 0) { throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); } else if (!detectedIndent) { textIndent = nodeIndent + tmp - 1; detectedIndent = true; } else { throwError(state, 'repeat of an indentation width identifier'); } } else { break; } } if (is_WHITE_SPACE(ch)) { do { ch = state.input.charCodeAt(++state.position); } while (is_WHITE_SPACE(ch)); if (ch === 0x23/* # */) { do { ch = state.input.charCodeAt(++state.position); } while (!is_EOL(ch) && (ch !== 0)); } } while (ch !== 0) { readLineBreak(state); state.lineIndent = 0; ch = state.input.charCodeAt(state.position); while ((!detectedIndent || state.lineIndent < textIndent) && (ch === 0x20/* Space */)) { state.lineIndent++; ch = state.input.charCodeAt(++state.position); } if (!detectedIndent && state.lineIndent > textIndent) { textIndent = state.lineIndent; } if (is_EOL(ch)) { emptyLines++; continue; } // End of the scalar. if (state.lineIndent < textIndent) { // Perform the chomping. if (chomping === CHOMPING_KEEP) { state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); } else if (chomping === CHOMPING_CLIP) { if (didReadContent) { // i.e. only if the scalar is not empty. state.result += '\n'; } } // Break this `while` cycle and go to the funciton's epilogue. break; } // Folded style: use fancy rules to handle line breaks. if (folding) { // Lines starting with white space characters (more-indented lines) are not folded. if (is_WHITE_SPACE(ch)) { atMoreIndented = true; // except for the first content line (cf. Example 8.1) state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); // End of more-indented block. } else if (atMoreIndented) { atMoreIndented = false; state.result += common.repeat('\n', emptyLines + 1); // Just one line break - perceive as the same line. } else if (emptyLines === 0) { if (didReadContent) { // i.e. only if we have already read some scalar content. state.result += ' '; } // Several line breaks - perceive as different lines. } else { state.result += common.repeat('\n', emptyLines); } // Literal style: just add exact number of line breaks between content lines. } else { // Keep all line breaks except the header line break. state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); } didReadContent = true; detectedIndent = true; emptyLines = 0; captureStart = state.position; while (!is_EOL(ch) && (ch !== 0)) { ch = state.input.charCodeAt(++state.position); } captureSegment(state, captureStart, state.position, false); } return true; } function readBlockSequence(state, nodeIndent) { var _line, _tag = state.tag, _anchor = state.anchor, _result = [], following, detected = false, ch; // there is a leading tab before this token, so it can't be a block sequence/mapping; // it can still be flow sequence/mapping or a scalar if (state.firstTabInLine !== -1) return false; if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(state.position); while (ch !== 0) { if (state.firstTabInLine !== -1) { state.position = state.firstTabInLine; throwError(state, 'tab characters must not be used in indentation'); } if (ch !== 0x2D/* - */) { break; } following = state.input.charCodeAt(state.position + 1); if (!is_WS_OR_EOL(following)) { break; } detected = true; state.position++; if (skipSeparationSpace(state, true, -1)) { if (state.lineIndent <= nodeIndent) { _result.push(null); ch = state.input.charCodeAt(state.position); continue; } } _line = state.line; composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); _result.push(state.result); skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { throwError(state, 'bad indentation of a sequence entry'); } else if (state.lineIndent < nodeIndent) { break; } } if (detected) { state.tag = _tag; state.anchor = _anchor; state.kind = 'sequence'; state.result = _result; return true; } return false; } function readBlockMapping(state, nodeIndent, flowIndent) { var following, allowCompact, _line, _keyLine, _keyLineStart, _keyPos, _tag = state.tag, _anchor = state.anchor, _result = {}, overridableKeys = Object.create(null), keyTag = null, keyNode = null, valueNode = null, atExplicitKey = false, detected = false, ch; // there is a leading tab before this token, so it can't be a block sequence/mapping; // it can still be flow sequence/mapping or a scalar if (state.firstTabInLine !== -1) return false; if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(state.position); while (ch !== 0) { if (!atExplicitKey && state.firstTabInLine !== -1) { state.position = state.firstTabInLine; throwError(state, 'tab characters must not be used in indentation'); } following = state.input.charCodeAt(state.position + 1); _line = state.line; // Save the current line. // // Explicit notation case. There are two separate blocks: // first for the key (denoted by "?") and second for the value (denoted by ":") // if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { if (ch === 0x3F/* ? */) { if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } detected = true; atExplicitKey = true; allowCompact = true; } else if (atExplicitKey) { // i.e. 0x3A/* : */ === character after the explicit key. atExplicitKey = false; allowCompact = true; } else { throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); } state.position += 1; ch = following; // // Implicit notation case. Flow-style node as the key first, then ":", and the value. // } else { _keyLine = state.line; _keyLineStart = state.lineStart; _keyPos = state.position; if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { // Neither implicit nor explicit notation. // Reading is done. Go to the epilogue. break; } if (state.line === _line) { ch = state.input.charCodeAt(state.position); while (is_WHITE_SPACE(ch)) { ch = state.input.charCodeAt(++state.position); } if (ch === 0x3A/* : */) { ch = state.input.charCodeAt(++state.position); if (!is_WS_OR_EOL(ch)) { throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); } if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } detected = true; atExplicitKey = false; allowCompact = false; keyTag = state.tag; keyNode = state.result; } else if (detected) { throwError(state, 'can not read an implicit mapping pair; a colon is missed'); } else { state.tag = _tag; state.anchor = _anchor; return true; // Keep the result of `composeNode`. } } else if (detected) { throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); } else { state.tag = _tag; state.anchor = _anchor; return true; // Keep the result of `composeNode`. } } // // Common reading code for both explicit and implicit notations. // if (state.line === _line || state.lineIndent > nodeIndent) { if (atExplicitKey) { _keyLine = state.line; _keyLineStart = state.lineStart; _keyPos = state.position; } if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { if (atExplicitKey) { keyNode = state.result; } else { valueNode = state.result; } } if (!atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); } if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { throwError(state, 'bad indentation of a mapping entry'); } else if (state.lineIndent < nodeIndent) { break; } } // // Epilogue. // // Special case: last mapping's node contains only the key in explicit notation. if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); } // Expose the resulting mapping. if (detected) { state.tag = _tag; state.anchor = _anchor; state.kind = 'mapping'; state.result = _result; } return detected; } function readTagProperty(state) { var _position, isVerbatim = false, isNamed = false, tagHandle, tagName, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x21/* ! */) return false; if (state.tag !== null) { throwError(state, 'duplication of a tag property'); } ch = state.input.charCodeAt(++state.position); if (ch === 0x3C/* < */) { isVerbatim = true; ch = state.input.charCodeAt(++state.position); } else if (ch === 0x21/* ! */) { isNamed = true; tagHandle = '!!'; ch = state.input.charCodeAt(++state.position); } else { tagHandle = '!'; } _position = state.position; if (isVerbatim) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 0 && ch !== 0x3E/* > */); if (state.position < state.length) { tagName = state.input.slice(_position, state.position); ch = state.input.charCodeAt(++state.position); } else { throwError(state, 'unexpected end of the stream within a verbatim tag'); } } else { while (ch !== 0 && !is_WS_OR_EOL(ch)) { if (ch === 0x21/* ! */) { if (!isNamed) { tagHandle = state.input.slice(_position - 1, state.position + 1); if (!PATTERN_TAG_HANDLE.test(tagHandle)) { throwError(state, 'named tag handle cannot contain such characters'); } isNamed = true; _position = state.position + 1; } else { throwError(state, 'tag suffix cannot contain exclamation marks'); } } ch = state.input.charCodeAt(++state.position); } tagName = state.input.slice(_position, state.position); if (PATTERN_FLOW_INDICATORS.test(tagName)) { throwError(state, 'tag suffix cannot contain flow indicator characters'); } } if (tagName && !PATTERN_TAG_URI.test(tagName)) { throwError(state, 'tag name cannot contain such characters: ' + tagName); } try { tagName = decodeURIComponent(tagName); } catch (err) { throwError(state, 'tag name is malformed: ' + tagName); } if (isVerbatim) { state.tag = tagName; } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) { state.tag = state.tagMap[tagHandle] + tagName; } else if (tagHandle === '!') { state.tag = '!' + tagName; } else if (tagHandle === '!!') { state.tag = 'tag:yaml.org,2002:' + tagName; } else { throwError(state, 'undeclared tag handle "' + tagHandle + '"'); } return true; } function readAnchorProperty(state) { var _position, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x26/* & */) return false; if (state.anchor !== null) { throwError(state, 'duplication of an anchor property'); } ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { ch = state.input.charCodeAt(++state.position); } if (state.position === _position) { throwError(state, 'name of an anchor node must contain at least one character'); } state.anchor = state.input.slice(_position, state.position); return true; } function readAlias(state) { var _position, alias, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x2A/* * */) return false; ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { ch = state.input.charCodeAt(++state.position); } if (state.position === _position) { throwError(state, 'name of an alias node must contain at least one character'); } alias = state.input.slice(_position, state.position); if (!_hasOwnProperty$1.call(state.anchorMap, alias)) { throwError(state, 'unidentified alias "' + alias + '"'); } state.result = state.anchorMap[alias]; skipSeparationSpace(state, true, -1); return true; } function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { var allowBlockStyles, allowBlockScalars, allowBlockCollections, indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { indentStatus = 1; } else if (state.lineIndent === parentIndent) { indentStatus = 0; } else if (state.lineIndent < parentIndent) { indentStatus = -1; } } } if (indentStatus === 1) { while (readTagProperty(state) || readAnchorProperty(state)) { if (skipSeparationSpace(state, true, -1)) { atNewLine = true; allowBlockCollections = allowBlockStyles; if (state.lineIndent > parentIndent) { indentStatus = 1; } else if (state.lineIndent === parentIndent) { indentStatus = 0; } else if (state.lineIndent < parentIndent) { indentStatus = -1; } } else { allowBlockCollections = false; } } } if (allowBlockCollections) { allowBlockCollections = atNewLine || allowCompact; } if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { flowIndent = parentIndent; } else { flowIndent = parentIndent + 1; } blockIndent = state.position - state.lineStart; if (indentStatus === 1) { if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) { hasContent = true; } else { if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) { hasContent = true; } else if (readAlias(state)) { hasContent = true; if (state.tag !== null || state.anchor !== null) { throwError(state, 'alias node should not have any properties'); } } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { hasContent = true; if (state.tag === null) { state.tag = '?'; } } if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } } } else if (indentStatus === 0) { // Special case: block sequences are allowed to have same indentation level as the parent. // http://www.yaml.org/spec/1.2/spec.html#id2799784 hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); } } if (state.tag === null) { if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } } else if (state.tag === '?') { // Implicit resolving is not allowed for non-scalar types, and '?' // non-specific tag is only automatically assigned to plain scalars. // // We only need to check kind conformity in case user explicitly assigns '?' // tag, for example like this: "! [0]" // if (state.result !== null && state.kind !== 'scalar') { throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); } for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { type = state.implicitTypes[typeIndex]; if (type.resolve(state.result)) { // `state.result` updated in resolver if matched state.result = type.construct(state.result); state.tag = type.tag; if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } break; } } } else if (state.tag !== '!') { if (_hasOwnProperty$1.call(state.typeMap[state.kind || 'fallback'], state.tag)) { type = state.typeMap[state.kind || 'fallback'][state.tag]; } else { // looking for multi type type = null; typeList = state.typeMap.multi[state.kind || 'fallback']; for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { type = typeList[typeIndex]; break; } } } if (!type) { throwError(state, 'unknown tag !<' + state.tag + '>'); } if (state.result !== null && type.kind !== state.kind) { throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); } if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); } else { state.result = type.construct(state.result, state.tag); if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } } } if (state.listener !== null) { state.listener('close', state); } return state.tag !== null || state.anchor !== null || hasContent; } function readDocument(state) { var documentStart = state.position, _position, directiveName, directiveArgs, hasDirectives = false, ch; state.version = null; state.checkLineBreaks = state.legacy; state.tagMap = Object.create(null); state.anchorMap = Object.create(null); while ((ch = state.input.charCodeAt(state.position)) !== 0) { skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); if (state.lineIndent > 0 || ch !== 0x25/* % */) { break; } hasDirectives = true; ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch)) { ch = state.input.charCodeAt(++state.position); } directiveName = state.input.slice(_position, state.position); directiveArgs = []; if (directiveName.length < 1) { throwError(state, 'directive name must not be less than one character in length'); } while (ch !== 0) { while (is_WHITE_SPACE(ch)) { ch = state.input.charCodeAt(++state.position); } if (ch === 0x23/* # */) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 0 && !is_EOL(ch)); break; } if (is_EOL(ch)) break; _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch)) { ch = state.input.charCodeAt(++state.position); } directiveArgs.push(state.input.slice(_position, state.position)); } if (ch !== 0) readLineBreak(state); if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) { directiveHandlers[directiveName](state, directiveName, directiveArgs); } else { throwWarning(state, 'unknown document directive "' + directiveName + '"'); } } skipSeparationSpace(state, true, -1); if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 0x2D/* - */ && state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { state.position += 3; skipSeparationSpace(state, true, -1); } else if (hasDirectives) { throwError(state, 'directives end mark is expected'); } composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); skipSeparationSpace(state, true, -1); if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { throwWarning(state, 'non-ASCII line breaks are interpreted as content'); } state.documents.push(state.result); if (state.position === state.lineStart && testDocumentSeparator(state)) { if (state.input.charCodeAt(state.position) === 0x2E/* . */) { state.position += 3; skipSeparationSpace(state, true, -1); } return; } if (state.position < (state.length - 1)) { throwError(state, 'end of the stream or a document separator is expected'); } else { return; } } function loadDocuments(input, options) { input = String(input); options = options || {}; if (input.length !== 0) { // Add tailing `\n` if not exists if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { input += '\n'; } // Strip BOM if (input.charCodeAt(0) === 0xFEFF) { input = input.slice(1); } } var state = new State$1(input, options); var nullpos = input.indexOf('\0'); if (nullpos !== -1) { state.position = nullpos; throwError(state, 'null byte is not allowed in input'); } // Use 0 as string terminator. That significantly simplifies bounds check. state.input += '\0'; while (state.input.charCodeAt(state.position) === 0x20/* Space */) { state.lineIndent += 1; state.position += 1; } while (state.position < (state.length - 1)) { readDocument(state); } return state.documents; } function loadAll$1(input, iterator, options) { if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { options = iterator; iterator = null; } var documents = loadDocuments(input, options); if (typeof iterator !== 'function') { return documents; } for (var index = 0, length = documents.length; index < length; index += 1) { iterator(documents[index]); } } function load$1(input, options) { var documents = loadDocuments(input, options); if (documents.length === 0) { /*eslint-disable no-undefined*/ return undefined; } else if (documents.length === 1) { return documents[0]; } throw new exception('expected a single document in the stream, but found more'); } var loadAll_1 = loadAll$1; var load_1 = load$1; var loader$2 = { loadAll: loadAll_1, load: load_1 }; var load = loader$2.load; const logger$9 = getLogger('py-env'); // Premise used to connect to the first available runtime (can be pyodide or others) let runtime; runtimeLoaded.subscribe(value => { runtime = value; }); class PyEnv extends HTMLElement { shadow; wrapper; code; environment; runtime; env; paths; constructor() { super(); this.shadow = this.attachShadow({ mode: 'open' }); this.wrapper = document.createElement('slot'); } connectedCallback() { logger$9.info("The tag is deprecated, please use instead."); this.code = this.innerHTML; this.innerHTML = ''; const env = []; const paths = []; this.environment = load(this.code); if (this.environment === undefined) return; for (const entry of Array.isArray(this.environment) ? this.environment : []) { if (typeof entry == 'string') { env.push(entry); } else if (entry && typeof entry === 'object') { const obj = entry; for (const path of Array.isArray(obj.paths) ? obj.paths : []) { if (typeof path === 'string') { paths.push(path); } } } } this.env = env; this.paths = paths; async function loadEnv() { logger$9.info("Loading env: ", env); await runtime.installPackage(env); } async function loadPaths() { logger$9.info("Paths to load: ", paths); for (const singleFile of paths) { logger$9.info(` loading path: ${singleFile}`); try { await runtime.loadFromFile(singleFile); } catch (e) { //Should we still export full error contents to console? handleFetchError(e, singleFile); } } logger$9.info("All paths loaded"); } addInitializer(loadEnv); addInitializer(loadPaths); } } const logger$8 = getLogger('py-loader'); class PyLoader extends BaseEvalElement { widths; label; mount_name; details; operation; constructor() { super(); } connectedCallback() { this.innerHTML = `
`; this.mount_name = this.id.split('-').join('_'); this.operation = document.getElementById('pyscript-operation'); this.details = document.getElementById('pyscript-operation-details'); } log(msg) { // loader messages are showed both in the HTML and in the console logger$8.info(msg); const newLog = document.createElement('p'); newLog.innerText = msg; this.details.appendChild(newLog); } close() { logger$8.info('Closing'); this.remove(); } } // Compressed representation of the Grapheme_Cluster_Break=Extend // information from // http://www.unicode.org/Public/13.0.0/ucd/auxiliary/GraphemeBreakProperty.txt. // Each pair of elements represents a range, as an offet from the // previous range and a length. Numbers are in base-36, with the empty // string being a shorthand for 1. let extend = /*@__PURE__*/"lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(s => s ? parseInt(s, 36) : 1); // Convert offsets into absolute values for (let i = 1; i < extend.length; i++) extend[i] += extend[i - 1]; function isExtendingChar(code) { for (let i = 1; i < extend.length; i += 2) if (extend[i] > code) return extend[i - 1] <= code; return false; } function isRegionalIndicator(code) { return code >= 0x1F1E6 && code <= 0x1F1FF; } const ZWJ = 0x200d; /** Returns a next grapheme cluster break _after_ (not equal to) `pos`, if `forward` is true, or before otherwise. Returns `pos` itself if no further cluster break is available in the string. Moves across surrogate pairs, extending characters (when `includeExtending` is true), characters joined with zero-width joiners, and flag emoji. */ function findClusterBreak(str, pos, forward = true, includeExtending = true) { return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending); } function nextClusterBreak(str, pos, includeExtending) { if (pos == str.length) return pos; // If pos is in the middle of a surrogate pair, move to its start if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1))) pos--; let prev = codePointAt(str, pos); pos += codePointSize(prev); while (pos < str.length) { let next = codePointAt(str, pos); if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) { pos += codePointSize(next); prev = next; } else if (isRegionalIndicator(next)) { let countBefore = 0, i = pos - 2; while (i >= 0 && isRegionalIndicator(codePointAt(str, i))) { countBefore++; i -= 2; } if (countBefore % 2 == 0) break; else pos += 2; } else { break; } } return pos; } function prevClusterBreak(str, pos, includeExtending) { while (pos > 0) { let found = nextClusterBreak(str, pos - 2, includeExtending); if (found < pos) return found; pos--; } return 0; } function surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; } function surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; } /** Find the code point at the given position in a string (like the [`codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt) string method). */ function codePointAt(str, pos) { let code0 = str.charCodeAt(pos); if (!surrogateHigh(code0) || pos + 1 == str.length) return code0; let code1 = str.charCodeAt(pos + 1); if (!surrogateLow(code1)) return code0; return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000; } /** Given a Unicode codepoint, return the JavaScript string that respresents it (like [`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)). */ function fromCodePoint(code) { if (code <= 0xffff) return String.fromCharCode(code); code -= 0x10000; return String.fromCharCode((code >> 10) + 0xd800, (code & 1023) + 0xdc00); } /** The first character that takes up two positions in a JavaScript string. It is often useful to compare with this after calling `codePointAt`, to figure out whether your character takes up 1 or 2 index positions. */ function codePointSize(code) { return code < 0x10000 ? 1 : 2; } /** Count the column position at the given offset into the string, taking extending characters and tab size into account. */ function countColumn(string, tabSize, to = string.length) { let n = 0; for (let i = 0; i < to;) { if (string.charCodeAt(i) == 9) { n += tabSize - (n % tabSize); i++; } else { n++; i = findClusterBreak(string, i); } } return n; } /** Find the offset that corresponds to the given column position in a string, taking extending characters and tab size into account. By default, the string length is returned when it is too short to reach the column. Pass `strict` true to make it return -1 in that situation. */ function findColumn(string, col, tabSize, strict) { for (let i = 0, n = 0;;) { if (n >= col) return i; if (i == string.length) break; n += string.charCodeAt(i) == 9 ? tabSize - (n % tabSize) : 1; i = findClusterBreak(string, i); } return strict === true ? -1 : string.length; } /** The data structure for documents. */ class Text { /** @internal */ constructor() { } /** Get the line description around the given position. */ lineAt(pos) { if (pos < 0 || pos > this.length) throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`); return this.lineInner(pos, false, 1, 0); } /** Get the description for the given (1-based) line number. */ line(n) { if (n < 1 || n > this.lines) throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`); return this.lineInner(n, true, 1, 0); } /** Replace a range of the text with the given content. */ replace(from, to, text) { let parts = []; this.decompose(0, from, parts, 2 /* To */); if (text.length) text.decompose(0, text.length, parts, 1 /* From */ | 2 /* To */); this.decompose(to, this.length, parts, 1 /* From */); return TextNode.from(parts, this.length - (to - from) + text.length); } /** Append another document to this one. */ append(other) { return this.replace(this.length, this.length, other); } /** Retrieve the text between the given points. */ slice(from, to = this.length) { let parts = []; this.decompose(from, to, parts, 0); return TextNode.from(parts, to - from); } /** Test whether this text is equal to another instance. */ eq(other) { if (other == this) return true; if (other.length != this.length || other.lines != this.lines) return false; let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1); let a = new RawTextCursor(this), b = new RawTextCursor(other); for (let skip = start, pos = start;;) { a.next(skip); b.next(skip); skip = 0; if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value) return false; pos += a.value.length; if (a.done || pos >= end) return true; } } /** Iterate over the text. When `dir` is `-1`, iteration happens from end to start. This will return lines and the breaks between them as separate strings, and for long lines, might split lines themselves into multiple chunks as well. */ iter(dir = 1) { return new RawTextCursor(this, dir); } /** Iterate over a range of the text. When `from` > `to`, the iterator will run in reverse. */ iterRange(from, to = this.length) { return new PartialTextCursor(this, from, to); } /** Return a cursor that iterates over the given range of lines, _without_ returning the line breaks between, and yielding empty strings for empty lines. When `from` and `to` are given, they should be 1-based line numbers. */ iterLines(from, to) { let inner; if (from == null) { inner = this.iter(); } else { if (to == null) to = this.lines + 1; let start = this.line(from).from; inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to)); } return new LineCursor(inner); } /** @internal */ toString() { return this.sliceString(0); } /** Convert the document to an array of lines (which can be deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#text.Text^of)). */ toJSON() { let lines = []; this.flatten(lines); return lines; } /** Create a `Text` instance for the given array of lines. */ static of(text) { if (text.length == 0) throw new RangeError("A document must have at least one line"); if (text.length == 1 && !text[0]) return Text.empty; return text.length <= 32 /* Branch */ ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, [])); } } // Leaves store an array of line strings. There are always line breaks // between these strings. Leaves are limited in size and have to be // contained in TextNode instances for bigger documents. class TextLeaf extends Text { constructor(text, length = textLength(text)) { super(); this.text = text; this.length = length; } get lines() { return this.text.length; } get children() { return null; } lineInner(target, isLine, line, offset) { for (let i = 0;; i++) { let string = this.text[i], end = offset + string.length; if ((isLine ? line : end) >= target) return new Line(offset, end, line, string); offset = end + 1; line++; } } decompose(from, to, target, open) { let text = from <= 0 && to >= this.length ? this : new TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from)); if (open & 1 /* From */) { let prev = target.pop(); let joined = appendText(text.text, prev.text.slice(), 0, text.length); if (joined.length <= 32 /* Branch */) { target.push(new TextLeaf(joined, prev.length + text.length)); } else { let mid = joined.length >> 1; target.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid))); } } else { target.push(text); } } replace(from, to, text) { if (!(text instanceof TextLeaf)) return super.replace(from, to, text); let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to); let newLen = this.length + text.length - (to - from); if (lines.length <= 32 /* Branch */) return new TextLeaf(lines, newLen); return TextNode.from(TextLeaf.split(lines, []), newLen); } sliceString(from, to = this.length, lineSep = "\n") { let result = ""; for (let pos = 0, i = 0; pos <= to && i < this.text.length; i++) { let line = this.text[i], end = pos + line.length; if (pos > from && i) result += lineSep; if (from < end && to > pos) result += line.slice(Math.max(0, from - pos), to - pos); pos = end + 1; } return result; } flatten(target) { for (let line of this.text) target.push(line); } scanIdentical() { return 0; } static split(text, target) { let part = [], len = -1; for (let line of text) { part.push(line); len += line.length + 1; if (part.length == 32 /* Branch */) { target.push(new TextLeaf(part, len)); part = []; len = -1; } } if (len > -1) target.push(new TextLeaf(part, len)); return target; } } // Nodes provide the tree structure of the `Text` type. They store a // number of other nodes or leaves, taking care to balance themselves // on changes. There are implied line breaks _between_ the children of // a node (but not before the first or after the last child). class TextNode extends Text { constructor(children, length) { super(); this.children = children; this.length = length; this.lines = 0; for (let child of children) this.lines += child.lines; } lineInner(target, isLine, line, offset) { for (let i = 0;; i++) { let child = this.children[i], end = offset + child.length, endLine = line + child.lines - 1; if ((isLine ? endLine : end) >= target) return child.lineInner(target, isLine, line, offset); offset = end + 1; line = endLine + 1; } } decompose(from, to, target, open) { for (let i = 0, pos = 0; pos <= to && i < this.children.length; i++) { let child = this.children[i], end = pos + child.length; if (from <= end && to >= pos) { let childOpen = open & ((pos <= from ? 1 /* From */ : 0) | (end >= to ? 2 /* To */ : 0)); if (pos >= from && end <= to && !childOpen) target.push(child); else child.decompose(from - pos, to - pos, target, childOpen); } pos = end + 1; } } replace(from, to, text) { if (text.lines < this.lines) for (let i = 0, pos = 0; i < this.children.length; i++) { let child = this.children[i], end = pos + child.length; // Fast path: if the change only affects one child and the // child's size remains in the acceptable range, only update // that child if (from >= pos && to <= end) { let updated = child.replace(from - pos, to - pos, text); let totalLines = this.lines - child.lines + updated.lines; if (updated.lines < (totalLines >> (5 /* BranchShift */ - 1)) && updated.lines > (totalLines >> (5 /* BranchShift */ + 1))) { let copy = this.children.slice(); copy[i] = updated; return new TextNode(copy, this.length - (to - from) + text.length); } return super.replace(pos, end, updated); } pos = end + 1; } return super.replace(from, to, text); } sliceString(from, to = this.length, lineSep = "\n") { let result = ""; for (let i = 0, pos = 0; i < this.children.length && pos <= to; i++) { let child = this.children[i], end = pos + child.length; if (pos > from && i) result += lineSep; if (from < end && to > pos) result += child.sliceString(from - pos, to - pos, lineSep); pos = end + 1; } return result; } flatten(target) { for (let child of this.children) child.flatten(target); } scanIdentical(other, dir) { if (!(other instanceof TextNode)) return 0; let length = 0; let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length] : [this.children.length - 1, other.children.length - 1, -1, -1]; for (;; iA += dir, iB += dir) { if (iA == eA || iB == eB) return length; let chA = this.children[iA], chB = other.children[iB]; if (chA != chB) return length + chA.scanIdentical(chB, dir); length += chA.length + 1; } } static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) { let lines = 0; for (let ch of children) lines += ch.lines; if (lines < 32 /* Branch */) { let flat = []; for (let ch of children) ch.flatten(flat); return new TextLeaf(flat, length); } let chunk = Math.max(32 /* Branch */, lines >> 5 /* BranchShift */), maxChunk = chunk << 1, minChunk = chunk >> 1; let chunked = [], currentLines = 0, currentLen = -1, currentChunk = []; function add(child) { let last; if (child.lines > maxChunk && child instanceof TextNode) { for (let node of child.children) add(node); } else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) { flush(); chunked.push(child); } else if (child instanceof TextLeaf && currentLines && (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf && child.lines + last.lines <= 32 /* Branch */) { currentLines += child.lines; currentLen += child.length + 1; currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length); } else { if (currentLines + child.lines > chunk) flush(); currentLines += child.lines; currentLen += child.length + 1; currentChunk.push(child); } } function flush() { if (currentLines == 0) return; chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen)); currentLen = -1; currentLines = currentChunk.length = 0; } for (let child of children) add(child); flush(); return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length); } } Text.empty = /*@__PURE__*/new TextLeaf([""], 0); function textLength(text) { let length = -1; for (let line of text) length += line.length + 1; return length; } function appendText(text, target, from = 0, to = 1e9) { for (let pos = 0, i = 0, first = true; i < text.length && pos <= to; i++) { let line = text[i], end = pos + line.length; if (end >= from) { if (end > to) line = line.slice(0, to - pos); if (pos < from) line = line.slice(from - pos); if (first) { target[target.length - 1] += line; first = false; } else target.push(line); } pos = end + 1; } return target; } function sliceText(text, from, to) { return appendText(text, [""], from, to); } class RawTextCursor { constructor(text, dir = 1) { this.dir = dir; this.done = false; this.lineBreak = false; this.value = ""; this.nodes = [text]; this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf ? text.text.length : text.children.length) << 1]; } nextInner(skip, dir) { this.done = this.lineBreak = false; for (;;) { let last = this.nodes.length - 1; let top = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1; let size = top instanceof TextLeaf ? top.text.length : top.children.length; if (offset == (dir > 0 ? size : 0)) { if (last == 0) { this.done = true; this.value = ""; return this; } if (dir > 0) this.offsets[last - 1]++; this.nodes.pop(); this.offsets.pop(); } else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) { this.offsets[last] += dir; if (skip == 0) { this.lineBreak = true; this.value = "\n"; return this; } skip--; } else if (top instanceof TextLeaf) { // Move to the next string let next = top.text[offset + (dir < 0 ? -1 : 0)]; this.offsets[last] += dir; if (next.length > Math.max(0, skip)) { this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip); return this; } skip -= next.length; } else { let next = top.children[offset + (dir < 0 ? -1 : 0)]; if (skip > next.length) { skip -= next.length; this.offsets[last] += dir; } else { if (dir < 0) this.offsets[last]--; this.nodes.push(next); this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1); } } } } next(skip = 0) { if (skip < 0) { this.nextInner(-skip, (-this.dir)); skip = this.value.length; } return this.nextInner(skip, this.dir); } } class PartialTextCursor { constructor(text, start, end) { this.value = ""; this.done = false; this.cursor = new RawTextCursor(text, start > end ? -1 : 1); this.pos = start > end ? text.length : 0; this.from = Math.min(start, end); this.to = Math.max(start, end); } nextInner(skip, dir) { if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) { this.value = ""; this.done = true; return this; } skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos); let limit = dir < 0 ? this.pos - this.from : this.to - this.pos; if (skip > limit) skip = limit; limit -= skip; let { value } = this.cursor.next(skip); this.pos += (value.length + skip) * dir; this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit); this.done = !this.value; return this; } next(skip = 0) { if (skip < 0) skip = Math.max(skip, this.from - this.pos); else if (skip > 0) skip = Math.min(skip, this.to - this.pos); return this.nextInner(skip, this.cursor.dir); } get lineBreak() { return this.cursor.lineBreak && this.value != ""; } } class LineCursor { constructor(inner) { this.inner = inner; this.afterBreak = true; this.value = ""; this.done = false; } next(skip = 0) { let { done, lineBreak, value } = this.inner.next(skip); if (done) { this.done = true; this.value = ""; } else if (lineBreak) { if (this.afterBreak) { this.value = ""; } else { this.afterBreak = true; this.next(); } } else { this.value = value; this.afterBreak = false; } return this; } get lineBreak() { return false; } } if (typeof Symbol != "undefined") { Text.prototype[Symbol.iterator] = function () { return this.iter(); }; RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] = LineCursor.prototype[Symbol.iterator] = function () { return this; }; } /** This type describes a line in the document. It is created on-demand when lines are [queried](https://codemirror.net/6/docs/ref/#text.Text.lineAt). */ class Line { /** @internal */ constructor( /** The position of the start of the line. */ from, /** The position at the end of the line (_before_ the line break, or at the end of document for the last line). */ to, /** This line's line number (1-based). */ number, /** The line's content. */ text) { this.from = from; this.to = to; this.number = number; this.text = text; } /** The length of the line (not including any line break after it). */ get length() { return this.to - this.from; } } const DefaultSplit = /\r\n?|\n/; /** Distinguishes different ways in which positions can be mapped. */ var MapMode = /*@__PURE__*/(function (MapMode) { /** Map a position to a valid new position, even when its context was deleted. */ MapMode[MapMode["Simple"] = 0] = "Simple"; /** Return null if deletion happens across the position. */ MapMode[MapMode["TrackDel"] = 1] = "TrackDel"; /** Return null if the character _before_ the position is deleted. */ MapMode[MapMode["TrackBefore"] = 2] = "TrackBefore"; /** Return null if the character _after_ the position is deleted. */ MapMode[MapMode["TrackAfter"] = 3] = "TrackAfter"; return MapMode})(MapMode || (MapMode = {})); /** A change description is a variant of [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) that doesn't store the inserted text. As such, it can't be applied, but is cheaper to store and manipulate. */ class ChangeDesc { // Sections are encoded as pairs of integers. The first is the // length in the current document, and the second is -1 for // unaffected sections, and the length of the replacement content // otherwise. So an insertion would be (0, n>0), a deletion (n>0, // 0), and a replacement two positive numbers. /** @internal */ constructor( /** @internal */ sections) { this.sections = sections; } /** The length of the document before the change. */ get length() { let result = 0; for (let i = 0; i < this.sections.length; i += 2) result += this.sections[i]; return result; } /** The length of the document after the change. */ get newLength() { let result = 0; for (let i = 0; i < this.sections.length; i += 2) { let ins = this.sections[i + 1]; result += ins < 0 ? this.sections[i] : ins; } return result; } /** False when there are actual changes in this set. */ get empty() { return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0; } /** Iterate over the unchanged parts left by these changes. */ iterGaps(f) { for (let i = 0, posA = 0, posB = 0; i < this.sections.length;) { let len = this.sections[i++], ins = this.sections[i++]; if (ins < 0) { f(posA, posB, len); posB += len; } else { posB += ins; } posA += len; } } /** Iterate over the ranges changed by these changes. (See [`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a variant that also provides you with the inserted text.) When `individual` is true, adjacent changes (which are kept separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are reported separately. */ iterChangedRanges(f, individual = false) { iterChanges(this, f, individual); } /** Get a description of the inverted form of these changes. */ get invertedDesc() { let sections = []; for (let i = 0; i < this.sections.length;) { let len = this.sections[i++], ins = this.sections[i++]; if (ins < 0) sections.push(len, ins); else sections.push(ins, len); } return new ChangeDesc(sections); } /** Compute the combined effect of applying another set of changes after this one. The length of the document after this set should match the length before `other`. */ composeDesc(other) { return this.empty ? other : other.empty ? this : composeSets(this, other); } /** Map this description, which should start with the same document as `other`, over another set of changes, so that it can be applied after it. When `before` is true, map as if the changes in `other` happened before the ones in `this`. */ mapDesc(other, before = false) { return other.empty ? this : mapSet(this, other, before); } mapPos(pos, assoc = -1, mode = MapMode.Simple) { let posA = 0, posB = 0; for (let i = 0; i < this.sections.length;) { let len = this.sections[i++], ins = this.sections[i++], endA = posA + len; if (ins < 0) { if (endA > pos) return posB + (pos - posA); posB += len; } else { if (mode != MapMode.Simple && endA >= pos && (mode == MapMode.TrackDel && posA < pos && endA > pos || mode == MapMode.TrackBefore && posA < pos || mode == MapMode.TrackAfter && endA > pos)) return null; if (endA > pos || endA == pos && assoc < 0 && !len) return pos == posA || assoc < 0 ? posB : posB + ins; posB += ins; } posA = endA; } if (pos > posA) throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`); return posB; } /** Check whether these changes touch a given range. When one of the changes entirely covers the range, the string `"cover"` is returned. */ touchesRange(from, to = from) { for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) { let len = this.sections[i++], ins = this.sections[i++], end = pos + len; if (ins >= 0 && pos <= to && end >= from) return pos < from && end > to ? "cover" : true; pos = end; } return false; } /** @internal */ toString() { let result = ""; for (let i = 0; i < this.sections.length;) { let len = this.sections[i++], ins = this.sections[i++]; result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : ""); } return result; } /** Serialize this change desc to a JSON-representable value. */ toJSON() { return this.sections; } /** Create a change desc from its JSON representation (as produced by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON). */ static fromJSON(json) { if (!Array.isArray(json) || json.length % 2 || json.some(a => typeof a != "number")) throw new RangeError("Invalid JSON representation of ChangeDesc"); return new ChangeDesc(json); } } /** A change set represents a group of modifications to a document. It stores the document length, and can only be applied to documents with exactly that length. */ class ChangeSet extends ChangeDesc { /** @internal */ constructor(sections, /** @internal */ inserted) { super(sections); this.inserted = inserted; } /** Apply the changes to a document, returning the modified document. */ apply(doc) { if (this.length != doc.length) throw new RangeError("Applying change set to a document with the wrong length"); iterChanges(this, (fromA, toA, fromB, _toB, text) => doc = doc.replace(fromB, fromB + (toA - fromA), text), false); return doc; } mapDesc(other, before = false) { return mapSet(this, other, before, true); } /** Given the document as it existed _before_ the changes, return a change set that represents the inverse of this set, which could be used to go from the document created by the changes back to the document as it existed before the changes. */ invert(doc) { let sections = this.sections.slice(), inserted = []; for (let i = 0, pos = 0; i < sections.length; i += 2) { let len = sections[i], ins = sections[i + 1]; if (ins >= 0) { sections[i] = ins; sections[i + 1] = len; let index = i >> 1; while (inserted.length < index) inserted.push(Text.empty); inserted.push(len ? doc.slice(pos, pos + len) : Text.empty); } pos += len; } return new ChangeSet(sections, inserted); } /** Combine two subsequent change sets into a single set. `other` must start in the document produced by `this`. If `this` goes `docA` → `docB` and `other` represents `docB` → `docC`, the returned value will represent the change `docA` → `docC`. */ compose(other) { return this.empty ? other : other.empty ? this : composeSets(this, other, true); } /** Given another change set starting in the same document, maps this change set over the other, producing a new change set that can be applied to the document produced by applying `other`. When `before` is `true`, order changes as if `this` comes before `other`, otherwise (the default) treat `other` as coming first. Given two changes `A` and `B`, `A.compose(B.map(A))` and `B.compose(A.map(B, true))` will produce the same document. This provides a basic form of [operational transformation](https://en.wikipedia.org/wiki/Operational_transformation), and can be used for collaborative editing. */ map(other, before = false) { return other.empty ? this : mapSet(this, other, before, true); } /** Iterate over the changed ranges in the document, calling `f` for each, with the range in the original document (`fromA`-`toA`) and the range that replaces it in the new document (`fromB`-`toB`). When `individual` is true, adjacent changes are reported separately. */ iterChanges(f, individual = false) { iterChanges(this, f, individual); } /** Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change set. */ get desc() { return new ChangeDesc(this.sections); } /** @internal */ filter(ranges) { let resultSections = [], resultInserted = [], filteredSections = []; let iter = new SectionIter(this); done: for (let i = 0, pos = 0;;) { let next = i == ranges.length ? 1e9 : ranges[i++]; while (pos < next || pos == next && iter.len == 0) { if (iter.done) break done; let len = Math.min(iter.len, next - pos); addSection(filteredSections, len, -1); let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0; addSection(resultSections, len, ins); if (ins > 0) addInsert(resultInserted, resultSections, iter.text); iter.forward(len); pos += len; } let end = ranges[i++]; while (pos < end) { if (iter.done) break done; let len = Math.min(iter.len, end - pos); addSection(resultSections, len, -1); addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0); iter.forward(len); pos += len; } } return { changes: new ChangeSet(resultSections, resultInserted), filtered: new ChangeDesc(filteredSections) }; } /** Serialize this change set to a JSON-representable value. */ toJSON() { let parts = []; for (let i = 0; i < this.sections.length; i += 2) { let len = this.sections[i], ins = this.sections[i + 1]; if (ins < 0) parts.push(len); else if (ins == 0) parts.push([len]); else parts.push([len].concat(this.inserted[i >> 1].toJSON())); } return parts; } /** Create a change set for the given changes, for a document of the given length, using `lineSep` as line separator. */ static of(changes, length, lineSep) { let sections = [], inserted = [], pos = 0; let total = null; function flush(force = false) { if (!force && !sections.length) return; if (pos < length) addSection(sections, length - pos, -1); let set = new ChangeSet(sections, inserted); total = total ? total.compose(set.map(total)) : set; sections = []; inserted = []; pos = 0; } function process(spec) { if (Array.isArray(spec)) { for (let sub of spec) process(sub); } else if (spec instanceof ChangeSet) { if (spec.length != length) throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`); flush(); total = total ? total.compose(spec.map(total)) : spec; } else { let { from, to = from, insert } = spec; if (from > to || from < 0 || to > length) throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`); let insText = !insert ? Text.empty : typeof insert == "string" ? Text.of(insert.split(lineSep || DefaultSplit)) : insert; let insLen = insText.length; if (from == to && insLen == 0) return; if (from < pos) flush(); if (from > pos) addSection(sections, from - pos, -1); addSection(sections, to - from, insLen); addInsert(inserted, sections, insText); pos = to; } } process(changes); flush(!total); return total; } /** Create an empty changeset of the given length. */ static empty(length) { return new ChangeSet(length ? [length, -1] : [], []); } /** Create a changeset from its JSON representation (as produced by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON). */ static fromJSON(json) { if (!Array.isArray(json)) throw new RangeError("Invalid JSON representation of ChangeSet"); let sections = [], inserted = []; for (let i = 0; i < json.length; i++) { let part = json[i]; if (typeof part == "number") { sections.push(part, -1); } else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i) => i && typeof e != "string")) { throw new RangeError("Invalid JSON representation of ChangeSet"); } else if (part.length == 1) { sections.push(part[0], 0); } else { while (inserted.length < i) inserted.push(Text.empty); inserted[i] = Text.of(part.slice(1)); sections.push(part[0], inserted[i].length); } } return new ChangeSet(sections, inserted); } } function addSection(sections, len, ins, forceJoin = false) { if (len == 0 && ins <= 0) return; let last = sections.length - 2; if (last >= 0 && ins <= 0 && ins == sections[last + 1]) sections[last] += len; else if (len == 0 && sections[last] == 0) sections[last + 1] += ins; else if (forceJoin) { sections[last] += len; sections[last + 1] += ins; } else sections.push(len, ins); } function addInsert(values, sections, value) { if (value.length == 0) return; let index = (sections.length - 2) >> 1; if (index < values.length) { values[values.length - 1] = values[values.length - 1].append(value); } else { while (values.length < index) values.push(Text.empty); values.push(value); } } function iterChanges(desc, f, individual) { let inserted = desc.inserted; for (let posA = 0, posB = 0, i = 0; i < desc.sections.length;) { let len = desc.sections[i++], ins = desc.sections[i++]; if (ins < 0) { posA += len; posB += len; } else { let endA = posA, endB = posB, text = Text.empty; for (;;) { endA += len; endB += ins; if (ins && inserted) text = text.append(inserted[(i - 2) >> 1]); if (individual || i == desc.sections.length || desc.sections[i + 1] < 0) break; len = desc.sections[i++]; ins = desc.sections[i++]; } f(posA, endA, posB, endB, text); posA = endA; posB = endB; } } } function mapSet(setA, setB, before, mkSet = false) { let sections = [], insert = mkSet ? [] : null; let a = new SectionIter(setA), b = new SectionIter(setB); for (let posA = 0, posB = 0;;) { if (a.ins == -1) { posA += a.len; a.next(); } else if (b.ins == -1 && posB < posA) { let skip = Math.min(b.len, posA - posB); b.forward(skip); addSection(sections, skip, -1); posB += skip; } else if (b.ins >= 0 && (a.done || posB < posA || posB == posA && (b.len < a.len || b.len == a.len && !before))) { addSection(sections, b.ins, -1); while (posA > posB && !a.done && posA + a.len < posB + b.len) { posA += a.len; a.next(); } posB += b.len; b.next(); } else if (a.ins >= 0) { let len = 0, end = posA + a.len; for (;;) { if (b.ins >= 0 && posB > posA && posB + b.len < end) { len += b.ins; posB += b.len; b.next(); } else if (b.ins == -1 && posB < end) { let skip = Math.min(b.len, end - posB); len += skip; b.forward(skip); posB += skip; } else { break; } } addSection(sections, len, a.ins); if (insert) addInsert(insert, sections, a.text); posA = end; a.next(); } else if (a.done && b.done) { return insert ? new ChangeSet(sections, insert) : new ChangeDesc(sections); } else { throw new Error("Mismatched change set lengths"); } } } function composeSets(setA, setB, mkSet = false) { let sections = []; let insert = mkSet ? [] : null; let a = new SectionIter(setA), b = new SectionIter(setB); for (let open = false;;) { if (a.done && b.done) { return insert ? new ChangeSet(sections, insert) : new ChangeDesc(sections); } else if (a.ins == 0) { // Deletion in A addSection(sections, a.len, 0, open); a.next(); } else if (b.len == 0 && !b.done) { // Insertion in B addSection(sections, 0, b.ins, open); if (insert) addInsert(insert, sections, b.text); b.next(); } else if (a.done || b.done) { throw new Error("Mismatched change set lengths"); } else { let len = Math.min(a.len2, b.len), sectionLen = sections.length; if (a.ins == -1) { let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins; addSection(sections, len, insB, open); if (insert && insB) addInsert(insert, sections, b.text); } else if (b.ins == -1) { addSection(sections, a.off ? 0 : a.len, len, open); if (insert) addInsert(insert, sections, a.textBit(len)); } else { addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open); if (insert && !b.off) addInsert(insert, sections, b.text); } open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen); a.forward2(len); b.forward(len); } } } class SectionIter { constructor(set) { this.set = set; this.i = 0; this.next(); } next() { let { sections } = this.set; if (this.i < sections.length) { this.len = sections[this.i++]; this.ins = sections[this.i++]; } else { this.len = 0; this.ins = -2; } this.off = 0; } get done() { return this.ins == -2; } get len2() { return this.ins < 0 ? this.len : this.ins; } get text() { let { inserted } = this.set, index = (this.i - 2) >> 1; return index >= inserted.length ? Text.empty : inserted[index]; } textBit(len) { let { inserted } = this.set, index = (this.i - 2) >> 1; return index >= inserted.length && !len ? Text.empty : inserted[index].slice(this.off, len == null ? undefined : this.off + len); } forward(len) { if (len == this.len) this.next(); else { this.len -= len; this.off += len; } } forward2(len) { if (this.ins == -1) this.forward(len); else if (len == this.ins) this.next(); else { this.ins -= len; this.off += len; } } } /** A single selection range. When [`allowMultipleSelections`](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections) is enabled, a [selection](https://codemirror.net/6/docs/ref/#state.EditorSelection) may hold multiple ranges. By default, selections hold exactly one range. */ class SelectionRange { /** @internal */ constructor( /** The lower boundary of the range. */ from, /** The upper boundary of the range. */ to, flags) { this.from = from; this.to = to; this.flags = flags; } /** The anchor of the range—the side that doesn't move when you extend it. */ get anchor() { return this.flags & 16 /* Inverted */ ? this.to : this.from; } /** The head of the range, which is moved when the range is [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend). */ get head() { return this.flags & 16 /* Inverted */ ? this.from : this.to; } /** True when `anchor` and `head` are at the same position. */ get empty() { return this.from == this.to; } /** If this is a cursor that is explicitly associated with the character on one of its sides, this returns the side. -1 means the character before its position, 1 the character after, and 0 means no association. */ get assoc() { return this.flags & 4 /* AssocBefore */ ? -1 : this.flags & 8 /* AssocAfter */ ? 1 : 0; } /** The bidirectional text level associated with this cursor, if any. */ get bidiLevel() { let level = this.flags & 3 /* BidiLevelMask */; return level == 3 ? null : level; } /** The goal column (stored vertical offset) associated with a cursor. This is used to preserve the vertical position when [moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across lines of different length. */ get goalColumn() { let value = this.flags >> 5 /* GoalColumnOffset */; return value == 33554431 /* NoGoalColumn */ ? undefined : value; } /** Map this range through a change, producing a valid range in the updated document. */ map(change, assoc = -1) { let from, to; if (this.empty) { from = to = change.mapPos(this.from, assoc); } else { from = change.mapPos(this.from, 1); to = change.mapPos(this.to, -1); } return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags); } /** Extend this range to cover at least `from` to `to`. */ extend(from, to = from) { if (from <= this.anchor && to >= this.anchor) return EditorSelection.range(from, to); let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to; return EditorSelection.range(this.anchor, head); } /** Compare this range to another range. */ eq(other) { return this.anchor == other.anchor && this.head == other.head; } /** Return a JSON-serializable object representing the range. */ toJSON() { return { anchor: this.anchor, head: this.head }; } /** Convert a JSON representation of a range to a `SelectionRange` instance. */ static fromJSON(json) { if (!json || typeof json.anchor != "number" || typeof json.head != "number") throw new RangeError("Invalid JSON representation for SelectionRange"); return EditorSelection.range(json.anchor, json.head); } } /** An editor selection holds one or more selection ranges. */ class EditorSelection { /** @internal */ constructor( /** The ranges in the selection, sorted by position. Ranges cannot overlap (but they may touch, if they aren't empty). */ ranges, /** The index of the _main_ range in the selection (which is usually the range that was added last). */ mainIndex = 0) { this.ranges = ranges; this.mainIndex = mainIndex; } /** Map a selection through a change. Used to adjust the selection position for changes. */ map(change, assoc = -1) { if (change.empty) return this; return EditorSelection.create(this.ranges.map(r => r.map(change, assoc)), this.mainIndex); } /** Compare this selection to another selection. */ eq(other) { if (this.ranges.length != other.ranges.length || this.mainIndex != other.mainIndex) return false; for (let i = 0; i < this.ranges.length; i++) if (!this.ranges[i].eq(other.ranges[i])) return false; return true; } /** Get the primary selection range. Usually, you should make sure your code applies to _all_ ranges, by using methods like [`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange). */ get main() { return this.ranges[this.mainIndex]; } /** Make sure the selection only has one range. Returns a selection holding only the main range from this selection. */ asSingle() { return this.ranges.length == 1 ? this : new EditorSelection([this.main]); } /** Extend this selection with an extra range. */ addRange(range, main = true) { return EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1); } /** Replace a given range with another range, and then normalize the selection to merge and sort ranges if necessary. */ replaceRange(range, which = this.mainIndex) { let ranges = this.ranges.slice(); ranges[which] = range; return EditorSelection.create(ranges, this.mainIndex); } /** Convert this selection to an object that can be serialized to JSON. */ toJSON() { return { ranges: this.ranges.map(r => r.toJSON()), main: this.mainIndex }; } /** Create a selection from a JSON representation. */ static fromJSON(json) { if (!json || !Array.isArray(json.ranges) || typeof json.main != "number" || json.main >= json.ranges.length) throw new RangeError("Invalid JSON representation for EditorSelection"); return new EditorSelection(json.ranges.map((r) => SelectionRange.fromJSON(r)), json.main); } /** Create a selection holding a single range. */ static single(anchor, head = anchor) { return new EditorSelection([EditorSelection.range(anchor, head)], 0); } /** Sort and merge the given set of ranges, creating a valid selection. */ static create(ranges, mainIndex = 0) { if (ranges.length == 0) throw new RangeError("A selection needs at least one range"); for (let pos = 0, i = 0; i < ranges.length; i++) { let range = ranges[i]; if (range.empty ? range.from <= pos : range.from < pos) return normalized(ranges.slice(), mainIndex); pos = range.to; } return new EditorSelection(ranges, mainIndex); } /** Create a cursor selection range at the given position. You can safely ignore the optional arguments in most situations. */ static cursor(pos, assoc = 0, bidiLevel, goalColumn) { return new SelectionRange(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 4 /* AssocBefore */ : 8 /* AssocAfter */) | (bidiLevel == null ? 3 : Math.min(2, bidiLevel)) | ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431 /* NoGoalColumn */) << 5 /* GoalColumnOffset */)); } /** Create a selection range. */ static range(anchor, head, goalColumn) { let goal = (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431 /* NoGoalColumn */) << 5 /* GoalColumnOffset */; return head < anchor ? new SelectionRange(head, anchor, 16 /* Inverted */ | goal | 8 /* AssocAfter */) : new SelectionRange(anchor, head, goal | (head > anchor ? 4 /* AssocBefore */ : 0)); } } function normalized(ranges, mainIndex = 0) { let main = ranges[mainIndex]; ranges.sort((a, b) => a.from - b.from); mainIndex = ranges.indexOf(main); for (let i = 1; i < ranges.length; i++) { let range = ranges[i], prev = ranges[i - 1]; if (range.empty ? range.from <= prev.to : range.from < prev.to) { let from = prev.from, to = Math.max(range.to, prev.to); if (i <= mainIndex) mainIndex--; ranges.splice(--i, 2, range.anchor > range.head ? EditorSelection.range(to, from) : EditorSelection.range(from, to)); } } return new EditorSelection(ranges, mainIndex); } function checkSelection(selection, docLength) { for (let range of selection.ranges) if (range.to > docLength) throw new RangeError("Selection points outside of document"); } let nextID = 0; /** A facet is a labeled value that is associated with an editor state. It takes inputs from any number of extensions, and combines those into a single output value. Examples of facets are the [theme](https://codemirror.net/6/docs/ref/#view.EditorView^theme) styles associated with an editor or the [tab size](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) (which is reduced to a single value, using the input with the hightest precedence). */ class Facet { constructor( /** @internal */ combine, /** @internal */ compareInput, /** @internal */ compare, isStatic, /** @internal */ extensions) { this.combine = combine; this.compareInput = compareInput; this.compare = compare; this.isStatic = isStatic; this.extensions = extensions; /** @internal */ this.id = nextID++; this.default = combine([]); } /** Define a new facet. */ static define(config = {}) { return new Facet(config.combine || ((a) => a), config.compareInput || ((a, b) => a === b), config.compare || (!config.combine ? sameArray$1 : (a, b) => a === b), !!config.static, config.enables); } /** Returns an extension that adds the given value for this facet. */ of(value) { return new FacetProvider([], this, 0 /* Static */, value); } /** Create an extension that computes a value for the facet from a state. You must take care to declare the parts of the state that this value depends on, since your function is only called again for a new state when one of those parts changed. In most cases, you'll want to use the [`provide`](https://codemirror.net/6/docs/ref/#state.StateField^define^config.provide) option when defining a field instead. */ compute(deps, get) { if (this.isStatic) throw new Error("Can't compute a static facet"); return new FacetProvider(deps, this, 1 /* Single */, get); } /** Create an extension that computes zero or more values for this facet from a state. */ computeN(deps, get) { if (this.isStatic) throw new Error("Can't compute a static facet"); return new FacetProvider(deps, this, 2 /* Multi */, get); } from(field, get) { if (!get) get = x => x; return this.compute([field], state => get(state.field(field))); } } function sameArray$1(a, b) { return a == b || a.length == b.length && a.every((e, i) => e === b[i]); } class FacetProvider { constructor(dependencies, facet, type, value) { this.dependencies = dependencies; this.facet = facet; this.type = type; this.value = value; this.id = nextID++; } dynamicSlot(addresses) { var _a; let getter = this.value; let compare = this.facet.compareInput; let id = this.id, idx = addresses[id] >> 1, multi = this.type == 2 /* Multi */; let depDoc = false, depSel = false, depAddrs = []; for (let dep of this.dependencies) { if (dep == "doc") depDoc = true; else if (dep == "selection") depSel = true; else if ((((_a = addresses[dep.id]) !== null && _a !== void 0 ? _a : 1) & 1) == 0) depAddrs.push(addresses[dep.id]); } return { create(state) { state.values[idx] = getter(state); return 1 /* Changed */; }, update(state, tr) { if ((depDoc && tr.docChanged) || (depSel && (tr.docChanged || tr.selection)) || depAddrs.some(addr => (ensureAddr(state, addr) & 1 /* Changed */) > 0)) { let newVal = getter(state); if (multi ? !compareArray(newVal, state.values[idx], compare) : !compare(newVal, state.values[idx])) { state.values[idx] = newVal; return 1 /* Changed */; } } return 0; }, reconfigure(state, oldState) { let newVal = getter(state); let oldAddr = oldState.config.address[id]; if (oldAddr != null) { let oldVal = getAddr(oldState, oldAddr); if (multi ? compareArray(newVal, oldVal, compare) : compare(newVal, oldVal)) { state.values[idx] = oldVal; return 0; } } state.values[idx] = newVal; return 1 /* Changed */; } }; } } function compareArray(a, b, compare) { if (a.length != b.length) return false; for (let i = 0; i < a.length; i++) if (!compare(a[i], b[i])) return false; return true; } function dynamicFacetSlot(addresses, facet, providers) { let providerAddrs = providers.map(p => addresses[p.id]); let providerTypes = providers.map(p => p.type); let dynamic = providerAddrs.filter(p => !(p & 1)); let idx = addresses[facet.id] >> 1; function get(state) { let values = []; for (let i = 0; i < providerAddrs.length; i++) { let value = getAddr(state, providerAddrs[i]); if (providerTypes[i] == 2 /* Multi */) for (let val of value) values.push(val); else values.push(value); } return facet.combine(values); } return { create(state) { for (let addr of providerAddrs) ensureAddr(state, addr); state.values[idx] = get(state); return 1 /* Changed */; }, update(state, tr) { if (!dynamic.some(dynAddr => ensureAddr(state, dynAddr) & 1 /* Changed */)) return 0; let value = get(state); if (facet.compare(value, state.values[idx])) return 0; state.values[idx] = value; return 1 /* Changed */; }, reconfigure(state, oldState) { let depChanged = providerAddrs.some(addr => ensureAddr(state, addr) & 1 /* Changed */); let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet); if (oldProviders && !depChanged && sameArray$1(providers, oldProviders)) { state.values[idx] = oldValue; return 0; } let value = get(state); if (facet.compare(value, oldValue)) { state.values[idx] = oldValue; return 0; } state.values[idx] = value; return 1 /* Changed */; } }; } const initField = /*@__PURE__*/Facet.define({ static: true }); /** Fields can store additional information in an editor state, and keep it in sync with the rest of the state. */ class StateField { constructor( /** @internal */ id, createF, updateF, compareF, /** @internal */ spec) { this.id = id; this.createF = createF; this.updateF = updateF; this.compareF = compareF; this.spec = spec; /** @internal */ this.provides = undefined; } /** Define a state field. */ static define(config) { let field = new StateField(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config); if (config.provide) field.provides = config.provide(field); return field; } create(state) { let init = state.facet(initField).find(i => i.field == this); return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state); } /** @internal */ slot(addresses) { let idx = addresses[this.id] >> 1; return { create: (state) => { state.values[idx] = this.create(state); return 1 /* Changed */; }, update: (state, tr) => { let oldVal = state.values[idx]; let value = this.updateF(oldVal, tr); if (this.compareF(oldVal, value)) return 0; state.values[idx] = value; return 1 /* Changed */; }, reconfigure: (state, oldState) => { if (oldState.config.address[this.id] != null) { state.values[idx] = oldState.field(this); return 0; } state.values[idx] = this.create(state); return 1 /* Changed */; } }; } /** Returns an extension that enables this field and overrides the way it is initialized. Can be useful when you need to provide a non-default starting value for the field. */ init(create) { return [this, initField.of({ field: this, create })]; } /** State field instances can be used as [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a given state. */ get extension() { return this; } } const Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 }; function prec(value) { return (ext) => new PrecExtension(ext, value); } /** By default extensions are registered in the order they are found in the flattened form of nested array that was provided. Individual extension values can be assigned a precedence to override this. Extensions that do not have a precedence set get the precedence of the nearest parent with a precedence, or [`default`](https://codemirror.net/6/docs/ref/#state.Prec.default) if there is no such parent. The final ordering of extensions is determined by first sorting by precedence and then by order within each precedence. */ const Prec = { /** The lowest precedence level. Meant for things that should end up near the end of the extension order. */ lowest: /*@__PURE__*/prec(Prec_.lowest), /** A lower-than-default precedence, for extensions. */ low: /*@__PURE__*/prec(Prec_.low), /** The default precedence, which is also used for extensions without an explicit precedence. */ default: /*@__PURE__*/prec(Prec_.default), /** A higher-than-default precedence, for extensions that should come before those with default precedence. */ high: /*@__PURE__*/prec(Prec_.high), /** The highest precedence level, for extensions that should end up near the start of the precedence ordering. */ highest: /*@__PURE__*/prec(Prec_.highest), // FIXME Drop these in some future breaking version /** Backwards-compatible synonym for `Prec.lowest`. */ fallback: /*@__PURE__*/prec(Prec_.lowest), /** Backwards-compatible synonym for `Prec.high`. */ extend: /*@__PURE__*/prec(Prec_.high), /** Backwards-compatible synonym for `Prec.highest`. */ override: /*@__PURE__*/prec(Prec_.highest) }; class PrecExtension { constructor(inner, prec) { this.inner = inner; this.prec = prec; } } /** Extension compartments can be used to make a configuration dynamic. By [wrapping](https://codemirror.net/6/docs/ref/#state.Compartment.of) part of your configuration in a compartment, you can later [replace](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) that part through a transaction. */ class Compartment { /** Create an instance of this compartment to add to your [state configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions). */ of(ext) { return new CompartmentInstance(this, ext); } /** Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that reconfigures this compartment. */ reconfigure(content) { return Compartment.reconfigure.of({ compartment: this, extension: content }); } /** Get the current content of the compartment in the state, or `undefined` if it isn't present. */ get(state) { return state.config.compartments.get(this); } } class CompartmentInstance { constructor(compartment, inner) { this.compartment = compartment; this.inner = inner; } } class Configuration { constructor(base, compartments, dynamicSlots, address, staticValues, facets) { this.base = base; this.compartments = compartments; this.dynamicSlots = dynamicSlots; this.address = address; this.staticValues = staticValues; this.facets = facets; this.statusTemplate = []; while (this.statusTemplate.length < dynamicSlots.length) this.statusTemplate.push(0 /* Unresolved */); } staticFacet(facet) { let addr = this.address[facet.id]; return addr == null ? facet.default : this.staticValues[addr >> 1]; } static resolve(base, compartments, oldState) { let fields = []; let facets = Object.create(null); let newCompartments = new Map(); for (let ext of flatten(base, compartments, newCompartments)) { if (ext instanceof StateField) fields.push(ext); else (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext); } let address = Object.create(null); let staticValues = []; let dynamicSlots = []; for (let field of fields) { address[field.id] = dynamicSlots.length << 1; dynamicSlots.push(a => field.slot(a)); } let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets; for (let id in facets) { let providers = facets[id], facet = providers[0].facet; let oldProviders = oldFacets && oldFacets[id] || []; if (providers.every(p => p.type == 0 /* Static */)) { address[facet.id] = (staticValues.length << 1) | 1; if (sameArray$1(oldProviders, providers)) { staticValues.push(oldState.facet(facet)); } else { let value = facet.combine(providers.map(p => p.value)); staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value); } } else { for (let p of providers) { if (p.type == 0 /* Static */) { address[p.id] = (staticValues.length << 1) | 1; staticValues.push(p.value); } else { address[p.id] = dynamicSlots.length << 1; dynamicSlots.push(a => p.dynamicSlot(a)); } } address[facet.id] = dynamicSlots.length << 1; dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers)); } } let dynamic = dynamicSlots.map(f => f(address)); return new Configuration(base, newCompartments, dynamic, address, staticValues, facets); } } function flatten(extension, compartments, newCompartments) { let result = [[], [], [], [], []]; let seen = new Map(); function inner(ext, prec) { let known = seen.get(ext); if (known != null) { if (known >= prec) return; let found = result[known].indexOf(ext); if (found > -1) result[known].splice(found, 1); if (ext instanceof CompartmentInstance) newCompartments.delete(ext.compartment); } seen.set(ext, prec); if (Array.isArray(ext)) { for (let e of ext) inner(e, prec); } else if (ext instanceof CompartmentInstance) { if (newCompartments.has(ext.compartment)) throw new RangeError(`Duplicate use of compartment in extensions`); let content = compartments.get(ext.compartment) || ext.inner; newCompartments.set(ext.compartment, content); inner(content, prec); } else if (ext instanceof PrecExtension) { inner(ext.inner, ext.prec); } else if (ext instanceof StateField) { result[prec].push(ext); if (ext.provides) inner(ext.provides, prec); } else if (ext instanceof FacetProvider) { result[prec].push(ext); if (ext.facet.extensions) inner(ext.facet.extensions, prec); } else { let content = ext.extension; if (!content) throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`); inner(content, prec); } } inner(extension, Prec_.default); return result.reduce((a, b) => a.concat(b)); } function ensureAddr(state, addr) { if (addr & 1) return 2 /* Computed */; let idx = addr >> 1; let status = state.status[idx]; if (status == 4 /* Computing */) throw new Error("Cyclic dependency between fields and/or facets"); if (status & 2 /* Computed */) return status; state.status[idx] = 4 /* Computing */; let changed = state.computeSlot(state, state.config.dynamicSlots[idx]); return state.status[idx] = 2 /* Computed */ | changed; } function getAddr(state, addr) { return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1]; } const languageData = /*@__PURE__*/Facet.define(); const allowMultipleSelections = /*@__PURE__*/Facet.define({ combine: values => values.some(v => v), static: true }); const lineSeparator = /*@__PURE__*/Facet.define({ combine: values => values.length ? values[0] : undefined, static: true }); const changeFilter = /*@__PURE__*/Facet.define(); const transactionFilter = /*@__PURE__*/Facet.define(); const transactionExtender = /*@__PURE__*/Facet.define(); const readOnly = /*@__PURE__*/Facet.define({ combine: values => values.length ? values[0] : false }); /** Annotations are tagged values that are used to add metadata to transactions in an extensible way. They should be used to model things that effect the entire transaction (such as its [time stamp](https://codemirror.net/6/docs/ref/#state.Transaction^time) or information about its [origin](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent)). For effects that happen _alongside_ the other changes made by the transaction, [state effects](https://codemirror.net/6/docs/ref/#state.StateEffect) are more appropriate. */ class Annotation { /** @internal */ constructor( /** The annotation type. */ type, /** The value of this annotation. */ value) { this.type = type; this.value = value; } /** Define a new type of annotation. */ static define() { return new AnnotationType(); } } /** Marker that identifies a type of [annotation](https://codemirror.net/6/docs/ref/#state.Annotation). */ class AnnotationType { /** Create an instance of this annotation. */ of(value) { return new Annotation(this, value); } } /** Representation of a type of state effect. Defined with [`StateEffect.define`](https://codemirror.net/6/docs/ref/#state.StateEffect^define). */ class StateEffectType { /** @internal */ constructor( // The `any` types in these function types are there to work // around TypeScript issue #37631, where the type guard on // `StateEffect.is` mysteriously stops working when these properly // have type `Value`. /** @internal */ map) { this.map = map; } /** Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this type. */ of(value) { return new StateEffect(this, value); } } /** State effects can be used to represent additional effects associated with a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction.effects). They are often useful to model changes to custom [state fields](https://codemirror.net/6/docs/ref/#state.StateField), when those changes aren't implicit in document or selection changes. */ class StateEffect { /** @internal */ constructor( /** @internal */ type, /** The value of this effect. */ value) { this.type = type; this.value = value; } /** Map this effect through a position mapping. Will return `undefined` when that ends up deleting the effect. */ map(mapping) { let mapped = this.type.map(this.value, mapping); return mapped === undefined ? undefined : mapped == this.value ? this : new StateEffect(this.type, mapped); } /** Tells you whether this effect object is of a given [type](https://codemirror.net/6/docs/ref/#state.StateEffectType). */ is(type) { return this.type == type; } /** Define a new effect type. The type parameter indicates the type of values that his effect holds. */ static define(spec = {}) { return new StateEffectType(spec.map || (v => v)); } /** Map an array of effects through a change set. */ static mapEffects(effects, mapping) { if (!effects.length) return effects; let result = []; for (let effect of effects) { let mapped = effect.map(mapping); if (mapped) result.push(mapped); } return result; } } /** This effect can be used to reconfigure the root extensions of the editor. Doing this will discard any extensions [appended](https://codemirror.net/6/docs/ref/#state.StateEffect^appendConfig), but does not reset the content of [reconfigured](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) compartments. */ StateEffect.reconfigure = /*@__PURE__*/StateEffect.define(); /** Append extensions to the top-level configuration of the editor. */ StateEffect.appendConfig = /*@__PURE__*/StateEffect.define(); /** Changes to the editor state are grouped into transactions. Typically, a user action creates a single transaction, which may contain any number of document changes, may change the selection, or have other effects. Create a transaction by calling [`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update). */ class Transaction { /** @internal */ constructor( /** The state from which the transaction starts. */ startState, /** The document changes made by this transaction. */ changes, /** The selection set by this transaction, or undefined if it doesn't explicitly set a selection. */ selection, /** The effects added to the transaction. */ effects, /** @internal */ annotations, /** Whether the selection should be scrolled into view after this transaction is dispatched. */ scrollIntoView) { this.startState = startState; this.changes = changes; this.selection = selection; this.effects = effects; this.annotations = annotations; this.scrollIntoView = scrollIntoView; /** @internal */ this._doc = null; /** @internal */ this._state = null; if (selection) checkSelection(selection, changes.newLength); if (!annotations.some((a) => a.type == Transaction.time)) this.annotations = annotations.concat(Transaction.time.of(Date.now())); } /** The new document produced by the transaction. Contrary to [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't force the entire new state to be computed right away, so it is recommended that [transaction filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter when they need to look at the new document. */ get newDoc() { return this._doc || (this._doc = this.changes.apply(this.startState.doc)); } /** The new selection produced by the transaction. If [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined, this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's current selection through the changes made by the transaction. */ get newSelection() { return this.selection || this.startState.selection.map(this.changes); } /** The new state created by the transaction. Computed on demand (but retained for subsequent access), so itis recommended not to access it in [transaction filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible. */ get state() { if (!this._state) this.startState.applyTransaction(this); return this._state; } /** Get the value of the given annotation type, if any. */ annotation(type) { for (let ann of this.annotations) if (ann.type == type) return ann.value; return undefined; } /** Indicates whether the transaction changed the document. */ get docChanged() { return !this.changes.empty; } /** Indicates whether this transaction reconfigures the state (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or with a top-level configuration [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure). */ get reconfigured() { return this.startState.config != this.state.config; } /** Returns true if the transaction has a [user event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to or more specific than `event`. For example, if the transaction has `"select.pointer"` as user event, `"select"` and `"select.pointer"` will match it. */ isUserEvent(event) { let e = this.annotation(Transaction.userEvent); return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == ".")); } } /** Annotation used to store transaction timestamps. */ Transaction.time = /*@__PURE__*/Annotation.define(); /** Annotation used to associate a transaction with a user interface event. Holds a string identifying the event, using a dot-separated format to support attaching more specific information. The events used by the core libraries are: - `"input"` when content is entered - `"input.type"` for typed input - `"input.type.compose"` for composition - `"input.paste"` for pasted input - `"input.drop"` when adding content with drag-and-drop - `"input.complete"` when autocompleting - `"delete"` when the user deletes content - `"delete.selection"` when deleting the selection - `"delete.forward"` when deleting forward from the selection - `"delete.backward"` when deleting backward from the selection - `"delete.cut"` when cutting to the clipboard - `"move"` when content is moved - `"move.drop"` when content is moved within the editor through drag-and-drop - `"select"` when explicitly changing the selection - `"select.pointer"` when selecting with a mouse or other pointing device - `"undo"` and `"redo"` for history actions Use [`isUserEvent`](https://codemirror.net/6/docs/ref/#state.Transaction.isUserEvent) to check whether the annotation matches a given event. */ Transaction.userEvent = /*@__PURE__*/Annotation.define(); /** Annotation indicating whether a transaction should be added to the undo history or not. */ Transaction.addToHistory = /*@__PURE__*/Annotation.define(); /** Annotation indicating (when present and true) that a transaction represents a change made by some other actor, not the user. This is used, for example, to tag other people's changes in collaborative editing. */ Transaction.remote = /*@__PURE__*/Annotation.define(); function joinRanges(a, b) { let result = []; for (let iA = 0, iB = 0;;) { let from, to; if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) { from = a[iA++]; to = a[iA++]; } else if (iB < b.length) { from = b[iB++]; to = b[iB++]; } else return result; if (!result.length || result[result.length - 1] < from) result.push(from, to); else if (result[result.length - 1] < to) result[result.length - 1] = to; } } function mergeTransaction(a, b, sequential) { var _a; let mapForA, mapForB, changes; if (sequential) { mapForA = b.changes; mapForB = ChangeSet.empty(b.changes.length); changes = a.changes.compose(b.changes); } else { mapForA = b.changes.map(a.changes); mapForB = a.changes.mapDesc(b.changes, true); changes = a.changes.compose(mapForA); } return { changes, selection: b.selection ? b.selection.map(mapForB) : (_a = a.selection) === null || _a === void 0 ? void 0 : _a.map(mapForA), effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)), annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations, scrollIntoView: a.scrollIntoView || b.scrollIntoView }; } function resolveTransactionInner(state, spec, docSize) { let sel = spec.selection, annotations = asArray$1(spec.annotations); if (spec.userEvent) annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent)); return { changes: spec.changes instanceof ChangeSet ? spec.changes : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)), selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)), effects: asArray$1(spec.effects), annotations, scrollIntoView: !!spec.scrollIntoView }; } function resolveTransaction(state, specs, filter) { let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length); if (specs.length && specs[0].filter === false) filter = false; for (let i = 1; i < specs.length; i++) { if (specs[i].filter === false) filter = false; let seq = !!specs[i].sequential; s = mergeTransaction(s, resolveTransactionInner(state, specs[i], seq ? s.changes.newLength : state.doc.length), seq); } let tr = new Transaction(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView); return extendTransaction(filter ? filterTransaction(tr) : tr); } // Finish a transaction by applying filters if necessary. function filterTransaction(tr) { let state = tr.startState; // Change filters let result = true; for (let filter of state.facet(changeFilter)) { let value = filter(tr); if (value === false) { result = false; break; } if (Array.isArray(value)) result = result === true ? value : joinRanges(result, value); } if (result !== true) { let changes, back; if (result === false) { back = tr.changes.invertedDesc; changes = ChangeSet.empty(state.doc.length); } else { let filtered = tr.changes.filter(result); changes = filtered.changes; back = filtered.filtered.invertedDesc; } tr = new Transaction(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView); } // Transaction filters let filters = state.facet(transactionFilter); for (let i = filters.length - 1; i >= 0; i--) { let filtered = filters[i](tr); if (filtered instanceof Transaction) tr = filtered; else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction) tr = filtered[0]; else tr = resolveTransaction(state, asArray$1(filtered), false); } return tr; } function extendTransaction(tr) { let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr; for (let i = extenders.length - 1; i >= 0; i--) { let extension = extenders[i](tr); if (extension && Object.keys(extension).length) spec = mergeTransaction(tr, resolveTransactionInner(state, extension, tr.changes.newLength), true); } return spec == tr ? tr : new Transaction(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView); } const none$3 = []; function asArray$1(value) { return value == null ? none$3 : Array.isArray(value) ? value : [value]; } /** The categories produced by a [character categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used do things like selecting by word. */ var CharCategory = /*@__PURE__*/(function (CharCategory) { /** Word characters. */ CharCategory[CharCategory["Word"] = 0] = "Word"; /** Whitespace. */ CharCategory[CharCategory["Space"] = 1] = "Space"; /** Anything else. */ CharCategory[CharCategory["Other"] = 2] = "Other"; return CharCategory})(CharCategory || (CharCategory = {})); const nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; let wordChar; try { wordChar = /*@__PURE__*/new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u"); } catch (_) { } function hasWordChar(str) { if (wordChar) return wordChar.test(str); for (let i = 0; i < str.length; i++) { let ch = str[i]; if (/\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))) return true; } return false; } function makeCategorizer(wordChars) { return (char) => { if (!/\S/.test(char)) return CharCategory.Space; if (hasWordChar(char)) return CharCategory.Word; for (let i = 0; i < wordChars.length; i++) if (char.indexOf(wordChars[i]) > -1) return CharCategory.Word; return CharCategory.Other; }; } /** The editor state class is a persistent (immutable) data structure. To update a state, you [create](https://codemirror.net/6/docs/ref/#state.EditorState.update) a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction), which produces a _new_ state instance, without modifying the original object. As such, _never_ mutate properties of a state directly. That'll just break things. */ class EditorState { /** @internal */ constructor( /** @internal */ config, /** The current document. */ doc, /** The current selection. */ selection, /** @internal */ values, computeSlot, tr) { this.config = config; this.doc = doc; this.selection = selection; this.values = values; this.status = config.statusTemplate.slice(); this.computeSlot = computeSlot; // Fill in the computed state immediately, so that further queries // for it made during the update return this state if (tr) tr._state = this; for (let i = 0; i < this.config.dynamicSlots.length; i++) ensureAddr(this, i << 1); this.computeSlot = null; } field(field, require = true) { let addr = this.config.address[field.id]; if (addr == null) { if (require) throw new RangeError("Field is not present in this state"); return undefined; } ensureAddr(this, addr); return getAddr(this, addr); } /** Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec) can be passed. Unless [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec are assumed to start in the _current_ document (not the document produced by previous specs), and its [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer to the document created by its _own_ changes. The resulting transaction contains the combined effect of all the different specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later specs take precedence over earlier ones. */ update(...specs) { return resolveTransaction(this, specs, true); } /** @internal */ applyTransaction(tr) { let conf = this.config, { base, compartments } = conf; for (let effect of tr.effects) { if (effect.is(Compartment.reconfigure)) { if (conf) { compartments = new Map; conf.compartments.forEach((val, key) => compartments.set(key, val)); conf = null; } compartments.set(effect.value.compartment, effect.value.extension); } else if (effect.is(StateEffect.reconfigure)) { conf = null; base = effect.value; } else if (effect.is(StateEffect.appendConfig)) { conf = null; base = asArray$1(base).concat(effect.value); } } let startValues; if (!conf) { conf = Configuration.resolve(base, compartments, this); let intermediateState = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null); startValues = intermediateState.values; } else { startValues = tr.startState.values.slice(); } new EditorState(conf, tr.newDoc, tr.newSelection, startValues, (state, slot) => slot.update(state, tr), tr); } /** Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that replaces every selection range with the given content. */ replaceSelection(text) { if (typeof text == "string") text = this.toText(text); return this.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: text }, range: EditorSelection.cursor(range.from + text.length) })); } /** Create a set of changes and a new selection by running the given function for each range in the active selection. The function can return an optional set of changes (in the coordinate space of the start document), plus an updated range (in the coordinate space of the document produced by the call's own changes). This method will merge all the changes and ranges into a single changeset and selection, and return it as a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update). */ changeByRange(f) { let sel = this.selection; let result1 = f(sel.ranges[0]); let changes = this.changes(result1.changes), ranges = [result1.range]; let effects = asArray$1(result1.effects); for (let i = 1; i < sel.ranges.length; i++) { let result = f(sel.ranges[i]); let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes); for (let j = 0; j < i; j++) ranges[j] = ranges[j].map(newMapped); let mapBy = changes.mapDesc(newChanges, true); ranges.push(result.range.map(mapBy)); changes = changes.compose(newMapped); effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray$1(result.effects), mapBy)); } return { changes, selection: EditorSelection.create(ranges, sel.mainIndex), effects }; } /** Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change description, taking the state's document length and line separator into account. */ changes(spec = []) { if (spec instanceof ChangeSet) return spec; return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator)); } /** Using the state's [line separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a [`Text`](https://codemirror.net/6/docs/ref/#text.Text) instance from the given string. */ toText(string) { return Text.of(string.split(this.facet(EditorState.lineSeparator) || DefaultSplit)); } /** Return the given range of the document as a string. */ sliceDoc(from = 0, to = this.doc.length) { return this.doc.sliceString(from, to, this.lineBreak); } /** Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet). */ facet(facet) { let addr = this.config.address[facet.id]; if (addr == null) return facet.default; ensureAddr(this, addr); return getAddr(this, addr); } /** Convert this state to a JSON-serializable object. When custom fields should be serialized, you can pass them in as an object mapping property names (in the resulting object, which should not use `doc` or `selection`) to fields. */ toJSON(fields) { let result = { doc: this.sliceDoc(), selection: this.selection.toJSON() }; if (fields) for (let prop in fields) { let value = fields[prop]; if (value instanceof StateField) result[prop] = value.spec.toJSON(this.field(fields[prop]), this); } return result; } /** Deserialize a state from its JSON representation. When custom fields should be deserialized, pass the same object you passed to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as third argument. */ static fromJSON(json, config = {}, fields) { if (!json || typeof json.doc != "string") throw new RangeError("Invalid JSON representation for EditorState"); let fieldInit = []; if (fields) for (let prop in fields) { let field = fields[prop], value = json[prop]; fieldInit.push(field.init(state => field.spec.fromJSON(value, state))); } return EditorState.create({ doc: json.doc, selection: EditorSelection.fromJSON(json.selection), extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit }); } /** Create a new state. You'll usually only need this when initializing an editor—updated states are created by applying transactions. */ static create(config = {}) { let configuration = Configuration.resolve(config.extensions || [], new Map); let doc = config.doc instanceof Text ? config.doc : Text.of((config.doc || "").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit)); let selection = !config.selection ? EditorSelection.single(0) : config.selection instanceof EditorSelection ? config.selection : EditorSelection.single(config.selection.anchor, config.selection.head); checkSelection(selection, doc.length); if (!configuration.staticFacet(allowMultipleSelections)) selection = selection.asSingle(); return new EditorState(configuration, doc, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null); } /** The size (in columns) of a tab in the document, determined by the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet. */ get tabSize() { return this.facet(EditorState.tabSize); } /** Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator) string for this state. */ get lineBreak() { return this.facet(EditorState.lineSeparator) || "\n"; } /** Returns true when the editor is [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only. */ get readOnly() { return this.facet(readOnly); } /** Look up a translation for the given phrase (via the [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the original string if no translation is found. */ phrase(phrase) { for (let map of this.facet(EditorState.phrases)) if (Object.prototype.hasOwnProperty.call(map, phrase)) return map[phrase]; return phrase; } /** Find the values for a given language data field, provided by the the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet. */ languageDataAt(name, pos, side = -1) { let values = []; for (let provider of this.facet(languageData)) { for (let result of provider(this, pos, side)) { if (Object.prototype.hasOwnProperty.call(result, name)) values.push(result[name]); } } return values; } /** Return a function that can categorize strings (expected to represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#text.findClusterBreak)) into one of: - Word (contains an alphanumeric character or a character explicitly listed in the local language's `"wordChars"` language data, which should be a string) - Space (contains only whitespace) - Other (anything else) */ charCategorizer(at) { return makeCategorizer(this.languageDataAt("wordChars", at).join("")); } /** Find the word at the given position, meaning the range containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters around it. If no word characters are adjacent to the position, this returns null. */ wordAt(pos) { let { text, from, length } = this.doc.lineAt(pos); let cat = this.charCategorizer(pos); let start = pos - from, end = pos - from; while (start > 0) { let prev = findClusterBreak(text, start, false); if (cat(text.slice(prev, start)) != CharCategory.Word) break; start = prev; } while (end < length) { let next = findClusterBreak(text, end); if (cat(text.slice(end, next)) != CharCategory.Word) break; end = next; } return start == end ? null : EditorSelection.range(start + from, end + from); } } /** A facet that, when enabled, causes the editor to allow multiple ranges to be selected. Be careful though, because by default the editor relies on the native DOM selection, which cannot handle multiple selections. An extension like [`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) can be used to make secondary selections visible to the user. */ EditorState.allowMultipleSelections = allowMultipleSelections; /** Configures the tab size to use in this state. The first (highest-precedence) value of the facet is used. If no value is given, this defaults to 4. */ EditorState.tabSize = /*@__PURE__*/Facet.define({ combine: values => values.length ? values[0] : 4 }); /** The line separator to use. By default, any of `"\n"`, `"\r\n"` and `"\r"` is treated as a separator when splitting lines, and lines are joined with `"\n"`. When you configure a value here, only that precise separator will be used, allowing you to round-trip documents through the editor without normalizing line separators. */ EditorState.lineSeparator = lineSeparator; /** This facet controls the value of the [`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) getter, which is consulted by commands and extensions that implement editing functionality to determine whether they should apply. It defaults to false, but when its highest-precedence value is `true`, such functionality disables itself. Not to be confused with [`EditorView.editable`](https://codemirror.net/6/docs/ref/#view.EditorView^editable), which controls whether the editor's DOM is set to be editable (and thus focusable). */ EditorState.readOnly = readOnly; /** Registers translation phrases. The [`phrase`](https://codemirror.net/6/docs/ref/#state.EditorState.phrase) method will look through all objects registered with this facet to find translations for its argument. */ EditorState.phrases = /*@__PURE__*/Facet.define(); /** A facet used to register [language data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) providers. */ EditorState.languageData = languageData; /** Facet used to register change filters, which are called for each transaction (unless explicitly [disabled](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter)), and can suppress part of the transaction's changes. Such a function can return `true` to indicate that it doesn't want to do anything, `false` to completely stop the changes in the transaction, or a set of ranges in which changes should be suppressed. Such ranges are represented as an array of numbers, with each pair of two number indicating the start and end of a range. So for example `[10, 20, 100, 110]` suppresses changes between 10 and 20, and between 100 and 110. */ EditorState.changeFilter = changeFilter; /** Facet used to register a hook that gets a chance to update or replace transaction specs before they are applied. This will only be applied for transactions that don't have [`filter`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter) set to `false`. You can either return a single transaction spec (possibly the input transaction), or an array of specs (which will be combined in the same way as the arguments to [`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update)). When possible, it is recommended to avoid accessing [`Transaction.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state) in a filter, since it will force creation of a state that will then be discarded again, if the transaction is actually filtered. (This functionality should be used with care. Indiscriminately modifying transaction is likely to break something or degrade the user experience.) */ EditorState.transactionFilter = transactionFilter; /** This is a more limited form of [`transactionFilter`](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter), which can only add [annotations](https://codemirror.net/6/docs/ref/#state.TransactionSpec.annotations) and [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects). _But_, this type of filter runs even the transaction has disabled regular [filtering](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter), making it suitable for effects that don't need to touch the changes or selection, but do want to process every transaction. Extenders run _after_ filters, when both are applied. */ EditorState.transactionExtender = transactionExtender; Compartment.reconfigure = /*@__PURE__*/StateEffect.define(); /** Utility function for combining behaviors to fill in a config object from an array of provided configs. Will, by default, error when a field gets two values that aren't `===`-equal, but you can provide combine functions per field to do something else. */ function combineConfig(configs, defaults, // Should hold only the optional properties of Config, but I haven't managed to express that combine = {}) { let result = {}; for (let config of configs) for (let key of Object.keys(config)) { let value = config[key], current = result[key]; if (current === undefined) result[key] = value; else if (current === value || value === undefined) ; // No conflict else if (Object.hasOwnProperty.call(combine, key)) result[key] = combine[key](current, value); else throw new Error("Config merge conflict for field " + key); } for (let key in defaults) if (result[key] === undefined) result[key] = defaults[key]; return result; } const C = "\u037c"; const COUNT = typeof Symbol == "undefined" ? "__" + C : Symbol.for(C); const SET = typeof Symbol == "undefined" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet"); const top = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : {}; // :: - Style modules encapsulate a set of CSS rules defined from // JavaScript. Their definitions are only available in a given DOM // root after it has been _mounted_ there with `StyleModule.mount`. // // Style modules should be created once and stored somewhere, as // opposed to re-creating them every time you need them. The amount of // CSS rules generated for a given DOM root is bounded by the amount // of style modules that were used. So to avoid leaking rules, don't // create these dynamically, but treat them as one-time allocations. class StyleModule { // :: (Object